{"id":20284165,"url":"https://github.com/clebert/state-guard","last_synced_at":"2025-04-11T08:24:06.588Z","repository":{"id":172272842,"uuid":"649096178","full_name":"clebert/state-guard","owner":"clebert","description":"Type-safe, deterministic state management featuring state machines and automatic stale snapshot invalidation.","archived":false,"fork":false,"pushed_at":"2024-07-16T20:27:21.000Z","size":547,"stargazers_count":3,"open_issues_count":2,"forks_count":0,"subscribers_count":2,"default_branch":"main","last_synced_at":"2025-04-10T19:19:50.495Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/clebert.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-06-03T19:05:34.000Z","updated_at":"2024-09-24T07:29:35.000Z","dependencies_parsed_at":"2024-10-24T10:47:46.523Z","dependency_job_id":"e46595c4-af98-49c4-9715-6dd76c7d6e96","html_url":"https://github.com/clebert/state-guard","commit_stats":{"total_commits":59,"total_committers":1,"mean_commits":59.0,"dds":0.0,"last_synced_commit":"27ca35cbb3b7bc28f1a6eadd84b66206878fc5a7"},"previous_names":["clebert/state-guard"],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clebert%2Fstate-guard","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clebert%2Fstate-guard/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clebert%2Fstate-guard/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/clebert%2Fstate-guard/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/clebert","download_url":"https://codeload.github.com/clebert/state-guard/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248361059,"owners_count":21090808,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-11-14T14:18:33.440Z","updated_at":"2025-04-11T08:24:06.556Z","avatar_url":"https://github.com/clebert.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# StateGuard\n\n\u003e Type-safe, deterministic state management featuring state machines and automatic stale snapshot\n\u003e invalidation.\n\nStateGuard is a JavaScript library for managing state with an emphasis on type safety, enabling\nseamless integration with TypeScript. It facilitates deterministic behavior by offering an\nencapsulated state machine, user-defined actions and state transformers, as well as automatic stale\nsnapshot invalidation.\n\n_✅ 536 B with all dependencies, minified and gzipped._\n\n## Installation\n\n```sh\nnpm install state-guard\n```\n\n## Usage Example\n\nHere's how to use StateGuard to define a simple state machine for fetching website content:\n\n1. Import `createMachine` function from the StateGuard package.\n\n```ts\nimport { createMachine } from 'state-guard';\n```\n\n2. Create a `websiteContent` machine using the `createMachine` function, with the initial state,\n   value, a transformer map, and transitions map.\n\n```ts\nconst websiteContent = createMachine({\n  initialState: `resetted`,\n  initialValue: undefined,\n\n  transformerMap: {\n    resetted: () =\u003e undefined,\n    fetching: (url: string) =\u003e ({ url }),\n    resolved: (text: string) =\u003e ({ text }),\n    rejected: (error: unknown) =\u003e ({ error }),\n  },\n\n  transitionsMap: {\n    resetted: { fetch: `fetching` },\n    fetching: { resolve: `resolved`, reject: `rejected` },\n    resolved: { reset: `resetted` },\n    rejected: { reset: `resetted` },\n  },\n});\n```\n\n3. Subscribe to `websiteContent` to start fetching if in the `fetching` state.\n\n```ts\nwebsiteContent.subscribe(async () =\u003e {\n  const fetching = websiteContent.get(`fetching`);\n\n  if (fetching) {\n    try {\n      const response = await fetch(fetching.value.url);\n      const text = await response.text();\n\n      if (fetching.isFresh()) {\n        fetching.actions.resolve(text);\n      }\n    } catch (error) {\n      if (fetching.isFresh()) {\n        fetching.actions.reject(error);\n      }\n    }\n  }\n});\n```\n\n4. Subscribe to `websiteContent` to log the current state and value.\n\n```ts\nwebsiteContent.subscribe(() =\u003e {\n  const { state, value } = websiteContent.get();\n\n  console.log(state, value);\n});\n```\n\n5. Trigger the `fetch` action in the `resetted` state.\n\n```ts\nwebsiteContent.assert(`resetted`).actions.fetch(`https://example.com`);\n```\n\n6. Implement a React component using the `useSyncExternalStore` hook for state synchronization.\n\n```ts\nimport * as React from 'react';\n\nconst YourComponent = () =\u003e {\n  const websiteContentSnapshot = React.useSyncExternalStore(websiteContent.subscribe, () =\u003e\n    websiteContent.get(),\n  );\n\n  // Your component logic and rendering.\n};\n```\n\n### Ensuring Snapshot Freshness\n\nIn scenarios where snapshots are used following asynchronous operations, it's critical to validate\ntheir freshness to ensure actions are based on the current state. To achieve this, use the\n`isFresh()` method on an existing snapshot instead of acquiring a new one via `get()`. This approach\nis preferred because even though a new snapshot might represent a state with the same name, it might\nnot reflect the same execution context you're working within. A snapshot that remains fresh ensures\nthat your code's execution branch is still active and relevant to the current state of the\napplication.\n\nImportantly, when performing such checks, avoid using `await` within blocks guarded by `isFresh()`.\nThe reason is that during the delay introduced by `await`, the snapshot's state could have been\naltered by other operations, rendering it stale once the asynchronous operation completes. This\ncould potentially lead to actions being taken based on outdated information.\n\n### Avoiding State Transitions in Subscription Listeners\n\nPerforming state transitions directly within a subscription listener is prohibited in StateGuard.\nUsing actions to change the state within a listener will lead to exceptions being thrown. This\nenforcement helps prevent cascading updates, exponential state changes, and potential violation of\nthe unidirectional data flow principle.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclebert%2Fstate-guard","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fclebert%2Fstate-guard","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fclebert%2Fstate-guard/lists"}