From ad90cf5b257be01ba0332e35c946902ace5e7589 Mon Sep 17 00:00:00 2001 From: Ryan Lee Date: Tue, 6 Oct 2026 03:36:33 +0000 Subject: [PATCH 001/112] feat(global): import statelyai/xstate v6 packages verbatim Six packages of statelyai/xstate branch `next` at 2146ae26ebfc7e6a624b3a1f237f9e6ddc30b9f5 (MIT, Copyright (c) 2015 David Khourshid) are copied unchanged under packages/xstate/, as owned members (REPO-O1). Upstream is a reference, never a merge source. - packages/core -> packages/xstate/xstate - packages/xstate-effect -> packages/xstate/xstate-effect - packages/xstate-test -> packages/xstate/xstate-test - packages/xstate-react -> packages/xstate/xstate-react - packages/xstate-store -> packages/xstate/xstate-store - packages/xstate-store-react -> packages/xstate/xstate-store-react Identity: every copied src/ and test/ tree object equals the upstream tree object at the pin (git write-tree --prefix vs git rev-parse :), except xstate-store/test, which differs only by the excluded files below. Excluded (build configuration, or tests of bindings this repo does not fork): - packages/{core,xstate-effect,xstate-test,xstate-react,xstate-store,xstate-store-react}/vitest.config.mts - packages/xstate-store/vitest.config.vue.mts, vitest.config.solid.mts - packages/xstate-store/test/{vue.test.ts,UseActor.vue,UseActorRef.vue,UseSelector.vue} (imports @xstate/vue) - packages/core/{actors,durable,fsm,graph,validation}/package.json (preconstruct entrypoint stubs) - packages/core/.gitignore, packages/xstate-store-react/tsconfig.json Added: the repository's root MIT LICENSE in xstate-effect and xstate-store-react, which upstream ships without a package LICENSE. Declared bypass (CONST-W3): committed with --no-verify. The pre-commit hook runs dprint fmt over staged files, which would rewrite upstream sources and break the tree identity above. The commit message was checked with `pnpm exec commitlint`. Formatting lands as the next, separate commit; the dprint check gate runs on the pull request head. --- xstate-effect/CHANGELOG.md | 105 + xstate-effect/LICENSE | 22 + xstate-effect/README.md | 265 + xstate-effect/docs/actors.md | 236 + xstate-effect/docs/atoms-and-react.md | 248 + xstate-effect/docs/effect-logic.md | 183 + xstate-effect/docs/matching-states.md | 125 + xstate-effect/docs/meta.json | 13 + xstate-effect/docs/observing-actors.md | 228 + xstate-effect/docs/quick-start.md | 152 + xstate-effect/docs/schemas-and-actions.md | 171 + xstate-effect/docs/testing-and-errors.md | 198 + xstate-effect/package.json | 47 + xstate-effect/src/actor.test.ts | 459 + xstate-effect/src/actor.ts | 415 + xstate-effect/src/actorScope.ts | 16 + xstate-effect/src/atom.test.ts | 264 + xstate-effect/src/atom.ts | 176 + xstate-effect/src/brands.ts | 3 + xstate-effect/src/createEffectActor.ts | 407 + xstate-effect/src/effectActor.ts | 265 + xstate-effect/src/errors.ts | 43 + xstate-effect/src/fromEffect.ts | 709 ++ xstate-effect/src/index.test.ts | 875 ++ xstate-effect/src/index.ts | 52 + xstate-effect/src/internal.ts | 291 + xstate-effect/src/lint.test.ts | 108 + xstate-effect/src/persistence.test.ts | 657 ++ xstate-effect/src/requirements.types.test.ts | 335 + xstate-effect/src/runtime.test.ts | 1198 ++ xstate-effect/src/schema.ts | 214 + xstate-effect/src/setupEffect.ts | 423 + xstate-effect/src/state.test.ts | 154 + xstate-effect/src/state.ts | 133 + xstate-effect/src/types.ts | 111 + .../test/lint-fixtures/declared-effect.ts | 26 + .../test/lint-fixtures/inline-effect.ts | 28 + .../test/lint-fixtures/oxlintrc.fixtures.json | 10 + xstate-react/CHANGELOG.md | 1067 ++ xstate-react/LICENSE | 22 + xstate-react/README.md | 52 + xstate-react/docs/global-state.md | 108 + xstate-react/docs/input-and-snapshots.md | 118 + xstate-react/docs/meta.json | 12 + xstate-react/docs/selectors.md | 118 + xstate-react/docs/server-rendering.md | 102 + xstate-react/docs/shared-actors.md | 161 + xstate-react/docs/testing.md | 143 + xstate-react/docs/use-machine.md | 140 + xstate-react/package.json | 80 + xstate-react/src/createActorContext.ts | 84 + xstate-react/src/false.ts | 1 + xstate-react/src/index.ts | 8 + xstate-react/src/shallowEqual.ts | 37 + xstate-react/src/true.ts | 1 + xstate-react/src/useActor.ts | 72 + xstate-react/src/useActorRef.ts | 144 + xstate-react/src/useMachine.ts | 22 + xstate-react/src/useSelector.ts | 56 + xstate-react/test/createActorContext.test.tsx | 545 + .../test/fastRefresh.production.test.tsx | 47 + xstate-react/test/fastRefresh.test.tsx | 285 + xstate-react/test/issueRegressions.test.tsx | 137 + .../lint-fixtures/machine-in-component.tsx | 45 + .../machine-outside-component.tsx | 21 + .../test/lint-fixtures/oxlintrc.fixtures.json | 10 + xstate-react/test/lint.test.ts | 92 + xstate-react/test/types.test.tsx | 270 + xstate-react/test/useActor.test.tsx | 1019 ++ xstate-react/test/useActorRef.test.tsx | 645 ++ xstate-react/test/useSelector.test.tsx | 1022 ++ xstate-react/test/utils.tsx | 37 + xstate-store-react/CHANGELOG.md | 133 + xstate-store-react/LICENSE | 22 + xstate-store-react/README.md | 187 + xstate-store-react/package.json | 50 + xstate-store-react/src/index.test.tsx | 476 + xstate-store-react/src/index.ts | 387 + xstate-store-react/src/types.test.tsx | 251 + xstate-store/CHANGELOG.md | 1752 +++ xstate-store/LICENSE | 22 + xstate-store/MIGRATION.md | 439 + xstate-store/README.md | 523 + .../docs/effects-and-emitted-events.md | 61 + xstate-store/docs/events-and-context.md | 82 + xstate-store/docs/frameworks.md | 27 + xstate-store/docs/meta.json | 14 + xstate-store/docs/migration.md | 21 + xstate-store/docs/persistence.md | 48 + xstate-store/docs/quick-start.md | 62 + xstate-store/docs/selectors.md | 57 + xstate-store/docs/typescript.md | 32 + xstate-store/docs/undo-redo.md | 43 + xstate-store/package.json | 64 + xstate-store/src/alien.ts | 654 ++ xstate-store/src/atom.ts | 420 + xstate-store/src/fromStore.ts | 337 + xstate-store/src/index.ts | 72 + xstate-store/src/persist.ts | 1083 ++ xstate-store/src/reset.ts | 96 + xstate-store/src/schema.ts | 77 + xstate-store/src/select.test.ts | 243 + xstate-store/src/shallowEqual.ts | 37 + xstate-store/src/store.ts | 869 ++ xstate-store/src/types.ts | 784 ++ xstate-store/src/undo.ts | 464 + xstate-store/src/validate.ts | 266 + xstate-store/src/validationError.ts | 9 + xstate-store/test/atom.test.ts | 1045 ++ xstate-store/test/broadcast.test.ts | 194 + xstate-store/test/fromStore.test.ts | 180 + xstate-store/test/persist.test.ts | 1565 +++ xstate-store/test/reset.test.ts | 175 + xstate-store/test/store.test.ts | 1555 +++ xstate-store/test/types.test.tsx | 520 + xstate-store/test/undo.test.ts | 1244 +++ xstate-store/test/validate.test.ts | 347 + xstate-test/CHANGELOG.md | 167 + xstate-test/LICENSE | 21 + xstate-test/README.md | 1813 +++ xstate-test/package.json | 61 + xstate-test/src/adapter.ts | 525 + xstate-test/src/effect-schema.ts | 64 + xstate-test/src/engine/constants.ts | 2 + xstate-test/src/engine/coverage.ts | 1196 ++ xstate-test/src/engine/deduplicatePaths.ts | 65 + xstate-test/src/engine/eventDescriptors.ts | 245 + xstate-test/src/engine/index.ts | 6 + xstate-test/src/engine/outcomes.ts | 122 + .../src/engine/propertyLinearizability.ts | 337 + xstate-test/src/engine/propertyTest.ts | 4687 ++++++++ xstate-test/src/engine/report.ts | 930 ++ xstate-test/src/engine/suite.ts | 455 + xstate-test/src/engine/testPaths.ts | 1021 ++ xstate-test/src/engine/utils.ts | 60 + xstate-test/src/failures.ts | 156 + xstate-test/src/index.ts | 115 + xstate-test/src/pick.ts | 41 + xstate-test/src/playwright.ts | 669 ++ xstate-test/src/propertyTest.ts | 424 + xstate-test/src/scheduler.ts | 122 + xstate-test/src/schema.ts | 1408 +++ xstate-test/src/vitest.ts | 321 + xstate-test/test/advancedPropertyTest.test.ts | 908 ++ xstate-test/test/campaignAssertions.test.ts | 300 + xstate-test/test/docsExamples.test.ts | 1431 +++ xstate-test/test/effectSchema.test.ts | 31 + .../test/engine/perfPairsDedup.test.ts | 190 + .../test/engine/propertyExecuted.test.ts | 202 + .../test/engine/propertyExploration.test.ts | 262 + .../engine/propertyLinearizability.test.ts | 232 + .../test/engine/propertyRegressions.test.ts | 474 + .../test/engine/propertyReplay.test.ts | 141 + .../test/engine/propertyReport.test.ts | 160 + .../test/engine/propertySearch.test.ts | 153 + xstate-test/test/engine/propertySuite.test.ts | 198 + xstate-test/test/engine/propertyTest.test.ts | 409 + .../test/engine/propertyTestAdapter.ts | 219 + xstate-test/test/engine/symmetry.test.ts | 183 + xstate-test/test/engine/testPaths.test.ts | 520 + .../engine/testPathsInternalEvents.test.ts | 218 + .../test/engine/unifiedTestApi.test.ts | 137 + xstate-test/test/executedEffects.test.ts | 197 + xstate-test/test/exploration.test.ts | 202 + xstate-test/test/failureDatabase.test.ts | 184 + xstate-test/test/fakePage.ts | 245 + xstate-test/test/fastCheckWrappers.test.ts | 143 + .../test/pairsRequirementsWeights.test.ts | 224 + xstate-test/test/pick.types.test.ts | 75 + xstate-test/test/playwrightArtifacts.test.ts | 264 + xstate-test/test/playwrightPage.types.test.ts | 29 + xstate-test/test/playwrightSut.test.ts | 416 + xstate-test/test/propertyTest.test.ts | 391 + xstate-test/test/propertyTest.types.test.ts | 136 + xstate-test/test/randomAdapter.ts | 201 + xstate-test/test/reachability.test.ts | 196 + xstate-test/test/reportingOptions.test.ts | 154 + xstate-test/test/scheduler.test.ts | 163 + xstate-test/test/schema.test.ts | 562 + xstate-test/test/search.test.ts | 125 + xstate-test/test/suite.test.ts | 72 + xstate-test/test/symmetry.test.ts | 248 + .../test/temporalPayloadsReplay.test.ts | 691 ++ xstate-test/test/vitest.test.ts | 186 + xstate/CHANGELOG.md | 9765 +++++++++++++++++ xstate/LICENSE | 22 + xstate/README.md | 637 ++ xstate/bin/xstate.js | 36 + xstate/package.json | 155 + xstate/src/IndexedHeap.ts | 65 + xstate/src/Mailbox.ts | 57 + xstate/src/SimulatedClock.ts | 89 + xstate/src/State.ts | 809 ++ xstate/src/StateMachine.ts | 1858 ++++ xstate/src/StateNode.ts | 736 ++ xstate/src/actions.ts | 66 + xstate/src/actorScope.ts | 85 + xstate/src/actorSource.ts | 26 + xstate/src/actors/attached.ts | 116 + xstate/src/actors/callback.ts | 314 + xstate/src/actors/index.ts | 73 + xstate/src/actors/listener.ts | 83 + xstate/src/actors/logic.ts | 591 + xstate/src/actors/observable.ts | 550 + xstate/src/actors/promise.ts | 507 + xstate/src/actors/subscription.ts | 103 + xstate/src/assert.ts | 50 + xstate/src/base.types.ts | 137 + xstate/src/constants.ts | 15 + xstate/src/createActor.ts | 1422 +++ xstate/src/createMachine.ts | 419 + xstate/src/createMachineFromConfig.ts | 1110 ++ xstate/src/delay.ts | 65 + xstate/src/devDiagnostics.ts | 162 + xstate/src/durable/index.ts | 882 ++ xstate/src/effectDescriptor.ts | 206 + xstate/src/eventUtils.ts | 128 + xstate/src/false.ts | 1 + xstate/src/fsm.ts | 481 + xstate/src/fsm/index.ts | 17 + xstate/src/graph/actorScope.ts | 16 + xstate/src/graph/adjacency.ts | 153 + xstate/src/graph/alterPath.ts | 33 + xstate/src/graph/graph.ts | 256 + xstate/src/graph/index.ts | 12 + xstate/src/graph/pathFromEvents.ts | 96 + xstate/src/graph/shortestPaths.ts | 140 + xstate/src/graph/simplePaths.ts | 127 + .../test/__snapshots__/graph.test.ts.snap | 1232 +++ xstate/src/graph/test/adjacency.test.ts | 104 + xstate/src/graph/test/dieHard.test.ts | 217 + xstate/src/graph/test/graph.test.ts | 895 ++ xstate/src/graph/test/index.test.ts | 171 + xstate/src/graph/test/paths.test.ts | 212 + xstate/src/graph/test/shortestPaths.test.ts | 181 + .../graph/test/traversal-regressions.test.ts | 140 + xstate/src/graph/types.test.ts | 182 + xstate/src/graph/types.ts | 204 + xstate/src/hotSwap.ts | 189 + xstate/src/index.ts | 221 + xstate/src/inertActorScope.ts | 291 + xstate/src/inspection.ts | 133 + xstate/src/inspectionAmbient.ts | 45 + xstate/src/machine.schema.json | 393 + xstate/src/machineVersion.types.ts | 61 + xstate/src/machineVersions.ts | 576 + xstate/src/mapState.ts | 93 + xstate/src/memo.ts | 14 + xstate/src/persistedSnapshot.schema.json | 144 + xstate/src/persistedSnapshotFormat.ts | 65 + xstate/src/remoteActorRef.ts | 141 + xstate/src/reportUnhandledError.ts | 13 + xstate/src/runtimeHelpers.ts | 202 + xstate/src/schema.types.ts | 152 + xstate/src/serialize.ts | 229 + xstate/src/setup.ts | 5618 ++++++++++ xstate/src/snapshotActorRef.ts | 319 + xstate/src/spawn.ts | 65 + xstate/src/stateUtils.ts | 2980 +++++ xstate/src/symbolObservable.ts | 3 + xstate/src/system.ts | 1093 ++ xstate/src/systemLogicMetadata.ts | 2 + xstate/src/systemTransition.ts | 1137 ++ xstate/src/timerClock.ts | 15 + xstate/src/toPromise.ts | 38 + xstate/src/transition.ts | 353 + xstate/src/transitionActions.ts | 1337 +++ xstate/src/true.ts | 1 + xstate/src/types.ts | 3603 ++++++ xstate/src/types.v6.ts | 2399 ++++ xstate/src/typestates.types.ts | 107 + xstate/src/utils.ts | 465 + xstate/src/validation.ts | 14 + xstate/src/validation.types.ts | 49 + xstate/src/validation/index.ts | 419 + xstate/src/waitFor.ts | 130 + xstate/test/actions.test.ts | 4214 +++++++ xstate/test/activities.test.ts | 400 + xstate/test/actor.test.ts | 2132 ++++ xstate/test/actorLogic.test.ts | 1578 +++ xstate/test/addressFirstIdentity.test.ts | 1584 +++ xstate/test/after.test.ts | 704 ++ xstate/test/assert.test.ts | 111 + xstate/test/assert.v6.test.ts | 121 + xstate/test/assign.test.ts | 264 + xstate/test/asyncErrorSchema.types.test.ts | 131 + xstate/test/asyncTransition.test.ts | 211 + .../test/childCompletionEvents.types.test.ts | 125 + xstate/test/choice.test.ts | 192 + xstate/test/clock.test.ts | 148 + xstate/test/conversion.test.ts | 70 + xstate/test/createActor.test.ts | 281 + xstate/test/createInvoke.test.ts | 841 ++ xstate/test/custom-interpreter.test.ts | 971 ++ xstate/test/declarations.test.ts | 233 + xstate/test/deep.test.ts | 495 + xstate/test/delayNames.types.test.ts | 161 + xstate/test/deterministic.test.ts | 295 + xstate/test/durable-adapters/inngest.test.ts | 180 + xstate/test/durable-adapters/rivet.test.ts | 175 + xstate/test/durable-address-first.test.ts | 657 ++ xstate/test/durable-adoption.test.ts | 346 + xstate/test/durable-conformance.ts | 349 + .../test/durable-event-journal-timers.test.ts | 185 + .../test/durable-execution-identity.test.ts | 226 + xstate/test/durable-execution.test.ts | 376 + xstate/test/durable-inspection.test.ts | 80 + xstate/test/durable-interpreter.test.ts | 395 + xstate/test/durable-reference-host.test.ts | 223 + xstate/test/durable-restore.test.ts | 544 + xstate/test/emit.test.ts | 552 + xstate/test/errorPrecedence.test.ts | 322 + xstate/test/errors.test.ts | 1621 +++ xstate/test/event.test.ts | 149 + xstate/test/eventBoundary.test.ts | 251 + xstate/test/eventDescriptors.test.ts | 543 + xstate/test/eventDescriptors.types.test.ts | 162 + xstate/test/examples.6.16.test.ts | 57 + xstate/test/examples.6.17.test.ts | 136 + xstate/test/examples.6.6.test.ts | 63 + xstate/test/examples.6.8.test.ts | 79 + xstate/test/examples.6.9.test.ts | 108 + xstate/test/examples.cd.test.ts | 89 + xstate/test/final.test.ts | 1707 +++ xstate/test/firstTenMinutes.v6.test.ts | 198 + .../declarations/created-invoke-inference.ts | 768 ++ .../fixtures/declarations/created-invoke.ts | 130 + .../fixtures/declarations/narrowed-context.ts | 27 + .../declarations/registered-child-consumer.ts | 19 + .../declarations/registered-child-parent.ts | 68 + .../fixtures/declarations/registered-child.ts | 42 + .../fixtures/declarations/strict-targets.ts | 52 + xstate/test/fsm-entrypoint.test.ts | 25 + xstate/test/fsm.actor.test.ts | 79 + xstate/test/fsm.differential.test.ts | 107 + xstate/test/fsm.setup.test.ts | 221 + xstate/test/fsm.test.ts | 132 + xstate/test/fsm.types.test.ts | 147 + xstate/test/guards.test.ts | 957 ++ xstate/test/history.test.ts | 1633 +++ xstate/test/id.test.ts | 216 + xstate/test/initial.test.ts | 192 + xstate/test/input.test.ts | 410 + xstate/test/inspect.test.ts | 705 ++ xstate/test/inspection.conformance.v6.test.ts | 229 + xstate/test/internalEvents.test.ts | 254 + xstate/test/internalTransitions.test.ts | 432 + xstate/test/interpreter.test.ts | 2161 ++++ xstate/test/invalid.test.ts | 166 + xstate/test/invoke.test.ts | 3837 +++++++ xstate/test/issue5454.test.ts | 119 + xstate/test/issueRegressions.test.ts | 291 + xstate/test/issueRegressions.types.test.ts | 248 + xstate/test/json.test.ts | 1236 +++ xstate/test/listen.test.ts | 728 ++ xstate/test/logger.test.ts | 46 + xstate/test/logical-timers.test.ts | 297 + xstate/test/machine.test.ts | 403 + xstate/test/machineFromConfig.test.ts | 157 + xstate/test/machineOutput.types.test.ts | 312 + xstate/test/machineVersions.test.ts | 1159 ++ xstate/test/machineVersions.types.test.ts | 284 + xstate/test/macrostepBound.test.ts | 107 + xstate/test/mapState.test.ts | 523 + xstate/test/match.test.ts | 122 + xstate/test/memory.test.ts | 215 + xstate/test/meta.test.ts | 721 ++ xstate/test/microstep.test.ts | 421 + xstate/test/microstep.v6.test.ts | 175 + xstate/test/multiple.test.ts | 160 + xstate/test/multiple.v6.test.ts | 160 + xstate/test/order.test.ts | 86 + xstate/test/parallel.test.ts | 1666 +++ xstate/test/parallelConformance.test.ts | 147 + xstate/test/persistedSnapshot.types.test.ts | 200 + xstate/test/persistenceConformance.v6.test.ts | 779 ++ xstate/test/predictableExec.test.ts | 601 + xstate/test/rehydration.test.ts | 663 ++ xstate/test/rehydration.v6.test.ts | 516 + xstate/test/resolve.test.ts | 73 + xstate/test/resolve.v6.test.ts | 73 + xstate/test/restoreEventless.test.ts | 75 + xstate/test/restoreTerminal.test.ts | 109 + xstate/test/restored-effects.test.ts | 156 + xstate/test/route.test.ts | 554 + xstate/test/runtimeValidation.test.ts | 772 ++ xstate/test/runtimeValidation.types.test.ts | 190 + xstate/test/select.test.ts | 332 + .../test/serialization.conformance.v6.test.ts | 509 + xstate/test/setup.test.ts | 297 + xstate/test/setupStateContracts.test.ts | 2062 ++++ xstate/test/sourceTyping.types.test.ts | 344 + xstate/test/spawn.test.ts | 25 + xstate/test/spawn.types.test.ts | 198 + xstate/test/spawnChild.test.ts | 208 + xstate/test/state.test.ts | 551 + xstate/test/stateIn.test.ts | 549 + xstate/test/stateInput.persistence.test.ts | 187 + xstate/test/stateInput.test.ts | 2533 +++++ xstate/test/strictTargets.types.test.ts | 376 + xstate/test/system.test.ts | 765 ++ xstate/test/systemOnRejectedEvent.test.ts | 113 + xstate/test/systemTransition.test.ts | 1003 ++ xstate/test/tags.test.ts | 148 + xstate/test/timeout.test.ts | 705 ++ xstate/test/timers.persistence.test.ts | 305 + xstate/test/toPromise.test.ts | 147 + xstate/test/transient.test.ts | 877 ++ xstate/test/transition.test.ts | 3251 ++++++ xstate/test/transitionFunctions.test.ts | 106 + xstate/test/trigger.test.ts | 126 + xstate/test/typeHelpers.test.ts | 257 + xstate/test/typeSchemas.test.ts | 380 + xstate/test/typeStates.test.ts | 97 + xstate/test/types.test.ts | 6891 ++++++++++++ xstate/test/unhandledEvents.test.ts | 120 + xstate/test/utils.ts | 117 + xstate/test/v5ConfigDiagnostics.test.ts | 291 + xstate/test/v6.test.ts | 156 + xstate/test/versioning.test.ts | 200 + xstate/test/vizTypeFriction.types.test.ts | 67 + xstate/test/waitFor.test.ts | 404 + 422 files changed, 186185 insertions(+) create mode 100644 xstate-effect/CHANGELOG.md create mode 100644 xstate-effect/LICENSE create mode 100644 xstate-effect/README.md create mode 100644 xstate-effect/docs/actors.md create mode 100644 xstate-effect/docs/atoms-and-react.md create mode 100644 xstate-effect/docs/effect-logic.md create mode 100644 xstate-effect/docs/matching-states.md create mode 100644 xstate-effect/docs/meta.json create mode 100644 xstate-effect/docs/observing-actors.md create mode 100644 xstate-effect/docs/quick-start.md create mode 100644 xstate-effect/docs/schemas-and-actions.md create mode 100644 xstate-effect/docs/testing-and-errors.md create mode 100644 xstate-effect/package.json create mode 100644 xstate-effect/src/actor.test.ts create mode 100644 xstate-effect/src/actor.ts create mode 100644 xstate-effect/src/actorScope.ts create mode 100644 xstate-effect/src/atom.test.ts create mode 100644 xstate-effect/src/atom.ts create mode 100644 xstate-effect/src/brands.ts create mode 100644 xstate-effect/src/createEffectActor.ts create mode 100644 xstate-effect/src/effectActor.ts create mode 100644 xstate-effect/src/errors.ts create mode 100644 xstate-effect/src/fromEffect.ts create mode 100644 xstate-effect/src/index.test.ts create mode 100644 xstate-effect/src/index.ts create mode 100644 xstate-effect/src/internal.ts create mode 100644 xstate-effect/src/lint.test.ts create mode 100644 xstate-effect/src/persistence.test.ts create mode 100644 xstate-effect/src/requirements.types.test.ts create mode 100644 xstate-effect/src/runtime.test.ts create mode 100644 xstate-effect/src/schema.ts create mode 100644 xstate-effect/src/setupEffect.ts create mode 100644 xstate-effect/src/state.test.ts create mode 100644 xstate-effect/src/state.ts create mode 100644 xstate-effect/src/types.ts create mode 100644 xstate-effect/test/lint-fixtures/declared-effect.ts create mode 100644 xstate-effect/test/lint-fixtures/inline-effect.ts create mode 100644 xstate-effect/test/lint-fixtures/oxlintrc.fixtures.json create mode 100644 xstate-react/CHANGELOG.md create mode 100644 xstate-react/LICENSE create mode 100644 xstate-react/README.md create mode 100644 xstate-react/docs/global-state.md create mode 100644 xstate-react/docs/input-and-snapshots.md create mode 100644 xstate-react/docs/meta.json create mode 100644 xstate-react/docs/selectors.md create mode 100644 xstate-react/docs/server-rendering.md create mode 100644 xstate-react/docs/shared-actors.md create mode 100644 xstate-react/docs/testing.md create mode 100644 xstate-react/docs/use-machine.md create mode 100644 xstate-react/package.json create mode 100644 xstate-react/src/createActorContext.ts create mode 100644 xstate-react/src/false.ts create mode 100644 xstate-react/src/index.ts create mode 100644 xstate-react/src/shallowEqual.ts create mode 100644 xstate-react/src/true.ts create mode 100644 xstate-react/src/useActor.ts create mode 100644 xstate-react/src/useActorRef.ts create mode 100644 xstate-react/src/useMachine.ts create mode 100644 xstate-react/src/useSelector.ts create mode 100644 xstate-react/test/createActorContext.test.tsx create mode 100644 xstate-react/test/fastRefresh.production.test.tsx create mode 100644 xstate-react/test/fastRefresh.test.tsx create mode 100644 xstate-react/test/issueRegressions.test.tsx create mode 100644 xstate-react/test/lint-fixtures/machine-in-component.tsx create mode 100644 xstate-react/test/lint-fixtures/machine-outside-component.tsx create mode 100644 xstate-react/test/lint-fixtures/oxlintrc.fixtures.json create mode 100644 xstate-react/test/lint.test.ts create mode 100644 xstate-react/test/types.test.tsx create mode 100644 xstate-react/test/useActor.test.tsx create mode 100644 xstate-react/test/useActorRef.test.tsx create mode 100644 xstate-react/test/useSelector.test.tsx create mode 100644 xstate-react/test/utils.tsx create mode 100644 xstate-store-react/CHANGELOG.md create mode 100644 xstate-store-react/LICENSE create mode 100644 xstate-store-react/README.md create mode 100644 xstate-store-react/package.json create mode 100644 xstate-store-react/src/index.test.tsx create mode 100644 xstate-store-react/src/index.ts create mode 100644 xstate-store-react/src/types.test.tsx create mode 100644 xstate-store/CHANGELOG.md create mode 100644 xstate-store/LICENSE create mode 100644 xstate-store/MIGRATION.md create mode 100644 xstate-store/README.md create mode 100644 xstate-store/docs/effects-and-emitted-events.md create mode 100644 xstate-store/docs/events-and-context.md create mode 100644 xstate-store/docs/frameworks.md create mode 100644 xstate-store/docs/meta.json create mode 100644 xstate-store/docs/migration.md create mode 100644 xstate-store/docs/persistence.md create mode 100644 xstate-store/docs/quick-start.md create mode 100644 xstate-store/docs/selectors.md create mode 100644 xstate-store/docs/typescript.md create mode 100644 xstate-store/docs/undo-redo.md create mode 100644 xstate-store/package.json create mode 100644 xstate-store/src/alien.ts create mode 100644 xstate-store/src/atom.ts create mode 100644 xstate-store/src/fromStore.ts create mode 100644 xstate-store/src/index.ts create mode 100644 xstate-store/src/persist.ts create mode 100644 xstate-store/src/reset.ts create mode 100644 xstate-store/src/schema.ts create mode 100644 xstate-store/src/select.test.ts create mode 100644 xstate-store/src/shallowEqual.ts create mode 100644 xstate-store/src/store.ts create mode 100644 xstate-store/src/types.ts create mode 100644 xstate-store/src/undo.ts create mode 100644 xstate-store/src/validate.ts create mode 100644 xstate-store/src/validationError.ts create mode 100644 xstate-store/test/atom.test.ts create mode 100644 xstate-store/test/broadcast.test.ts create mode 100644 xstate-store/test/fromStore.test.ts create mode 100644 xstate-store/test/persist.test.ts create mode 100644 xstate-store/test/reset.test.ts create mode 100644 xstate-store/test/store.test.ts create mode 100644 xstate-store/test/types.test.tsx create mode 100644 xstate-store/test/undo.test.ts create mode 100644 xstate-store/test/validate.test.ts create mode 100644 xstate-test/CHANGELOG.md create mode 100644 xstate-test/LICENSE create mode 100644 xstate-test/README.md create mode 100644 xstate-test/package.json create mode 100644 xstate-test/src/adapter.ts create mode 100644 xstate-test/src/effect-schema.ts create mode 100644 xstate-test/src/engine/constants.ts create mode 100644 xstate-test/src/engine/coverage.ts create mode 100644 xstate-test/src/engine/deduplicatePaths.ts create mode 100644 xstate-test/src/engine/eventDescriptors.ts create mode 100644 xstate-test/src/engine/index.ts create mode 100644 xstate-test/src/engine/outcomes.ts create mode 100644 xstate-test/src/engine/propertyLinearizability.ts create mode 100644 xstate-test/src/engine/propertyTest.ts create mode 100644 xstate-test/src/engine/report.ts create mode 100644 xstate-test/src/engine/suite.ts create mode 100644 xstate-test/src/engine/testPaths.ts create mode 100644 xstate-test/src/engine/utils.ts create mode 100644 xstate-test/src/failures.ts create mode 100644 xstate-test/src/index.ts create mode 100644 xstate-test/src/pick.ts create mode 100644 xstate-test/src/playwright.ts create mode 100644 xstate-test/src/propertyTest.ts create mode 100644 xstate-test/src/scheduler.ts create mode 100644 xstate-test/src/schema.ts create mode 100644 xstate-test/src/vitest.ts create mode 100644 xstate-test/test/advancedPropertyTest.test.ts create mode 100644 xstate-test/test/campaignAssertions.test.ts create mode 100644 xstate-test/test/docsExamples.test.ts create mode 100644 xstate-test/test/effectSchema.test.ts create mode 100644 xstate-test/test/engine/perfPairsDedup.test.ts create mode 100644 xstate-test/test/engine/propertyExecuted.test.ts create mode 100644 xstate-test/test/engine/propertyExploration.test.ts create mode 100644 xstate-test/test/engine/propertyLinearizability.test.ts create mode 100644 xstate-test/test/engine/propertyRegressions.test.ts create mode 100644 xstate-test/test/engine/propertyReplay.test.ts create mode 100644 xstate-test/test/engine/propertyReport.test.ts create mode 100644 xstate-test/test/engine/propertySearch.test.ts create mode 100644 xstate-test/test/engine/propertySuite.test.ts create mode 100644 xstate-test/test/engine/propertyTest.test.ts create mode 100644 xstate-test/test/engine/propertyTestAdapter.ts create mode 100644 xstate-test/test/engine/symmetry.test.ts create mode 100644 xstate-test/test/engine/testPaths.test.ts create mode 100644 xstate-test/test/engine/testPathsInternalEvents.test.ts create mode 100644 xstate-test/test/engine/unifiedTestApi.test.ts create mode 100644 xstate-test/test/executedEffects.test.ts create mode 100644 xstate-test/test/exploration.test.ts create mode 100644 xstate-test/test/failureDatabase.test.ts create mode 100644 xstate-test/test/fakePage.ts create mode 100644 xstate-test/test/fastCheckWrappers.test.ts create mode 100644 xstate-test/test/pairsRequirementsWeights.test.ts create mode 100644 xstate-test/test/pick.types.test.ts create mode 100644 xstate-test/test/playwrightArtifacts.test.ts create mode 100644 xstate-test/test/playwrightPage.types.test.ts create mode 100644 xstate-test/test/playwrightSut.test.ts create mode 100644 xstate-test/test/propertyTest.test.ts create mode 100644 xstate-test/test/propertyTest.types.test.ts create mode 100644 xstate-test/test/randomAdapter.ts create mode 100644 xstate-test/test/reachability.test.ts create mode 100644 xstate-test/test/reportingOptions.test.ts create mode 100644 xstate-test/test/scheduler.test.ts create mode 100644 xstate-test/test/schema.test.ts create mode 100644 xstate-test/test/search.test.ts create mode 100644 xstate-test/test/suite.test.ts create mode 100644 xstate-test/test/symmetry.test.ts create mode 100644 xstate-test/test/temporalPayloadsReplay.test.ts create mode 100644 xstate-test/test/vitest.test.ts create mode 100644 xstate/CHANGELOG.md create mode 100644 xstate/LICENSE create mode 100644 xstate/README.md create mode 100755 xstate/bin/xstate.js create mode 100644 xstate/package.json create mode 100644 xstate/src/IndexedHeap.ts create mode 100644 xstate/src/Mailbox.ts create mode 100644 xstate/src/SimulatedClock.ts create mode 100644 xstate/src/State.ts create mode 100644 xstate/src/StateMachine.ts create mode 100644 xstate/src/StateNode.ts create mode 100644 xstate/src/actions.ts create mode 100644 xstate/src/actorScope.ts create mode 100644 xstate/src/actorSource.ts create mode 100644 xstate/src/actors/attached.ts create mode 100644 xstate/src/actors/callback.ts create mode 100644 xstate/src/actors/index.ts create mode 100644 xstate/src/actors/listener.ts create mode 100644 xstate/src/actors/logic.ts create mode 100644 xstate/src/actors/observable.ts create mode 100644 xstate/src/actors/promise.ts create mode 100644 xstate/src/actors/subscription.ts create mode 100644 xstate/src/assert.ts create mode 100644 xstate/src/base.types.ts create mode 100644 xstate/src/constants.ts create mode 100644 xstate/src/createActor.ts create mode 100644 xstate/src/createMachine.ts create mode 100644 xstate/src/createMachineFromConfig.ts create mode 100644 xstate/src/delay.ts create mode 100644 xstate/src/devDiagnostics.ts create mode 100644 xstate/src/durable/index.ts create mode 100644 xstate/src/effectDescriptor.ts create mode 100644 xstate/src/eventUtils.ts create mode 100644 xstate/src/false.ts create mode 100644 xstate/src/fsm.ts create mode 100644 xstate/src/fsm/index.ts create mode 100644 xstate/src/graph/actorScope.ts create mode 100644 xstate/src/graph/adjacency.ts create mode 100644 xstate/src/graph/alterPath.ts create mode 100644 xstate/src/graph/graph.ts create mode 100644 xstate/src/graph/index.ts create mode 100644 xstate/src/graph/pathFromEvents.ts create mode 100644 xstate/src/graph/shortestPaths.ts create mode 100644 xstate/src/graph/simplePaths.ts create mode 100644 xstate/src/graph/test/__snapshots__/graph.test.ts.snap create mode 100644 xstate/src/graph/test/adjacency.test.ts create mode 100644 xstate/src/graph/test/dieHard.test.ts create mode 100644 xstate/src/graph/test/graph.test.ts create mode 100644 xstate/src/graph/test/index.test.ts create mode 100644 xstate/src/graph/test/paths.test.ts create mode 100644 xstate/src/graph/test/shortestPaths.test.ts create mode 100644 xstate/src/graph/test/traversal-regressions.test.ts create mode 100644 xstate/src/graph/types.test.ts create mode 100644 xstate/src/graph/types.ts create mode 100644 xstate/src/hotSwap.ts create mode 100644 xstate/src/index.ts create mode 100644 xstate/src/inertActorScope.ts create mode 100644 xstate/src/inspection.ts create mode 100644 xstate/src/inspectionAmbient.ts create mode 100644 xstate/src/machine.schema.json create mode 100644 xstate/src/machineVersion.types.ts create mode 100644 xstate/src/machineVersions.ts create mode 100644 xstate/src/mapState.ts create mode 100644 xstate/src/memo.ts create mode 100644 xstate/src/persistedSnapshot.schema.json create mode 100644 xstate/src/persistedSnapshotFormat.ts create mode 100644 xstate/src/remoteActorRef.ts create mode 100644 xstate/src/reportUnhandledError.ts create mode 100644 xstate/src/runtimeHelpers.ts create mode 100644 xstate/src/schema.types.ts create mode 100644 xstate/src/serialize.ts create mode 100644 xstate/src/setup.ts create mode 100644 xstate/src/snapshotActorRef.ts create mode 100644 xstate/src/spawn.ts create mode 100644 xstate/src/stateUtils.ts create mode 100644 xstate/src/symbolObservable.ts create mode 100644 xstate/src/system.ts create mode 100644 xstate/src/systemLogicMetadata.ts create mode 100644 xstate/src/systemTransition.ts create mode 100644 xstate/src/timerClock.ts create mode 100644 xstate/src/toPromise.ts create mode 100644 xstate/src/transition.ts create mode 100644 xstate/src/transitionActions.ts create mode 100644 xstate/src/true.ts create mode 100644 xstate/src/types.ts create mode 100644 xstate/src/types.v6.ts create mode 100644 xstate/src/typestates.types.ts create mode 100644 xstate/src/utils.ts create mode 100644 xstate/src/validation.ts create mode 100644 xstate/src/validation.types.ts create mode 100644 xstate/src/validation/index.ts create mode 100644 xstate/src/waitFor.ts create mode 100644 xstate/test/actions.test.ts create mode 100644 xstate/test/activities.test.ts create mode 100644 xstate/test/actor.test.ts create mode 100644 xstate/test/actorLogic.test.ts create mode 100644 xstate/test/addressFirstIdentity.test.ts create mode 100644 xstate/test/after.test.ts create mode 100644 xstate/test/assert.test.ts create mode 100644 xstate/test/assert.v6.test.ts create mode 100644 xstate/test/assign.test.ts create mode 100644 xstate/test/asyncErrorSchema.types.test.ts create mode 100644 xstate/test/asyncTransition.test.ts create mode 100644 xstate/test/childCompletionEvents.types.test.ts create mode 100644 xstate/test/choice.test.ts create mode 100644 xstate/test/clock.test.ts create mode 100644 xstate/test/conversion.test.ts create mode 100644 xstate/test/createActor.test.ts create mode 100644 xstate/test/createInvoke.test.ts create mode 100644 xstate/test/custom-interpreter.test.ts create mode 100644 xstate/test/declarations.test.ts create mode 100644 xstate/test/deep.test.ts create mode 100644 xstate/test/delayNames.types.test.ts create mode 100644 xstate/test/deterministic.test.ts create mode 100644 xstate/test/durable-adapters/inngest.test.ts create mode 100644 xstate/test/durable-adapters/rivet.test.ts create mode 100644 xstate/test/durable-address-first.test.ts create mode 100644 xstate/test/durable-adoption.test.ts create mode 100644 xstate/test/durable-conformance.ts create mode 100644 xstate/test/durable-event-journal-timers.test.ts create mode 100644 xstate/test/durable-execution-identity.test.ts create mode 100644 xstate/test/durable-execution.test.ts create mode 100644 xstate/test/durable-inspection.test.ts create mode 100644 xstate/test/durable-interpreter.test.ts create mode 100644 xstate/test/durable-reference-host.test.ts create mode 100644 xstate/test/durable-restore.test.ts create mode 100644 xstate/test/emit.test.ts create mode 100644 xstate/test/errorPrecedence.test.ts create mode 100644 xstate/test/errors.test.ts create mode 100644 xstate/test/event.test.ts create mode 100644 xstate/test/eventBoundary.test.ts create mode 100644 xstate/test/eventDescriptors.test.ts create mode 100644 xstate/test/eventDescriptors.types.test.ts create mode 100644 xstate/test/examples.6.16.test.ts create mode 100644 xstate/test/examples.6.17.test.ts create mode 100644 xstate/test/examples.6.6.test.ts create mode 100644 xstate/test/examples.6.8.test.ts create mode 100644 xstate/test/examples.6.9.test.ts create mode 100644 xstate/test/examples.cd.test.ts create mode 100644 xstate/test/final.test.ts create mode 100644 xstate/test/firstTenMinutes.v6.test.ts create mode 100644 xstate/test/fixtures/declarations/created-invoke-inference.ts create mode 100644 xstate/test/fixtures/declarations/created-invoke.ts create mode 100644 xstate/test/fixtures/declarations/narrowed-context.ts create mode 100644 xstate/test/fixtures/declarations/registered-child-consumer.ts create mode 100644 xstate/test/fixtures/declarations/registered-child-parent.ts create mode 100644 xstate/test/fixtures/declarations/registered-child.ts create mode 100644 xstate/test/fixtures/declarations/strict-targets.ts create mode 100644 xstate/test/fsm-entrypoint.test.ts create mode 100644 xstate/test/fsm.actor.test.ts create mode 100644 xstate/test/fsm.differential.test.ts create mode 100644 xstate/test/fsm.setup.test.ts create mode 100644 xstate/test/fsm.test.ts create mode 100644 xstate/test/fsm.types.test.ts create mode 100644 xstate/test/guards.test.ts create mode 100644 xstate/test/history.test.ts create mode 100644 xstate/test/id.test.ts create mode 100644 xstate/test/initial.test.ts create mode 100644 xstate/test/input.test.ts create mode 100644 xstate/test/inspect.test.ts create mode 100644 xstate/test/inspection.conformance.v6.test.ts create mode 100644 xstate/test/internalEvents.test.ts create mode 100644 xstate/test/internalTransitions.test.ts create mode 100644 xstate/test/interpreter.test.ts create mode 100644 xstate/test/invalid.test.ts create mode 100644 xstate/test/invoke.test.ts create mode 100644 xstate/test/issue5454.test.ts create mode 100644 xstate/test/issueRegressions.test.ts create mode 100644 xstate/test/issueRegressions.types.test.ts create mode 100644 xstate/test/json.test.ts create mode 100644 xstate/test/listen.test.ts create mode 100644 xstate/test/logger.test.ts create mode 100644 xstate/test/logical-timers.test.ts create mode 100644 xstate/test/machine.test.ts create mode 100644 xstate/test/machineFromConfig.test.ts create mode 100644 xstate/test/machineOutput.types.test.ts create mode 100644 xstate/test/machineVersions.test.ts create mode 100644 xstate/test/machineVersions.types.test.ts create mode 100644 xstate/test/macrostepBound.test.ts create mode 100644 xstate/test/mapState.test.ts create mode 100644 xstate/test/match.test.ts create mode 100644 xstate/test/memory.test.ts create mode 100644 xstate/test/meta.test.ts create mode 100644 xstate/test/microstep.test.ts create mode 100644 xstate/test/microstep.v6.test.ts create mode 100644 xstate/test/multiple.test.ts create mode 100644 xstate/test/multiple.v6.test.ts create mode 100644 xstate/test/order.test.ts create mode 100644 xstate/test/parallel.test.ts create mode 100644 xstate/test/parallelConformance.test.ts create mode 100644 xstate/test/persistedSnapshot.types.test.ts create mode 100644 xstate/test/persistenceConformance.v6.test.ts create mode 100644 xstate/test/predictableExec.test.ts create mode 100644 xstate/test/rehydration.test.ts create mode 100644 xstate/test/rehydration.v6.test.ts create mode 100644 xstate/test/resolve.test.ts create mode 100644 xstate/test/resolve.v6.test.ts create mode 100644 xstate/test/restoreEventless.test.ts create mode 100644 xstate/test/restoreTerminal.test.ts create mode 100644 xstate/test/restored-effects.test.ts create mode 100644 xstate/test/route.test.ts create mode 100644 xstate/test/runtimeValidation.test.ts create mode 100644 xstate/test/runtimeValidation.types.test.ts create mode 100644 xstate/test/select.test.ts create mode 100644 xstate/test/serialization.conformance.v6.test.ts create mode 100644 xstate/test/setup.test.ts create mode 100644 xstate/test/setupStateContracts.test.ts create mode 100644 xstate/test/sourceTyping.types.test.ts create mode 100644 xstate/test/spawn.test.ts create mode 100644 xstate/test/spawn.types.test.ts create mode 100644 xstate/test/spawnChild.test.ts create mode 100644 xstate/test/state.test.ts create mode 100644 xstate/test/stateIn.test.ts create mode 100644 xstate/test/stateInput.persistence.test.ts create mode 100644 xstate/test/stateInput.test.ts create mode 100644 xstate/test/strictTargets.types.test.ts create mode 100644 xstate/test/system.test.ts create mode 100644 xstate/test/systemOnRejectedEvent.test.ts create mode 100644 xstate/test/systemTransition.test.ts create mode 100644 xstate/test/tags.test.ts create mode 100644 xstate/test/timeout.test.ts create mode 100644 xstate/test/timers.persistence.test.ts create mode 100644 xstate/test/toPromise.test.ts create mode 100644 xstate/test/transient.test.ts create mode 100644 xstate/test/transition.test.ts create mode 100644 xstate/test/transitionFunctions.test.ts create mode 100644 xstate/test/trigger.test.ts create mode 100644 xstate/test/typeHelpers.test.ts create mode 100644 xstate/test/typeSchemas.test.ts create mode 100644 xstate/test/typeStates.test.ts create mode 100644 xstate/test/types.test.ts create mode 100644 xstate/test/unhandledEvents.test.ts create mode 100644 xstate/test/utils.ts create mode 100644 xstate/test/v5ConfigDiagnostics.test.ts create mode 100644 xstate/test/v6.test.ts create mode 100644 xstate/test/versioning.test.ts create mode 100644 xstate/test/vizTypeFriction.types.test.ts create mode 100644 xstate/test/waitFor.test.ts diff --git a/xstate-effect/CHANGELOG.md b/xstate-effect/CHANGELOG.md new file mode 100644 index 00000000..e7476a79 --- /dev/null +++ b/xstate-effect/CHANGELOG.md @@ -0,0 +1,105 @@ +# @xstate/effect + +## 0.1.0-alpha.7 + +### Patch Changes + +- 902becb: `createEffectActor` accepts a persisted snapshot. The actor resumes in the persisted state and context without re-running entry actions, and pending delayed transitions keep their original deadlines on Effect's `Clock`. + + ```ts + const saved = actor.getPersistedSnapshot(); + // later, possibly in another process + const restored = yield* createEffectActor(machine, { snapshot: saved }); + ``` + + State-machine children resume their persisted state, and completed children do not restart. Running Effect tasks and streams, including a root `fromEffect` or `fromEffectStream` actor, restart from the beginning, as running async and callback actors do with XState's `createActor(logic, { snapshot })`. A snapshot-only restore does not need `input`. + +## 0.1.0-alpha.6 + +### Patch Changes + +- e6bb41e: Require stable Effect 4 (`^4.0.0`) instead of the Effect 4 release candidate. + + Update atom integration to use Effect 4’s `effect/reactivity` module. + +## 0.1.0-alpha.5 + +### Patch Changes + +- 5228c00: Infer the current service requirements of actions and actors replaced with `machine.provide`. Require declared actor input in `createActorAtoms`, consistently with `createEffectActor`. + + Effect tasks and streams now release their resources when they complete, fail or are cancelled. Actor shutdown waits for task cleanup before releasing resources shared for the actor's lifetime. Use `withActorScope` around an acquisition to keep its resource until the owning Effect actor stops: + + ```ts + import { Effect } from 'effect'; + import { withActorScope } from '@xstate/effect'; + + const session = Effect.acquireRelease( + Effect.succeed({ id: 'session' }), + () => Effect.log('Session closed') + ).pipe(withActorScope); + ``` + + Improve XState Effect guides with complete, tested workflow, stream, inspection and React examples. + +## 0.1.0-alpha.4 + +### Patch Changes + +- 8576291: Remove the `@xstate.deadletter` inspection event; observe undelivered events with the `onRejectedEvent` option. The inspection protocol is now exactly `@xstate.actor` and `@xstate.transition`. In `@xstate/effect`, `deadLetters(actor)` now streams `EventRejection` objects. + + ```ts + createActor(machine, { + onRejectedEvent: (rejection) => { + console.log(rejection.event.type, rejection.reason, rejection.issues); + } + }); + ``` + + Undelivered events are also available through `system.onRejectedEvent(listener)`, which accepts any number of listeners added at any time and returns a subscription. The `onRejectedEvent` option registers a listener the same way. + + ```ts + const subscription = actor.system.onRejectedEvent((rejection) => { + console.log(rejection.event.type, rejection.reason); + }); + subscription.unsubscribe(); + ``` + +## 0.1.0-alpha.3 + +### Patch Changes + +- f5ea38e: Clarify that joining a machine exposes unknown errors, distinguish stopped actors from failed actors, and provide a typed oxlint plugin for strict TypeScript projects. + +## 0.1.0-alpha.2 + +### Minor Changes + +- dcc21df: Add experimental Effect 4 integration for XState v6. + + - `createEffectActor(logic)` starts an actor as a scoped Effect resource: it stops, and its running Effects are interrupted, when the enclosing `Scope` closes. Delays run on the Effect `Clock`, so `TestClock` drives delayed transitions, and declared Effect actions run with the services in scope. It returns an `EffectActor` handle that implements XState's `ActorRef` contract; `send` enqueues the event and the actor processes it on its own fiber. + - `fromEffect`, `fromEffectStream` and `fromEffectEventStream` turn Effects and Streams into actor logic with typed failures and service requirements. Interruption from inside the Effect reports an `EffectInterruptedError`. + - `setupEffect` accepts Effect schemas and Effect-returning actions. + - `@xstate/effect/atom` exports `createActorAtoms`, which runs an actor in an `Atom.runtime` from `effect/unstable/reactivity` and exposes `actor`, `snapshot`, `send` and `select` atoms for reactive UIs such as `@effect/atom-react`. + - `taggedState(snapshot)` and `TaggedState` view a machine snapshot as a tagged union over its states, with `_tag` as the dotted state path and `context` narrowed to that state, for `Match.tag` and `Match.exhaustive`. The `state` atom from `createActorAtoms` exposes the same view. + - `send`, `snapshots`, `emitted`, `waitFor`, `join`, `inspect` and `deadLetters` expose an actor as Effects and Streams. `send` and `waitFor` are dual, so they take the actor first or can be piped. `waitFor` narrows its result when given a type predicate, and accepts a `timeout` that fails with `Cause.TimeoutError`. `join` waits for an actor's final output. `deadLetters` streams the events the actor's system could not deliver. + + ```ts + import { Effect, Schema } from 'effect'; + import { createEffectActor, fromEffect, join } from '@xstate/effect'; + + const loadUser = fromEffect({ + schemas: { + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ id: Schema.String }) + }, + effect: ({ input }) => Effect.succeed({ id: input.id }) + }); + + const program = Effect.gen(function* () { + const actor = yield* createEffectActor(loadUser, { input: { id: '42' } }); + return yield* join(actor); + }); + + await Effect.runPromise(Effect.scoped(program)); + ``` diff --git a/xstate-effect/LICENSE b/xstate-effect/LICENSE new file mode 100644 index 00000000..fc1fe941 --- /dev/null +++ b/xstate-effect/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Khourshid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/xstate-effect/README.md b/xstate-effect/README.md new file mode 100644 index 00000000..4f7f9d37 --- /dev/null +++ b/xstate-effect/README.md @@ -0,0 +1,265 @@ +# @xstate/effect + +Combine XState's event-driven workflows with Effect services, scopes, clocks and tracing. + +- Model approval, cancellation, deadlines and retry as explicit states and events. +- Invoke Effect tasks when their result determines the next state. +- Provide services once for the actor and its child logic. +- Keep actor lifetime inside your Effect application. + +This package is experimental. It targets XState v6 alpha and Effect 4. + +## Installation + + + +```bash +npm install @xstate/effect@alpha xstate@alpha effect@^4 +``` + +## XState Effect: Quick start + + + +A release waits for approval, expires after 30 seconds, and allows cancellation during deployment. A failed deployment waits for an explicit retry: + + + +```ts +import { Context, Effect, Schema } from 'effect'; +import { + createEffectActor, + fromEffect, + send, + setupEffect, + waitFor +} from '@xstate/effect'; + +export class Deployments extends Context.Service< + Deployments, + { readonly deploy: (release: string) => Effect.Effect } +>()('@app/Deployments') {} + +const deploy = fromEffect({ + schemas: { input: Schema.Struct({ release: Schema.String }) }, + effect: ({ input }) => Deployments.use((api) => api.deploy(input.release)) +}); + +export const approvalMachine = setupEffect({ + schemas: { input: Schema.Struct({ release: Schema.String }) }, + actors: { deploy } +}).createMachine({ + context: ({ input }) => ({ release: input.release, url: '' }), + initial: 'awaitingApproval', + states: { + awaitingApproval: { + after: { 30000: { target: 'expired' } }, + on: { + APPROVE: { target: 'deploying' }, + CANCEL: { target: 'cancelled' } + } + }, + deploying: { + invoke: { + src: 'deploy', + input: ({ context }) => ({ release: context.release }), + onDone: ({ context, event }) => ({ + target: 'deployed', + context: { ...context, url: event.output } + }), + onError: { target: 'failed' } + }, + on: { CANCEL: { target: 'cancelled' } } + }, + failed: { + on: { + RETRY: { target: 'deploying' }, + CANCEL: { target: 'cancelled' } + } + }, + deployed: { type: 'final' }, + expired: { type: 'final' }, + cancelled: { type: 'final' } + } +}); + +export const program = Effect.gen(function* () { + const actor = yield* createEffectActor(approvalMachine, { + input: { release: 'v1.2.0' } + }); + // A UI, webhook or CLI can send this event after a person approves. + yield* send(actor, { type: 'APPROVE' }); + const snapshot = yield* waitFor(actor, (s) => s.matches('deployed'), { + timeout: '5 seconds' + }); + return snapshot.context.url; +}); + +export const result = await Effect.runPromise( + program.pipe( + Effect.scoped, + Effect.provideService(Deployments, { + // Replace this demo service with your deployment API. + deploy: (release) => Effect.succeed(`https://example.com/${release}`) + }) + ) +); +console.log(result); // 'https://example.com/v1.2.0' +``` + +The demo service runs locally. Replace it with your deployment API. The machine defines which events are valid in each state; Effect provides the deployment service and owns the actor's lifetime. + +Start Effect-backed logic with `createEffectActor` inside an Effect scope. + +
+Runtime and cancellation details + +- `createEffectActor` runs pure XState transitions from an Effect fiber. Its mailbox processes events in order; timers use Effect's `Clock`. +- Events are processed asynchronously. Read their outcomes with `waitFor`, `join` or `snapshots`. +- Starting Effect-backed logic with XState's `createActor` produces an error because the Effect host is missing. +- Leaving an invoking state interrupts its local Effect. It does not undo work already accepted by an external API; model cancellation or rollback explicitly when needed. + +
+ +## Guides + +| Guide | Examples | +| --- | --- | +| [Quick start](docs/quick-start.md) | Release approval, expiry, cancellation and retry. | +| [Actors](docs/actors.md) | Share an actor through a Layer and ManagedRuntime. | +| [Observing actors](docs/observing-actors.md) | Snapshot history, output and streamed reminders. | +| [Matching states](docs/matching-states.md) | Exhaustive matching and per-state context. | +| [Effect actor logic](docs/effect-logic.md) | Report tasks, upload progress and rollout health events. | +| [Schemas and actions](docs/schemas-and-actions.md) | Runtime event validation and background audit entries. | +| [Atoms and React](docs/atoms-and-react.md) | Registry ownership, approval controls and useSelector. | +| [Testing and errors](docs/testing-and-errors.md) | TestClock, task retries, supervision and typed failures. | + +Runnable copies live in [examples/effect-workflows](../../examples/effect-workflows). Their tests verify the docs use the same code. + +## Actors + +The actor stops and interrupts its hosted Effects when its enclosing scope closes. Use `Effect.scoped` for a bounded program, or `Layer.effect` to share an actor for an application's lifetime. + +- Invoked Effect tasks and streams own their resources and release them on completion, failure or cancellation. +- Background actions use the owning actor's scope. +- Use `withActorScope` around resource acquisition to keep a resource until the owning actor stops. + +Provide Layers outside the actor's scope, so services remain available during cleanup. Dispose a `ManagedRuntime` when its owner shuts down. See [actors](docs/actors.md). + +### Requirements + +`RequirementsFrom` collects services from declared Effect actions, declared actors and inline invocations, including child machines up to 10 levels deep. `createEffectActor` returns `Effect, never, R | Scope>`. Provided action and actor overrides update that service union. Actor and invocation scopes are supplied automatically. + +
+Requirement limits + +Deeper requirements are not inferred. Provide them explicitly or flatten the machine tree. Inline spawned Effect logic is rejected; register it in `actors` before spawning it. + +The actor's later errors are observed through `join` or snapshots. Invalid input rejected during creation is a defect. + +
+ +### Observing actors + + + +| Function | Use | +| --- | --- | +| `send` | Enqueue an event. | +| `snapshots` | Stream the current snapshot and changes. | +| `waitFor` | Await a snapshot predicate, optionally with a timeout. | +| `join` | Await final output or failure. | +| `emitted` | Stream notifications emitted by the actor. | +| `inspect` | Stream system inspection events. | +| `deadLetters` | Observe delivery failures. | + +`send` and `waitFor` support direct and pipeable usage. See [complete observation examples](docs/observing-actors.md). + +### Matching states + + + +`taggedState(snapshot)` exposes `_tag`, `value`, `context` and `snapshot`. Use `TaggedState` with Effect's `Match.tag` and `Match.exhaustive`. Per-state context narrows with the tag. See [matching states](docs/matching-states.md). + +## Effect actor logic + + + +| Function | Behavior | +| --- | --- | +| `fromEffect` | Run a task; its success value is the actor's output. | +| `fromEffectStream` | Expose the latest stream item as snapshot context. | +| `fromEffectEventStream` | Relay stream items to the parent as events. | + +For example, a progress stream can feed an upload UI: + + + +```ts +import { Effect, Option, Stream } from 'effect'; +import { createEffectActor, fromEffectStream, snapshots } from '@xstate/effect'; + +// Demo upload progress. Replace with your upload SDK's progress stream. +const uploadProgress = fromEffectStream(Stream.make(0, 25, 60, 100)); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(uploadProgress); + return yield* snapshots(actor).pipe( + Stream.filter((s) => s.context !== undefined), + Stream.map((s) => s.context), + Stream.runLast, + Effect.map(Option.getOrThrow) + ); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 100 +``` + +See [Effect actor logic](docs/effect-logic.md) for tasks and a stream that drives rollout transitions. + +## Schemas and actions + + + +`setupEffect` accepts Effect schemas for input, context, events, output and per-state context. Types are inferred without manual conversion. Add `standardSchemaValidator()` from `xstate/validation` for runtime checks. + +### Declared only + + + +- Register background Effect actions in `setupEffect({ actions })`; enqueue them with explicit arguments. +- Invoke `fromEffect` logic when the machine needs to wait for a result. +- Register spawned Effect logic in `actors`, then use `enq.spawn(args.actors.worker)`. + +See [schemas and actions](docs/schemas-and-actions.md) for a complete audit example, runtime schema constraints and inline-source pitfalls. + +## Atoms and React + + + +`createActorAtoms` from `@xstate/effect/atom` exposes `actor`, `snapshot`, `result`, `send`, `select` and `state`. Its `Atom.runtime` must provide the logic's services. Pass `{ input }` when the logic requires input; missing or mismatched input is a type error. + +- Read atoms with `@effect/atom-react` in React, or an `AtomRegistry` elsewhere. +- The registry owns their lifetime; dispose it when its owner shuts down. +- `useSelector` from `@xstate/react` can also read an existing `EffectActor` directly. + +See [atoms and React](docs/atoms-and-react.md) for complete examples with imports, runtime setup and cleanup. + +## Testing and errors + + + +- Use `TestClock` to drive deadlines without waiting for real time. +- `ActorStoppedError` reports a stop before an awaited result. +- `EffectInterruptedError` reports self-interruption inside Effect logic. +- Timed waits fail with Effect's `Cause.TimeoutError`. +- `join` preserves a task's typed failure. Unexpected machine errors have type `unknown`. + +See [testing and errors](docs/testing-and-errors.md) for executable deadline, retry and failure examples. Persisted snapshots record actor state; pass one to `createEffectActor(logic, { snapshot })` to resume the actor. See [persisting and restoring](docs/actors.md#persisting-and-restoring). + +## Tracing + + + +Hosted work uses spans named `fromEffect`, `fromEffectStream`, `fromEffectEventStream` and `action.`. Each carries `xstate.actor.id` and `xstate.actor.address`. Provide a `Tracer` to record and export them. diff --git a/xstate-effect/docs/actors.md b/xstate-effect/docs/actors.md new file mode 100644 index 00000000..2d7bd7af --- /dev/null +++ b/xstate-effect/docs/actors.md @@ -0,0 +1,236 @@ +--- +title: "XState Effect: Actors" +description: Create actors whose lifetime and dependencies belong to an Effect application. +--- + +`createEffectActor(logic, options?)` starts an actor and returns its handle as a scoped Effect. + +- Pass `options.input` when the logic requires input. +- Pass `options.snapshot` to resume an actor from a persisted snapshot. See [persisting and restoring](#persisting-and-restoring). +- Provide the services required by its declared actions and child actors. +- Use `Effect.scoped` for a bounded program, or a Layer for an application service. + +The [quick start](quick-start.md) shows an actor with input and a deployment service. + +## Lifetime + +The enclosing scope owns the actor. When that scope closes, the actor stops and its hosted Effects are interrupted. + +- `Effect.scoped(program)` closes the scope when `program` finishes. +- `actor.stop()` stops the actor explicitly. +- Tasks created with `fromEffect`, `fromEffectStream` and `fromEffectEventStream` have their own scopes. Their resources are released when the task completes, fails or is interrupted. +- Background Effect actions use the owning actor's scope. Their resources are released when that actor stops. +- Use `withActorScope` around a resource acquisition to keep it until the owning actor stops. +- The enclosing scope waits for the actor's finalizers before finishing its own cleanup. + +Provide application Layers outside `Effect.scoped`, with `program.pipe(Effect.scoped, Effect.provide(AppLayer))`, so services remain available while actor cleanup runs. + +### Resource lifetimes + +This release task owns a temporary workspace and opens a cache for the rest of the workflow. The workspace closes before the machine handles `onDone`; the cache closes when the owning actor stops. + + + +```ts +import { Effect } from 'effect'; +import { + createEffectActor, + fromEffect, + waitFor, + withActorScope +} from '@xstate/effect'; +import { setup } from 'xstate'; + +const events: string[] = []; +const prepareRelease = fromEffect( + Effect.gen(function* () { + // Keep the shared cache open for the rest of the release workflow. + yield* Effect.acquireRelease( + Effect.succeed({ name: 'release-cache' }), + () => Effect.sync(() => events.push('close cache')) + ).pipe(withActorScope); + + // This temporary workspace belongs to this invocation. + yield* Effect.acquireRelease( + Effect.succeed({ directory: '/tmp/release' }), + () => Effect.sync(() => events.push('remove workspace')) + ); + events.push('prepare release'); + return 'artifact ready'; + }) +); + +const releaseMachine = setup({ actors: { prepareRelease } }).createMachine({ + initial: 'preparing', + states: { + preparing: { + invoke: { src: 'prepareRelease', onDone: { target: 'ready' } } + }, + ready: {} + } +}); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(releaseMachine); + yield* waitFor(actor, (snapshot) => snapshot.matches('ready')); + events.push('ready for approval'); + // The workspace is gone; the cache stays open while the actor is alive. +}); + +await Effect.runPromise(Effect.scoped(program)); +export const result = events; +console.log(result); +// ['prepare release', 'remove workspace', 'ready for approval', 'close cache'] +``` + +The resource objects in this demo are local stand-ins. Replace their acquisition and release Effects with your file, connection or subscription APIs. + +`withActorScope` uses the scope of the root actor created by `createEffectActor`, including when called from a nested invocation. Apply it to the acquisition whose lifetime you want to extend. + +## Provide an actor as a service + +Use `Layer.effect` to share one actor across requests. This review actor stays alive across calls to the `ManagedRuntime`: + + + +```ts +import { Context, Effect, Layer, ManagedRuntime } from 'effect'; +import { + createEffectActor, + send, + waitFor, + type EffectActor +} from '@xstate/effect'; +import { createMachine } from 'xstate'; + +const reviewMachine = createMachine({ + initial: 'pending', + states: { + pending: { on: { APPROVE: { target: 'approved' } } }, + approved: {} + } +}); + +class ReviewActor extends Context.Service< + ReviewActor, + EffectActor +>()('@app/ReviewActor') {} + +const ReviewActorLayer = Layer.effect( + ReviewActor, + createEffectActor(reviewMachine) +); +const runtime = ManagedRuntime.make(ReviewActorLayer); + +try { + const snapshot = await runtime.runPromise( + Effect.gen(function* () { + const actor = yield* ReviewActor; + yield* send(actor, { type: 'APPROVE' }); + return yield* waitFor(actor, (s) => s.matches('approved')); + }) + ); + console.log(snapshot.value); // 'approved' +} finally { + await runtime.dispose(); +} +``` + +- The Layer starts the actor when it is built. +- `EffectActor` types the service and its events. +- `runtime.dispose()` closes the runtime, stops the actor and releases its resources. Call it when your application shuts down. + +If the machine requires services, provide their Layers to the actor Layer with `Layer.provide`. + +## Clock + +`after` transitions and delayed sends use Effect's `Clock`. In tests, `TestClock` advances those timers without waiting for real time. See the [complete deadline example](testing-and-errors.md#testclock). + +Timers are interrupted when the actor stops. + +## Persisting and restoring + +An actor can outlive its process. Save `actor.getPersistedSnapshot()` after an event, then pass the saved snapshot to `createEffectActor` when the next event arrives, in the same process or another one. + + + +```ts +import { Effect } from 'effect'; +import { createEffectActor, waitFor } from '@xstate/effect'; +import { createMachine, type Snapshot } from 'xstate'; + +const review = createMachine({ + id: 'review', + initial: 'draft', + states: { + draft: { on: { SUBMIT: { target: 'inReview' } } }, + inReview: { on: { APPROVE: { target: 'approved' } } }, + approved: { type: 'final' } + } +}); + +// Handle one event, then return the snapshot to store. +const handle = ( + stored: Snapshot | undefined, + event: { type: 'SUBMIT' } | { type: 'APPROVE' } +) => + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(review, { snapshot: stored }); + const before = actor.getSnapshot(); + actor.send(event); + yield* waitFor(actor, (snapshot) => snapshot !== before); + return JSON.parse(JSON.stringify(actor.getPersistedSnapshot())); + }) + ); + +const program = Effect.gen(function* () { + const submitted = yield* handle(undefined, { type: 'SUBMIT' }); + // Store `submitted` in a database row or a Durable Object, possibly for days. + const approved = yield* handle(submitted, { type: 'APPROVE' }); + return approved.status; +}); + +export const result = await Effect.runPromise(program); +console.log(result); // 'done' +``` + +Restoring resumes the persisted state and context without running entry actions again. + +- A pending `after` transition or delayed send keeps its original deadline, measured on Effect's `Clock`. A deadline that passed while the snapshot was stored fires as soon as the actor starts. +- State-machine children resume their persisted state and context. +- Completed children do not restart. +- Running Effect tasks and streams restart from the beginning: a `fromEffect` task runs its Effect again, and a `fromEffectStream` or `fromEffectEventStream` stream starts again from its first item. A half-finished Effect cannot be persisted, so this matches how XState restarts running async and callback actors. Make that work safe to repeat, for example with an idempotency key. +- A snapshot-only restore does not need `input`, even when the logic requires it. +- The restored actor belongs to the enclosing scope like any other: closing the scope stops it, its children and its timers. + +## Actor handle + +The `EffectActor` handle supports: + +- `send`, `getSnapshot`, `subscribe` and `on` from XState's actor reference contract; +- `inspect`, `getPersistedSnapshot` and `stop`; +- this package's [actor functions](observing-actors.md) and `useSelector` from `@xstate/react`. + +## Requirements + +`RequirementsFrom` collects the services needed by: + +- actions registered with `setupEffect({ actions })`; +- actors registered with `setup({ actors })` or `setupEffect({ actors })`; +- inline `invoke.src` logic, at the root or in a state; +- those same sources inside child machines, up to 10 levels of nesting. + +`createEffectActor` returns `Effect, never, R | Scope>`, where `R` is that service union. TypeScript checks that you provide those services before running the program. Overrides passed to `machine.provide` contribute their current services, replacing the requirements of the sources they override. Actor and invocation scopes are supplied automatically. + +Declare spawned Effect logic in `actors` and spawn it by name. See [declared sources](schemas-and-actions.md#declared-sources). + +
+Requirement inference limits and creation errors + +- Requirements deeper than 10 machine levels are not collected. Flatten that tree, or provide the deeper services explicitly. +- Inline logic passed to `enq.spawn` is invisible to requirement inference and is rejected at runtime. +- The `never` error channel means actor creation has no typed failures. It does not describe the actor's later result; use `join` to observe that result. +- Missing services and other programming errors can put the actor in the `error` status. Invalid input rejected by a runtime validator makes creation fail as a defect. + +
diff --git a/xstate-effect/docs/atoms-and-react.md b/xstate-effect/docs/atoms-and-react.md new file mode 100644 index 00000000..138566b3 --- /dev/null +++ b/xstate-effect/docs/atoms-and-react.md @@ -0,0 +1,248 @@ +--- +title: "XState Effect: Atoms and React" +description: Read workflow state and send events from an Effect-powered UI. +--- + +Use `@xstate/effect/atom` to expose an actor through Effect's reactive atoms. The runtime owns the actor; components read its state and send events. + +`effect/reactivity` is an unstable Effect module. This entry point follows it and may change independently of the rest of the package. + +## Create actor atoms + +`createActorAtoms(runtime, logic, options?)` takes an `Atom.runtime` whose Layer provides the logic's services. When the logic requires input, pass `{ input }`; TypeScript rejects missing or mismatched input, just as it does with `createEffectActor`. + +This complete example waits for the runtime, sends an approval and reads a selector: + + + +```ts +import { Effect, Layer } from 'effect'; +import { AsyncResult, Atom, AtomRegistry } from 'effect/reactivity'; +import { waitFor } from '@xstate/effect'; +import { createActorAtoms } from '@xstate/effect/atom'; +import { createMachine } from 'xstate'; + +const reviewMachine = createMachine({ + initial: 'pending', + states: { + pending: { on: { APPROVE: { target: 'approved' } } }, + approved: {} + } +}); + +const runtime = Atom.runtime(Layer.empty); +const review = createActorAtoms(runtime, reviewMachine); +const status = review.select((snapshot) => snapshot.value); +const registry = AtomRegistry.make(); +const unmount = registry.mount(status); + +export let result: string | undefined; +try { + const actor = await Effect.runPromise( + AtomRegistry.getResult(registry, review.actor) + ); + // Wait for the runtime before sending. + registry.set(review.send, { type: 'APPROVE' }); + await Effect.runPromise(waitFor(actor, (s) => s.matches('approved'))); + const current = registry.get(status); + if (AsyncResult.isSuccess(current)) { + result = current.value; + console.log(result); // 'approved' + } +} finally { + unmount(); + registry.dispose(); +} +``` + +- The actor starts when one of its atoms is first read or mounted. +- It is released when its atoms have no consumers, subject to the registry's idle lifetime. +- Dispose the registry when its owner shuts down. +- A runtime missing a required service is a type error. + +## Atom reference + +| Atom | Value | +| --- | --- | +| `actor` | `AsyncResult>`. | +| `snapshot` | `AsyncResult`, including error snapshots. | +| `result` | A failure when the actor errors, suitable for error handling. | +| `send` | Writable atom that accepts an event and reports the last send. | +| `select(f)` | Derived `AsyncResult` from the snapshot. | +| `state` | The snapshot as a [tagged union](matching-states.md). | + +The runtime Layer's error type is included in the atoms' error channels. `result` also includes the actor's `ErrorFrom`. + +
+Sending before the runtime is ready + +The `send` atom enqueues an event once the actor is ready. Sending while the runtime is still building records `NotReadyError` instead. That class is exported from `@xstate/effect/atom`. Wait for the actor, or render controls after `useAtomSuspense` has resolved. + +
+ +## React + +Install the React bindings that match your Effect version: + +```bash +npm install @effect/atom-react react react-dom +``` + +The example uses an approval workflow with a demo publishing task. `RegistryProvider` owns the atom registry, and `Suspense` handles startup: + + + +```tsx +import { Suspense } from 'react'; +import { Effect, Layer } from 'effect'; +import { Atom } from 'effect/reactivity'; +import { + RegistryProvider, + useAtomSet, + useAtomSuspense +} from '@effect/atom-react'; +import { fromEffect, setupEffect } from '@xstate/effect'; +import { createActorAtoms } from '@xstate/effect/atom'; + +const reviewMachine = setupEffect({ + actors: { publish: fromEffect(Effect.sleep('10 millis')) } +}).createMachine({ + initial: 'pending', + states: { + pending: { on: { APPROVE: { target: 'publishing' } } }, + publishing: { + invoke: { src: 'publish', onDone: { target: 'published' } } + }, + published: {} + } +}); + +const runtime = Atom.runtime(Layer.empty); +const review = createActorAtoms(runtime, reviewMachine); +const status = review.select((snapshot) => snapshot.value); + +function Review() { + const { value } = useAtomSuspense(status); + const send = useAtomSet(review.send); + return ( +
+

{value}

+ +
+ ); +} + +export function App() { + return ( + + Starting review…

}> + +
+
+ ); +} +``` + +- `useAtomSuspense` waits for the runtime and actor, then returns a successful result. +- `useAtomValue` returns the `AsyncResult` directly, for components that render loading and failure states themselves. +- `useAtomMount(review.actor)` lets an owner component retain the actor while child components read selectors. +- Use `Atom.keepAlive` to retain an atom for the registry's lifetime, or `Atom.family` for one actor per input. + +
+Starting actors from React hooks + +`useMachine`, `useActor` and `useActorRef` from `@xstate/react` start logic through XState's `createActor`. Start Effect-backed logic in an Effect runtime with `createEffectActor`, then consume it through atoms or `useSelector`. + +
+ +## Use an actor handle directly + +`useSelector` accepts an `EffectActor`. Build the actor in a `ManagedRuntime`, pass it to a component and dispose the runtime when the application shuts down: + + + +```tsx +import { Context, Layer, ManagedRuntime } from 'effect'; +import { createEffectActor, type EffectActor } from '@xstate/effect'; +import { useSelector } from '@xstate/react'; +import { createMachine } from 'xstate'; + +const reviewMachine = createMachine({ + initial: 'pending', + states: { + pending: { on: { APPROVE: { target: 'approved' } } }, + approved: {} + } +}); + +class ReviewActor extends Context.Service< + ReviewActor, + EffectActor +>()('@app/ReviewActor') {} + +export const runtime = ManagedRuntime.make( + Layer.effect(ReviewActor, createEffectActor(reviewMachine)) +); +export const actor = await runtime.runPromise(ReviewActor); + +// Render in your React application. +export function Review({ + actor +}: { + actor: EffectActor; +}) { + const status = useSelector(actor, (s) => s.value); + return ( + + ); +} + +// Call await runtime.dispose() when the application shuts down. +``` + +## Required input + +Pass the actor's input when creating its atoms: + + + +```ts +import { Effect, Layer, Schema } from 'effect'; +import { Atom, AtomRegistry } from 'effect/reactivity'; +import { fromEffect, join } from '@xstate/effect'; +import { createActorAtoms } from '@xstate/effect/atom'; + +const prepare = fromEffect({ + schemas: { input: Schema.Struct({ release: Schema.String }) }, + effect: ({ input }) => Effect.succeed(`Prepared ${input.release}`) +}); + +const runtime = Atom.runtime(Layer.empty); +const atoms = createActorAtoms(runtime, prepare, { + input: { release: 'v1.2.0' } +}); +const registry = AtomRegistry.make(); +const unmount = registry.mount(atoms.snapshot); + +export let result: string | undefined; +try { + const actor = await Effect.runPromise( + AtomRegistry.getResult(registry, atoms.actor) + ); + result = await Effect.runPromise(join(actor)); + console.log(result); // Prepared v1.2.0 +} finally { + unmount(); + registry.dispose(); +} +``` diff --git a/xstate-effect/docs/effect-logic.md b/xstate-effect/docs/effect-logic.md new file mode 100644 index 00000000..12c89862 --- /dev/null +++ b/xstate-effect/docs/effect-logic.md @@ -0,0 +1,183 @@ +--- +title: "XState Effect: Actor logic" +description: Use Effect tasks and streams as parts of an event-driven workflow. +--- + +Turn an Effect or Stream into [actor logic](../../../docs/actor-logic.md) with one of these functions. Start it with `createEffectActor`, or invoke it from a machine running under `createEffectActor`. + +| Function | Use it for | +| --- | --- | +| `fromEffect` | A task whose result decides the next state. | +| `fromEffectStream` | A changing value, such as upload progress. | +| `fromEffectEventStream` | Events that drive a workflow, such as health checks. | + +Each accepts a value, a function of actor arguments that returns the value, or a configuration object with `id`, `schemas`, `validator` and `effect` or `stream`. + +## `fromEffect` + +Use `fromEffect` for work the machine waits for: publishing a release, reserving inventory or building a report. The [quick start](quick-start.md) invokes a deployment task and handles success, failure and cancellation. + +Here is a complete task with typed input and output: + + + +```ts +import { Effect, Schema } from 'effect'; +import { createEffectActor, fromEffect, join } from '@xstate/effect'; + +const buildReport = fromEffect({ + schemas: { input: Schema.Struct({ orderIds: Schema.Array(Schema.String) }) }, + effect: ({ input, emit }) => + Effect.sync(() => { + emit({ type: 'reportBuilt', count: input.orderIds.length }); + return { total: input.orderIds.length }; + }) +}); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(buildReport, { + input: { orderIds: ['order-1', 'order-2'] } + }); + return yield* join(actor); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // { total: 2 } +``` + +- The actor is `active` while the Effect runs. +- Success puts it in `done` and stores the value in `output`. +- Failure puts it in `error`; `join` and an invoking machine's `onError` receive the typed error. +- The task actor has no context of its own. + +### Actor arguments + +The function form receives `EffectSourceArgs` once per actor start: + +| Field | Description | +| --- | --- | +| `input` | The actor's input. | +| `self` | The actor's reference. | +| `system` | The actor system. | +| `emit` | Emits a notification for `actor.on(...)` and `emitted(actor)`. | + +Input and output schemas are optional. Missing types are inferred from the function or Effect. See [schemas and actions](schemas-and-actions.md) for runtime validation. + +### Cancellation and failure + +Leaving an invoking state or stopping the actor interrupts the running Effect. Each task runs in its own scope: + +- `Effect.acquireRelease` and `Effect.addFinalizer` clean up before a completed or failed task reports its outcome. +- Cancelling an invocation interrupts the task and runs its cleanup while the parent can continue in another state. +- Use `withActorScope` for resources that should stay open until the owning actor stops. See [resource lifetimes](actors.md#resource-lifetimes). + +Use Effect's retry and timeout combinators inside the task. + +
+How Effect exits map to actors + +| Exit | Actor result | +| --- | --- | +| Success | `done`, with the success value as `output`. | +| Typed failure | `error`, with the failure value as `error`. | +| Defect | `error`, with the squashed cause. | +| Interrupted because the actor stopped or the invoking state exited | Stopped, without an error. | +| Self-interruption inside the Effect | `error`, with `EffectInterruptedError`. | + +`Effect.timeout` fails with `Cause.TimeoutError`. A lost `Effect.race` interrupts only the loser; the actor completes with the winner. + +
+ +## `fromEffectStream` + +Use `fromEffectStream` when consumers need the latest value. For example, upload progress becomes the actor's snapshot context: + + + +```ts +import { Effect, Option, Stream } from 'effect'; +import { createEffectActor, fromEffectStream, snapshots } from '@xstate/effect'; + +// Demo upload progress. Replace with your upload SDK's progress stream. +const uploadProgress = fromEffectStream(Stream.make(0, 25, 60, 100)); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(uploadProgress); + return yield* snapshots(actor).pipe( + Stream.filter((s) => s.context !== undefined), + Stream.map((s) => s.context), + Stream.runLast, + Effect.map(Option.getOrThrow) + ); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 100 +``` + +The demo stream is finite. Replace it with your upload SDK's progress stream; the actor exposes each new percentage as `snapshot.context`. + +- Context is `undefined` until the first item arrives. +- Completion puts the actor in `done`, with no output; the last context remains readable. +- Stream failure puts the actor in `error`. +- Read changing values with `snapshots`, `waitFor` or a UI selector. + +## `fromEffectEventStream` + +Use `fromEffectEventStream` when stream items should trigger transitions. This deployment feed first reports a healthy rollout, then a health failure that requests rollback: + + + +```ts +import { Effect, Stream } from 'effect'; +import { + createEffectActor, + fromEffectEventStream, + join, + setupEffect +} from '@xstate/effect'; + +// A deployment feed drives the workflow, rather than just displaying data. +const deploymentEvents = fromEffectEventStream( + Stream.make({ type: 'HEALTHY' }, { type: 'UNHEALTHY' }) +); + +const rolloutMachine = setupEffect({ + actors: { deploymentEvents } +}).createMachine({ + output: () => 'rollback requested', + initial: 'monitoring', + states: { + monitoring: { + invoke: { src: 'deploymentEvents' }, + initial: 'checking', + states: { + checking: { on: { HEALTHY: { target: 'healthy' } } }, + healthy: {} + }, + on: { UNHEALTHY: { target: 'rollingBack' } } + }, + rollingBack: { type: 'final' } + } +}); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(rolloutMachine); + return yield* join(actor); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 'rollback requested' +``` + +The stream belongs to `monitoring`, so it stays active when that state moves from `checking` to `healthy`. Leaving `monitoring` stops the stream actor and interrupts its consumption. + +- Each item is relayed to the parent machine as an event. +- Completion puts the stream actor in `done`, with no output. +- Stream failure puts it in `error`; handle it with the invocation's `onError`. + +Use this pattern for WebSocket messages, job updates or subscription feeds that change a workflow's state. + +## Tracing + +The three functions run inside spans named `fromEffect`, `fromEffectStream` and `fromEffectEventStream`. See [tracing](testing-and-errors.md#tracing). diff --git a/xstate-effect/docs/matching-states.md b/xstate-effect/docs/matching-states.md new file mode 100644 index 00000000..762e1037 --- /dev/null +++ b/xstate-effect/docs/matching-states.md @@ -0,0 +1,125 @@ +--- +title: "XState Effect: Matching states" +description: Render workflow states with exhaustive Effect Match branches. +--- + +`taggedState(snapshot)` gives a machine snapshot an Effect-style `_tag`. Use `Match.tag` and `Match.exhaustive` to describe every state of a workflow. + +In this review example, only the approved state has a `reviewer`. Matching that tag also narrows its context: + + + +```ts +import { Effect, Match, Schema, Stream } from 'effect'; +import { + createEffectActor, + send, + setupEffect, + snapshots, + taggedState, + type TaggedState +} from '@xstate/effect'; + +const reviewMachine = setupEffect({ + states: { + approved: { + schemas: { context: Schema.Struct({ reviewer: Schema.String }) } + } + } +}).createMachine({ + initial: 'pending', + states: { + pending: { + on: { APPROVE: { target: 'approved', context: { reviewer: 'Ada' } } } + }, + approved: { type: 'final' } + } +}); + +const describe = Match.type>().pipe( + Match.tag('pending', () => 'Waiting for review'), + Match.tag('approved', ({ context }) => `Approved by ${context.reviewer}`), + Match.exhaustive +); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(reviewMachine); + return [ + ...(yield* snapshots(actor).pipe( + Stream.tap((s) => + s.matches('pending') ? send(actor, { type: 'APPROVE' }) : Effect.void + ), + Stream.map(taggedState), + Stream.map(describe), + Stream.runCollect + )) + ]; +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // ['Waiting for review', 'Approved by Ada'] +``` + +Adding a state requires adding a matching branch before `Match.exhaustive` will typecheck. + +## Tagged state fields + +| Field | Description | +| --- | --- | +| `_tag` | The dotted state path, such as `review.approved`. | +| `value` | The XState state value. | +| `context` | The context for that state, including its per-state schema. | +| `snapshot` | The original snapshot. | + +- `TaggedState` names the union for a machine. +- `TaggedStateFrom` names it for a snapshot type. +- `StateTag` names the tag for one state value. + +Declare per-state context with `setupEffect({ states })`. See [schemas and actions](schemas-and-actions.md). + +## Parallel states + +A parallel workflow can wait for review while building a release. Its `_tag` stops at the parallel state; when the root is parallel, the tag is `'(machine)'`. Inspect `value` or use `snapshot.matches` to read individual regions: + + + +```ts +import { Effect, Match } from 'effect'; +import { + createEffectActor, + taggedState, + type TaggedState +} from '@xstate/effect'; +import { createMachine } from 'xstate'; + +const releaseMachine = createMachine({ + type: 'parallel', + states: { + review: { initial: 'pending', states: { pending: {}, approved: {} } }, + build: { initial: 'running', states: { running: {}, passed: {} } } + } +}); + +const describe = Match.type>().pipe( + Match.tag('(machine)', ({ snapshot }) => + snapshot.matches({ build: 'running' }) + ? 'Build in progress' + : 'Build finished' + ), + Match.exhaustive +); + +export const result = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(releaseMachine); + return describe(taggedState(actor.getSnapshot())); + }) + ) +); +console.log(result); // 'Build in progress' +``` + +## UI atoms + +`createActorAtoms` exposes this same tagged union through its `state` atom. A UI can match on states without calling `taggedState` itself. See [atoms and React](atoms-and-react.md). diff --git a/xstate-effect/docs/meta.json b/xstate-effect/docs/meta.json new file mode 100644 index 00000000..59a98d26 --- /dev/null +++ b/xstate-effect/docs/meta.json @@ -0,0 +1,13 @@ +{ + "title": "XState Effect", + "pages": [ + "quick-start", + "actors", + "observing-actors", + "matching-states", + "effect-logic", + "schemas-and-actions", + "atoms-and-react", + "testing-and-errors" + ] +} diff --git a/xstate-effect/docs/observing-actors.md b/xstate-effect/docs/observing-actors.md new file mode 100644 index 00000000..4d7a6185 --- /dev/null +++ b/xstate-effect/docs/observing-actors.md @@ -0,0 +1,228 @@ +--- +title: "XState Effect: Observing actors" +description: Send events and observe workflow state, results and notifications. +--- + +Use these functions with an `EffectActor`, a child from `snapshot.children` or another XState actor reference. + +| Function | Result | +| --- | --- | +| `send(actor, event)` | Enqueues an event as `Effect`. | +| `snapshots(actor)` | Streams the current snapshot, then changes. | +| `waitFor(actor, predicate)` | Waits for a matching snapshot. | +| `join(actor)` | Waits for the actor's final output. | +| `emitted(actor)` | Streams emitted events. | +| `inspect(actor)` | Streams system inspection events. | +| `deadLetters(actor)` | Streams events the system could not deliver. | + +## Send, observe and join + +This example records a review's state changes and reads its final output: + + + +```ts +import { Effect, Stream, pipe } from 'effect'; +import { + createEffectActor, + join, + send, + snapshots, + waitFor +} from '@xstate/effect'; +import { createMachine } from 'xstate'; + +const reviewMachine = createMachine({ + output: () => ({ approved: true }), + initial: 'pending', + states: { + pending: { on: { APPROVE: { target: 'approved' } } }, + approved: { type: 'final' } + } +}); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(reviewMachine); + const history = yield* snapshots(actor).pipe( + // Send after the subscription sees the initial state. + Stream.tap((s) => + s.matches('pending') + ? pipe(actor, send({ type: 'APPROVE' })) + : Effect.void + ), + Stream.map((s) => s.value), + Stream.runCollect + ); + yield* waitFor(actor, (s) => s.matches('approved'), { timeout: '5 seconds' }); + return { history: [...history], output: yield* join(actor) }; +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); +// { history: ['pending', 'approved'], output: { approved: true } } +``` + +- `send` enqueues an event; use `waitFor`, `snapshots` or `join` to observe the outcome. +- `send` and `waitFor` also support pipeable usage, as shown with `pipe(actor, send(...))`. +- `snapshots` begins with the current snapshot and ends when the actor completes or stops. An error snapshot is emitted before the stream ends. +- `waitFor` succeeds immediately if the current snapshot already matches. Its `{ timeout }` option bounds the wait. +- A type predicate passed to `waitFor` narrows the returned snapshot. +- `join` succeeds with `output` when the actor reaches `done`. + +
+Wait and join failures + +- `waitFor` fails with `ActorStoppedError` if the actor stops or errors before matching. Its timeout fails with Effect's `Cause.TimeoutError`. +- `join` fails with `snapshot.error` when the actor errors, or `ActorStoppedError` when it stops without output. +- `join` on `fromEffect` logic preserves the Effect's typed error. A machine's error type is `unknown`: actions can throw arbitrary values and unhandled child errors can fail the machine. +- Model expected domain outcomes as final states with output. Handle unexpected machine errors with `Effect.catch`, or use `Effect.orDie` to treat them as defects. + +
+ +## Stream notifications + +Use `emitted` for notifications sent with `enq.emit` or `EffectSourceArgs.emit`. This workflow emits a reminder every second while a review is pending: + + + +```ts +import { Effect, Schema, Stream } from 'effect'; +import { createEffectActor, emitted, setupEffect } from '@xstate/effect'; + +const reminderMachine = setupEffect({ + schemas: { + emitted: { reminder: Schema.Struct({ message: Schema.String }) } + } +}).createMachine({ + initial: 'waiting', + states: { + waiting: { after: { 1000: { target: 'reminding' } } }, + reminding: { + entry: (_, enq) => + enq.emit({ type: 'reminder', message: 'Review pending' }), + after: { 0: { target: 'waiting' } } + } + } +}); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(reminderMachine); + return [...(yield* emitted(actor).pipe(Stream.take(1), Stream.runCollect))]; +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // [{ type: 'reminder', message: 'Review pending' }] +``` + +`Stream.take(1)` ends this consumer after one reminder. Use `Stream.runForEach` for a subscriber that handles ongoing notifications. Emitted events are not replayed; start the consumer before the events you need to observe. + +`emitted` ends when the actor completes, errors or stops. Interrupting the consumer also ends it and removes its listener. + +## Inspect execution + +`inspect(actor)` streams [inspection events](../../../docs/inspection.md) for the actor's system. Use `Stream.runForEach(inspect(actor), ...)` to record actor creation and transitions. Start that consumer before the events you want to inspect, and keep it in the same scope as the actor. + +For a visual inspector, forward `actor.inspect` events through the SDK's `actor`, `event` and `snapshot` methods, using session IDs to identify actors across execution steps. This demo uses the optional `INSPECT=1` flag and releases the subscription and inspector with its Effect scope: + + + +```ts +import { createInspector } from '@statelyai/sdk'; +import { Effect } from 'effect'; +import type { Snapshot } from 'xstate'; +import { + createEffectActor, + fromEffect, + join, + send, + setupEffect +} from '@xstate/effect'; + +const reviewMachine = setupEffect({ + actors: { publish: fromEffect(Effect.succeed('Release published')) } +}).createMachine({ + id: 'releaseReview', + output: () => 'Release published', + initial: 'awaitingApproval', + states: { + awaitingApproval: { on: { APPROVE: { target: 'publishing' } } }, + publishing: { invoke: { src: 'publish', onDone: { target: 'published' } } }, + published: { type: 'final' } + } +}); + +// Keep wire snapshots JSON-safe; actor snapshots contain live child references. +const inspectorSnapshot = (snapshot: Snapshot) => ({ + status: snapshot.status, + ...('value' in snapshot ? { value: snapshot.value } : {}) +}); + +export const program = Effect.gen(function* () { + const inspector = yield* Effect.acquireRelease( + Effect.sync(() => + process.env.INSPECT === '1' ? createInspector() : undefined + ), + (inspector) => Effect.sync(() => inspector?.destroy()) + ); + const actor = yield* createEffectActor(reviewMachine); + if (inspector) { + inspector.actor(actor.sessionId!, { + machine: reviewMachine.config, + snapshot: inspectorSnapshot(actor.getSnapshot()) + }); + yield* Effect.acquireRelease( + Effect.sync(() => + actor.inspect((event) => { + // Session IDs stay stable across Effect's pure execution steps. + const id = event.actorRef.sessionId!; + if (event.type === '@xstate.actor') { + inspector.actor(id, { + parent: event.parentRef?.sessionId, + snapshot: inspectorSnapshot(event.snapshot) + }); + } else { + inspector.event(id, event.event, { + source: event.sourceRef?.sessionId + }); + inspector.snapshot( + id, + inspectorSnapshot(event.snapshot), + event.event + ); + if (event.snapshot.status !== 'active') inspector.stop(id); + } + }) + ), + (subscription) => Effect.sync(() => subscription.unsubscribe()) + ); + // Let the inspector connect before the demo sends its first event. + yield* Effect.promise(() => inspector.ready); + } + yield* send(actor, { type: 'APPROVE' }); + return yield* join(actor); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 'Release published' +``` + +Set `INSPECT=1` when running the program to open the Stately inspector and send machine definitions, snapshots and events to its hosted relay. Without the flag, the demo runs locally. + +## Dead letters + +Observe `deadLetters` to diagnose delivery failures. For example, run `Stream.runForEach(deadLetters(actor), (rejection) => Effect.logWarning(rejection))` in a scoped fiber while the actor is in use. + +Each rejection includes the event and a reason: + +- `stopped`: the target has stopped; +- `invalidEvent`: the payload failed the target's runtime schema validation; +- `internalEvent`: an internal event was sent from outside its owning actor. + +A delivered event can still have no transition in the current state. Dead letters describe delivery, not whether the workflow changed state. + +
+Why send does not fail + +`send` has no typed failures. A dead letter is reported through `system.onRejectedEvent`, separately from actor errors and inspection events. `deadLetters` removes that listener when the stream ends. + +
diff --git a/xstate-effect/docs/quick-start.md b/xstate-effect/docs/quick-start.md new file mode 100644 index 00000000..e6f02958 --- /dev/null +++ b/xstate-effect/docs/quick-start.md @@ -0,0 +1,152 @@ +--- +title: "XState Effect: Quick start" +description: Combine event-driven workflows with Effect services, cancellation and testing. +--- + +XState models how a workflow responds to events. Effect runs the work inside it. Use them together when a process needs both: + +- **Explicit states:** show whether a release is waiting for approval, deploying, failed or complete. +- **Events over time:** accept approval from a person, cancellation from a UI or retry from an operator. +- **Effect services:** provide the same dependencies, clock and tracing to the machine's work. +- **Scoped lifetime:** stop the actor and interrupt its hosted Effects when its scope closes. + +## Install + +This package is experimental. It targets XState v6 alpha and Effect 4. + +```bash +npm install @xstate/effect@alpha xstate@alpha effect@^4 +``` + +## Model a release approval + +A release waits for approval for up to 30 seconds. Approval starts deployment; cancellation is available while waiting or deploying. If deployment fails, an operator can retry. + + + +```ts +import { Context, Effect, Schema } from 'effect'; +import { + createEffectActor, + fromEffect, + send, + setupEffect, + waitFor +} from '@xstate/effect'; + +export class Deployments extends Context.Service< + Deployments, + { readonly deploy: (release: string) => Effect.Effect } +>()('@app/Deployments') {} + +const deploy = fromEffect({ + schemas: { input: Schema.Struct({ release: Schema.String }) }, + effect: ({ input }) => Deployments.use((api) => api.deploy(input.release)) +}); + +export const approvalMachine = setupEffect({ + schemas: { input: Schema.Struct({ release: Schema.String }) }, + actors: { deploy } +}).createMachine({ + context: ({ input }) => ({ release: input.release, url: '' }), + initial: 'awaitingApproval', + states: { + awaitingApproval: { + after: { 30000: { target: 'expired' } }, + on: { + APPROVE: { target: 'deploying' }, + CANCEL: { target: 'cancelled' } + } + }, + deploying: { + invoke: { + src: 'deploy', + input: ({ context }) => ({ release: context.release }), + onDone: ({ context, event }) => ({ + target: 'deployed', + context: { ...context, url: event.output } + }), + onError: { target: 'failed' } + }, + on: { CANCEL: { target: 'cancelled' } } + }, + failed: { + on: { + RETRY: { target: 'deploying' }, + CANCEL: { target: 'cancelled' } + } + }, + deployed: { type: 'final' }, + expired: { type: 'final' }, + cancelled: { type: 'final' } + } +}); + +export const program = Effect.gen(function* () { + const actor = yield* createEffectActor(approvalMachine, { + input: { release: 'v1.2.0' } + }); + // A UI, webhook or CLI can send this event after a person approves. + yield* send(actor, { type: 'APPROVE' }); + const snapshot = yield* waitFor(actor, (s) => s.matches('deployed'), { + timeout: '5 seconds' + }); + return snapshot.context.url; +}); + +export const result = await Effect.runPromise( + program.pipe( + Effect.scoped, + Effect.provideService(Deployments, { + // Replace this demo service with your deployment API. + deploy: (release) => Effect.succeed(`https://example.com/${release}`) + }) + ) +); +console.log(result); // 'https://example.com/v1.2.0' +``` + +The service is a local demo, so the example runs without credentials. Replace `Deployments` with your API implementation when connecting it to your application. + +The machine makes the workflow rules visible: + +- `APPROVE` starts deployment only from `awaitingApproval`. +- `after` expires an unanswered approval using Effect's clock. +- Leaving `deploying` interrupts the invoked Effect. Your service can use Effect's interruption and cleanup support to release local resources. +- `failed` accepts `RETRY`; completed and cancelled workflows are final. + +Effect provides the deployment service and owns the actor's lifetime. You can test the same machine with a different service and `TestClock`. + +
+Cancellation and external work + +Interrupting the local deployment Effect does not undo a deployment already accepted by an external API. If your API supports cancellation or rollback, model that operation explicitly. + +
+ +## Run Effect-backed logic + +Start Effect-backed logic with `createEffectActor`, inside an Effect scope. + +
+Why use createEffectActor? + +`createEffectActor` supplies the Effect runtime that hosts the actor's Effects. Starting Effect-backed logic with XState's `createActor` puts it in the `error` status because that host is missing. + +
+ +## How it runs + +- XState calculates the next snapshot and the actions to run from each event. +- An Effect fiber processes the actor's mailbox in order. +- Timers use Effect's `Clock`; declared Effect actions run without blocking the mailbox. +- Child actors use the same Effect host and its services. + +Use `waitFor`, `join` or `snapshots` to read the result of a send. The actor processes events asynchronously. + +## Next steps + +- [Actors](actors.md): scopes, services and lifetime. +- [Observing actors](observing-actors.md): snapshots, results and event streams. +- [Effect actor logic](effect-logic.md): tasks, upload progress and deployment feeds. +- [Testing and errors](testing-and-errors.md): deadlines, retries and typed failures. diff --git a/xstate-effect/docs/schemas-and-actions.md b/xstate-effect/docs/schemas-and-actions.md new file mode 100644 index 00000000..149bfcf3 --- /dev/null +++ b/xstate-effect/docs/schemas-and-actions.md @@ -0,0 +1,171 @@ +--- +title: "XState Effect: Schemas and actions" +description: Type workflow data and run background work with setupEffect. +--- + +`setupEffect` is the Effect-aware form of XState's [`setup`](../../../docs/setup-and-provide.md). + +- Declare input, context, events and output with Effect schemas. +- Register actions that return Effects. +- Register actors, guards and delays as you would with `setup`. +- Start the machine with `createEffectActor`. + +## Schemas and background actions + +This machine accepts a typed approval event and records an audit entry without blocking its transition: + + + +```ts +import { Context, Effect, Latch, Schema } from 'effect'; +import { createEffectActor, send, setupEffect, waitFor } from '@xstate/effect'; +import { standardSchemaValidator } from 'xstate/validation'; + +class Audit extends Context.Service< + Audit, + { readonly record: (reviewer: string) => Effect.Effect } +>()('@app/Audit') {} + +const reviewMachine = setupEffect({ + schemas: { events: { APPROVE: Schema.Struct({ reviewer: Schema.String }) } }, + actions: { + audit: ({ event }) => Audit.use((audit) => audit.record(event.reviewer)) + } +}).createMachine({ + validator: standardSchemaValidator(), + initial: 'pending', + states: { + pending: { + on: { + APPROVE: (args, enq) => { + enq(args.actions.audit, args); + return { target: 'approved' }; + } + } + }, + // Keep the actor alive while its background audit runs. + approved: {} + } +}); + +const program = Effect.gen(function* () { + const recorded = yield* Latch.make(); + const actor = yield* createEffectActor(reviewMachine).pipe( + Effect.provideService(Audit, { record: () => Effect.asVoid(recorded.open) }) + ); + yield* send(actor, { type: 'APPROVE', reviewer: 'Ada' }); + yield* waitFor(actor, (s) => s.matches('approved')); + // Wait for the demo audit before closing the scope. + yield* recorded.await; + return actor.getSnapshot().value; +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 'approved' +``` + +The latch lets this demo wait for the audit before closing its scope. In an application, keep the actor alive for the workflow's lifetime. + +### Effect schemas + +`setupEffect` accepts Effect schemas in `schemas`, per-state `states` declarations and `extend`. + +- Types come from the decoded `Schema.Type`; no manual conversion is needed. +- Per-state schemas narrow context with [`taggedState`](matching-states.md). +- Standard Schemas can be mixed with Effect schemas. `EffectSchemaLike` represents either kind. +- `fromEffect` also accepts Effect input and output schemas. + +### Runtime validation + +Add `standardSchemaValidator()` from `xstate/validation` to check values at runtime, as above. Without a validator, schemas provide types only. + +
+Runtime schema constraints + +XState checks values but does not replace them with decoded values. With runtime validation enabled, encoded and decoded types must match; transforming schemas such as `Schema.NumberFromString` are rejected by TypeScript. Schemas must decode synchronously, without service requirements. + +
+ +## Choose an action or an actor + +- Use an **Effect action** for background work: audit entries, logging, telemetry or notifications. The transition commits without waiting for it. +- Use an **invoked Effect actor** when success or failure decides the next state. `fromEffect` gives `onDone` and `onError` typed results and interrupts the task when its invoking state exits. + +An Effect action runs in the actor's Effect context. Its failures and defects route to the current state's `onError`; stopping the actor interrupts it without reporting an error. + +
+Action execution and completion + +The action function is called synchronously during the transition. The returned Effect runs after the transition commits, in a forked fiber, without blocking subsequent events. + +- The transition enqueues the action with explicit arguments: `enq(args.actions.audit, args)`. +- `EffectActionArgs` and `EffectAction` name the argument and action types. +- An Effect action cannot use the transition's enqueue API after the transition. It can call `self.send` to send a new event. +- A final state or a closing scope can interrupt pending background work. Invoke a task when the workflow must wait for completion. + +
+ +## Provide an action + +Use `machine.provide({ actions })` to replace an action for a particular environment. The provided machine requires the replacement's services. In this example, an audit implementation adds the `Audit` service: + + + +```ts +import { Context, Effect, Latch } from 'effect'; +import { createEffectActor, send, setupEffect } from '@xstate/effect'; + +class Audit extends Context.Service }>()( + 'Audit' +) {} + +const recorded = Latch.makeUnsafe(); +const machine = setupEffect({ + actions: { audit: (_args) => Effect.void } +}).createMachine({ + on: { APPROVE: (args, enq) => enq(args.actions.audit, args) } +}); + +const auditedMachine = machine.provide({ + actions: { audit: () => Audit.use((audit) => audit.record) } +}); + +const program = Effect.gen(function* () { + // The override adds Audit to this machine's required services. + const actor = yield* createEffectActor(auditedMachine); + yield* send(actor, { type: 'APPROVE' }); + yield* recorded.await; + return 'approval recorded'; +}); + +export const result = await Effect.runPromise( + program.pipe( + Effect.scoped, + Effect.provideService(Audit, { record: Effect.asVoid(recorded.open) }) + ) +); +console.log(result); // approval recorded +``` + +- Other actions and their service requirements stay in place. +- Replacing the audit with an action that requires a different service updates the required service type again. +- A plain action can replace an Effect action and remove its service requirement. + +## Declared sources + +Declare Effect actions and spawned Effect actors so their services contribute to [requirement inference](actors.md#requirements). + +- Register actions with `setupEffect({ actions })`, then enqueue the named action. +- Register spawned logic in `actors`, then use `enq.spawn(args.actors.worker)`. +- Inline `invoke.src` logic is supported and contributes requirements; declaring it in `actors` also gives it a reusable name. + +
+Inline action and spawn pitfalls + +An inline callback such as `enq(() => Effect.log('saved'))` creates an Effect that is discarded. Inline Effect logic passed to `enq.spawn` is rejected at runtime because its service requirements cannot be inferred. + +The `xstate-effect/no-inline-effect` oxlint rule checks these two patterns. It recognizes the root identifier `Effect`; Effects returned by helper functions are outside that check. + +The rule is not published as a package. To use it, install `@oxlint/plugins`, copy [`oxlint-plugin-xstate-effect.ts`](https://github.com/statelyai/xstate/blob/next/scripts/oxlint-plugin-xstate-effect.ts) from the XState repository and configure it in `jsPlugins`. Loading the TypeScript source requires Node.js 22.18+ or a newer release with native TypeScript support. + +
diff --git a/xstate-effect/docs/testing-and-errors.md b/xstate-effect/docs/testing-and-errors.md new file mode 100644 index 00000000..68d65b2d --- /dev/null +++ b/xstate-effect/docs/testing-and-errors.md @@ -0,0 +1,198 @@ +--- +title: "XState Effect: Testing and errors" +description: Test deadlines, recover from failures and supervise workflow actors. +--- + +Test the workflow with its real machine and provide local Effect services. Use `waitFor` for state assertions and `join` for final output. + +## TestClock + +A release approval expires after 30 seconds. `TestClock` drives the same `after` transition without waiting for real time: + + + +```ts +import { Effect } from 'effect'; +import { TestClock } from 'effect/testing'; +import { createEffectActor, waitFor } from '@xstate/effect'; +import { createMachine } from 'xstate'; + +const reviewMachine = createMachine({ + initial: 'pending', + states: { + pending: { + after: { 30000: { target: 'expired' } }, + on: { APPROVE: { target: 'approved' } } + }, + approved: { type: 'final' }, + expired: { type: 'final' } + } +}); + +const test = Effect.gen(function* () { + const actor = yield* createEffectActor(reviewMachine); + yield* TestClock.adjust('30 seconds'); + const snapshot = yield* waitFor(actor, (s) => s.matches('expired')); + return snapshot.value; +}); + +export const result = await Effect.runPromise( + test.pipe(Effect.scoped, Effect.provide(TestClock.layer())) +); +console.log(result); // 'expired', with no 30-second wait +``` + +- Timers use Effect's `Clock`, including delayed sends. +- `waitFor` and `join` fail if the actor stops before reaching the expected result. +- Add `waitFor`'s `{ timeout }` to bound a wait. With `TestClock`, advance the clock to trigger that timeout too. +- Use `inspect` for execution traces and `deadLetters` for delivery failures. + +XState's [path generation](../../../docs/model-based-testing.md) works on the machine itself. Execute generated paths against an actor from `createEffectActor`, or use `testPaths()` from `@xstate/test`. + +## Retry a task + +Use Effect's retry combinators inside `fromEffect` for transient failures within one task. This local publisher succeeds on its third attempt: + + + +```ts +import { Effect, Schedule } from 'effect'; +import { createEffectActor, fromEffect, join } from '@xstate/effect'; + +let attempts = 0; +const publish = fromEffect( + Effect.suspend(() => { + attempts++; + return attempts < 3 + ? Effect.fail(new Error('Publisher temporarily unavailable')) + : Effect.succeed('published'); + }).pipe( + Effect.retry({ schedule: Schedule.exponential('10 millis'), times: 3 }) + ) +); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(publish); + return yield* join(actor); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 'published', on attempt 3 +``` + +Use a machine state when retry requires a person or an event. The [quick start](quick-start.md) accepts `RETRY` only after deployment fails. + +## Supervise an actor + +Retry a scoped unit when a failure should create a fresh actor: + + + +```ts +import { Effect, Schedule } from 'effect'; +import { createEffectActor, fromEffect, join } from '@xstate/effect'; + +let attempts = 0; +const worker = fromEffect( + Effect.suspend(() => { + attempts++; + return attempts < 3 + ? Effect.fail(new Error('Worker disconnected')) + : Effect.succeed('complete'); + }) +); + +const attempt = Effect.gen(function* () { + const actor = yield* createEffectActor(worker); + return yield* join(actor); +}); + +// Each failed attempt closes its scope before a new actor starts. +const supervised = Effect.scoped(attempt).pipe( + Effect.retry({ schedule: Schedule.exponential('10 millis'), times: 3 }) +); + +export const result = await Effect.runPromise(supervised); +console.log(result); // 'complete', from the third actor +``` + +Each attempt stops its actor and releases its resources before the next attempt starts. + +
+Choosing failures to retry + +`join` reports the actor's failure, so the retry policy sees that error. A machine's error type is `unknown`; narrow it if only some failures should be retried. Keep `Effect.scoped` inside the retry, so failed actors are released after each attempt. + +Retrying can repeat external operations. Use stable operation IDs or idempotent APIs when repetition could create duplicate work. + +
+ +## Handle typed failures + +A `fromEffect` actor preserves its Effect's error type. Handle a domain failure with `Effect.catchTag`: + + + +```ts +import { Data, Effect } from 'effect'; +import { createEffectActor, fromEffect, join } from '@xstate/effect'; + +class PublishFailed extends Data.TaggedError('PublishFailed')<{ + readonly reason: string; +}> {} + +const publish = fromEffect( + Effect.fail(new PublishFailed({ reason: 'Release needs approval' })) +); + +const program = Effect.gen(function* () { + const actor = yield* createEffectActor(publish); + return yield* join(actor).pipe( + Effect.catchTag('PublishFailed', (error) => Effect.succeed(error.reason)) + ); +}); + +export const result = await Effect.runPromise(Effect.scoped(program)); +console.log(result); // 'Release needs approval' +``` + +For machine workflows, expected outcomes such as declined or expired can be final states with output. `join(machineActor)` has an `unknown` error channel for unexpected machine failures. + +## Error reference + +| Error | Raised by | +| --- | --- | +| `ActorStoppedError` | `waitFor` when the actor stops or errors before matching; `join` when it stops without output. | +| `EffectInterruptedError` | Effect logic that interrupts itself. | +| `Cause.TimeoutError` | `waitFor` with a timeout, or Effect's timeout combinators. | + +- `ActorStoppedError` includes `actorId` and `snapshot`. +- `EffectInterruptedError` includes its interrupt `cause`. +- Both package errors are `Data.TaggedError` classes. +- An actor's own typed failure is available through `snapshot.error` and `join`; `ErrorFrom` names its type. + +
+Observe root actor errors + +A root Effect actor's error is a value. Read it with `join`, `waitFor`, `subscribe` or the `result` atom. An unobserved errored actor is silent, like a failed forked fiber. + +
+ +## Persistence + +`actor.getPersistedSnapshot()` records the actor's state. It does not record progress inside a running Effect: an Effect task or stream that was running when the snapshot was taken starts again from the beginning after a restore. See [persisting and restoring](actors.md#persisting-and-restoring). + +## Tracing + +Hosted Effects run inside spans: + +| Span | Work | +| --- | --- | +| `fromEffect` | A task actor's Effect. | +| `fromEffectStream` | A stream of snapshot values. | +| `fromEffectEventStream` | A stream of parent events. | +| `action.` | A declared Effect action. | + +Spans carry `xstate.actor.id` and `xstate.actor.address`. The address is the actor's `/`-joined path from the root, identifying its place in the actor tree. + +Provide a `Tracer` to record and export spans. diff --git a/xstate-effect/package.json b/xstate-effect/package.json new file mode 100644 index 00000000..c4179485 --- /dev/null +++ b/xstate-effect/package.json @@ -0,0 +1,47 @@ +{ + "name": "@xstate/effect", + "version": "0.1.0-alpha.7", + "type": "module", + "description": "Effect integration for XState", + "keywords": [ + "xstate", + "effect", + "state machine", + "statechart" + ], + "author": "David Khourshid ", + "homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-effect#readme", + "license": "MIT", + "exports": { + "./atom": "./dist/xstate-effect-atom.js", + ".": "./dist/xstate-effect.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/statelyai/xstate.git" + }, + "bugs": { + "url": "https://github.com/statelyai/xstate/issues" + }, + "scripts": {}, + "peerDependencies": { + "effect": "^4.0.0", + "xstate": "workspace:^" + }, + "devDependencies": { + "effect": "4.0.0", + "fast-check": "4.10.2", + "xstate": "workspace:^" + }, + "preconstruct": { + "entrypoints": [ + "./index.ts", + "./atom.ts" + ] + } +} diff --git a/xstate-effect/src/actor.test.ts b/xstate-effect/src/actor.test.ts new file mode 100644 index 00000000..fbad373f --- /dev/null +++ b/xstate-effect/src/actor.test.ts @@ -0,0 +1,459 @@ +import { expectTypeOf } from 'vitest'; +import { Cause, Duration, Effect, Exit, Fiber, Scope, Stream } from 'effect'; +import { + createMachine, + types, + type AnyActorRef, + type SnapshotFrom +} from 'xstate'; +import { + ActorStoppedError, + EffectActor, + createEffectActor, + emitted, + fromEffect, + inspect, + send, + snapshots, + join, + waitFor +} from './index.ts'; + +/** + * Polls until `predicate` holds. The actor processes events on its own fiber, + * so tests wait for the condition they assert on. + */ +const until = async (predicate: () => boolean, timeoutMs = 1000) => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 1)); + } +}; + +let scopes: Scope.Closeable[] = []; + +afterEach(async () => { + const pending = scopes; + scopes = []; + for (const scope of pending) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } +}); + +/** Runs a scoped Effect in a scope that stays open until the test ends. */ +const runScoped = async ( + effect: Effect.Effect +): Promise => { + const scope = await Effect.runPromise(Scope.make()); + scopes.push(scope); + return Effect.runPromise(Scope.provide(effect, scope)); +}; + +/** + * Runs `drive` right after the API under test subscribes to the actor, so + * tests never race the Effect scheduler with a timer. + */ +const afterSubscribe = (actor: AnyActorRef, drive: () => void): void => { + const actorSubscribe = actor.subscribe.bind(actor); + let driven = false; + actor.subscribe = ((...args: Parameters) => { + const subscription = actorSubscribe(...args); + if (!driven) { + driven = true; + queueMicrotask(drive); + } + return subscription; + }) as typeof actor.subscribe; +}; + +/** The `actor.inspect` counterpart of {@link afterSubscribe}. */ +const afterInspect = (actor: EffectActor, drive: () => void): void => { + const actorInspect = actor.inspect.bind(actor); + actor.inspect = ((observer: Parameters[0]) => { + const subscription = actorInspect(observer); + queueMicrotask(drive); + return subscription; + }) as typeof actor.inspect; +}; + +const counterMachine = createMachine({ + schemas: { + events: { + INCREMENT: types<{}>(), + FINISH: types<{}>() + } + }, + context: { count: 0 }, + initial: 'counting', + states: { + counting: { + on: { + INCREMENT: ({ context }) => ({ + context: { count: context.count + 1 } + }), + FINISH: { target: 'finished' } + } + }, + finished: { type: 'final' } + }, + output: ({ context }) => ({ count: context.count }) +}); + +type CounterSnapshot = SnapshotFrom; +type DoneCounterSnapshot = CounterSnapshot & { status: 'done' }; + +/** A type-predicate predicate, so `waitFor` narrows what it resolves with. */ +const isDone = (snapshot: CounterSnapshot): snapshot is DoneCounterSnapshot => + snapshot.status === 'done'; + +const emitterMachine = createMachine({ + initial: 'active', + states: { + active: { + on: { + PING: (_args, enq) => { + enq.emit({ type: 'pinged' }); + } + } + } + } +}); + +describe('send', () => { + it('sends an event to the actor', async () => { + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + + yield* send(actor, { type: 'INCREMENT' }); + yield* send(actor, { type: 'INCREMENT' }); + yield* waitFor(actor, (state) => state.context.count === 2); + + expect(actor.getSnapshot().context).toEqual({ count: 2 }); + }) + ); + }); + + it('accepts the data-last form', async () => { + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + + yield* send({ type: 'INCREMENT' } as const)(actor); + yield* waitFor(actor, (state) => state.context.count === 1); + + expect(actor.getSnapshot().context).toEqual({ count: 1 }); + }) + ); + }); + + it('rejects events the actor cannot receive', async () => { + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + + const sendUnknownEvent = () => + // @ts-expect-error -- the event type is derived from the actor + send(actor, { type: 'UNKNOWN' }); + + void sendUnknownEvent; + }) + ); + }); +}); + +describe('snapshots', () => { + it('emits the current snapshot, then every change, and ends on completion', async () => { + const collected = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.send({ type: 'INCREMENT' }); + actor.send({ type: 'FINISH' }); + }); + + return yield* Stream.runCollect(snapshots(actor)); + }) + ); + + expect(collected.map((snapshot) => snapshot.context.count)).toEqual([ + 0, 1, 1 + ]); + expect(collected.map((snapshot) => snapshot.status)).toEqual([ + 'active', + 'active', + 'done' + ]); + }); + + it('emits the error snapshot and ends when the actor errors', async () => { + const failure = { code: 'BOOM' as const }; + const collected = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor( + fromEffect(Effect.fail(failure).pipe(Effect.delay(10))) + ); + + return yield* Stream.runCollect(snapshots(actor)); + }) + ); + + expect(collected.map((snapshot) => snapshot.status)).toEqual([ + 'active', + 'error' + ]); + expect(collected[1].error).toEqual(failure); + }); + + it('unsubscribes from the actor when the stream is interrupted', async () => { + let unsubscribed = 0; + const collected = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + const actorSubscribe = actor.subscribe.bind(actor); + actor.subscribe = ((...args: Parameters) => { + const subscription = actorSubscribe(...args); + queueMicrotask(() => { + actor.send({ type: 'INCREMENT' }); + actor.send({ type: 'INCREMENT' }); + }); + return { + unsubscribe: () => { + unsubscribed++; + subscription.unsubscribe(); + } + }; + }) as typeof actor.subscribe; + + return yield* Stream.runCollect(snapshots(actor).pipe(Stream.take(2))); + }) + ); + + expect(collected.map((snapshot) => snapshot.context.count)).toEqual([0, 1]); + expect(unsubscribed).toBe(1); + }); +}); + +describe('emitted', () => { + it('streams emitted events and ends when the actor stops', async () => { + const collected: unknown[] = []; + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(emitterMachine); + let listening = false; + const actorOn = actor.on.bind(actor); + actor.on = ((...args: Parameters) => { + listening = true; + return actorOn(...args); + }) as typeof actor.on; + + const fiber = yield* Effect.forkScoped( + Stream.runForEach(emitted(actor), (event) => + Effect.sync(() => { + collected.push(event); + }) + ) + ); + yield* Effect.promise(() => until(() => listening)); + + actor.send({ type: 'PING' }); + actor.send({ type: 'PING' }); + yield* Effect.promise(() => until(() => collected.length === 2)); + + actor.stop(); + yield* Fiber.join(fiber); + }) + ); + + expect(collected).toEqual([{ type: 'pinged' }, { type: 'pinged' }]); + }); +}); + +describe('waitFor', () => { + it('resolves immediately when the current snapshot matches', async () => { + const snapshot = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + + return yield* waitFor(actor, (state) => state.context.count === 0); + }) + ); + + expect(snapshot.context).toEqual({ count: 0 }); + }); + + it('resolves on the first later snapshot that matches', async () => { + const snapshot = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.send({ type: 'INCREMENT' }); + actor.send({ type: 'INCREMENT' }); + }); + + return yield* waitFor(actor, (state) => state.context.count === 2); + }) + ); + + expect(snapshot.context).toEqual({ count: 2 }); + }); + + it('accepts the data-last form', async () => { + const snapshot = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.send({ type: 'INCREMENT' }); + }); + + return yield* waitFor( + (state: CounterSnapshot) => state.context.count === 1 + )(actor); + }) + ); + + expect(snapshot.context).toEqual({ count: 1 }); + }); + + it('narrows the snapshot with a type-predicate predicate', async () => { + const snapshot = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.send({ type: 'FINISH' }); + }); + + return yield* waitFor(actor, isDone); + }) + ); + + snapshot satisfies { status: 'done' }; + expect(snapshot.output).toEqual({ count: 0 }); + }); + + it('fails with ActorStoppedError when the actor stops first', async () => { + const error = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.stop(); + }); + + return yield* Effect.flip( + waitFor(actor, (state) => state.context.count === 10) + ); + }) + ); + + expect(error).toBeInstanceOf(ActorStoppedError); + expect(error.message).toMatch(/stopped before completing/); + }); + + it('fails with TimeoutError when the timeout elapses', async () => { + const error = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + + return yield* Effect.flip( + waitFor(actor, (state) => state.context.count === 10, { + timeout: Duration.millis(10) + }) + ); + }) + ); + + expect(Cause.isTimeoutError(error)).toBe(true); + }); +}); + +describe('join', () => { + it('succeeds with the actor output when it is done', async () => { + const output = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.send({ type: 'INCREMENT' }); + actor.send({ type: 'FINISH' }); + }); + + return yield* join(actor); + }) + ); + + expect(output).toEqual({ count: 1 }); + }); + + it('fails with the typed actor error', async () => { + const failure = { code: 'X' as const }; + const error = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor( + fromEffect(Effect.fail(failure).pipe(Effect.delay(10))) + ); + + return yield* Effect.flip(join(actor)); + }) + ); + + error satisfies { code: 'X' } | ActorStoppedError; + expect(error).toEqual(failure); + }); + + it('exposes machine errors as unknown and preserves the thrown value', async () => { + const failure = { code: 'MACHINE_FAILURE' }; + const machine = createMachine({ + on: { + FAIL: () => { + throw failure; + } + } + }); + const error = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + const result = join(actor); + expectTypeOf>().toEqualTypeOf(); + afterSubscribe(actor, () => actor.send({ type: 'FAIL' })); + return yield* Effect.flip(result); + }) + ); + + expect(error).toBe(failure); + }); + + it('fails with ActorStoppedError when the actor is stopped', async () => { + const error = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterSubscribe(actor, () => { + actor.stop(); + }); + + return yield* Effect.flip(join(actor)); + }) + ); + + expect(error).toBeInstanceOf(ActorStoppedError); + }); +}); + +describe('inspect', () => { + it('streams inspection events from the actor system', async () => { + const events = await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(counterMachine); + afterInspect(actor, () => { + actor.send({ type: 'INCREMENT' }); + }); + + return yield* Stream.runCollect(inspect(actor).pipe(Stream.take(1))); + }) + ); + + expect(events.map((event) => event.type)).toEqual(['@xstate.transition']); + expect(events[0]).toMatchObject({ event: { type: 'INCREMENT' } }); + }); +}); diff --git a/xstate-effect/src/actor.ts b/xstate-effect/src/actor.ts new file mode 100644 index 00000000..77143cf9 --- /dev/null +++ b/xstate-effect/src/actor.ts @@ -0,0 +1,415 @@ +import { Cause, Duration, Effect, Queue, Stream } from 'effect'; +import { dual } from 'effect/Function'; +import type { + Actor, + ActorRef, + AnyActor, + AnyActorRef, + AnyEventObject, + EmittedFrom, + EventRejection, + ErrorFrom, + InspectionEvent, + OutputFrom, + Snapshot, + SnapshotFrom, + Subscription +} from 'xstate'; +import type { EffectActor } from './effectActor.ts'; +import { ActorStoppedError } from './errors.ts'; + +/** The event type accepted by an actor's `send` method. */ +export type SendableEventFrom = Parameters< + TActor['send'] +>[0]; + +/** The event type an actor emits through `actor.on(...)`. */ +export type EmittedEventFrom = + TActor extends EffectActor + ? EmittedFrom + : TActor extends Actor + ? EmittedFrom + : TActor extends ActorRef + ? TEmitted + : AnyEventObject; + +/** Options for {@link waitFor}. */ +export interface WaitForOptions { + /** + * Fails with `Cause.TimeoutError` when no snapshot satisfies the predicate + * within this duration. + */ + readonly timeout: Duration.Input; +} + +const noopSubscription: Subscription = { unsubscribe: () => {} }; + +function actorId(actor: AnyActorRef): string { + return (actor as Partial).id ?? '(unknown)'; +} + +/** + * Marks an already-errored actor's error as observed, so XState does not + * report it as unhandled: the caller consumes it as a typed failure. + */ +function observeError(actor: AnyActorRef): void { + actor.subscribe({ error: () => {} }).unsubscribe(); +} + +function stoppedError(actor: AnyActorRef): ActorStoppedError { + return new ActorStoppedError({ + actorId: actorId(actor), + snapshot: actor.getSnapshot() + }); +} + +function isActorRef(value: unknown): value is AnyActorRef { + return ( + typeof value === 'object' && + value !== null && + typeof (value as AnyActorRef).send === 'function' && + typeof (value as AnyActorRef).getSnapshot === 'function' + ); +} + +/** + * Sends an event to an actor. The returned Effect always succeeds: the event + * is enqueued, like `actor.send(event)`, and processed on the actor's own + * fiber. An event that cannot be delivered (for example to a stopped actor) + * is reported as a dead letter, observable with {@link deadLetters}. + */ +export const send: { + ( + event: SendableEventFrom + ): (actor: TActor) => Effect.Effect; + ( + actor: TActor, + event: SendableEventFrom + ): Effect.Effect; +} = dual( + 2, + ( + actor: TActor, + event: SendableEventFrom + ): Effect.Effect => + Effect.sync(() => { + actor.send(event); + }) +); + +/** + * Streams an actor's snapshots, starting with the current one. The stream ends + * when the actor completes or stops, and emits the error snapshot before + * ending when the actor errors. Interrupting the stream unsubscribes from the + * actor. + */ +export function snapshots( + actor: TActor +): Stream.Stream> { + return Stream.callback>((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const current = actor.getSnapshot(); + Queue.offerUnsafe(queue, current); + + if (current.status !== 'active') { + observeError(actor); + Queue.endUnsafe(queue); + return noopSubscription; + } + + return actor.subscribe({ + next: (snapshot) => { + Queue.offerUnsafe(queue, snapshot); + }, + error: () => { + Queue.offerUnsafe(queue, actor.getSnapshot()); + Queue.endUnsafe(queue); + }, + complete: () => { + Queue.endUnsafe(queue); + } + }) as Subscription; + }), + (subscription) => + Effect.sync(() => { + subscription.unsubscribe(); + }) + ) + ); +} + +/** + * Streams every event an actor emits, as delivered to `actor.on('*', …)`. The + * stream ends when the actor completes, errors or stops. Interrupting the + * stream removes the listener. + */ +export function emitted( + actor: TActor +): Stream.Stream> { + return Stream.callback>((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const listener = actor.on('*', (event) => { + Queue.offerUnsafe(queue, event as EmittedEventFrom); + }); + + if (actor.getSnapshot().status !== 'active') { + Queue.endUnsafe(queue); + return [listener, noopSubscription] as const; + } + + const subscription = actor.subscribe({ + error: () => { + Queue.endUnsafe(queue); + }, + complete: () => { + Queue.endUnsafe(queue); + } + }) as Subscription; + + return [listener, subscription] as const; + }), + ([listener, subscription]) => + Effect.sync(() => { + listener.unsubscribe(); + subscription.unsubscribe(); + }) + ) + ); +} + +/** + * Waits for the first actor snapshot that satisfies `predicate`, succeeding + * immediately when the current snapshot already does. Fails with + * `ActorStoppedError` if the actor stops or errors first, and with + * `Cause.TimeoutError` when `options.timeout` elapses. Interrupting the Effect + * unsubscribes from the actor. + */ +export const waitFor: { + >( + predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed + ): (actor: TActor) => Effect.Effect; + ( + predicate: (snapshot: SnapshotFrom) => boolean + ): (actor: TActor) => Effect.Effect, ActorStoppedError>; + >( + predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed, + options: WaitForOptions + ): ( + actor: TActor + ) => Effect.Effect; + ( + predicate: (snapshot: SnapshotFrom) => boolean, + options: WaitForOptions + ): ( + actor: TActor + ) => Effect.Effect< + SnapshotFrom, + ActorStoppedError | Cause.TimeoutError + >; + >( + actor: TActor, + predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed + ): Effect.Effect; + ( + actor: TActor, + predicate: (snapshot: SnapshotFrom) => boolean + ): Effect.Effect, ActorStoppedError>; + >( + actor: TActor, + predicate: (snapshot: SnapshotFrom) => snapshot is TNarrowed, + options: WaitForOptions + ): Effect.Effect; + ( + actor: TActor, + predicate: (snapshot: SnapshotFrom) => boolean, + options: WaitForOptions + ): Effect.Effect< + SnapshotFrom, + ActorStoppedError | Cause.TimeoutError + >; +} = dual( + (args) => isActorRef(args[0]), + ( + actor: TActor, + predicate: (snapshot: SnapshotFrom) => boolean, + options?: WaitForOptions + ): Effect.Effect< + SnapshotFrom, + ActorStoppedError | Cause.TimeoutError + > => { + const waiting = Effect.callback, ActorStoppedError>( + (resume) => { + const current: Snapshot = actor.getSnapshot(); + + if (predicate(current as SnapshotFrom)) { + resume(Effect.succeed(current as SnapshotFrom)); + return; + } + + if (current.status !== 'active') { + observeError(actor); + resume(Effect.fail(stoppedError(actor))); + return; + } + + let settled = false; + // oxlint-disable-next-line prefer-const + let subscription: Subscription | undefined; // avoid TDZ when settling synchronously + const dispose = () => { + settled = true; + subscription?.unsubscribe(); + }; + + subscription = actor.subscribe({ + next: (snapshot: SnapshotFrom) => { + if (settled || !predicate(snapshot)) { + return; + } + dispose(); + resume(Effect.succeed(snapshot)); + }, + error: () => { + if (settled) { + return; + } + dispose(); + resume(Effect.fail(stoppedError(actor))); + }, + complete: () => { + if (settled) { + return; + } + dispose(); + resume(Effect.fail(stoppedError(actor))); + } + }) as Subscription; + + if (settled) { + subscription.unsubscribe(); + } + + return Effect.sync(dispose); + } + ); + + return options === undefined + ? waiting + : Effect.timeout(waiting, options.timeout); + } +); + +/** + * Joins an actor's final result, like `Fiber.join`: succeeds with its `output` + * when it is done, fails with `snapshot.error` when it errors, and fails with + * `ActorStoppedError` when it stops without output. Waits for a still-active + * actor to settle. + */ +export function join( + actor: TActor +): Effect.Effect, ErrorFrom | ActorStoppedError> { + return Effect.callback< + OutputFrom, + ErrorFrom | ActorStoppedError + >((resume) => { + const settle = () => { + const snapshot = actor.getSnapshot(); + if (snapshot.status === 'done') { + resume(Effect.succeed(snapshot.output as OutputFrom)); + } else if (snapshot.status === 'error') { + resume(Effect.fail(snapshot.error as ErrorFrom)); + } else { + resume(Effect.fail(stoppedError(actor))); + } + }; + + if (actor.getSnapshot().status !== 'active') { + observeError(actor); + settle(); + return; + } + + let settled = false; + // oxlint-disable-next-line prefer-const + let subscription: Subscription | undefined; // avoid TDZ when settling synchronously + const dispose = () => { + settled = true; + subscription?.unsubscribe(); + }; + const onSettled = () => { + if (settled) { + return; + } + dispose(); + settle(); + }; + + subscription = actor.subscribe({ + error: onSettled, + complete: onSettled + }) as Subscription; + + if (settled) { + subscription.unsubscribe(); + } + + return Effect.sync(dispose); + }); +} + +/** + * Streams the inspection events of the actor's system, as delivered to + * `system.inspect(…)`. The stream runs until it is interrupted or its scope + * closes. + */ +export function inspect(actor: AnyActorRef): Stream.Stream { + return Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => { + const observer: (inspectionEvent: InspectionEvent) => void = ( + inspectionEvent + ) => { + Queue.offerUnsafe(queue, inspectionEvent); + }; + const inspectable = actor as { + inspect?: ( + observer: (inspectionEvent: InspectionEvent) => void + ) => Subscription; + }; + return inspectable.inspect + ? inspectable.inspect(observer) + : (actor as unknown as AnyActor).system.inspect(observer); + }), + (subscription) => + Effect.sync(() => { + subscription.unsubscribe(); + }) + ) + ); +} + +/** + * Streams the events the actor's system could not deliver, as reported by + * `system.onRejectedEvent`: sends to a stopped actor, invalid external + * events and internal events sent from outside their owner. A dead letter is + * not an actor error. The stream runs until it is interrupted or its scope + * closes. + */ +export function deadLetters(actor: AnyActorRef): Stream.Stream { + return Stream.callback((queue) => + Effect.acquireRelease( + Effect.sync(() => + (actor as unknown as AnyActor).system.onRejectedEvent( + (rejection: EventRejection) => { + Queue.offerUnsafe(queue, rejection); + } + ) + ), + (subscription) => + Effect.sync(() => { + subscription.unsubscribe(); + }) + ) + ); +} diff --git a/xstate-effect/src/actorScope.ts b/xstate-effect/src/actorScope.ts new file mode 100644 index 00000000..6892125f --- /dev/null +++ b/xstate-effect/src/actorScope.ts @@ -0,0 +1,16 @@ +import { Context, Effect, Scope } from 'effect'; + +/** The owning Effect actor's scope, supplied by `createEffectActor`. */ +export class ActorScope extends Context.Service()( + '@xstate/effect/ActorScope' +) {} + +/** + * Acquires resources in the owning actor's scope. Their finalizers run when + * that actor stops, even if the invoking task finishes or is cancelled first. + */ +export function withActorScope( + effect: Effect.Effect +): Effect.Effect | ActorScope> { + return ActorScope.use((scope) => Scope.provide(effect, scope)); +} diff --git a/xstate-effect/src/atom.test.ts b/xstate-effect/src/atom.test.ts new file mode 100644 index 00000000..35d5b3b9 --- /dev/null +++ b/xstate-effect/src/atom.test.ts @@ -0,0 +1,264 @@ +import { Cause, Context, Effect, Layer, Schema } from 'effect'; +import { AsyncResult, Atom, AtomRegistry } from 'effect/reactivity'; +import { createMachine, setup } from 'xstate'; +import { createActorAtoms } from './atom.ts'; +import { fromEffect, setupEffect, withActorScope } from './index.ts'; +import { NotReadyError } from './atom.ts'; + +const until = async (predicate: () => boolean, timeoutMs = 1000) => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 1)); + } +}; + +const counterMachine = createMachine({ + context: { count: 0 }, + on: { + INC: ({ context }) => ({ context: { count: context.count + 1 } }) + } +}); + +describe('createActorAtoms', () => { + it.each(['invocation', 'actor'] as const)( + 'provides the %s resource scope', + async (lifetime) => { + let released = false; + const acquire = Effect.acquireRelease(Effect.succeed('resource'), () => + Effect.sync(() => { + released = true; + }) + ); + const logic = + lifetime === 'actor' + ? fromEffect(acquire.pipe(withActorScope)) + : fromEffect(acquire); + const registry = AtomRegistry.make(); + const atoms = createActorAtoms(Atom.runtime(Layer.empty), logic); + const unmount = registry.mount(atoms.snapshot); + try { + await until(() => { + const snapshot = registry.get(atoms.snapshot); + return ( + released && + AsyncResult.isSuccess(snapshot) && + snapshot.value.status === 'done' + ); + }); + const snapshot = registry.get(atoms.snapshot); + expect(AsyncResult.isSuccess(snapshot) && snapshot.value.output).toBe( + 'resource' + ); + } finally { + unmount(); + registry.dispose(); + } + } + ); + + it('requires and passes the input declared by the logic', async () => { + const logic = fromEffect({ + schemas: { input: Schema.Struct({ id: Schema.String }) }, + effect: ({ input }) => Effect.succeed(input.id) + }); + const runtime = Atom.runtime(Layer.empty); + const invalid = () => { + // @ts-expect-error -- required input cannot be omitted + createActorAtoms(runtime, logic); + // @ts-expect-error -- the options must contain input + createActorAtoms(runtime, logic, {}); + // @ts-expect-error -- input must match the schema + createActorAtoms(runtime, logic, { input: { id: 1 } }); + }; + void invalid; + const registry = AtomRegistry.make(); + const atoms = createActorAtoms(runtime, logic, { + input: { id: 'release' } + }); + const unmount = registry.mount(atoms.snapshot); + try { + await until(() => { + const result = registry.get(atoms.snapshot); + return AsyncResult.isSuccess(result) && result.value.status === 'done'; + }); + const result = registry.get(atoms.snapshot); + expect(AsyncResult.isSuccess(result) && result.value.output).toBe( + 'release' + ); + } finally { + unmount(); + } + }); + + it('starts the actor on first read and exposes its snapshot', async () => { + const registry = AtomRegistry.make(); + const runtime = Atom.runtime(Layer.empty); + const atoms = createActorAtoms(runtime, counterMachine); + + const unmount = registry.mount(atoms.snapshot); + await until(() => AsyncResult.isSuccess(registry.get(atoms.snapshot))); + + const snapshot = registry.get(atoms.snapshot); + expect(AsyncResult.isSuccess(snapshot) && snapshot.value.context).toEqual({ + count: 0 + }); + unmount(); + }); + + it('sends events through the send atom and updates the snapshot', async () => { + const registry = AtomRegistry.make(); + const runtime = Atom.runtime(Layer.empty); + const atoms = createActorAtoms(runtime, counterMachine); + const counts: number[] = []; + + const unsubscribe = registry.subscribe( + atoms.select((snapshot) => snapshot.context.count), + (result) => { + if (AsyncResult.isSuccess(result)) { + counts.push(result.value); + } + }, + { immediate: true } + ); + await until(() => counts.length > 0); + + registry.set(atoms.send, { type: 'INC' }); + registry.set(atoms.send, { type: 'INC' }); + await until(() => counts.at(-1) === 2); + + expect(counts).toEqual([0, 1, 2]); + unsubscribe(); + }); + + it('runs Effect logic with services from the runtime layer', async () => { + class Greeting extends Context.Service()( + 'Greeting' + ) {} + const greet = fromEffect( + Greeting.use((greeting) => Effect.succeed(greeting.value)) + ); + const machine = setup({ actors: { greet } }).createMachine({ + context: { greeting: '' }, + initial: 'loading', + states: { + loading: { + invoke: { + src: 'greet', + onDone: { + target: 'done', + context: ({ event }) => ({ greeting: event.output }) + } + } + }, + done: {} + } + }); + const registry = AtomRegistry.make(); + const runtime = Atom.runtime(Layer.succeed(Greeting, { value: 'hello' })); + const atoms = createActorAtoms(runtime, machine); + + const unmount = registry.mount(atoms.snapshot); + await until(() => { + const result = registry.get(atoms.snapshot); + return AsyncResult.isSuccess(result) && result.value.value === 'done'; + }); + + const result = registry.get(atoms.snapshot); + expect(AsyncResult.isSuccess(result) && result.value.context).toEqual({ + greeting: 'hello' + }); + unmount(); + }); + + it('rejects a runtime that does not provide a required service', () => { + class Greeting extends Context.Service()( + 'Greeting' + ) {} + const machine = setupEffect({ + actions: { + greet: (_args) => Greeting.use(() => Effect.void) + } + }).createMachine({ + on: { GREET: (args, enq) => enq(args.actions.greet, args) } + }); + const runtime = Atom.runtime(Layer.empty); + + const create = () => { + // @ts-expect-error -- the runtime layer does not provide Greeting + createActorAtoms(runtime, machine); + }; + void create; + }); + + it('stops the actor when its atoms are released', async () => { + const registry = AtomRegistry.make(); + const runtime = Atom.runtime(Layer.empty); + const atoms = createActorAtoms(runtime, counterMachine); + + const unmount = registry.mount(atoms.snapshot); + await until(() => AsyncResult.isSuccess(registry.get(atoms.actor))); + const result = registry.get(atoms.actor); + const actor = AsyncResult.isSuccess(result) ? result.value : undefined; + expect(actor?.getSnapshot().status).toBe('active'); + + unmount(); + await until(() => actor?.getSnapshot().status === 'stopped'); + + expect(actor?.getSnapshot().status).toBe('stopped'); + }); + + it('reports NotReadyError when an event is sent before the runtime is ready', async () => { + class Slow extends Context.Service()('Slow') {} + const registry = AtomRegistry.make(); + const runtime = Atom.runtime( + Layer.effect( + Slow, + Effect.delay(Effect.succeed({ ready: true as const }), '5 millis') + ) + ); + const atoms = createActorAtoms(runtime, counterMachine); + + const unmount = registry.mount(atoms.send); + registry.set(atoms.send, { type: 'INC' }); + const early = registry.get(atoms.send); + expect(AsyncResult.isFailure(early)).toBe(true); + expect( + AsyncResult.isFailure(early) && Cause.squash(early.cause) + ).toBeInstanceOf(NotReadyError); + + await until(() => AsyncResult.isSuccess(registry.get(atoms.actor))); + registry.set(atoms.send, { type: 'INC' }); + const late = registry.get(atoms.actor); + await until( + () => + AsyncResult.isSuccess(late) && + late.value.getSnapshot().context.count === 1 + ); + expect( + AsyncResult.isSuccess(late) && late.value.getSnapshot().context + ).toEqual({ + count: 1 + }); + expect(AsyncResult.isSuccess(registry.get(atoms.send))).toBe(true); + unmount(); + }); + + it('exposes an errored actor as a failed result', async () => { + const failure = { code: 'BOOM' as const }; + const registry = AtomRegistry.make(); + const runtime = Atom.runtime(Layer.empty); + const atoms = createActorAtoms(runtime, fromEffect(Effect.fail(failure))); + + const unmount = registry.mount(atoms.result); + await until(() => AsyncResult.isFailure(registry.get(atoms.result))); + + const result = registry.get(atoms.result); + expect(AsyncResult.isFailure(result) && Cause.squash(result.cause)).toEqual( + failure + ); + unmount(); + }); +}); diff --git a/xstate-effect/src/atom.ts b/xstate-effect/src/atom.ts new file mode 100644 index 00000000..81acc61b --- /dev/null +++ b/xstate-effect/src/atom.ts @@ -0,0 +1,176 @@ +import { Cause, type Effect } from 'effect'; +import { AsyncResult, Atom } from 'effect/reactivity'; +import type { + AnyActorLogic, + ErrorFrom, + EventFromLogic, + Snapshot, + SnapshotFrom +} from 'xstate'; +import { + createEffectActor, + type EffectActorOptionsArgs +} from './createEffectActor.ts'; +import type { EffectActor } from './effectActor.ts'; +import { NotReadyError } from './errors.ts'; +import { taggedState, type TaggedStateFrom } from './state.ts'; +import type { RequirementsFrom } from './types.ts'; + +export { NotReadyError } from './errors.ts'; + +/** + * Atoms that expose one actor to a reactive UI through + * `effect/reactivity`. Read them with the atom bindings for your + * framework, such as `@effect/atom-react`. + */ +export interface ActorAtoms { + /** + * The running actor. It starts when the atom is first read and stops when + * the atom is released, that is, when nothing reads or mounts it anymore. + */ + readonly actor: Atom.Atom, ER>>; + /** The actor's current snapshot, updated on every transition. */ + readonly snapshot: Atom.Atom< + AsyncResult.AsyncResult, ER> + >; + /** + * The snapshot as a result: a `Failure` carrying the actor's error once + * the actor's status is `error`, so an error boundary can handle it. + */ + readonly result: Atom.Atom< + AsyncResult.AsyncResult, ER | ErrorFrom> + >; + /** + * Sends an event to the actor synchronously. Set it with the event, for + * example through `useAtomSet` in React. Its value reports the last send: + * a `NotReadyError` failure when the runtime is still building, otherwise + * success. + */ + readonly send: Atom.Writable< + AsyncResult.AsyncResult, + EventFromLogic + >; + /** Derives an atom of a value selected from the snapshot. */ + readonly select: ( + selector: (snapshot: SnapshotFrom) => T + ) => Atom.Atom>; + /** + * The snapshot as a tagged union over the machine's states, for + * `Match.tag` or a `switch` on `_tag`. See `taggedState`. + */ + readonly state: Atom.Atom< + AsyncResult.AsyncResult>, ER> + >; +} + +interface MissingRequirements { + readonly 'The runtime does not provide services the logic requires': T; +} + +/** + * Creates atoms for an actor that runs in an `Atom.runtime`. The runtime's + * Layer must provide every service the logic requires; a missing service is + * a type error on the `runtime` argument. Logic with required input also + * requires an options object containing that input. + * + * The actor is created with `createEffectActor` inside the `actor` atom's + * scope, so its lifetime follows the atom: it starts on first read and stops + * when the atom is released. Wrap the atoms with `Atom.keepAlive` to pin the + * actor for the registry's lifetime, or with `Atom.family` to create one + * actor per input. + */ +export function createActorAtoms( + runtime: Atom.AtomRuntime & + ([RequirementsFrom] extends [R] + ? unknown + : MissingRequirements, R>>), + logic: TLogic, + ...[options]: EffectActorOptionsArgs +): ActorAtoms { + const host = runtime as Atom.AtomRuntime; + + const actor = host.atom( + createEffectActor(logic, options as never) as unknown as Effect.Effect< + EffectActor, + never + > + ); + + const snapshot = Atom.make( + (get): AsyncResult.AsyncResult, ER> => { + const result = get(actor); + if (!AsyncResult.isSuccess(result)) { + return AsyncResult.map(result, (running) => running.getSnapshot()); + } + const running = result.value; + const publish = () => { + get.setSelf(AsyncResult.success(running.getSnapshot())); + }; + // The atom is the consumer of the actor's error: `result` reports it, + // so the observer handles `error` and XState does not report it as + // unhandled. + const subscription = running.subscribe({ + next: publish, + error: publish, + complete: publish + }); + get.addFinalizer(() => { + subscription.unsubscribe(); + }); + return AsyncResult.success(running.getSnapshot()); + } + ); + + const result = Atom.make( + ( + get + ): AsyncResult.AsyncResult< + SnapshotFrom, + ER | ErrorFrom + > => { + const current = get(snapshot); + if (!AsyncResult.isSuccess(current)) { + return current; + } + const value = current.value as Snapshot; + if (value.status === 'error') { + return AsyncResult.failureWithPrevious( + Cause.fail(value.error as ErrorFrom), + { previous: get.self() } + ); + } + return current; + } + ); + + const sendAtom = Atom.writable< + AsyncResult.AsyncResult, + EventFromLogic + >( + (get) => AsyncResult.map(get(actor), () => undefined), + (ctx, event) => { + const current = ctx.get(actor); + if (AsyncResult.isInitial(current)) { + ctx.setSelf(AsyncResult.failure(Cause.fail(new NotReadyError()))); + } else if (AsyncResult.isFailure(current)) { + ctx.setSelf(AsyncResult.map(current, () => undefined)); + } else { + current.value.send(event); + ctx.setSelf(AsyncResult.success(undefined)); + } + } + ); + + function select( + selector: (snapshot: SnapshotFrom) => T + ): Atom.Atom> { + return Atom.map(snapshot, (result) => AsyncResult.map(result, selector)); + } + + const state = select( + (current) => + taggedState(current as never) as TaggedStateFrom> + ); + + return { actor, snapshot, result, send: sendAtom, select, state }; +} diff --git a/xstate-effect/src/brands.ts b/xstate-effect/src/brands.ts new file mode 100644 index 00000000..78ffb978 --- /dev/null +++ b/xstate-effect/src/brands.ts @@ -0,0 +1,3 @@ +export const effectActionBrand: unique symbol = Symbol.for( + '@xstate/effect/action' +) as any; diff --git a/xstate-effect/src/createEffectActor.ts b/xstate-effect/src/createEffectActor.ts new file mode 100644 index 00000000..5c70e289 --- /dev/null +++ b/xstate-effect/src/createEffectActor.ts @@ -0,0 +1,407 @@ +import { + Clock, + Context, + Duration, + Effect, + Exit, + Fiber, + Queue, + Scope +} from 'effect'; +import { + deliverEvent, + isMachineSnapshot, + stopActor, + terminateActor, + type ActorOptions, + type AnyActor, + type AnyActorLogic, + type AnyEventObject, + type EventFromLogic, + type InspectionEvent, + type InputFrom, + type RequiredActorOptionsFor, + type RequiredActorOptionsKeys, + type Snapshot, + type SnapshotFrom +} from 'xstate'; +import { createDurable, type DurableEffect } from 'xstate/durable'; +import { + EffectActor, + actionFailure, + isActionFailure, + safeCall, + type MailboxItem +} from './effectActor.ts'; +import { + bindEffectHost, + closeEffectHost, + createEffectHost, + withEffectHost, + type EffectHost +} from './internal.ts'; +import type { RequirementsFrom } from './types.ts'; +import { ActorScope } from './actorScope.ts'; + +const XSTATE_TIMER = 'xstate.timer'; +const XSTATE_INIT = '@xstate.init'; + +/** Options for {@link createEffectActor}. */ +export type EffectActorOptions = { + readonly input?: InputFrom; + /** + * A snapshot from `actor.getPersistedSnapshot()`. The actor resumes in that + * state without re-running entry actions, and pending timers keep their + * original deadlines, as with XState's `createActor(logic, { snapshot })`. + * State-machine children resume their persisted state and completed + * children stay done. Effect tasks and streams that were running, at the + * root or as children, start again from the beginning. A restored actor + * does not need `input`. + */ + readonly snapshot?: ActorOptions['snapshot']; +} & RequiredActorOptionsFor; + +export type EffectActorOptionsArgs = [ + RequiredActorOptionsKeys +] extends [never] + ? [options?: EffectActorOptions] + : [options: EffectActorOptions]; + +/** + * Creates and starts an actor as an Effect interpreter over pure transitions. + * + * Each step is `transition(snapshot, event)`, a pure function that returns + * the next snapshot and the actions to run. An Effect fiber owns the loop: + * the mailbox is a `Queue`, timers are `Effect.sleep` fibers on the Effect + * `Clock`, and declared Effect actions run as forked Effects in the actor's + * `Scope` with the services captured here. Child actors are started as live + * XState actors whose Effects run in the same host. + * + * The actor is a scoped resource: it stops, and every Effect it hosts is + * interrupted, when the enclosing `Scope` closes. The returned Effect never + * fails; the actor's own outcome is its snapshot status, read with `join`. + */ +export function createEffectActor( + logic: TLogic, + ...[options]: EffectActorOptionsArgs +): Effect.Effect< + EffectActor, + never, + RequirementsFrom | Scope.Scope +> { + return Effect.acquireRelease( + Effect.gen(function* () { + const parentScope = yield* Effect.scope; + const actorScope = yield* Scope.fork(parentScope); + const baseContext = yield* Effect.context(); + const context = Context.add( + Context.add(baseContext, Scope.Scope, actorScope), + ActorScope, + actorScope + ); + const host = createEffectHost(context, actorScope); + const runFork = Effect.runForkWith(context); + const runPromise = Effect.runPromiseWith(context); + + const mailbox = + yield* Queue.unbounded>>(); + const timers = new Map>(); + // `root` and `actor` are declared after the adapter below; its + // callbacks only run once they are initialized. + let stopped = false; + const isRoot = (candidate: AnyActor) => + candidate.address === durable.rootAddress; + + const offer = (item: MailboxItem>) => { + if (!stopped) { + Queue.offerUnsafe(mailbox, item); + } + }; + const timerKey = (source: AnyActor, id: string) => + `${source.sessionId}:${id}`; + + const inspectors = new Set<(event: InspectionEvent) => void>(); + let rootAnnounced = false; + const clock = Context.get(context, Clock.Clock); + const durable = createDurable( + logic, + { + // Timer deadlines are measured on the same clock the timers sleep + // on, so a restored timer resumes with its remaining delay. + now: () => clock.currentTimeMillisUnsafe(), + executeAction: (action, _metadata, runtime) => { + // Fire-and-forget: the action starts now and the loop continues. + // A rejection reaches the machine as an execution error. + try { + const result = withEffectHost(host, () => action.exec(runtime)); + if ( + result && + typeof (result as PromiseLike).then === 'function' + ) { + void Promise.resolve(result).catch((error: unknown) => { + offer({ [actionFailure]: true, error }); + }); + } + } catch (error) { + offer({ [actionFailure]: true, error }); + } + }, + spawnActor: (_source, child) => { + // Every actor of this execution hosts its Effects here. + bindEffectHost(child, host); + }, + startActor: (child) => { + child.start(); + }, + stopActor: (child) => { + if (!isRoot(child)) { + stopActor(child); + } + }, + terminateActor: (child, termination) => { + if (!isRoot(child)) { + terminateActor(child, termination); + } + }, + sendEvent: (source, target, event) => { + if (isRoot(target)) { + offer(event as EventFromLogic); + return; + } + deliverEvent(source, target, event); + }, + emitEvent: (source, event) => { + if (isRoot(source)) { + actor._emit(event as never); + return; + } + (source as AnyActor & { _emit(value: unknown): void })._emit(event); + }, + scheduleTimer: (source, id, delay) => { + const key = timerKey(source, id); + timers.get(key)?.interruptUnsafe(); + const fiber = Fiber.runIn( + runFork( + Effect.andThen( + Effect.sleep(Duration.millis(delay)), + Effect.sync(() => { + timers.delete(key); + const timerEvent: AnyEventObject = { + type: XSTATE_TIMER, + id + }; + if (isRoot(source)) { + offer(timerEvent as EventFromLogic); + } else { + deliverEvent(source, source, timerEvent); + } + }) + ) + ), + actorScope + ); + timers.set(key, fiber); + }, + cancelTimer: (source, id) => { + const key = timerKey(source, id); + timers.get(key)?.interruptUnsafe(); + timers.delete(key); + }, + cancelAllTimers: (source) => { + for (const [key, fiber] of timers) { + if (key.startsWith(`${source.sessionId}:`)) { + fiber.interruptUnsafe(); + timers.delete(key); + } + } + }, + waitForEvent: () => + runPromise(Queue.take(mailbox)) as Promise> + }, + { + inspect: (event) => { + // The pure step scope re-materializes the root ref per step and + // announces it again; observers should see the root once. + if ( + event.type === '@xstate.actor' && + (event.actorRef as AnyActor).address === durable.rootAddress + ) { + if (rootAnnounced) { + return; + } + rootAnnounced = true; + } + for (const inspector of inspectors) { + safeCall(inspector, event); + } + } + } + ); + + const errorSnapshot = ( + snapshot: SnapshotFrom, + error: unknown + ): SnapshotFrom => + ({ + ...(snapshot as Snapshot), + status: 'error', + error + }) as SnapshotFrom; + + const stopChildren = (snapshot: SnapshotFrom) => { + const children = ( + snapshot as { children?: Record } + ).children; + for (const child of Object.values(children ?? {})) { + if (child && !isRoot(child)) { + stopActor(child); + } + } + }; + + const stop = () => { + if (stopped) { + return; + } + stopped = true; + for (const fiber of timers.values()) { + fiber.interruptUnsafe(); + } + timers.clear(); + const current = actor.getSnapshot(); + if (current) { + stopChildren(current); + } + runFork(Queue.shutdown(mailbox)); + if (!actor._isSettled) { + actor._settle({ + ...(actor.getSnapshot() as Snapshot), + status: 'stopped' + } as SnapshotFrom); + } + closeEffectHost(host); + }; + + // The first transition (or the restore) runs here so the handle is + // ready when this Effect succeeds, and the initial actions start before + // any send. Restoring runs no entry actions; its effects resume + // machine children, restart running Effect children and re-arm pending + // timers. + let [snapshot, effects] = options?.snapshot + ? durable.restore(options.snapshot) + : durable.initialTransition(options?.input as never); + const initial: Snapshot = snapshot; + if ( + options?.snapshot && + !isMachineSnapshot(initial) && + initial.status === 'active' + ) { + // A restored machine resumes through the effects above. Other logic + // (an Effect task or stream at the root) reattaches its active work by + // replaying its init event, as its restored `start` does under + // `createActor`. + const [started, startEffects] = durable.transition(snapshot, { + type: XSTATE_INIT, + input: 'input' in initial ? initial.input : undefined + } as EventFromLogic); + snapshot = started; + effects = [...effects, ...startEffects]; + } + const root = durable.getActorRef(snapshot)!; + // Restored children are created by the snapshot, not spawned through + // the adapter; they find this host through their parent chain. + bindEffectHost(root, host); + // The root exists from here on; later announcements are step + // re-materializations, not new actors. + rootAnnounced = true; + const actor = new EffectActor( + logic, + root!, + snapshot, + mailbox, + stop, + inspectors + ); + bindEffectHost(actor, host); + + const executeEffects = ( + batch: DurableEffect[] + ): Effect.Effect => + Effect.promise(() => + durable.executeEffects(batch).then( + () => undefined, + (error: unknown) => { + offer({ [actionFailure]: true, error }); + } + ) + ); + + const loop = Effect.gen(function* () { + yield* executeEffects(effects); + while ( + (snapshot as Snapshot).status === 'active' && + !stopped + ) { + const item = yield* Effect.promise(() => + durable.waitForEvent().then( + (event) => event as MailboxItem>, + () => undefined + ) + ); + if (item === undefined || stopped) { + break; + } + let event: EventFromLogic; + if (isActionFailure(item)) { + const errorEvent = ( + logic as { + getExecutionErrorEvent?: ( + snapshot: SnapshotFrom, + error: unknown + ) => EventFromLogic | undefined; + } + ).getExecutionErrorEvent?.(snapshot, item.error); + if (!errorEvent) { + snapshot = errorSnapshot(snapshot, item.error); + break; + } + event = errorEvent; + } else { + event = item; + } + try { + [snapshot, effects] = durable.transition(snapshot, event); + } catch (error) { + snapshot = errorSnapshot(snapshot, error); + break; + } + actor._publish(snapshot); + yield* executeEffects(effects); + } + if (!stopped) { + actor._publish(snapshot); + if ((snapshot as Snapshot).status !== 'active') { + stopChildren(snapshot); + closeEffectHost(host); + } + } + }); + + yield* Effect.forkIn(loop, actorScope); + return { actor, host }; + }), + ({ actor, host }: { actor: EffectActor; host: EffectHost }) => + Effect.gen(function* () { + actor.stop(); + if (host.closing) { + yield* Fiber.join(host.closing); + } else { + yield* Scope.close(host.scope, Exit.void); + } + }) + ).pipe(Effect.map(({ actor }) => actor)) as unknown as Effect.Effect< + EffectActor, + never, + RequirementsFrom | Scope.Scope + >; +} diff --git a/xstate-effect/src/effectActor.ts b/xstate-effect/src/effectActor.ts new file mode 100644 index 00000000..2c1f365a --- /dev/null +++ b/xstate-effect/src/effectActor.ts @@ -0,0 +1,265 @@ +import { Queue } from 'effect'; +import type { + ActorRef, + AnyActor, + AnyActorLogic, + EmittedFrom, + EventFromLogic, + InspectionEvent, + Observer, + Snapshot, + SnapshotFrom, + Subscription +} from 'xstate'; + +/** A mailbox item that reports a failed fire-and-forget action. */ +export interface ActionFailure { + readonly [actionFailure]: true; + readonly error: unknown; +} + +export const actionFailure: unique symbol = Symbol.for( + '@xstate/effect/actionFailure' +) as any; + +export function isActionFailure(value: unknown): value is ActionFailure { + return typeof value === 'object' && value !== null && actionFailure in value; +} + +export type MailboxItem = TEvent | ActionFailure; + +const symbolObservable: typeof Symbol.observable = (() => + (typeof Symbol === 'function' && Symbol.observable) || + '@@observable')() as any; + +/** + * Calls a listener and reports an exception it throws without letting it + * escape into the interpreter, matching core's `safeCall`. + */ +export function safeCall(fn: ((arg: T) => void) | undefined, arg?: T) { + try { + fn?.(arg as T); + } catch (err) { + setTimeout(() => { + throw err; + }); + } +} + +function toObserver( + nextHandler?: Observer | ((value: T) => void), + errorHandler?: (error: any) => void, + completionHandler?: () => void +): Observer { + if (typeof nextHandler === 'object') { + return nextHandler; + } + return { + next: nextHandler, + error: errorHandler, + complete: completionHandler + }; +} + +/** + * The handle `createEffectActor` returns. It implements XState's `ActorRef` + * contract (`send`, `getSnapshot`, `subscribe`, `on`), so it works with + * `useSelector`, this package's actor functions and the inspection APIs, while + * the actor itself is driven by an Effect fiber over pure transitions. + */ +export class EffectActor implements ActorRef< + SnapshotFrom, + EventFromLogic, + EmittedFrom +> { + readonly id: string; + readonly address: string; + readonly sessionId: string | undefined; + /** The actor system that hosts this actor and its children. */ + readonly system: AnyActor['system']; + /** @internal */ + readonly _root: AnyActor; + + private _snapshot: SnapshotFrom; + private readonly _observers = new Set>>(); + private readonly _listeners = new Map< + string, + Set<(emitted: EmittedFrom) => void> + >(); + private _settled = false; + + constructor( + readonly logic: TLogic, + root: AnyActor, + snapshot: SnapshotFrom, + private readonly _mailbox: Queue.Queue>>, + private readonly _stopExecution: () => void, + private readonly _inspectors: Set<(event: InspectionEvent) => void> + ) { + this._root = root; + this.id = root.id; + this.address = root.address; + this.sessionId = root.sessionId; + this.system = root.system; + this._snapshot = snapshot; + } + + getSnapshot(): SnapshotFrom { + return this._snapshot; + } + + getPersistedSnapshot(): Snapshot { + return this.logic.getPersistedSnapshot(this._snapshot as never); + } + + /** Sends an event; the actor processes it on its own fiber. */ + send(event: EventFromLogic): void { + if (this._settled) { + this.system.deadLetter(undefined, this._root, event, 'stopped'); + return; + } + Queue.offerUnsafe(this._mailbox, event); + } + + /** Stops the actor, its children and every Effect it hosts. */ + stop(): this { + this._stopExecution(); + return this; + } + + subscribe(observer: Observer>): Subscription; + subscribe( + nextListener?: (snapshot: SnapshotFrom) => void, + errorListener?: (error: any) => void, + completeListener?: () => void + ): Subscription; + subscribe( + nextListenerOrObserver?: + | ((snapshot: SnapshotFrom) => void) + | Observer>, + errorListener?: (error: any) => void, + completeListener?: () => void + ): Subscription { + const observer = toObserver( + nextListenerOrObserver, + errorListener, + completeListener + ); + if (this._settled) { + const snapshot = this._snapshot as Snapshot; + if (snapshot.status === 'error') { + safeCall(observer.error, snapshot.error); + } else { + safeCall(observer.complete); + } + return { unsubscribe: () => {} }; + } + this._observers.add(observer); + return { + unsubscribe: () => { + this._observers.delete(observer); + } + }; + } + + on['type'] | '*'>( + type: TType, + handler: ( + emitted: EmittedFrom & + (TType extends '*' ? unknown : { type: TType }) + ) => void + ): Subscription { + let listeners = this._listeners.get(type); + if (!listeners) { + listeners = new Set(); + this._listeners.set(type, listeners); + } + const listener = handler as (emitted: EmittedFrom) => void; + listeners.add(listener); + return { + unsubscribe: () => { + listeners.delete(listener); + } + }; + } + + /** @internal Delivers an emitted event to `on` listeners. */ + _emit(event: EmittedFrom): void { + const listeners = [ + ...(this._listeners.get(event.type) ?? []), + ...(this._listeners.get('*') ?? []) + ]; + for (const listener of listeners) { + safeCall(listener, event); + } + } + + /** + * Observes the inspection events of this actor and its children: every + * actor creation and transition of the execution. + */ + inspect( + observer: Observer | ((event: InspectionEvent) => void) + ): Subscription { + const handler = + typeof observer === 'function' + ? observer + : (event: InspectionEvent) => observer.next?.(event); + this._inspectors.add(handler); + return { + unsubscribe: () => { + this._inspectors.delete(handler); + } + }; + } + + [symbolObservable]() { + return this; + } + + toJSON() { + return { xstate$$type: 1, id: this.id }; + } + + /** @internal Publishes a snapshot produced by the execution loop. */ + _publish(snapshot: SnapshotFrom): void { + this._snapshot = snapshot; + const status = (snapshot as Snapshot).status; + if (status === 'active') { + for (const observer of this._observers) { + safeCall(observer.next, snapshot); + } + return; + } + this._settle(snapshot); + } + + /** @internal Marks the actor stopped and notifies observers. */ + _settle(snapshot: SnapshotFrom): void { + if (this._settled) { + return; + } + this._snapshot = snapshot; + this._settled = true; + const observers = [...this._observers]; + this._observers.clear(); + const status = (snapshot as Snapshot).status; + if (status === 'done') { + for (const observer of observers) { + safeCall(observer.next, snapshot); + } + } + for (const observer of observers) { + if (status === 'error') { + safeCall(observer.error, (snapshot as Snapshot).error); + } else { + safeCall(observer.complete); + } + } + } + + /** @internal */ + get _isSettled(): boolean { + return this._settled; + } +} diff --git a/xstate-effect/src/errors.ts b/xstate-effect/src/errors.ts new file mode 100644 index 00000000..df35b319 --- /dev/null +++ b/xstate-effect/src/errors.ts @@ -0,0 +1,43 @@ +import { Cause, Data } from 'effect'; +import type { Snapshot } from 'xstate'; + +/** + * The failure an Effect-backed actor reports when its Effect was interrupted + * by something other than the actor being stopped, such as `Effect.interrupt`, + * losing an `Effect.race`, or an `Effect.timeout` that interrupts. + */ +export class EffectInterruptedError extends Data.TaggedError( + 'EffectInterruptedError' +)<{ + readonly cause: Cause.Cause; +}> { + override get message(): string { + return 'Effect was interrupted before the actor completed'; + } +} + +/** + * Reported by `waitFor` when the actor stops or errors before a snapshot + * matches, and by `join` when the actor stops without output. `join` reports + * an errored actor's own `snapshot.error` instead. + */ +export class ActorStoppedError extends Data.TaggedError('ActorStoppedError')<{ + readonly actorId: string; + readonly snapshot: Snapshot; +}> { + override get message(): string { + return `Actor "${this.actorId}" ${ + this.snapshot.status === 'error' ? 'errored' : 'stopped' + } before completing`; + } +} + +/** + * Reported by the `send` atom of `createActorAtoms` when an event is sent + * before the actor's runtime has finished building. + */ +export class NotReadyError extends Data.TaggedError('NotReadyError') { + override get message(): string { + return 'The actor is not ready yet'; + } +} diff --git a/xstate-effect/src/fromEffect.ts b/xstate-effect/src/fromEffect.ts new file mode 100644 index 00000000..8b19fec7 --- /dev/null +++ b/xstate-effect/src/fromEffect.ts @@ -0,0 +1,709 @@ +import { Cause, Effect, Exit, Stream } from 'effect'; +import { + createLogic, + type ActorLogicValidator, + type ActorLogic, + type AnyActorLogic, + type AnyActorRef, + type AnyActorSystem, + type AnyEventObject, + type EventObject, + type Snapshot, + type StandardSchemaV1 +} from 'xstate'; +import { EffectInterruptedError } from './errors.ts'; +import type { EffectRequirements } from './types.ts'; +import { relayToParent, startHostedEffect } from './internal.ts'; +import { + type EffectSchemaLike, + type ToStandardSchema, + type ValidateEffectActorSchemas, + toStandardSchema +} from './schema.ts'; + +const EFFECT_INIT = '@xstate.init'; +const EFFECT_RESOLVE = 'xstate.effect.resolve'; +const EFFECT_REJECT = 'xstate.effect.reject'; +const EFFECT_NEXT = 'xstate.effect.next'; +const EFFECT_COMPLETE = 'xstate.effect.complete'; + +const effectLogicBrand: unique symbol = Symbol.for( + '@xstate/effect/logic' +) as any; + +/** + * Type-level marker attached to logic created by `fromEffect`, + * `fromEffectStream` and `fromEffectEventStream`. It carries the logic's + * failure type and its Effect service requirements, which is how + * `RequirementsFrom` collects the `R` channel of `createEffectActor` without + * inspecting the logic at runtime. + */ +export interface EffectLogicBrand { + readonly [effectLogicBrand]: { + readonly error: TError; + readonly requirements: TRequirements; + }; +} + +/** + * Snapshot of a `fromEffect` actor. The actor holds no context of its own: it + * is `active` while the Effect runs, `done` with the Effect's success value as + * `output`, or `error` with the Effect's failure, defect or + * `EffectInterruptedError` as `error`. + */ +export type EffectSnapshot = Snapshot & { + readonly context: undefined; + readonly input: TInput | undefined; + readonly error: TError | undefined; +}; + +/** + * Argument passed to the function form of an Effect source. It gives the + * source the actor's `input`, its own reference (`self`), the actor `system`, + * and `emit` for publishing events that `actor.on(...)` and `emitted(actor)` + * observe. + */ +export type EffectSourceArgs = { + readonly input: TInput; + readonly self: AnyActorRef; + readonly system: AnyActorSystem; + /** Emits an event that can be observed with `actor.on(...)` or `emitted(actor)`. */ + readonly emit: (event: AnyEventObject) => void; +}; + +/** + * What `fromEffect` accepts as its Effect: either an Effect value, or a + * function of {@link EffectSourceArgs} returning one. The function form is + * called once per actor start, so it sees that actor's input. + */ +export type EffectSource = + | Effect.Effect + | (( + args: EffectSourceArgs + ) => Effect.Effect); + +type EffectActorSchemas = { + readonly input?: EffectSchemaLike; + readonly output?: EffectSchemaLike; +}; + +type EffectSourceConfig< + TOutput, + TError, + TInput, + TRequirements, + TSchemas extends EffectActorSchemas = EffectActorSchemas, + TValidator extends ActorLogicValidator | undefined = + | ActorLogicValidator + | undefined +> = { + readonly id?: string; + readonly validator?: TValidator; + readonly schemas?: TSchemas & + ([TValidator] extends [ActorLogicValidator] + ? ValidateEffectActorSchemas + : unknown); + readonly effect: EffectSource; +}; + +type SchemaOutput = + StandardSchemaV1.InferOutput>; + +type EffectSuccess = T extends Effect.Effect ? A : never; + +type EffectFailure = T extends Effect.Effect ? E : never; + +type EffectSchemaValidationConfig = + | { + readonly validator: ActorLogicValidator; + readonly schemas: TSchemas & ValidateEffectActorSchemas; + } + | { + readonly validator?: undefined; + readonly schemas: TSchemas; + }; + +/** + * Actor logic produced by `fromEffect` and `fromEffectEventStream`. It is + * ordinary XState actor logic carrying {@link EffectLogicBrand}, so a machine + * can invoke or spawn it, and `createEffectActor` can collect its + * requirements. + */ +export type EffectActorLogic = + ActorLogic< + EffectSnapshot, + EventObject, + TInput, + AnyActorSystem + > & { readonly id?: string } & EffectLogicBrand; + +/** + * Snapshot of a `fromEffectStream` actor. `context` holds the most recent + * stream item, or `undefined` before the first one. The actor reaches `done` + * with no output when the stream completes, and `error` when it fails. + */ +export type EffectStreamSnapshot = + Snapshot & { + readonly context: TItem | undefined; + readonly input: TInput | undefined; + readonly error: TError | undefined; + }; + +/** + * Actor logic produced by `fromEffectStream`. Its snapshot is an + * {@link EffectStreamSnapshot}, so the parent reads the latest item from the + * child's `context` rather than from events. + */ +export type EffectStreamActorLogic = + ActorLogic< + EffectStreamSnapshot, + EventObject, + TInput, + AnyActorSystem + > & { readonly id?: string } & EffectLogicBrand; + +function toError(exit: Exit.Exit): unknown { + if (Exit.isSuccess(exit)) { + return undefined; + } + if (Cause.hasInterruptsOnly(exit.cause)) { + return new EffectInterruptedError({ + cause: exit.cause as Cause.Cause + }); + } + return Cause.squash(exit.cause); +} + +function createSourceArgs( + input: TInput, + self: AnyActorRef, + system: AnyActorSystem +): EffectSourceArgs { + return { + input, + self, + system, + emit: (event) => { + void system.emitEvent(self as any, event); + } + }; +} + +function brandLogic( + logic: TLogic, + error: unknown, + requirements: unknown +): TLogic { + Object.defineProperty(logic, effectLogicBrand, { + configurable: false, + enumerable: false, + value: { error, requirements } + }); + return logic; +} + +/** + * Creates actor logic that runs an Effect. The actor completes with the + * Effect's success value as its output and fails with the Effect's error, its + * squashed defect, or an `EffectInterruptedError` when the Effect interrupts + * itself. Stopping the actor interrupts the Effect without an error. Accepts + * an Effect, a function of {@link EffectSourceArgs} returning one, or a config + * object with `id`, `schemas`, `validator` and `effect`. The logic must be run + * under `createEffectActor`, which provides the Effect services it declares. + * Resources belong to this task's scope and close on completion, failure or + * interruption. Use `withActorScope` to retain a resource until the owning + * Effect actor stops. + */ +export function fromEffect< + const TInputSchema extends EffectSchemaLike, + const TOutputSchema extends EffectSchemaLike, + TError = unknown, + TRequirements = never +>( + config: Omit< + EffectSourceConfig< + SchemaOutput, + TError, + SchemaOutput, + TRequirements + >, + 'schemas' | 'validator' + > & + EffectSchemaValidationConfig<{ + input: TInputSchema; + output: TOutputSchema; + }> +): EffectActorLogic< + SchemaOutput, + TError, + SchemaOutput, + TRequirements +>; +export function fromEffect< + const TInputSchema extends EffectSchemaLike, + TEffect extends Effect.Effect +>( + config: Omit< + EffectSourceConfig< + EffectSuccess, + EffectFailure, + SchemaOutput, + EffectRequirements, + { input: TInputSchema } + >, + 'effect' | 'schemas' | 'validator' + > & + EffectSchemaValidationConfig<{ + input: TInputSchema; + output?: never; + }> & { + effect: + | TEffect + | ((args: EffectSourceArgs>) => TEffect); + } +): EffectActorLogic< + EffectSuccess, + EffectFailure, + SchemaOutput, + EffectRequirements +>; +export function fromEffect< + const TOutputSchema extends EffectSchemaLike, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + config: Omit< + EffectSourceConfig< + SchemaOutput, + TError, + TInput, + TRequirements + >, + 'schemas' | 'validator' + > & + EffectSchemaValidationConfig<{ + input?: never; + output: TOutputSchema; + }> +): EffectActorLogic, TError, TInput, TRequirements>; +export function fromEffect< + TOutput, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + config: EffectSourceConfig & { + schemas?: undefined; + } +): EffectActorLogic; + +export function fromEffect( + effect: Effect.Effect +): EffectActorLogic; +export function fromEffect< + TOutput, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + effect: ( + args: EffectSourceArgs + ) => Effect.Effect +): EffectActorLogic; +export function fromEffect< + TOutput, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + sourceOrConfig: + | EffectSource + | EffectSourceConfig +): EffectActorLogic { + const config: EffectSourceConfig = + typeof sourceOrConfig === 'function' || Effect.isEffect(sourceOrConfig) + ? { effect: sourceOrConfig } + : sourceOrConfig; + const source = config.effect; + const schemas = config.schemas + ? { + ...(config.schemas.input + ? { input: toStandardSchema(config.schemas.input) } + : {}), + ...(config.schemas.output + ? { output: toStandardSchema(config.schemas.output) } + : {}) + } + : undefined; + const logic = createLogic< + undefined, + TOutput, + EventObject, + TInput, + EventObject + >({ + id: config.id, + validator: config.validator, + schemas, + context: undefined, + run: ({ event, input, self, system }, enq) => { + if (event.type === EFFECT_RESOLVE) { + return { + status: 'done', + output: (event as EventObject & { output: TOutput }).output, + input: undefined + }; + } + + if (event.type === EFFECT_REJECT) { + return { + status: 'error', + error: (event as EventObject & { error: TError }).error, + input: undefined + }; + } + + if (event.type !== EFFECT_INIT) { + return; + } + + const effect = + typeof source === 'function' + ? source(createSourceArgs(input, self as AnyActorRef, system)) + : source; + + enq.effect(() => + startHostedEffect( + self as AnyActorRef, + Effect.scoped(effect) as Effect.Effect, + 'fromEffect', + (exit) => { + if (self.getSnapshot().status !== 'active') { + return; + } + + if (Exit.isSuccess(exit)) { + self.send({ type: EFFECT_RESOLVE, output: exit.value } as any); + } else { + self.send({ type: EFFECT_REJECT, error: toError(exit) } as any); + } + } + ) + ); + } + }); + + return brandLogic( + logic, + undefined as TError, + undefined as TRequirements + ) as unknown as EffectActorLogic; +} + +/** + * What `fromEffectStream` and `fromEffectEventStream` accept as their stream: + * either a Stream value, or a function of {@link EffectSourceArgs} returning + * one. The function form is called once per actor start. + */ +export type EffectStreamSource = + | Stream.Stream + | (( + args: EffectSourceArgs + ) => Stream.Stream); + +type EffectStreamConfig< + TItem, + TError, + TInput, + TRequirements, + TSchemas extends { readonly input?: EffectSchemaLike } = { + readonly input?: EffectSchemaLike; + }, + TValidator extends ActorLogicValidator | undefined = + | ActorLogicValidator + | undefined +> = { + readonly id?: string; + readonly validator?: TValidator; + readonly schemas?: TSchemas & + ([TValidator] extends [ActorLogicValidator] + ? ValidateEffectActorSchemas + : unknown); + readonly stream: EffectStreamSource; +}; + +type StreamItem = T extends Stream.Stream ? A : never; +type StreamError = T extends Stream.Stream ? E : never; +type StreamRequirements = + T extends Stream.Stream ? R : never; + +function resolveStreamConfig( + sourceOrConfig: + | EffectStreamSource + | EffectStreamConfig +): EffectStreamConfig { + return typeof sourceOrConfig === 'function' || Stream.isStream(sourceOrConfig) + ? { stream: sourceOrConfig } + : sourceOrConfig; +} + +function toLogicSchemas( + schemas: { readonly input?: EffectSchemaLike } | undefined +) { + return schemas?.input + ? { input: toStandardSchema(schemas.input) } + : undefined; +} + +/** + * Creates actor logic that runs a Stream and exposes its most recent item as + * the actor's `context`. The actor reaches `done` when the stream completes + * and `error` when it fails. Accepts a Stream, a function of + * {@link EffectSourceArgs} returning one, or a config object with `id`, + * `schemas`, `validator` and `stream`. Its resources close when the stream + * completes, fails or is interrupted. + */ +export function fromEffectStream< + const TInputSchema extends EffectSchemaLike, + TStream extends Stream.Stream +>( + config: Omit< + EffectStreamConfig< + StreamItem, + StreamError, + SchemaOutput, + StreamRequirements + >, + 'stream' | 'schemas' | 'validator' + > & + EffectSchemaValidationConfig<{ input: TInputSchema }> & { + stream: + | TStream + | ((args: EffectSourceArgs>) => TStream); + } +): EffectStreamActorLogic< + StreamItem, + StreamError, + SchemaOutput, + StreamRequirements +>; +export function fromEffectStream< + TItem, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + config: EffectStreamConfig & { + schemas?: undefined; + } +): EffectStreamActorLogic; +export function fromEffectStream< + TItem, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + stream: EffectStreamSource +): EffectStreamActorLogic; +export function fromEffectStream< + TItem, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + sourceOrConfig: + | EffectStreamSource + | EffectStreamConfig +): EffectStreamActorLogic { + const config = resolveStreamConfig(sourceOrConfig); + const stream = config.stream; + const logic = createLogic< + TItem | undefined, + undefined, + EventObject, + TInput, + EventObject + >({ + id: config.id, + validator: config.validator, + schemas: toLogicSchemas(config.schemas), + context: undefined, + run: ({ event, input, self, system }, enq) => { + if (event.type === EFFECT_NEXT) { + return { context: (event as EventObject & { value: TItem }).value }; + } + if (event.type === EFFECT_COMPLETE) { + return { status: 'done', input: undefined }; + } + if (event.type === EFFECT_REJECT) { + return { + status: 'error', + error: (event as EventObject & { error: TError }).error, + input: undefined + }; + } + if (event.type !== EFFECT_INIT) { + return; + } + + const streamValue = + typeof stream === 'function' + ? stream(createSourceArgs(input, self as AnyActorRef, system)) + : stream; + const consume = Stream.runForEach(streamValue, (value) => + Effect.sync(() => { + if (self.getSnapshot().status === 'active') { + self.send({ type: EFFECT_NEXT, value } as any); + } + }) + ); + + enq.effect(() => + startHostedEffect( + self as AnyActorRef, + Effect.scoped(consume) as Effect.Effect, + 'fromEffectStream', + (exit) => { + if (self.getSnapshot().status !== 'active') { + return; + } + if (Exit.isSuccess(exit)) { + self.send({ type: EFFECT_COMPLETE }); + } else { + self.send({ type: EFFECT_REJECT, error: toError(exit) } as any); + } + } + ) + ); + } + }); + + return brandLogic( + logic, + undefined as TError, + undefined as TRequirements + ) as unknown as EffectStreamActorLogic; +} + +/** + * Creates actor logic that runs a Stream of events and relays each item to the + * parent machine as an event, the way `fromEventObservable` does. The actor + * has no output: it reaches `done` when the stream completes and `error` when + * it fails. Accepts the same forms as `fromEffectStream`. Its resources close + * when the stream completes, fails or is interrupted. + */ +export function fromEffectEventStream< + const TInputSchema extends EffectSchemaLike, + TStream extends Stream.Stream +>( + config: Omit< + EffectStreamConfig< + StreamItem, + StreamError, + SchemaOutput, + StreamRequirements + >, + 'stream' | 'schemas' | 'validator' + > & + EffectSchemaValidationConfig<{ input: TInputSchema }> & { + stream: + | TStream + | ((args: EffectSourceArgs>) => TStream); + } +): EffectActorLogic< + undefined, + StreamError, + SchemaOutput, + StreamRequirements +>; +export function fromEffectEventStream< + TEvent extends EventObject, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + config: EffectStreamConfig & { + schemas?: undefined; + } +): EffectActorLogic; +export function fromEffectEventStream< + TEvent extends EventObject, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + stream: EffectStreamSource +): EffectActorLogic; +export function fromEffectEventStream< + TEvent extends EventObject, + TError = unknown, + TInput = undefined, + TRequirements = never +>( + sourceOrConfig: + | EffectStreamSource + | EffectStreamConfig +): EffectActorLogic { + const config = resolveStreamConfig(sourceOrConfig); + const stream = config.stream; + const logic = createLogic< + undefined, + undefined, + EventObject, + TInput, + EventObject + >({ + id: config.id, + validator: config.validator, + schemas: toLogicSchemas(config.schemas), + context: undefined, + run: ({ event, input, self, system }, enq) => { + if (event.type === EFFECT_COMPLETE) { + return { status: 'done', input: undefined }; + } + if (event.type === EFFECT_REJECT) { + return { + status: 'error', + error: (event as EventObject & { error: TError }).error, + input: undefined + }; + } + if (event.type !== EFFECT_INIT) { + return; + } + + const streamValue = + typeof stream === 'function' + ? stream(createSourceArgs(input, self as AnyActorRef, system)) + : stream; + const consume = Stream.runForEach(streamValue, (value) => + Effect.sync(() => relayToParent(self as AnyActorRef, value)) + ); + + enq.effect(() => + startHostedEffect( + self as AnyActorRef, + Effect.scoped(consume) as Effect.Effect, + 'fromEffectEventStream', + (exit) => { + if (self.getSnapshot().status !== 'active') { + return; + } + if (Exit.isSuccess(exit)) { + self.send({ type: EFFECT_COMPLETE }); + } else { + self.send({ type: EFFECT_REJECT, error: toError(exit) } as any); + } + } + ) + ); + } + }); + + return brandLogic( + logic, + undefined as TError, + undefined as TRequirements + ) as unknown as EffectActorLogic; +} diff --git a/xstate-effect/src/index.test.ts b/xstate-effect/src/index.test.ts new file mode 100644 index 00000000..37d336e0 --- /dev/null +++ b/xstate-effect/src/index.test.ts @@ -0,0 +1,875 @@ +import { + Context, + Effect, + Exit, + Layer, + ManagedRuntime, + Option, + Schema, + Scope, + Stream +} from 'effect'; +import { + createActor, + createMachine, + initialTransition, + setup, + types, + type StandardSchemaV1 +} from 'xstate'; +import { standardSchemaValidator } from 'xstate/validation'; +import { + createEffectActor, + fromEffect, + fromEffectEventStream, + fromEffectStream, + setupEffect +} from './index.ts'; + +/** + * Polls until `predicate` holds. Effects run on detached fibers, so tests wait + * for the condition they assert on instead of for a fixed number of ticks. + */ +const until = async (predicate: () => boolean, timeoutMs = 1000) => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 1)); + } +}; + +/** + * Runs a value through a converted schema with the Standard Schema interface + * XState validates against, and reports whether the schema rejected it. + */ +const rejects = (schema: StandardSchemaV1, value: unknown): boolean => { + const result = schema['~standard'].validate(value); + if (result instanceof Promise) { + throw new Error('Expected a synchronous schema'); + } + return !!result.issues; +}; + +let scopes: Scope.Closeable[] = []; + +afterEach(async () => { + const pending = scopes; + scopes = []; + for (const scope of pending) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } +}); + +/** Runs a scoped Effect in a scope that stays open until the test ends. */ +const runScoped = async ( + effect: Effect.Effect +): Promise => { + const scope = await Effect.runPromise(Scope.make()); + scopes.push(scope); + return Effect.runPromise(Scope.provide(effect, scope)); +}; + +describe('@xstate/effect', () => { + it('accepts Effect schemas in setupEffect with full type inference', async () => { + const effectSetup = setupEffect({ + schemas: { + context: Schema.Struct({ count: Schema.Number }), + events: { + ADD: Schema.Struct({ value: Schema.Number }), + RESET: types<{}>() + } + } + }); + const machine = effectSetup.createMachine({ + context: { count: 0 }, + initial: 'active', + states: { + active: { + on: { + ADD: ({ context, event }) => { + context.count satisfies number; + event.value satisfies number; + return { context: { count: context.count + event.value } }; + }, + RESET: { context: { count: 0 } } + } + } + } + }); + + const actor = await runScoped(createEffectActor(machine)); + actor.send({ type: 'ADD', value: 3 }); + const sendInvalidEvent = () => { + // @ts-expect-error -- Effect schemas constrain event payloads + actor.send({ type: 'ADD', value: 'invalid' }); + }; + void sendInvalidEvent; + await until(() => actor.getSnapshot().context.count === 3); + + expect(actor.getSnapshot().context).toEqual({ count: 3 }); + }); + + it('validates converted context and event schemas at runtime', async () => { + const machine = setupEffect({ + validator: standardSchemaValidator(), + schemas: { + context: Schema.Struct({ count: Schema.Number }), + events: { ADD: Schema.Struct({ value: Schema.Number }) } + } + }).createMachine({ + context: { count: 0 }, + on: { + ADD: ({ context, event }) => ({ + context: { count: context.count + event.value } + }) + } + }); + const actor = await runScoped(createEffectActor(machine)); + + actor.send({ type: 'ADD', value: 2 }); + await until(() => actor.getSnapshot().context.count === 2); + + // The converted event schema is what runtime validation asserts against, + // so an invalid payload is rejected instead of transitioning. A second + // valid event, processed after it, proves the invalid one was dropped. + actor.send({ type: 'ADD', value: 'invalid' } as any); + actor.send({ type: 'ADD', value: 1 }); + await until(() => actor.getSnapshot().context.count === 3); + expect(actor.getSnapshot().context).toEqual({ count: 3 }); + + const invalidContext = setupEffect({ + validator: standardSchemaValidator(), + schemas: { context: Schema.Struct({ count: Schema.Number }) } + }).createMachine({ context: { count: 'invalid' } as any }); + + expect(() => initialTransition(invalidContext)).toThrow('Invalid context'); + }); + + it('accepts Effect schemas when extending setupEffect', async () => { + const effectSetup = setupEffect({ + schemas: { + context: Schema.Struct({ count: Schema.Number }) + } + }).extend({ + schemas: { + events: { + ADD: Schema.Struct({ value: Schema.Number }) + } + }, + guards: { + canAdd: ({ context, event }) => { + context.count satisfies number; + event.value satisfies number; + return event.value > 0; + } + } + }); + const machine = effectSetup.createMachine({ + context: { count: 0 }, + on: { + ADD: { + context: ({ context, event }) => ({ + count: context.count + event.value + }) + } + } + }); + const actor = await runScoped(createEffectActor(machine)); + + actor.send({ type: 'ADD', value: 2 }); + await until(() => actor.getSnapshot().context.count === 2); + + expect(actor.getSnapshot().context).toEqual({ count: 2 }); + expect(rejects(effectSetup.schemas.events.ADD, { value: 'invalid' })).toBe( + true + ); + }); + + it('preserves runtime validation compatibility through setupEffect.extend', () => { + const validated = setupEffect({ + validator: standardSchemaValidator() + }); + const incompatibleSchemas = setupEffect({ + schemas: { input: Schema.NumberFromString } + }); + const incompatibleStates = setupEffect({ + states: { + loading: { schemas: { input: Schema.NumberFromString } } + } + }); + + if (false) { + validated.extend({ + schemas: { + // @ts-expect-error -- extended schemas inherit runtime validation + input: Schema.NumberFromString + } + }); + + // @ts-expect-error -- validation cannot be installed over a transforming schema + incompatibleSchemas.extend({ validator: standardSchemaValidator() }); + + // @ts-expect-error -- inherited state schemas must also be compatible + incompatibleStates.extend({ validator: standardSchemaValidator() }); + } + + validated.extend({ + validator: undefined, + schemas: { input: Schema.NumberFromString } + }); + }); + + it('preserves Effect action requirements when extending setupEffect', () => { + const Audit = Context.Service<{ record: () => void }>('Audit'); + const machine = setupEffect() + .extend({ + actions: { + audit: (_args) => + Audit.use((audit) => Effect.sync(() => audit.record())) + } + }) + .createMachine({ + on: { + AUDIT: (args, enq) => enq(args.actions.audit, args) + } + }); + const runWithoutAudit = () => { + // @ts-expect-error -- extended Effect actions contribute requirements + runScoped(createEffectActor(machine)); + }; + + void runWithoutAudit; + }); + + it('converts nested Effect state schemas', () => { + const effectSetup = setupEffect({ + states: { + running: { + schemas: { + input: Schema.Struct({ timeout: Schema.Number }) + }, + states: { + retrying: { + schemas: { + context: Schema.Struct({ attempt: Schema.Number }) + } + } + } + } + } + }); + + expect(rejects(effectSetup.states.running.schemas!.input!, {})).toBe(true); + expect( + rejects(effectSetup.states.running.schemas!.input!, { timeout: 5 }) + ).toBe(false); + expect( + rejects(effectSetup.states.running.states!.retrying.schemas!.context!, { + attempt: 'no' + }) + ).toBe(true); + }); + + it('converts Effect schemas in every setup schema map', () => { + const effectSetup = setupEffect({ + schemas: { + internalEvents: { + TICK: Schema.Struct({ count: Schema.Number }) + }, + actions: { + track: { params: Schema.Struct({ key: Schema.String }) } + }, + guards: { + hasAccess: { params: Schema.Struct({ role: Schema.String }) } + }, + emitted: { + changed: Schema.Struct({ value: Schema.Number }) + }, + meta: Schema.Struct({ label: Schema.String }), + tags: Schema.Literals(['active']), + children: { + child: Schema.Unknown + } + } + }); + + expect( + rejects(effectSetup.schemas.internalEvents.TICK, { count: 'no' }) + ).toBe(true); + expect(rejects(effectSetup.schemas.actions.track.params, { key: 1 })).toBe( + true + ); + expect( + rejects(effectSetup.schemas.guards.hasAccess.params, { role: 1 }) + ).toBe(true); + expect(rejects(effectSetup.schemas.emitted.changed, { value: 'no' })).toBe( + true + ); + expect(rejects(effectSetup.schemas.meta, { label: 1 })).toBe(true); + expect(rejects(effectSetup.schemas.tags, 'inactive')).toBe(true); + // `Schema.Unknown` accepts anything; converting it must not change that. + expect(rejects(effectSetup.schemas.children.child, 'anything')).toBe(false); + }); + + it('preserves __proto__ schema and state keys while converting', () => { + const effectSetup = setupEffect({ + schemas: { + events: { ['__proto__']: Schema.String } + }, + states: { + ['__proto__']: { + schemas: { input: Schema.String } + } + } + }); + + expect(Object.hasOwn(effectSetup.schemas.events, '__proto__')).toBe(true); + expect(rejects(effectSetup.schemas.events['__proto__'], 42)).toBe(true); + expect(Object.hasOwn(effectSetup.states, '__proto__')).toBe(true); + expect(rejects(effectSetup.states['__proto__'].schemas!.input!, 42)).toBe( + true + ); + }); + + it('uses converted Effect schemas with XState runtime validation', () => { + const machine = setupEffect({ + validator: standardSchemaValidator(), + schemas: { + input: Schema.Struct({ count: Schema.Number }) + } + }).createMachine({ + context: ({ input }) => ({ count: input.count }) + }); + + expect(() => + initialTransition(machine, { count: 'invalid' } as any) + ).toThrow('Invalid input'); + }); + + it('reports asynchronous Effect schemas as unsupported by runtime validation', () => { + const asyncString = Schema.String.pipe( + Schema.catchDecoding(() => + Effect.delay(Effect.succeed(Option.some('fallback')), 1) + ) + ); + const machine = setupEffect({ + validator: standardSchemaValidator(), + schemas: { input: asyncString } + }).createMachine({}); + + expect(() => initialTransition(machine, 42 as any)).toThrow( + 'Async schema validation is unsupported for input' + ); + }); + + it('rejects transforming Effect schemas when runtime validation is enabled', () => { + const invalidSetup = () => + setupEffect({ + validator: standardSchemaValidator(), + schemas: { + // @ts-expect-error -- XState validation asserts values but does not transform them + input: Schema.NumberFromString + } + }); + const invalidLogic = () => + fromEffect({ + // @ts-expect-error -- XState validation asserts values but does not transform them + validator: standardSchemaValidator(), + schemas: { + input: Schema.NumberFromString + }, + effect: ({ input }: { input: number }) => Effect.succeed(input) + }); + + void invalidSetup; + void invalidLogic; + }); + + it('accepts Effect schemas for fromEffect input and output', async () => { + const logic = fromEffect({ + schemas: { + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ greeting: Schema.String }) + }, + effect: ({ input }) => { + input.id satisfies string; + return Effect.succeed({ greeting: `Hello ${input.id}` }); + } + }); + + const actor = await runScoped( + createEffectActor(logic, { input: { id: '42' } }) + ); + const createWithInvalidInput = () => { + // @ts-expect-error -- input comes from the Effect schema + createEffectActor(logic, { input: { id: 42 } }); + }; + void createWithInvalidInput; + await until(() => actor.getSnapshot().status === 'done'); + + actor.getSnapshot().output?.greeting satisfies string | undefined; + expect(actor.getSnapshot().output).toEqual({ greeting: 'Hello 42' }); + }); + + it('rejects invalid fromEffect input with XState runtime validation', () => { + const logic = fromEffect({ + validator: standardSchemaValidator(), + schemas: { + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ greeting: Schema.String }) + }, + effect: ({ input }) => Effect.succeed({ greeting: `Hello ${input.id}` }) + }); + + expect(() => initialTransition(logic, { id: 42 } as any)).toThrow( + 'Invalid input' + ); + }); + + it('checks fromEffect results against the output schema', () => { + const invalidLogic = () => + fromEffect({ + // @ts-expect-error -- the Effect result must match the output schema + schemas: { output: Schema.String }, + effect: Effect.succeed(42) + }); + + void invalidLogic; + }); + + it('preserves failures and requirements with input and output schemas', () => { + const Service = Context.Service<{ name: string }>('Service'); + const failure = { code: 'NOT_FOUND' as const }; + const logic = fromEffect({ + schemas: { + input: Schema.Struct({ id: Schema.String }), + output: Schema.Struct({ name: Schema.String }) + }, + effect: ({ input }) => + Service.use((service) => + input.id === 'missing' + ? Effect.fail(failure) + : Effect.succeed({ name: service.name }) + ) + }); + setup({ actors: { logic } }).createMachine({ + invoke: { + src: 'logic', + input: { id: '42' }, + onError: ({ event }) => { + event.error.code satisfies 'NOT_FOUND'; + return {}; + } + } + }); + const runWithoutService = () => { + Effect.runPromise( + // @ts-expect-error -- both-schema actors preserve Effect requirements + createEffectActor(logic, { input: { id: '42' } }) + ); + }; + + void runWithoutService; + }); + + it('infers fromEffect output and requirements with only an input schema', () => { + const Service = Context.Service<{ prefix: string }>('Service'); + const logic = fromEffect({ + schemas: { + input: Schema.Struct({ id: Schema.String }) + }, + effect: ({ input }) => + Service.use((service) => Effect.succeed(`${service.prefix}${input.id}`)) + }); + + const runWithoutService = () => { + // @ts-expect-error -- schema inference preserves Effect requirements + runScoped(createEffectActor(logic, { input: { id: '42' } })); + }; + void runWithoutService; + }); + + it('accepts a constant Effect with only an input schema', async () => { + const logic = fromEffect({ + schemas: { + input: Schema.Struct({ id: Schema.String }) + }, + effect: Effect.succeed('ok') + }); + const actor = await runScoped( + createEffectActor(logic, { input: { id: '42' } }) + ); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().output).toBe('ok'); + }); + + it('accepts an output-only Effect schema', async () => { + const logic = fromEffect({ + schemas: { output: Schema.String }, + effect: Effect.succeed('ok') + }); + const actor = await runScoped(createEffectActor(logic)); + await until(() => actor.getSnapshot().status === 'done'); + + actor.getSnapshot().output satisfies string | undefined; + expect(actor.getSnapshot().output).toBe('ok'); + }); + + it('infers actor input with only an output schema', async () => { + const logic = fromEffect({ + schemas: { output: Schema.String }, + effect: ({ input }: { input: number }) => Effect.succeed(String(input)) + }); + const actor = await runScoped(createEffectActor(logic, { input: 42 })); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().output).toBe('42'); + }); + + it('validates fromEffect schemas when a validator is provided', async () => { + const logic = fromEffect({ + validator: standardSchemaValidator(), + schemas: { output: Schema.String }, + effect: Effect.succeed('ok') + }); + const actor = await runScoped(createEffectActor(logic)); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().status).toBe('done'); + }); + + it('rejects invalid fromEffect output with XState runtime validation', async () => { + let resolve!: (value: number) => void; + const output = new Promise((done) => { + resolve = done; + }); + const logic = fromEffect({ + validator: standardSchemaValidator(), + schemas: { output: Schema.String }, + effect: Effect.promise(() => output) as Effect.Effect + }); + const errors: unknown[] = []; + const actor = await runScoped(createEffectActor(logic)); + actor.subscribe({ error: (error) => errors.push(error) }); + resolve(42); + await until(() => actor.getSnapshot().status === 'error'); + + expect(errors).toHaveLength(1); + }); + + it('runs setupEffect actions inside the host Effect context', async () => { + interface Audit { + record: (value: number) => void; + } + const Audit = Context.Service('Audit'); + const recorded: number[] = []; + + const effectSetup = setupEffect({ + actions: { + audit: ({ context }) => + Audit.use((audit) => Effect.sync(() => audit.record(context.count))) + } + }); + const machine = effectSetup.createMachine({ + context: { count: 1 }, + initial: 'active', + states: { + active: { + on: { + AUDIT: (args, enq) => { + enq(args.actions.audit, args); + } + } + } + } + }); + + const actor = await runScoped( + Effect.provideService(createEffectActor(machine), Audit, { + record: (value) => recorded.push(value) + }) + ); + const runWithoutAudit = () => { + // @ts-expect-error -- the actor requires the Audit service + runScoped(createEffectActor(machine)); + }; + void runWithoutAudit; + + actor.send({ type: 'AUDIT' }); + await until(() => recorded.length === 1); + + expect(recorded).toEqual([1]); + }); + + it('uses scoped Layer services while the caller-owned runtime is alive', async () => { + const Resource = Context.Service<{ value: string }>('Resource'); + let acquired = 0; + let released = 0; + let observed: string | undefined; + const layer = Layer.effect( + Resource, + Effect.acquireRelease( + Effect.sync(() => { + acquired++; + return { value: 'scoped' }; + }), + () => + Effect.sync(() => { + released++; + }) + ) + ); + const runtime = ManagedRuntime.make(layer); + const machine = setupEffect({ + actions: { + read: (_args) => + Resource.use((resource) => + Effect.sync(() => { + observed = resource.value; + }) + ) + } + }).createMachine({ + on: { + READ: (args, enq) => enq(args.actions.read, args) + } + }); + + try { + const scope = await runtime.runPromise(Scope.make()); + scopes.push(scope); + const actor = await runtime.runPromise( + Scope.provide(createEffectActor(machine), scope) + ); + + expect(acquired).toBe(1); + expect(released).toBe(0); + actor.send({ type: 'READ' }); + await until(() => observed !== undefined); + expect(observed).toBe('scoped'); + + actor.stop(); + expect(released).toBe(0); + } finally { + await runtime.dispose(); + } + + expect(released).toBe(1); + }); + + it('routes failed Effect actions through the machine error transition', async () => { + const failure = { code: 'AUDIT_FAILED' as const }; + let received: unknown; + const effectSetup = setupEffect({ + actions: { + fail: (_args) => Effect.fail(failure) + } + }); + const machine = effectSetup.createMachine({ + initial: 'active', + states: { + active: { + on: { + FAIL: (args, enq) => enq(args.actions.fail, args) + }, + onError: ({ event }) => { + received = event.error; + return { target: 'failed' }; + } + }, + failed: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + actor.send({ type: 'FAIL' }); + await until(() => actor.getSnapshot().value === 'failed'); + + expect(received).toEqual(failure); + }); + + it('invokes an Effect actor and routes success to onDone', async () => { + const logic = fromEffect(Effect.succeed('ok')); + const machine = createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { + src: logic, + onDone: { + target: 'success', + context: ({ event }) => ({ result: event.output }) + } + } + }, + success: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + await until(() => actor.getSnapshot().value === 'success'); + + expect(actor.getSnapshot().context).toEqual({ result: 'ok' }); + }); + + it('uses the Effect runtime brand when distinguishing config objects', async () => { + const directEffect = Object.assign(Effect.succeed('direct'), { + effect: Effect.succeed('nested') + }); + const actor = await runScoped(createEffectActor(fromEffect(directEffect))); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().output).toBe('direct'); + }); + + it('routes typed Effect failures to onError', async () => { + const failure = { code: 'NOT_FOUND' as const }; + const logic = fromEffect(Effect.fail(failure)); + const machine = createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { + src: logic, + onError: { + target: 'failed', + context: ({ event }) => ({ error: event.error }) + } + } + }, + failed: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + await until(() => actor.getSnapshot().value === 'failed'); + + expect(actor.getSnapshot().context).toEqual({ error: failure }); + }); + + it('preserves typed Effect errors through registered v6 actors', () => { + const failure = { code: 'NOT_FOUND' as const }; + const request = fromEffect(Effect.fail(failure)); + const effectSetup = setupEffect({ actors: { request } }); + const machine = effectSetup.createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { + src: 'request', + onError: ({ event }) => { + const code: 'NOT_FOUND' = event.error.code; + // @ts-expect-error -- the Effect failure is discriminated + const other: 'OTHER' = code; + void other; + return { target: 'failed' }; + } + } + }, + failed: {} + } + }); + + expect(machine).toBeDefined(); + }); + + it('collects requirements from registered Effect actors', () => { + const Service = Context.Service<{ value: number }>('Service'); + const logic = fromEffect( + Service.use((service) => Effect.succeed(service.value)) + ); + const runWithoutService = () => { + // @ts-expect-error -- the actor requires Service + runScoped(createEffectActor(logic)); + }; + void runWithoutService; + const machine = setup({ actors: { logic } }).createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { src: 'logic' } + } + } + }); + + const runWithoutRegisteredService = () => { + // @ts-expect-error -- the registered actor requires Service + runScoped(createEffectActor(machine)); + }; + void runWithoutRegisteredService; + }); + + it('rejects running Effect logic through ordinary createActor', () => { + const actor = createActor(fromEffect(Effect.succeed('ok'))); + actor.subscribe({ error: () => {} }); + actor.start(); + + expect(actor.getSnapshot().status).toBe('error'); + }); + + it('exposes the latest item from an Effect stream and completes', async () => { + const actor = await runScoped( + createEffectActor(fromEffectStream(Stream.make(1, 2, 3))) + ); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().context).toBe(3); + }); + + it('infers stream input from the fromEffectStream config form', async () => { + const logic = fromEffectStream({ + schemas: { input: Schema.Struct({ n: Schema.Number }) }, + stream: ({ input }) => { + input satisfies { readonly n: number }; + return Stream.make(input.n, input.n + 1); + } + }); + + const actor = await runScoped( + createEffectActor(logic, { input: { n: 5 } }) + ); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().context).toBe(6); + }); + + it('relays a configured Effect event stream to its parent', async () => { + const relay = fromEffectEventStream({ + schemas: { input: Schema.Struct({ n: Schema.Number }) }, + stream: ({ input }) => { + input satisfies { readonly n: number }; + return Stream.make( + { type: 'VALUE' as const, value: input.n }, + { type: 'VALUE' as const, value: input.n * 2 } + ); + } + }); + const machine = setup({ + schemas: { events: { VALUE: types<{ value: number }>() } }, + actors: { relay } + }).createMachine({ + context: { seen: 0 }, + initial: 'active', + states: { + active: { + invoke: { src: 'relay', input: { n: 3 } }, + on: { + VALUE: { + context: ({ context, event }) => ({ + seen: context.seen + event.value + }) + } + } + } + } + }); + + const actor = await runScoped(createEffectActor(machine)); + await until(() => actor.getSnapshot().context.seen === 9); + + expect(actor.getSnapshot().context).toEqual({ seen: 9 }); + }); +}); diff --git a/xstate-effect/src/index.ts b/xstate-effect/src/index.ts new file mode 100644 index 00000000..6e0b419a --- /dev/null +++ b/xstate-effect/src/index.ts @@ -0,0 +1,52 @@ +export { + fromEffect, + fromEffectEventStream, + fromEffectStream, + type EffectActorLogic, + type EffectLogicBrand, + type EffectSnapshot, + type EffectSource, + type EffectSourceArgs, + type EffectStreamSource, + type EffectStreamActorLogic, + type EffectStreamSnapshot +} from './fromEffect.ts'; +export { + createEffectActor, + type EffectActorOptions +} from './createEffectActor.ts'; +export { EffectActor } from './effectActor.ts'; +export { ActorScope, withActorScope } from './actorScope.ts'; +export { + deadLetters, + emitted, + inspect, + join, + send, + snapshots, + waitFor, + type EmittedEventFrom, + type SendableEventFrom, + type WaitForOptions +} from './actor.ts'; +export { ActorStoppedError, EffectInterruptedError } from './errors.ts'; +export { + setupEffect, + type EffectAction, + type EffectActionArgs, + type EffectSetupReturn +} from './setupEffect.ts'; +export { type RequirementsFrom } from './types.ts'; +export { + taggedState, + type StateTag, + type TaggedState, + type TaggedStateFrom +} from './state.ts'; +export { type ErrorFrom } from 'xstate'; +export { + type EffectSchema, + type EffectSchemaLike, + type EffectSetupSchemas, + type EffectSetupStateSchema +} from './schema.ts'; diff --git a/xstate-effect/src/internal.ts b/xstate-effect/src/internal.ts new file mode 100644 index 00000000..ece804b9 --- /dev/null +++ b/xstate-effect/src/internal.ts @@ -0,0 +1,291 @@ +import { Cause, Context, Effect, Exit, Fiber, Scope } from 'effect'; +import type { AnyActor, AnyActorRef } from 'xstate'; + +export interface EffectHost { + /** The Effect context captured by `createEffectActor`, including the actor scope. */ + readonly context: Context.Context; + /** A scope that closes when the root actor stops. */ + readonly scope: Scope.Closeable; + /** The fiber running the scope's finalizers once the scope has closed. */ + closing?: Fiber.Fiber; + readonly interruptors: Map void>>; + readonly subscriptions: Map; + /** Includes interrupted fibers until their asynchronous finalizers finish. */ + readonly fibers: Set>; +} + +const effectHosts = new WeakMap(); +let ambientHost: EffectHost | undefined; + +/** + * Runs `fn` with `host` as the ambient host, so Effects started synchronously + * inside it (declared actions executed by an execution loop) resolve their + * host without an identity binding. + */ +export function withEffectHost(host: EffectHost, fn: () => T): T { + const previous = ambientHost; + ambientHost = host; + try { + return fn(); + } finally { + ambientHost = previous; + } +} + +export function createEffectHost( + context: Context.Context, + scope: Scope.Closeable +): EffectHost { + return { + context, + scope, + interruptors: new Map(), + subscriptions: new Map(), + fibers: new Set() + }; +} + +export function bindEffectHost(target: object, host: EffectHost): void { + effectHosts.set(target, host); +} + +function findEffectHost(actor: AnyActorRef): EffectHost | undefined { + let current: (AnyActorRef & { _parent?: AnyActorRef }) | undefined = + actor as AnyActorRef & { + _parent?: AnyActorRef; + }; + + while (current) { + const host = effectHosts.get(current); + if (host) { + return host; + } + current = current._parent as + | (AnyActorRef & { _parent?: AnyActorRef }) + | undefined; + } + + return ambientHost; +} + +type DeclaringMachine = { + sources?: { actors?: Record }; + idMap?: Map }>; +}; + +/** + * Rejects Effect logic that a machine spawned inline. Only declared actors + * (`setup({ actors })`) and `invoke` sources are visible to + * `RequirementsFrom`, so anything else would infer `R = never` and fail + * later with a missing service. + * + * A spawned declared actor carries its registered key as `src`; an invoked + * child carries the id of the `invoke` entry that created it. + */ +function assertDeclaredLogic(actor: AnyActorRef): void { + const self = actor as AnyActor & { logic?: unknown }; + const parent = self._parent; + const machine = parent?.logic as DeclaringMachine | undefined; + if (!machine?.sources || !machine.idMap || typeof self.src === 'string') { + return; + } + + if (Object.values(machine.sources.actors ?? {}).includes(self.logic)) { + return; + } + for (const stateNode of machine.idMap.values()) { + for (const definition of stateNode.invoke ?? []) { + if (definition.id === self.id) { + return; + } + } + } + + throw new Error( + `Effect logic spawned by "${parent!.id}" must be declared in setup({ actors }). Spawn a declared actor instead, for example enq.spawn(args.actors.name).` + ); +} + +function requireEffectHost(actor: AnyActorRef): EffectHost { + assertDeclaredLogic(actor); + const host = findEffectHost(actor); + if (!host) { + throw new Error( + 'Effect-backed actor logic must be created with createEffectActor().' + ); + } + return host; +} + +function untrackEffect( + actor: AnyActorRef, + host: EffectHost, + interrupt: () => void +): void { + const interruptors = host.interruptors.get(actor); + if (!interruptors) { + return; + } + + interruptors.delete(interrupt); + if (interruptors.size === 0) { + host.interruptors.delete(actor); + host.subscriptions.get(actor)?.unsubscribe(); + host.subscriptions.delete(actor); + } +} + +function cleanupActorEffects(actor: AnyActorRef, host: EffectHost): void { + const interruptors = host.interruptors.get(actor); + if (interruptors) { + host.interruptors.delete(actor); + for (const interrupt of interruptors) { + interrupt(); + } + } + + host.subscriptions.get(actor)?.unsubscribe(); + host.subscriptions.delete(actor); +} + +function trackEffect( + actor: AnyActorRef, + host: EffectHost, + interrupt: () => void +): void { + let interruptors = host.interruptors.get(actor); + if (!interruptors) { + interruptors = new Set(); + host.interruptors.set(actor, interruptors); + host.subscriptions.set( + actor, + actor.subscribe({ + passive: true, + error: () => cleanupActorEffects(actor, host), + complete: () => cleanupActorEffects(actor, host) + }) + ); + } + interruptors.add(interrupt); +} + +/** + * Runs an Effect in the actor's host context. The Effect is interrupted when + * the actor stops or when the returned function is called; `onExit` is not + * called after that. + * + * The fiber belongs to the host scope, so closing the owning actor also + * waits for asynchronous invocation finalizers. + */ +export function startHostedEffect( + actor: AnyActorRef, + effect: Effect.Effect, + spanName: string, + onExit: (exit: Exit.Exit) => void +): () => void { + const host = requireEffectHost(actor); + let active = true; + const traced = Effect.withSpan( + spanName, + { + attributes: { + 'xstate.actor.id': (actor as AnyActor).id, + 'xstate.actor.address': (actor as AnyActor).address + } + }, + { captureStackTrace: false } + )(effect); + const cancel = () => { + if (!active) { + return; + } + active = false; + untrackEffect(actor, host, cancel); + interrupt(); + }; + const fiber = Fiber.runIn( + Effect.runForkWith(host.context)(traced), + host.scope + ); + const interrupt = () => fiber.interruptUnsafe(); + host.fibers.add(fiber); + fiber.addObserver((exit) => { + host.fibers.delete(fiber); + if (!active) { + return; + } + active = false; + untrackEffect(actor, host, cancel); + onExit(exit); + }); + if (active) { + trackEffect(actor, host, cancel); + } + + return cancel; +} + +/** + * Runs an Effect in the actor's host context and settles when it exits. + * Interruption settles without error; failures and defects reject with the + * squashed cause so the actor's error handling can observe them. + */ +export function runHostedEffect( + actor: AnyActorRef, + effect: Effect.Effect, + spanName: string +): PromiseLike { + return new Promise((resolve, reject) => { + startHostedEffect(actor, effect, spanName, (exit) => { + if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) { + resolve(); + } else { + // Effect failures are arbitrary values, not necessarily Errors. + // oxlint-disable-next-line typescript/prefer-promise-reject-errors + reject(Cause.squash(exit.cause)); + } + }); + }); +} + +/** + * Finishes hosted task cleanup before closing the owning actor's resources. + * `createEffectActor`'s release awaits this fiber before its parent scope closes. + */ +export function closeEffectHost(host: EffectHost): void { + if (host.closing) { + return; + } + for (const [actor, interruptors] of host.interruptors) { + host.interruptors.delete(actor); + for (const interrupt of interruptors) { + interrupt(); + } + host.subscriptions.get(actor)?.unsubscribe(); + host.subscriptions.delete(actor); + } + host.closing = Effect.runForkWith(host.context)( + Effect.forEach([...host.fibers], (fiber) => Fiber.interrupt(fiber), { + concurrency: 'unbounded', + discard: true + }).pipe(Effect.andThen(Scope.close(host.scope, Exit.void))) + ); +} + +/** + * Delivers a stream item to the parent as an event. This runs outside a + * transition, so it uses the system relay like core's observable logic does. + */ +export function relayToParent( + actor: AnyActorRef, + event: { type: string; [key: string]: unknown } +): void { + const actorWithParent = actor as AnyActor & { _parent?: AnyActor }; + if (actorWithParent._parent) { + (actor as AnyActor).system._relay( + actorWithParent, + actorWithParent._parent, + event + ); + } +} diff --git a/xstate-effect/src/lint.test.ts b/xstate-effect/src/lint.test.ts new file mode 100644 index 00000000..cd9b93e7 --- /dev/null +++ b/xstate-effect/src/lint.test.ts @@ -0,0 +1,108 @@ +import { spawnSync } from 'node:child_process'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; + +const repoRoot = path.resolve( + path.dirname(fileURLToPath(import.meta.url)), + '../../..' +); +const fixtureDir = path.join( + repoRoot, + 'packages/xstate-effect/test/lint-fixtures' +); +const fixtureConfig = path.join(fixtureDir, 'oxlintrc.fixtures.json'); + +interface OxlintDiagnostic { + message: string; + code: string; + filename: string; +} + +/** + * Lints one fixture with a config that enables only this repository's + * `xstate-effect/no-inline-effect` rule, so the result is unaffected by the + * rest of the repository's lint configuration. + */ +const lint = (fixture: string): OxlintDiagnostic[] => { + const result = spawnSync( + 'pnpm', + [ + 'exec', + 'oxlint', + '-c', + path.relative(repoRoot, fixtureConfig), + '--format', + 'json', + path.relative(repoRoot, path.join(fixtureDir, fixture)) + ], + { cwd: repoRoot, encoding: 'utf8' } + ); + + if (result.error) { + throw result.error; + } + const stdout = result.stdout ?? ''; + const start = stdout.indexOf('{'); + if (start === -1) { + throw new Error(`oxlint produced no report:\n${stdout}\n${result.stderr}`); + } + return ( + JSON.parse(stdout.slice(start)) as { diagnostics: OxlintDiagnostic[] } + ).diagnostics; +}; + +/** The rule's own message table, keyed by messageId. */ +const messages = async (): Promise> => { + const specifier = pathToFileURL( + path.join(repoRoot, 'scripts/oxlint-plugin-xstate-effect.ts') + ).href; + const plugin = await import(specifier); + return plugin.default.rules['no-inline-effect'].meta.messages; +}; + +describe('xstate-effect/no-inline-effect', () => { + it('supports strict type-aware linting of the plugin itself', () => { + const result = spawnSync( + 'pnpm', + [ + 'exec', + 'oxlint', + '--type-aware', + ...[ + 'no-unsafe-assignment', + 'no-unsafe-call', + 'no-unsafe-member-access', + 'no-unsafe-argument', + 'no-unsafe-return', + 'strict-boolean-expressions' + ].flatMap((rule) => ['--deny', `typescript/${rule}`]), + 'scripts/oxlint-plugin-xstate-effect.ts' + ], + { cwd: repoRoot, encoding: 'utf8' } + ); + + expect(result.error).toBeUndefined(); + expect(result.status, result.stdout + result.stderr).toBe(0); + }, 60_000); + + it('reports inline Effect actions and inline spawned Effect logic', async () => { + const { inlineAction, inlineSpawn } = await messages(); + const diagnostics = lint('inline-effect.ts'); + + expect( + diagnostics.every( + (diagnostic) => diagnostic.code === 'xstate-effect(no-inline-effect)' + ) + ).toBe(true); + expect( + diagnostics.filter((diagnostic) => diagnostic.message === inlineAction) + ).toHaveLength(3); + expect( + diagnostics.filter((diagnostic) => diagnostic.message === inlineSpawn) + ).toHaveLength(2); + }, 60_000); + + it('reports nothing for declared actions and declared spawned actors', () => { + expect(lint('declared-effect.ts')).toEqual([]); + }, 60_000); +}); diff --git a/xstate-effect/src/persistence.test.ts b/xstate-effect/src/persistence.test.ts new file mode 100644 index 00000000..d4b34286 --- /dev/null +++ b/xstate-effect/src/persistence.test.ts @@ -0,0 +1,657 @@ +import { Clock, Duration, Effect, Exit, Layer, Scope, Stream } from 'effect'; +import { TestClock } from 'effect/testing'; +import fc from 'fast-check'; +import { + createMachine, + createObservableLogic, + setup, + types, + type AnyActorLogic, + type Snapshot +} from 'xstate'; +import { getShortestPaths } from 'xstate/graph'; +import { + createEffectActor, + fromEffect, + fromEffectStream, + join, + waitFor, + type EffectActor +} from './index.ts'; + +/** Persists like a host would: through JSON, into a different process. */ +const roundTrip = (snapshot: Snapshot): Snapshot => + JSON.parse(JSON.stringify(snapshot)); + +/** + * Polls until `predicate` holds. Effects run on detached fibers, so tests wait + * for the condition they assert on instead of for a fixed number of ticks. + */ +const until = (predicate: () => boolean, timeoutMs = 1000) => + Effect.promise(async () => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 1)); + } + }); + +/** + * A `TestClock` that reports the sleeps it is holding, so a test can advance + * time only once an actor's timers and tasks are actually waiting on it. + */ +const recordingClock = () => { + const state = { pending: 0, requested: [] as number[] }; + const layer = Layer.effect( + Clock.Clock, + Effect.map(TestClock.make(), (clock) => ({ + ...clock, + sleep: (duration: Duration.Duration) => + Effect.suspend(() => { + state.pending++; + state.requested.push(Duration.toMillis(duration)); + return clock.sleep(duration); + }).pipe(Effect.ensuring(Effect.sync(() => state.pending--))) + })) + ); + return { state, layer }; +}; + +/** Counts side effects across one run, including across a restore. */ +const tally = { entries: 0, expired: 0, ready: 0, fetches: 0 }; + +const counter = createMachine({ + context: { count: 0 }, + on: { + inc: ({ context, parent }, enq) => { + const count = context.count + 1; + const counted = { type: 'counted', count }; + enq.sendTo(parent!, counted); + return { context: { count } }; + } + } +}); + +const fetchReport = fromEffect( + Effect.gen(function* () { + tally.fetches++; + yield* Effect.sleep('1 second'); + return 'report'; + }) +); + +type Command = 'NEXT' | 'BACK' | 'FETCH' | 'PING' | 'TICK'; + +const record = (target: T) => ({ + target, + context: ({ + context, + event + }: { + context: Context; + event: { type: string }; + }) => ({ ...context, trail: context.trail + event.type[0] }) +}); + +type Context = { + trail: string; + sent: number; + counted: number; + syncs: number; + report: string; +}; + +/** + * Parallel and nested states, a delayed transition, an invoked machine child + * that keeps its own count, and an Effect task that needs the clock. + */ +const model = createMachine({ + id: 'model', + actors: { counter, fetchReport }, + schemas: { + events: { + NEXT: types<{}>(), + BACK: types<{}>(), + FETCH: types<{}>(), + PING: types<{}>(), + SYNC: types<{}>(), + counted: types<{ count: number }>() + } + }, + context: { + trail: '', + sent: 0, + counted: 0, + syncs: 0, + report: '' + } as Context, + entry: () => { + tally.entries++; + }, + invoke: { src: 'counter', id: 'counter' }, + on: { + PING: ({ context, children }, enq) => { + if (context.sent >= 2) { + return; + } + enq.sendTo(children.counter!, { type: 'inc' }); + return { + context: { + ...context, + trail: context.trail + 'P', + sent: context.sent + 1 + } + }; + }, + counted: ({ context, event }) => ({ + context: { ...context, counted: event.count } + }), + // A mailbox barrier: once it is processed, every earlier event has been. + SYNC: ({ context }) => ({ + context: { ...context, syncs: context.syncs + 1 } + }) + }, + type: 'parallel', + states: { + flow: { + initial: 'idle', + states: { + idle: { on: { NEXT: record('working') } }, + working: { + initial: 'one', + on: { BACK: record('idle') }, + states: { one: { on: { NEXT: record('two') } }, two: {} } + } + } + }, + report: { + initial: 'waiting', + states: { + waiting: { on: { FETCH: record('fetching') } }, + fetching: { + invoke: { + src: 'fetchReport', + onDone: { + target: 'ready', + context: ({ context, event }) => ({ + ...context, + report: event.output + }) + } + } + }, + ready: { + entry: () => { + tally.ready++; + } + } + } + }, + timer: { + initial: 'armed', + states: { + armed: { after: { 2000: { target: 'expired' } } }, + expired: { + entry: () => { + tally.expired++; + } + } + } + } + } +}); + +type ModelActor = EffectActor; +type Recording = ReturnType['state']; + +/** + * Waits until the actor is quiet: the barrier has been processed, the child + * has answered every ping, and exactly the sleeps its state implies (the + * pending timer, the running task) are registered on the clock. + */ +const settle = (actor: ModelActor, clock: Recording) => + until(() => { + const snapshot = actor.getSnapshot(); + const sleeping = + Number(snapshot.matches({ timer: 'armed' })) + + Number(snapshot.matches({ report: 'fetching' })); + return ( + snapshot.context.syncs === syncs && + snapshot.context.counted === snapshot.context.sent && + clock.pending === sleeping + ); + }); +let syncs = 0; + +const run = (actor: ModelActor, clock: Recording, command: Command) => + Effect.gen(function* () { + if (command === 'TICK') { + yield* TestClock.adjust('1 second'); + } else { + actor.send({ type: command }); + } + syncs++; + actor.send({ type: 'SYNC' }); + yield* settle(actor, clock); + }); + +const observe = (actor: ModelActor) => { + const snapshot = actor.getSnapshot(); + return { + value: snapshot.value, + context: snapshot.context, + child: snapshot.children.counter?.getSnapshot().context + }; +}; + +/** + * Runs `commands`, persisting and restoring before index `k` when `k` is + * given. Returns what an observer sees and what ran along the way. + */ +const execute = (commands: readonly Command[], k?: number) => { + Object.assign(tally, { entries: 0, expired: 0, ready: 0, fetches: 0 }); + syncs = 0; + const clock = recordingClock(); + let fetchingAtPersist = false; + return Effect.gen(function* () { + const first = commands.slice(0, k ?? commands.length); + const persisted = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(model); + yield* settle(actor, clock.state); + for (const command of first) { + yield* run(actor, clock.state, command); + } + fetchingAtPersist = actor.getSnapshot().matches({ report: 'fetching' }); + return k === undefined + ? observe(actor) + : roundTrip(actor.getPersistedSnapshot()); + }) + ); + if (k === undefined) { + return { observed: persisted, tally: { ...tally } }; + } + const observed = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(model, { + snapshot: persisted as Snapshot + }); + yield* settle(actor, clock.state); + for (const command of commands.slice(k)) { + yield* run(actor, clock.state, command); + } + return observe(actor); + }) + ); + return { observed, tally: { ...tally }, fetchingAtPersist }; + }).pipe(Effect.provide(clock.layer)); +}; + +/** Checks a restored run against the same commands run uninterrupted. */ +const expectSameAsUninterrupted = async ( + commands: readonly Command[], + k: number +) => { + const expected = await Effect.runPromise(execute(commands)); + const restored = await Effect.runPromise(execute(commands, k)); + expect(restored.observed).toEqual(expected.observed); + // Entry actions never re-run and timers fire once. + expect(restored.tally.entries).toBe(1); + expect(restored.tally.expired).toBe(expected.tally.expired); + expect(restored.tally.ready).toBe(expected.tally.ready); + // Only a task that was running when persisted runs again. + expect(restored.tally.fetches).toBe( + expected.tally.fetches + Number(restored.fetchingAtPersist) + ); +}; + +describe('createEffectActor with a persisted snapshot', () => { + it('resubscribes a restored root observable and receives values and completion', async () => { + let subscriptions = 0; + const logic = createObservableLogic(() => ({ + subscribe(observer) { + subscriptions++; + if (typeof observer === 'function') { + observer(subscriptions); + } else { + observer.next?.(subscriptions); + if (subscriptions === 2) { + observer.complete?.(); + } + } + return { unsubscribe() {} }; + } + })); + const snapshot = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(logic); + yield* waitFor(actor, (s) => s.context === 1); + return roundTrip(actor.getPersistedSnapshot()); + }) + ) + ); + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(logic, { snapshot }); + yield* join(actor); + expect(actor.getSnapshot().context).toBe(2); + expect(actor.getSnapshot().status).toBe('done'); + }) + ) + ); + expect(subscriptions).toBe(2); + }); + + it('restores a nested machine timer on the Effect clock with its remaining delay', async () => { + const child = createMachine({ + initial: 'waiting', + states: { + waiting: { after: { 1000: { target: 'done' } } }, + done: { type: 'final' } + } + }); + const parent = createMachine({ + actors: { child }, + invoke: { src: 'child', id: 'child' } + }); + const clock = recordingClock(); + await Effect.runPromise( + Effect.gen(function* () { + const snapshot = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(parent); + yield* until(() => clock.state.pending === 1); + yield* TestClock.adjust('600 millis'); + return roundTrip(actor.getPersistedSnapshot()); + }) + ); + yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(parent, { snapshot }); + yield* until(() => clock.state.pending === 1); + expect(clock.state.requested).toEqual([1000, 400]); + expect( + actor.getSnapshot().children.child?.getSnapshot().status + ).toBe('active'); + yield* TestClock.adjust('400 millis'); + yield* until( + () => + actor.getSnapshot().children.child?.getSnapshot().status === + 'done' + ); + }) + ); + }).pipe(Effect.provide(clock.layer)) + ); + }); + + it('matches an uninterrupted run when restored at every step of every shortest path', async () => { + const paths = getShortestPaths(model, { + events: [ + { type: 'NEXT' }, + { type: 'BACK' }, + { type: 'FETCH' }, + { type: 'PING' } + ], + serializeState: (snapshot) => + JSON.stringify([snapshot.value, snapshot.context.sent]) + }); + expect(paths.length).toBeGreaterThan(10); + for (const path of paths) { + // The first step of every path is the actor's own initialization. + const commands = path.steps + .slice(1) + .map((step) => step.event.type as Command); + for (let k = 0; k <= commands.length; k++) { + await expectSameAsUninterrupted(commands, k); + } + } + }); + + it('matches an uninterrupted run for generated events, clock advances and persist points', async () => { + await fc.assert( + fc.asyncProperty( + fc.array( + fc.constantFrom('NEXT', 'BACK', 'FETCH', 'PING', 'TICK'), + { + maxLength: 8 + } + ), + fc.nat(), + async (commands, point) => { + await expectSameAsUninterrupted( + commands, + point % (commands.length + 1) + ); + } + ), + { seed: 5773, numRuns: 40 } + ); + }); + + it('resumes a pending delayed transition with its remaining delay', async () => { + const machine = createMachine({ + initial: 'green', + states: { green: { after: { 1000: { target: 'yellow' } } }, yellow: {} } + }); + const clock = recordingClock(); + + await Effect.runPromise( + Effect.gen(function* () { + const persisted = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + yield* until(() => clock.state.pending === 1); + yield* TestClock.adjust('600 millis'); + return roundTrip(actor.getPersistedSnapshot()); + }) + ); + yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine, { + snapshot: persisted + }); + yield* until(() => clock.state.pending === 1); + expect(clock.state.requested).toEqual([1000, 400]); + yield* TestClock.adjust('400 millis'); + yield* waitFor(actor, (s) => s.matches('yellow')); + }) + ); + }).pipe(Effect.provide(clock.layer)) + ); + }); + + it('fires a delayed transition whose deadline passed while persisted', async () => { + const machine = createMachine({ + initial: 'green', + states: { green: { after: { 1000: { target: 'yellow' } } }, yellow: {} } + }); + const clock = recordingClock(); + + await Effect.runPromise( + Effect.gen(function* () { + const persisted = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + yield* until(() => clock.state.pending === 1); + return roundTrip(actor.getPersistedSnapshot()); + }) + ); + // Nothing runs the timer while the snapshot is at rest. + yield* TestClock.adjust('1 hour'); + yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine, { + snapshot: persisted + }); + yield* waitFor(actor, (s) => s.matches('yellow')); + }) + ); + }).pipe(Effect.provide(clock.layer)) + ); + }); + + it('stops a restored actor, its children and its timers when the scope closes', async () => { + const clock = recordingClock(); + const persisted = await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(model); + actor.send({ type: 'FETCH' }); + yield* until(() => clock.state.pending === 2); + return roundTrip(actor.getPersistedSnapshot()); + }) + ).pipe(Effect.provide(clock.layer)) + ); + + await Effect.runPromise( + Effect.gen(function* () { + tally.expired = 0; + const scope = yield* Scope.make(); + const actor = yield* Scope.provide( + createEffectActor(model, { snapshot: persisted }), + scope + ); + yield* until(() => clock.state.pending === 2); + yield* Scope.close(scope, Exit.void); + + expect(actor.getSnapshot().status).toBe('stopped'); + // The restarted task and the re-armed timer were interrupted. + expect(clock.state.pending).toBe(0); + yield* TestClock.adjust('1 hour'); + expect(tally.expired).toBe(0); + }).pipe(Effect.provide(clock.layer)) + ); + }); + + it('settles a restored final snapshot without running anything', async () => { + let entered = 0; + const machine = createMachine({ + initial: 'pending', + states: { + pending: { on: { FINISH: { target: 'done' } } }, + done: { + type: 'final', + entry: () => { + entered++; + } + } + }, + output: () => 'finished' + }); + + const output = await Effect.runPromise( + Effect.gen(function* () { + const persisted = yield* Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + actor.send({ type: 'FINISH' }); + yield* join(actor); + return roundTrip(actor.getPersistedSnapshot()); + }) + ); + return yield* Effect.scoped( + Effect.flatMap( + createEffectActor(machine, { snapshot: persisted }), + join + ) + ); + }) + ); + + expect(output).toBe('finished'); + expect(entered).toBe(1); + }); + + describe('Effect tasks and streams that were running when persisted', () => { + // A half-finished Effect is not serializable. Like XState's own restore + // of an active async or callback actor, it starts again from the + // beginning: its work runs at least once, possibly more than once. + const persistWhile = (logic: AnyActorLogic, started: () => boolean) => + Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(logic); + yield* until(started); + return roundTrip(actor.getPersistedSnapshot()); + }) + ) + ); + + it('restarts a root fromEffect task', async () => { + let attempts = 0; + const task = fromEffect( + Effect.suspend(() => + ++attempts === 1 ? Effect.never : Effect.succeed('done') + ) + ); + const snapshot = await persistWhile(task, () => attempts === 1); + const output = await Effect.runPromise( + Effect.scoped( + Effect.flatMap(createEffectActor(task, { snapshot }), join) + ) + ); + + expect(output).toBe('done'); + expect(attempts).toBe(2); + }); + + it('restarts root and child streams from their first item', async () => { + const seen: number[] = []; + let runs = 0; + const ticks = fromEffectStream(() => { + const items = Stream.fromIterable([1, 2, 3]).pipe( + Stream.tap((n) => Effect.sync(() => seen.push(n))) + ); + // The first run stalls after two items, as if the host went away. + return ++runs === 1 + ? Stream.concat(Stream.take(items, 2), Stream.never) + : items; + }); + const parent = setup({ actors: { ticks } }).createMachine({ + initial: 'listening', + states: { + listening: { invoke: { src: 'ticks', onDone: { target: 'done' } } }, + done: { type: 'final' } + } + }); + + for (const logic of [ticks, parent] as const) { + seen.length = 0; + runs = 0; + const snapshot = await persistWhile(logic, () => seen.length === 2); + await Effect.runPromise( + Effect.scoped( + Effect.flatMap( + createEffectActor(logic as typeof parent, { snapshot }), + join + ) + ) + ); + expect(runs).toBe(2); + expect(seen).toEqual([1, 2, 1, 2, 3]); + } + }); + }); + + it('restores without input when the logic requires input', () => { + const machine = createMachine({ + schemas: { input: types<{ id: string }>() }, + context: ({ input }) => ({ id: input.id }) + }); + const snapshot = {} as Snapshot; + + expectTypeOf(createEffectActor(machine, { snapshot })).not.toBeNever(); + expectTypeOf( + createEffectActor(machine, { input: { id: 'a' } }) + ).not.toBeNever(); + // @ts-expect-error -- a fresh actor still needs its input + createEffectActor(machine, {}); + // @ts-expect-error -- and so does one with no options at all + createEffectActor(machine); + }); +}); diff --git a/xstate-effect/src/requirements.types.test.ts b/xstate-effect/src/requirements.types.test.ts new file mode 100644 index 00000000..fc2c8531 --- /dev/null +++ b/xstate-effect/src/requirements.types.test.ts @@ -0,0 +1,335 @@ +import { Context, Effect, Scope } from 'effect'; +import { createMachine, setup, type AnyActorLogic } from 'xstate'; +import { + createEffectActor, + fromEffect, + setupEffect, + withActorScope, + type RequirementsFrom +} from './index.ts'; + +/** Invariant type equality. */ +type Equals = + (() => T extends A ? 1 : 2) extends () => T extends B ? 1 : 2 + ? true + : false; + +type IsNever = [T] extends [never] ? true : false; + +/** Whether `TWhole` (a requirements union) contains `TPart`. */ +type Includes = [TPart] extends [TWhole] ? true : false; + +/** + * The `R` channel of the Effect returned by `createEffectActor`. It carries + * the actor's own service requirements alongside `Scope`, so assertions about + * it use {@link Includes} rather than {@link Equals}. + */ +type ActorRequirements = + ReturnType> extends Effect.Effect< + any, + any, + infer R + > + ? R + : never; + +const Alpha = Context.Service<{ a: number }>('Alpha'); +const Beta = Context.Service<{ b: string }>('Beta'); + +const alphaEffect = Alpha.use((alpha) => Effect.succeed(alpha.a)); +const betaEffect = Beta.use((beta) => Effect.succeed(beta.b)); + +type RequirementsOfEffect = + T extends Effect.Effect ? R : never; + +type AlphaRequirement = RequirementsOfEffect; +type BetaRequirement = RequirementsOfEffect; + +const alphaLogic = fromEffect(alphaEffect); +const betaLogic = fromEffect(betaEffect); +const plainLogic = fromEffect(Effect.succeed(1)); + +describe('RequirementsFrom', () => { + it('supplies invocation and owning actor scopes without an application Layer', () => { + const task = fromEffect( + Effect.acquireRelease(alphaEffect, () => Effect.void) + ); + const shared = fromEffect( + Effect.acquireRelease(betaEffect, () => Effect.void).pipe(withActorScope) + ); + true satisfies Equals, AlphaRequirement>; + true satisfies Equals, BetaRequirement>; + true satisfies Includes, Scope.Scope>; + }); + + it('tracks services replaced by provided actors', () => { + const machine = setup({ actors: { work: alphaLogic } }).createMachine({ + invoke: { src: 'work' } + }); + const provided = machine.provide({ + actors: { work: fromEffect(Effect.as(betaEffect, 0)) } + }); + true satisfies Equals, BetaRequirement>; + }); + + it('tracks services introduced and replaced by provided actions', () => { + const machine = setupEffect({ + actions: { work: (_args) => Effect.void } + }).createMachine({ + on: { GO: (args, enq) => enq(args.actions.work, args) } + }); + const alpha = machine.provide({ actions: { work: () => alphaEffect } }); + const beta = alpha.provide({ actions: { work: () => betaEffect } }); + const plain = beta.provide({ actions: { work: () => {} } }); + true satisfies Equals, AlphaRequirement>; + true satisfies Equals, BetaRequirement>; + true satisfies IsNever>; + const parent = setup({ actors: { beta } }).createMachine({ + invoke: { src: 'beta' } + }); + true satisfies Equals, BetaRequirement>; + const missingService = () => { + // @ts-expect-error -- the provided action requires Alpha + Effect.runPromise(Effect.scoped(createEffectActor(alpha))); + }; + void missingService; + }); + + it('retains services of untouched and optionally provided actions', () => { + const machine = setupEffect({ + actions: { + first: (_args) => alphaEffect, + second: (_args) => alphaEffect + } + }).createMachine({}); + const provided = machine.provide({ actions: { first: () => betaEffect } }); + true satisfies Equals< + RequirementsFrom, + AlphaRequirement | BetaRequirement + >; + const optional: { first?: () => typeof betaEffect } = {}; + const maybe = machine.provide({ actions: optional }); + true satisfies Equals< + RequirementsFrom, + AlphaRequirement | BetaRequirement + >; + }); + + it('collects requirements from Effect logic directly', () => { + true satisfies Equals< + RequirementsFrom, + AlphaRequirement + >; + false satisfies IsNever>; + true satisfies Includes< + ActorRequirements, + AlphaRequirement + >; + }); + + it('collects requirements from a registered Effect actor', () => { + const machine = setup({ actors: { alphaLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'alphaLogic' } } } + }); + + true satisfies Equals, AlphaRequirement>; + true satisfies Includes< + ActorRequirements, + AlphaRequirement + >; + }); + + it('collects requirements from a registered Effect action', () => { + const machine = setupEffect({ + actions: { + alpha: (_args) => Alpha.use((alpha) => Effect.succeed(alpha.a)) + } + }).createMachine({ + on: { + GO: (args, enq) => enq(args.actions.alpha, args) + } + }); + + true satisfies Equals, AlphaRequirement>; + }); + + it('collects requirements through a registered child machine', () => { + const child = setup({ actors: { alphaLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'alphaLogic' } } } + }); + const parent = setup({ actors: { child } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'child' } } } + }); + + true satisfies Equals, AlphaRequirement>; + true satisfies Includes, AlphaRequirement>; + + // The gap this type closes: the parent's requirements used to infer + // `never`, so this probe used to compile. + // @ts-expect-error -- nested requirements must no longer be `never` + const probe: IsNever> extends true + ? 'NESTED_R_IS_NEVER' + : 'nested ok' = 'NESTED_R_IS_NEVER'; + void probe; + }); + + it('collects requirements two machine levels deep', () => { + const grandchild = setup({ actors: { alphaLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'alphaLogic' } } } + }); + const child = setup({ actors: { grandchild } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'grandchild' } } } + }); + const parent = setup({ actors: { child } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'child' } } } + }); + + true satisfies Equals, AlphaRequirement>; + true satisfies Includes, AlphaRequirement>; + }); + + it('infers `never` for a machine with no Effect sources', () => { + const child = setup({ actors: { plainLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'plainLogic' } } } + }); + const parent = setup({ actors: { child } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'child' } } } + }); + + true satisfies IsNever>; + true satisfies IsNever>; + // @ts-expect-error -- a machine with no Effect sources requires nothing + true satisfies Includes, AlphaRequirement>; + }); + + it('unions requirements from two different actors', () => { + const child = setup({ actors: { betaLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'betaLogic' } } } + }); + const parent = setup({ actors: { alphaLogic, child } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'alphaLogic' } } } + }); + + true satisfies Equals< + RequirementsFrom, + AlphaRequirement | BetaRequirement + >; + false satisfies Equals, AlphaRequirement>; + false satisfies Equals, BetaRequirement>; + true satisfies Includes, AlphaRequirement>; + true satisfies Includes, BetaRequirement>; + }); +}); + +describe('RequirementsFrom (inline invoke.src)', () => { + it('collects requirements from an inline root invoke', () => { + const machine = createMachine({ + invoke: { src: alphaLogic } + }); + + true satisfies Equals, AlphaRequirement>; + true satisfies Includes< + ActorRequirements, + AlphaRequirement + >; + }); + + it('collects requirements from an inline invoke nested two states deep', () => { + const machine = setup({}).createMachine({ + initial: 'outer', + states: { + outer: { + initial: 'inner', + states: { + inner: { invoke: { src: alphaLogic } } + } + } + } + }); + + true satisfies Equals, AlphaRequirement>; + }); + + it('collects requirements from an array of invoke configs', () => { + const machine = setup({ actors: { betaLogic } }).createMachine({ + initial: 'a', + states: { + a: { + invoke: [{ src: 'betaLogic' }, { src: alphaLogic }] + } + } + }); + + true satisfies Equals< + RequirementsFrom, + AlphaRequirement | BetaRequirement + >; + }); + + it('recurses into an inline child machine used as invoke.src', () => { + const child = createMachine({ + initial: 'a', + states: { a: { invoke: { src: alphaLogic } } } + }); + const parent = createMachine({ + initial: 'a', + states: { a: { invoke: { src: child } } } + }); + + true satisfies Equals, AlphaRequirement>; + true satisfies Includes, AlphaRequirement>; + }); + + it('no longer infers `never` for inline Effect logic', () => { + const inline = createMachine({ + initial: 'a', + states: { a: { invoke: { src: alphaLogic } } } + }); + + false satisfies IsNever>; + + // @ts-expect-error -- inline requirements must no longer be `never` + const probe: IsNever> extends true + ? 'INLINE_R_IS_NEVER' + : 'inline ok' = 'INLINE_R_IS_NEVER'; + void probe; + }); + + it('infers `never` when every invoke.src is a registered string', () => { + const machine = setup({ actors: { plainLogic } }).createMachine({ + initial: 'a', + states: { a: { invoke: { src: 'plainLogic' } } } + }); + + true satisfies IsNever>; + }); + + it('cannot see logic spawned inside a transition function body', () => { + const machine = createMachine({ + initial: 'a', + states: { + a: { + on: { + GO: (_args, enq) => { + enq.spawn(alphaLogic); + } + } + } + } + }); + + // Known limitation: `enq.spawn` happens inside a function body, so the + // spawned logic never reaches the machine's type. + true satisfies IsNever>; + }); +}); diff --git a/xstate-effect/src/runtime.test.ts b/xstate-effect/src/runtime.test.ts new file mode 100644 index 00000000..8634fba9 --- /dev/null +++ b/xstate-effect/src/runtime.test.ts @@ -0,0 +1,1198 @@ +import { Context, Duration, Effect, Exit, Scope, Stream } from 'effect'; +import { TestClock } from 'effect/testing'; +import { + createActor, + createMachine, + setup, + type AnyActorRef, + type EventRejection +} from 'xstate'; +import { + EffectActor, + EffectInterruptedError, + createEffectActor, + deadLetters, + emitted, + fromEffect, + fromEffectEventStream, + fromEffectStream, + setupEffect, + withActorScope +} from './index.ts'; + +/** + * Polls until `predicate` holds. Effects run on detached fibers, so tests wait + * for the condition they assert on instead of for a fixed number of ticks. + */ +const until = async (predicate: () => boolean, timeoutMs = 1000) => { + const deadline = Date.now() + timeoutMs; + while (!predicate()) { + if (Date.now() > deadline) { + throw new Error('Timed out waiting for condition'); + } + await new Promise((resolve) => setTimeout(resolve, 1)); + } +}; + +let scopes: Scope.Closeable[] = []; + +afterEach(async () => { + const pending = scopes; + scopes = []; + for (const scope of pending) { + await Effect.runPromise(Scope.close(scope, Exit.void)); + } +}); + +/** Runs a scoped Effect in a scope that stays open until the test ends. */ +const runScoped = async ( + effect: Effect.Effect +): Promise => { + const scope = await Effect.runPromise(Scope.make()); + scopes.push(scope); + return Effect.runPromise(Scope.provide(effect, scope)); +}; + +describe('@xstate/effect runtime', () => { + it('finishes task cleanup before releasing resources in the owning actor scope', async () => { + const order: string[] = []; + let started = false; + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + yield* createEffectActor( + fromEffect( + Effect.gen(function* () { + // Acquire after yielding, once the hosted fiber has been registered. + yield* Effect.sleep(1); + yield* Effect.acquireRelease(Effect.void, () => + Effect.sync(() => { + order.push('actor resource'); + }) + ).pipe(withActorScope); + yield* Effect.acquireRelease(Effect.void, () => + Effect.sleep(5).pipe( + Effect.andThen( + Effect.sync(() => { + order.push('task resource'); + }) + ) + ) + ); + started = true; + return yield* Effect.never; + }) + ) + ); + yield* Effect.promise(() => until(() => started)); + }) + ) + ); + expect(order).toEqual(['task resource', 'actor resource']); + }); + + it.each(['snapshot', 'event'] as const)( + 'releases %s stream resources when the invoking state exits', + async (kind) => { + let started = false; + let released = 0; + const stream = Stream.unwrap( + Effect.gen(function* () { + yield* Effect.acquireRelease(Effect.void, () => + Effect.sync(() => { + released++; + }) + ); + started = true; + return Stream.never; + }) + ); + const work = + kind === 'snapshot' + ? fromEffectStream(stream) + : fromEffectEventStream(stream); + const machine = setup({ actors: { work } }).createMachine({ + initial: 'working', + states: { + working: { + invoke: { src: 'work' }, + on: { CANCEL: { target: 'idle' } } + }, + idle: {} + } + }); + const actor = await runScoped(createEffectActor(machine)); + await until(() => started); + actor.send({ type: 'CANCEL' }); + await until(() => released === 1); + expect(actor.getSnapshot().matches('idle')).toBe(true); + expect(actor.getSnapshot().status).toBe('active'); + } + ); + + it.each(['success', 'cancel'] as const)( + 'keeps explicitly actor-scoped resources after invocation %s', + async (outcome) => { + let started = false; + let interrupted = false; + let released = 0; + const work = fromEffect( + Effect.gen(function* () { + yield* Effect.acquireRelease(Effect.void, () => + Effect.sleep(5).pipe( + Effect.andThen( + Effect.sync(() => { + released++; + }) + ) + ) + ).pipe(withActorScope); + started = true; + if (outcome === 'cancel') + return yield* Effect.never.pipe( + Effect.onInterrupt(() => + Effect.sync(() => { + interrupted = true; + }) + ) + ); + return 'complete'; + }) + ); + const machine = setup({ actors: { work } }).createMachine({ + initial: 'working', + states: { + working: { + invoke: { src: 'work', onDone: { target: 'idle' } }, + on: { CANCEL: { target: 'idle' } } + }, + idle: {} + } + }); + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + yield* Effect.promise(() => until(() => started)); + if (outcome === 'cancel') { + actor.send({ type: 'CANCEL' }); + yield* Effect.promise(() => until(() => interrupted)); + } + yield* Effect.promise(() => + until(() => actor.getSnapshot().matches('idle')) + ); + expect(released).toBe(0); + expect(actor.getSnapshot().status).toBe('active'); + }) + ) + ); + expect(released).toBe(1); + } + ); + + it('runs an action override with a newly required service', async () => { + class Audit extends Context.Service< + Audit, + { record: Effect.Effect } + >()('ProvidedAudit') {} + let recorded = false; + const machine = setupEffect({ actions: { audit: (_args) => Effect.void } }) + .createMachine({ + on: { GO: (args, enq) => enq(args.actions.audit, args) } + }) + .provide({ + actions: { audit: () => Audit.use((audit) => audit.record) } + }); + const actor = await runScoped( + createEffectActor(machine).pipe( + Effect.provideService(Audit, { + record: Effect.sync(() => { + recorded = true; + }) + }) + ) + ); + actor.send({ type: 'GO' }); + await until(() => recorded); + expect(actor.getSnapshot().status).toBe('active'); + }); + + it.each(['success', 'failure', 'cancel'] as const)( + 'releases invocation resources on %s while the parent stays active', + async (outcome) => { + let started = false; + let released = 0; + const work = fromEffect( + Effect.gen(function* () { + yield* Effect.acquireRelease(Effect.void, () => + Effect.sync(() => { + released++; + }) + ); + started = true; + yield* Effect.sleep(5); + if (outcome === 'failure') return yield* Effect.fail('failed'); + if (outcome === 'cancel') return yield* Effect.never; + return 'complete'; + }) + ); + const machine = setup({ actors: { work } }).createMachine({ + context: { releasedAtOutcome: 0 }, + initial: 'working', + states: { + working: { + invoke: { + src: 'work', + onDone: { + target: 'idle', + context: () => ({ releasedAtOutcome: released }) + }, + onError: { + target: 'idle', + context: () => ({ releasedAtOutcome: released }) + } + }, + on: { CANCEL: { target: 'idle' } } + }, + idle: {} + } + }); + const actor = await runScoped(createEffectActor(machine)); + await until(() => started); + if (outcome === 'cancel') actor.send({ type: 'CANCEL' }); + await until(() => actor.getSnapshot().matches('idle')); + await until(() => released === 1); + expect(actor.getSnapshot().status).toBe('active'); + expect(released).toBe(1); + if (outcome !== 'cancel') + expect(actor.getSnapshot().context.releasedAtOutcome).toBe(1); + } + ); + + it('awaits asynchronous invocation finalizers before the enclosing scope closes', async () => { + let started = false; + let released = false; + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + yield* createEffectActor( + fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sleep(10).pipe( + Effect.andThen( + Effect.sync(() => { + released = true; + }) + ) + ) + ); + started = true; + return yield* Effect.never; + }) + ) + ); + yield* Effect.promise(() => until(() => started)); + }) + ) + ); + expect(released).toBe(true); + }); + + it('stops the actor and interrupts its Effect when the enclosing scope closes', async () => { + let started = false; + let interrupted = false; + const logic = fromEffect( + Effect.ensuring( + Effect.sync(() => { + started = true; + }).pipe(Effect.andThen(Effect.never)), + Effect.sync(() => { + interrupted = true; + }) + ) + ); + let actor!: EffectActor; + + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + actor = yield* createEffectActor(logic); + yield* Effect.promise(() => until(() => started)); + + expect(actor.getSnapshot().status).toBe('active'); + expect(interrupted).toBe(false); + }) + ) + ); + + expect(actor.getSnapshot().status).toBe('stopped'); + expect(interrupted).toBe(true); + }); + + it('releases actor-scoped finalizers when the actor is stopped', async () => { + let started = false; + let released = 0; + const logic = fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + released++; + }) + ); + started = true; + return yield* Effect.never; + }) + ); + const actor = await runScoped(createEffectActor(logic)); + await until(() => started); + + expect(released).toBe(0); + + actor.stop(); + await until(() => released === 1); + + expect(released).toBe(1); + }); + + it('releases actor-scoped finalizers when the enclosing scope closes', async () => { + let started = false; + let released = 0; + + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + yield* createEffectActor( + fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + released++; + }) + ); + started = true; + return yield* Effect.never; + }) + ) + ); + yield* Effect.promise(() => until(() => started)); + + expect(released).toBe(0); + }) + ) + ); + + expect(released).toBe(1); + }); + + it('keeps actor-scoped finalizers open after the Effect itself completes', async () => { + let completed = false; + let released = 0; + const machine = setupEffect({ + actions: { + work: (_args) => + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + released++; + }) + ); + completed = true; + }) + } + }).createMachine({ + on: { + WORK: (args, enq) => enq(args.actions.work, args) + } + }); + const actor = await runScoped(createEffectActor(machine)); + + actor.send({ type: 'WORK' }); + await until(() => completed); + + expect(released).toBe(0); + expect(actor.getSnapshot().status).toBe('active'); + + actor.stop(); + await until(() => released === 1); + + expect(released).toBe(1); + }); + + it('runs a hosted finalizer before Effect.scoped resolves', async () => { + const order: string[] = []; + let started = false; + + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + yield* createEffectActor( + fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + order.push('finalizer'); + }) + ); + started = true; + return yield* Effect.never; + }) + ) + ); + yield* Effect.promise(() => until(() => started)); + }) + ) + ); + order.push('scope closed'); + + expect(order).toEqual(['finalizer', 'scope closed']); + }); + + it('runs a hosted finalizer when the actor errors', async () => { + let released = 0; + const logic = fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + released++; + }) + ); + return yield* Effect.fail({ code: 'BOOM' as const }).pipe( + Effect.delay(1) + ); + }) + ); + const actor = await runScoped(createEffectActor(logic)); + actor.subscribe({ error: () => {} }); + await until(() => actor.getSnapshot().status === 'error'); + await until(() => released === 1); + + expect(released).toBe(1); + }); + + it('tolerates stopping an actor before its scope closes', async () => { + let started = false; + let released = 0; + + await expect( + Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor( + fromEffect( + Effect.gen(function* () { + yield* Effect.addFinalizer(() => + Effect.sync(() => { + released++; + }) + ); + started = true; + return yield* Effect.never; + }) + ) + ); + yield* Effect.promise(() => until(() => started)); + + actor.stop(); + actor.stop(); + yield* Effect.promise(() => until(() => released === 1)); + + expect(actor.getSnapshot().status).toBe('stopped'); + }) + ) + ) + ).resolves.toBeUndefined(); + + expect(released).toBe(1); + }); + + it('drives delayed transitions with the Effect clock', async () => { + const machine = createMachine({ + initial: 'green', + states: { + green: { after: { 1000: { target: 'yellow' } } }, + yellow: {} + } + }); + + await Effect.runPromise( + Effect.scoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + + expect(actor.getSnapshot().value).toBe('green'); + + yield* TestClock.adjust('1 second'); + yield* Effect.promise(() => + until(() => actor.getSnapshot().value === 'yellow') + ); + + expect(actor.getSnapshot().value).toBe('yellow'); + }) + ).pipe(Effect.provide(TestClock.layer())) + ); + }); + + it('interrupts a pending after timer when the enclosing scope closes', async () => { + let entered = 0; + const machine = createMachine({ + initial: 'green', + states: { + green: { after: { 1000: { target: 'yellow' } } }, + yellow: { + entry: () => { + entered++; + } + } + } + }); + + await Effect.runPromise( + Effect.gen(function* () { + yield* Effect.scoped( + Effect.gen(function* () { + yield* createEffectActor(machine); + yield* TestClock.adjust('500 millis'); + }) + ); + + // The timer fiber lived in the actor scope, which is now closed. + yield* TestClock.adjust('5 seconds'); + + expect(entered).toBe(0); + }).pipe(Effect.provide(TestClock.layer())) + ); + }); + + it('reports self-interruption as an EffectInterruptedError', async () => { + const actor = await runScoped( + createEffectActor(fromEffect(Effect.interrupt)) + ); + await until(() => actor.getSnapshot().status === 'error'); + + const snapshot = actor.getSnapshot(); + const error: unknown = snapshot.error; + expect(error).toBeInstanceOf(EffectInterruptedError); + expect((error as EffectInterruptedError)._tag).toBe( + 'EffectInterruptedError' + ); + }); + + it('reports an Effect.timeout as a TimeoutError failure', async () => { + const logic = fromEffect(Effect.timeout(Effect.never, Duration.millis(1))); + const actor = await runScoped(createEffectActor(logic)); + actor.subscribe({ error: () => {} }); + await until(() => actor.getSnapshot().status === 'error'); + + const error: unknown = actor.getSnapshot().error; + expect((error as { _tag?: string })._tag).toBe('TimeoutError'); + expect(error).not.toBeInstanceOf(EffectInterruptedError); + }); + + it('reports a defect from Effect.die as the actor error', async () => { + const defect = new Error('defect'); + const actor = await runScoped( + createEffectActor(fromEffect(Effect.die(defect))) + ); + await until(() => actor.getSnapshot().status === 'error'); + + expect(actor.getSnapshot().status).toBe('error'); + expect(actor.getSnapshot().error).toBe(defect); + }); + + it('routes an interrupted invoked Effect to onError', async () => { + let received: unknown; + const worker = fromEffect(Effect.interrupt); + const machine = setup({ actors: { worker } }).createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { + src: 'worker', + onError: ({ event }) => { + received = event.error; + return { target: 'failed' }; + } + } + }, + failed: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + await until(() => actor.getSnapshot().value === 'failed'); + + expect(received).toBeInstanceOf(EffectInterruptedError); + }); + + it('does not report interruption when the invoking state exits', async () => { + let interrupted = false; + const worker = fromEffect( + Effect.ensuring( + Effect.never, + Effect.sync(() => { + interrupted = true; + }) + ) + ); + const machine = setup({ actors: { worker } }).createMachine({ + initial: 'working', + states: { + working: { + invoke: { src: 'worker', id: 'worker' }, + on: { CANCEL: { target: 'cancelled' } } + }, + cancelled: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + const child = actor.getSnapshot().children.worker; + + actor.send({ type: 'CANCEL' }); + await until(() => interrupted); + + expect(actor.getSnapshot().value).toBe('cancelled'); + expect(actor.getSnapshot().status).toBe('active'); + expect(child?.getSnapshot().status).toBe('stopped'); + expect(child?.getSnapshot().error).toBeUndefined(); + }); + + it('interrupts a running Effect action when its actor is stopped', async () => { + let started = false; + let interrupted = false; + const machine = setupEffect({ + actions: { + work: (_args) => + Effect.ensuring( + Effect.sync(() => { + started = true; + }).pipe(Effect.andThen(Effect.never)), + Effect.sync(() => { + interrupted = true; + }) + ) + } + }).createMachine({ + initial: 'active', + states: { + active: { + on: { + WORK: (args, enq) => enq(args.actions.work, args) + } + } + } + }); + const actor = await runScoped(createEffectActor(machine)); + + actor.send({ type: 'WORK' }); + await until(() => started); + actor.stop(); + await until(() => interrupted); + + expect(interrupted).toBe(true); + }); + + it('does not block the actor while an Effect action runs', async () => { + let started = false; + let finished = false; + const machine = setupEffect({ + actions: { + work: (_args) => + Effect.gen(function* () { + started = true; + yield* Effect.never; + finished = true; + }) + } + }).createMachine({ + context: { count: 0 }, + on: { + WORK: (args, enq) => enq(args.actions.work, args), + PING: ({ context }) => ({ context: { count: context.count + 1 } }) + } + }); + const actor = await runScoped(createEffectActor(machine)); + + actor.send({ type: 'WORK' }); + await until(() => started); + actor.send({ type: 'PING' }); + await until(() => actor.getSnapshot().context.count === 1); + + expect(actor.getSnapshot().context).toEqual({ count: 1 }); + expect(finished).toBe(false); + }); + + it('runs an Effect action provided through machine.provide in the host context', async () => { + const Audit = Context.Service<{ record: (value: string) => void }>('Audit'); + const recorded: string[] = []; + const machine = setupEffect({ + actions: { + audit: (_args) => + Audit.use((audit) => Effect.sync(() => audit.record('declared'))) + } + }).createMachine({ + on: { + AUDIT: (args, enq) => enq(args.actions.audit, args) + } + }); + const provided = machine.provide({ + actions: { + audit: (_args: unknown) => + Audit.use((audit) => Effect.sync(() => audit.record('provided'))) + } + }); + + const actor = await runScoped( + Effect.provideService(createEffectActor(provided), Audit, { + record: (value) => recorded.push(value) + }) + ); + actor.send({ type: 'AUDIT' }); + await until(() => recorded.length > 0, 50); + + expect(recorded).toEqual(['provided']); + }); + + it('runs a plain action provided through machine.provide', async () => { + const recorded: string[] = []; + const machine = setupEffect({ + actions: { + audit: (_args) => Effect.sync(() => recorded.push('declared')) + } + }).createMachine({ + on: { + AUDIT: (args, enq) => enq(args.actions.audit, args) + } + }); + const provided = machine.provide({ + actions: { + audit: () => { + recorded.push('provided'); + } + } + }); + + const actor = await runScoped(createEffectActor(provided)); + actor.send({ type: 'AUDIT' }); + await until(() => recorded.length > 0); + + expect(recorded).toEqual(['provided']); + }); + + it('observes events emitted from the fromEffect source args', async () => { + let release!: () => void; + const gate = new Promise((resolve) => { + release = resolve; + }); + const logic = fromEffect(({ emit }) => + Effect.gen(function* () { + yield* Effect.promise(() => gate); + emit({ type: 'progress', value: 1 }); + emit({ type: 'progress', value: 2 }); + return 'done'; + }) + ); + + const collected: unknown[] = []; + + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(logic); + let listeners = 0; + const actorOn = actor.on.bind(actor); + actor.on = ((...args: Parameters) => { + listeners++; + return actorOn(...args); + }) as typeof actor.on; + + yield* Effect.forkScoped( + Stream.runForEach(emitted(actor), (event) => + Effect.sync(() => { + collected.push(event); + }) + ) + ); + yield* Effect.promise(() => until(() => listeners > 0)); + release(); + yield* Effect.promise(() => until(() => collected.length === 2)); + }) + ); + + expect(collected).toEqual([ + { type: 'progress', value: 1 }, + { type: 'progress', value: 2 } + ]); + }); + + it('reports a failing Effect stream as an actor error', async () => { + const failure = { code: 'STREAM_FAILED' as const }; + const actor = await runScoped( + createEffectActor(fromEffectStream(Stream.fail(failure))) + ); + await until(() => actor.getSnapshot().status === 'error'); + + expect(actor.getSnapshot().error).toEqual(failure); + }); + + it('interrupts an Effect stream when the invoking state exits', async () => { + let interrupted = false; + const worker = fromEffectStream( + Stream.fromEffect( + Effect.ensuring( + Effect.never, + Effect.sync(() => { + interrupted = true; + }) + ) + ) + ); + const machine = setup({ actors: { worker } }).createMachine({ + initial: 'streaming', + states: { + streaming: { + invoke: { src: 'worker' }, + on: { CANCEL: { target: 'cancelled' } } + }, + cancelled: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + actor.send({ type: 'CANCEL' }); + await until(() => interrupted); + + expect(actor.getSnapshot().value).toBe('cancelled'); + }); + + it('does not report interruption of an Effect that loses an internal race', async () => { + let loserReleased = false; + const logic = fromEffect( + Effect.race( + Effect.as(Effect.sleep('5 millis'), 'winner'), + Effect.ensuring( + Effect.never, + Effect.sync(() => { + loserReleased = true; + }) + ) + ) + ); + + const actor = await runScoped(createEffectActor(logic)); + await until(() => actor.getSnapshot().status === 'done'); + + expect(actor.getSnapshot().output).toBe('winner'); + expect(actor.getSnapshot().error).toBeUndefined(); + expect(loserReleased).toBe(true); + }); + + it('resolves the Effect host through the parent chain', async () => { + const Greeting = Context.Service<{ value: string }>('Greeting'); + const leaf = fromEffect( + Greeting.use((greeting) => Effect.succeed(greeting.value)) + ); + const child = setup({ actors: { leaf } }).createMachine({ + context: { greeting: '' }, + initial: 'pending', + states: { + pending: { + invoke: { + src: 'leaf', + onDone: { + target: 'done', + context: ({ event }) => ({ greeting: event.output }) + } + } + }, + done: { type: 'final' } + } + }); + const root = setup({ actors: { child } }).createMachine({ + initial: 'pending', + states: { + pending: { + invoke: { src: 'child', id: 'child', onDone: { target: 'done' } } + }, + done: {} + } + }); + + const actor = await runScoped( + Effect.provideService(createEffectActor(root), Greeting, { + value: 'from the root' + }) + ); + await until(() => actor.getSnapshot().value === 'done'); + + expect(actor.getSnapshot().value).toBe('done'); + }); + + it('runs spawned Effect logic in the host Effect context', async () => { + const Greeting = Context.Service<{ value: string }>('Greeting'); + const leaf = fromEffect( + Greeting.use((greeting) => Effect.succeed(greeting.value)) + ); + const machine = setup({ actors: { leaf } }).createMachine({ + context: { ref: undefined as AnyActorRef | undefined }, + entry: ({ actors }, enq) => ({ + context: { ref: enq.spawn(actors.leaf) } + }) + }); + + const actor = await runScoped( + Effect.provideService(createEffectActor(machine), Greeting, { + value: 'spawned' + }) + ); + const ref = actor.getSnapshot().context.ref!; + await until(() => ref.getSnapshot().status === 'done'); + + expect(ref.getSnapshot().output).toBe('spawned'); + }); + + it('rejects inline Effect logic passed to enq.spawn', async () => { + const machine = setup({}).createMachine({ + context: { ref: undefined as AnyActorRef | undefined }, + entry: (_args, enq) => ({ + context: { ref: enq.spawn(fromEffect(Effect.succeed('inline'))) } + }) + }); + + const actor = await runScoped(createEffectActor(machine)); + const ref = actor.getSnapshot().context.ref!; + await until(() => ref.getSnapshot().status === 'error'); + + expect(String(ref.getSnapshot().error)).toMatch( + /must be declared in setup\(\{ actors \}\)/ + ); + }); + + it('rejects inline spawned logic even when another invoke has a dynamic src', async () => { + const leaf = fromEffect(Effect.succeed('leaf')); + const machine = setup({ actors: { leaf } }).createMachine({ + context: { + declared: undefined as AnyActorRef | undefined, + inline: undefined as AnyActorRef | undefined + }, + initial: 'working', + states: { + working: { + invoke: { + src: ({ actors }) => actors.leaf, + id: 'dynamic', + onDone: { target: 'done' } + }, + entry: ({ actors }, enq) => ({ + context: { + declared: enq.spawn(actors.leaf), + inline: enq.spawn(fromEffect(Effect.succeed('inline'))) + } + }) + }, + done: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + const { declared, inline } = actor.getSnapshot().context; + await until(() => declared!.getSnapshot().status === 'done'); + await until(() => inline!.getSnapshot().status === 'error'); + await until(() => actor.getSnapshot().value === 'done'); + + // A declared actor spawned by name is allowed… + expect(declared!.getSnapshot().output).toBe('leaf'); + // …an inline one is not, even though a dynamic `invoke.src` is nearby… + expect(String(inline!.getSnapshot().error)).toMatch( + /must be declared in setup\(\{ actors \}\)/ + ); + // …and the dynamically invoked child still ran. + expect(actor.getSnapshot().value).toBe('done'); + }); + + it('routes a defect in an Effect action to onError', async () => { + const defect = new Error('boom'); + let received: unknown; + const machine = setupEffect({ + actions: { + boom: (_args) => Effect.die(defect) + } + }).createMachine({ + initial: 'active', + states: { + active: { + on: { BOOM: (args, enq) => enq(args.actions.boom, args) }, + onError: ({ event }) => { + received = event.error; + return { target: 'failed' }; + } + }, + failed: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + actor.send({ type: 'BOOM' }); + await until(() => actor.getSnapshot().value === 'failed'); + + expect(received).toBe(defect); + }); + + it('reports a send to a stopped actor as a dead letter', async () => { + const worker = fromEffect(Effect.never); + const machine = setup({ actors: { worker } }).createMachine({ + initial: 'working', + states: { + working: { + invoke: { src: 'worker', id: 'worker' }, + on: { CANCEL: { target: 'cancelled' } } + }, + cancelled: {} + } + }); + const letters: Array<{ reason: string; type: string }> = []; + + await runScoped( + Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + let subscribed = false; + const onRejectedEvent = actor.system.onRejectedEvent; + actor.system.onRejectedEvent = ( + listener: (rejection: EventRejection) => void + ) => { + subscribed = true; + return onRejectedEvent.call(actor.system, listener); + }; + const listening = () => subscribed; + + yield* Effect.forkScoped( + Stream.runForEach(deadLetters(actor), (event) => + Effect.sync(() => { + letters.push({ + reason: event.reason, + type: event.event.type + }); + }) + ) + ); + yield* Effect.promise(() => until(listening)); + + const child = actor.getSnapshot().children.worker!; + actor.send({ type: 'CANCEL' }); + yield* Effect.promise(() => + until(() => child.getSnapshot().status === 'stopped') + ); + + child.send({ type: 'TO_CHILD' }); + actor.stop(); + actor.send({ type: 'TO_ROOT' }); + + yield* Effect.promise(() => until(() => letters.length === 2)); + }) + ); + + expect(letters).toEqual([ + { reason: 'stopped', type: 'TO_CHILD' }, + { reason: 'stopped', type: 'TO_ROOT' } + ]); + }); + + it('streams EventRejection objects and unsubscribes when the stream ends', async () => { + const actor = createActor(createMachine({})).start(); + actor.stop(); + let active = 0; + const onRejectedEvent = actor.system.onRejectedEvent; + actor.system.onRejectedEvent = ( + listener: (rejection: EventRejection) => void + ) => { + active++; + const subscription = onRejectedEvent.call(actor.system, listener); + return { + unsubscribe: () => { + active--; + subscription.unsubscribe(); + } + }; + }; + + const collected = Effect.runPromise( + Stream.runCollect(Stream.take(deadLetters(actor), 1)) + ); + await until(() => active === 1); + actor.send({ type: 'FIRST' }); + const letters: EventRejection[] = Array.from(await collected); + + expect(letters).toHaveLength(1); + expect(letters[0]).toMatchObject({ + event: { type: 'FIRST' }, + targetRef: actor, + reason: 'stopped' + }); + expect(active).toBe(0); + }); + + it('accepts a fromEffect config without schemas', async () => { + const logic = fromEffect({ + id: 'loadUser', + effect: ({ input }: { input: { id: string } }) => + Effect.succeed({ greeting: `Hello ${input.id}` }) + }); + + // `EffectActorLogic` does not surface the `id` that `createLogic` sets. + expect(logic.id).toBe('loadUser'); + + const actor = await runScoped( + createEffectActor(logic, { input: { id: '42' } }) + ); + await until(() => actor.getSnapshot().status === 'done'); + + actor.getSnapshot().output satisfies { greeting: string } | undefined; + expect(actor.getSnapshot().output).toEqual({ greeting: 'Hello 42' }); + }); + + it('runs hosted Effects inside spans named after their source', async () => { + const spans: Array<{ name: string; attributes: Record }> = + []; + const record = Effect.gen(function* () { + const span = yield* Effect.currentSpan; + spans.push({ + name: span.name, + attributes: Object.fromEntries(span.attributes) + }); + }); + const worker = fromEffect(Effect.as(record, 'ok')); + const machine = setupEffect({ + actors: { worker }, + actions: { audit: (_args) => record } + }).createMachine({ + initial: 'pending', + on: { AUDIT: (args, enq) => enq(args.actions.audit, args) }, + states: { + pending: { + invoke: { src: 'worker', id: 'worker', onDone: { target: 'done' } } + }, + done: {} + } + }); + + const actor = await runScoped(createEffectActor(machine)); + await until(() => actor.getSnapshot().value === 'done'); + actor.send({ type: 'AUDIT' }); + await until(() => spans.length === 2); + + expect(spans[0]).toEqual({ + name: 'fromEffect', + attributes: { + 'xstate.actor.id': 'worker', + 'xstate.actor.address': `${actor.address}/worker` + } + }); + expect(spans[1]).toEqual({ + name: 'action.audit', + attributes: { + 'xstate.actor.id': actor.id, + 'xstate.actor.address': actor.address + } + }); + }); +}); diff --git a/xstate-effect/src/schema.ts b/xstate-effect/src/schema.ts new file mode 100644 index 00000000..e7dad694 --- /dev/null +++ b/xstate-effect/src/schema.ts @@ -0,0 +1,214 @@ +import { Schema } from 'effect'; +import type { + SetupSchemas, + SetupStateSchema, + SetupStateSchemas, + StandardSchemaV1 +} from 'xstate'; + +/** + * An Effect `Schema` accepted by this package. `setupEffect`, `fromEffect`, + * `fromEffectStream` and `fromEffectEventStream` convert it to a Standard + * Schema, so XState infers the decoded `Schema.Type` without an explicit call + * to `Schema.toStandardSchemaV1`. + */ +export type EffectSchema = Schema.ConstraintDecoder; + +/** + * Either an Effect {@link EffectSchema} or a Standard Schema. Every schema + * position in this package accepts both, so Effect schemas and schemas from + * other libraries can be mixed in one machine. + */ +export type EffectSchemaLike = StandardSchemaV1 | EffectSchema; + +interface RuntimeValidationDoesNotSupportTransformingSchemas { + readonly __xstate_effect_error: 'Runtime validation does not support schemas with different encoded and decoded types'; +} + +type IsAny = 0 extends 1 & T ? true : false; + +export type ToStandardSchema = TSchema extends StandardSchemaV1 + ? TSchema + : TSchema extends EffectSchema + ? StandardSchemaV1 & TSchema + : never; + +type AssertNonTransformingSchema = TSchema extends EffectSchemaLike + ? IsAny>> extends true + ? TSchema + : IsAny< + StandardSchemaV1.InferOutput> + > extends true + ? TSchema + : [ + StandardSchemaV1.InferInput>, + StandardSchemaV1.InferOutput> + ] extends [ + StandardSchemaV1.InferOutput>, + StandardSchemaV1.InferInput> + ] + ? TSchema + : RuntimeValidationDoesNotSupportTransformingSchemas + : TSchema; + +type EffectSchemaShape = TValue extends StandardSchemaV1 + ? EffectSchemaLike + : TValue extends Record + ? { [K in keyof TValue]: EffectSchemaShape } + : TValue; + +type ToStandardSchemaShape = TValue extends EffectSchemaLike + ? ToStandardSchema + : TValue extends Record + ? { [K in keyof TValue]: ToStandardSchemaShape } + : TValue; + +/** + * The `schemas` option of `setupEffect`: XState's `SetupSchemas` with every + * schema position widened to {@link EffectSchemaLike}. Covers `context`, + * `input`, `output` and the per-key records for `events`, `internalEvents`, + * `emitted` and `children`. + */ +export type EffectSetupSchemas = { + [K in keyof SetupSchemas]?: EffectSchemaShape>; +}; + +export type ValidateEffectActorSchemas = { + [K in keyof TSchemas]: AssertNonTransformingSchema; +}; + +export type ValidateEffectSetupSchemas = { + [K in keyof TSchemas]: K extends + | 'events' + | 'internalEvents' + | 'emitted' + | 'children' + ? { + [P in keyof TSchemas[K]]: AssertNonTransformingSchema; + } + : K extends 'context' | 'input' | 'output' + ? AssertNonTransformingSchema + : TSchemas[K]; +}; + +export type ToStandardSetupSchemas = { + [K in keyof TSchemas]: ToStandardSchemaShape; +} extends infer TStandardSchemas extends SetupSchemas + ? TStandardSchemas + : never; + +/** + * One node of the `states` option of `setupEffect`: the schemas declared for + * that state, and the same shape recursively for its child states. It is + * XState's `SetupStateSchema` with Effect schemas allowed in every schema + * position. + */ +export interface EffectSetupStateSchema { + schemas?: EffectSchemaShape; + states?: Record; +} + +export type ValidateEffectSetupStates = { + [K in keyof TStates]: TStates[K] extends EffectSetupStateSchema + ? { + [P in keyof TStates[K]]: P extends 'schemas' + ? TStates[K][P] extends Record + ? { + [S in keyof TStates[K][P]]: AssertNonTransformingSchema< + TStates[K][P][S] + >; + } + : TStates[K][P] + : P extends 'states' + ? TStates[K][P] extends Record + ? ValidateEffectSetupStates + : TStates[K][P] + : TStates[K][P]; + } + : TStates[K]; +}; + +type ToStandardSetupStateSchema = + TStateSchema extends EffectSetupStateSchema + ? { + [K in keyof TStateSchema]: K extends 'schemas' + ? ToStandardSchemaShape + : K extends 'states' + ? TStateSchema[K] extends Record + ? ToStandardSetupStates + : TStateSchema[K] + : TStateSchema[K]; + } extends infer TStandardStateSchema extends SetupStateSchema + ? TStandardStateSchema + : never + : never; + +export type ToStandardSetupStates = { + [K in keyof TStates]: ToStandardSetupStateSchema; +}; + +function isStandardSchema(value: unknown): value is StandardSchemaV1 { + return ( + !!value && + (typeof value === 'object' || typeof value === 'function') && + '~standard' in value + ); +} + +export function toStandardSchema(schema: EffectSchemaLike): StandardSchemaV1 { + if (Schema.isSchema(schema)) { + return Schema.toStandardSchemaV1(schema as EffectSchema); + } + return schema as StandardSchemaV1; +} + +function mapSchemaRecord( + value: Record +): Record { + return Object.fromEntries( + Object.keys(value).map((key) => { + const entry = value[key]; + if (Schema.isSchema(entry) || isStandardSchema(entry)) { + return [key, toStandardSchema(entry as EffectSchemaLike)]; + } + if (entry && typeof entry === 'object' && !Array.isArray(entry)) { + return [key, mapSchemaRecord(entry as Record)]; + } + return [key, entry]; + }) + ); +} + +export function toStandardSetupSchemas( + schemas: EffectSetupSchemas | undefined +): SetupSchemas | undefined { + return schemas ? mapSchemaRecord(schemas) : undefined; +} + +export function toStandardSetupStates( + states: Record | undefined +): Record | undefined { + if (!states) { + return undefined; + } + + return Object.fromEntries( + Object.keys(states).map((key) => { + const state = states[key]; + return [ + key, + { + ...state, + ...(state.schemas + ? { + schemas: mapSchemaRecord(state.schemas) + } + : undefined), + ...(state.states + ? { states: toStandardSetupStates(state.states) } + : undefined) + } + ]; + }) + ) as Record; +} diff --git a/xstate-effect/src/setupEffect.ts b/xstate-effect/src/setupEffect.ts new file mode 100644 index 00000000..f8166260 --- /dev/null +++ b/xstate-effect/src/setupEffect.ts @@ -0,0 +1,423 @@ +import { Effect } from 'effect'; +import { + setup, + type ActorLogicValidator, + type AnyStateMachine, + type AnyActorRef, + type AnySetupConfig, + type EventObject, + type MachineContext, + type SetupConfig, + type SetupReturn, + type SetupSchemas, + type SetupStateSchema, + type Sources, + type SystemRegistry, + type SystemRuntime +} from 'xstate'; +import { effectActionBrand } from './brands.ts'; +import { runHostedEffect } from './internal.ts'; +import type { EffectRequirements } from './types.ts'; +import { + toStandardSetupSchemas, + toStandardSetupStates, + type EffectSetupSchemas, + type EffectSetupStateSchema, + type ToStandardSetupSchemas, + type ToStandardSetupStates, + type ValidateEffectSetupSchemas, + type ValidateEffectSetupStates +} from './schema.ts'; + +/** + * Argument an Effect action receives. It mirrors the v6 action argument + * object: the machine's `context` and the `event` that caused the transition, + * the actor itself and its family (`self`, `parent`, `children`), the + * registered `actions`, `actors`, `guards` and `delays`, the actor `system`, + * and the `params` and `output` the transition passed along. + */ +export type EffectActionArgs< + TContext extends MachineContext = MachineContext, + TEvent extends EventObject = EventObject +> = { + readonly context: TContext; + readonly event: TEvent; + readonly self: AnyActorRef; + readonly parent: AnyActorRef | undefined; + readonly children: Record; + readonly actions: Record; + readonly actors: Record; + readonly guards: Record; + readonly delays: Record; + readonly system: SystemRuntime; + readonly params?: unknown; + readonly output?: unknown; +}; + +/** + * An action registered with `setupEffect({ actions })`. It is called + * synchronously during the transition with the arguments the transition + * enqueued, and returns an Effect that runs afterwards in the actor's Effect + * context. The Effect is interrupted when the actor stops; its failures and + * defects route to the state's `onError`. + */ +export type EffectAction< + TContext extends MachineContext = MachineContext, + TEvent extends EventObject = EventObject, + TError = unknown, + TRequirements = never +> = ( + args: EffectActionArgs +) => Effect.Effect; + +type AnyEffectAction = EffectAction; + +type EffectActionRequirements = TAction extends ( + ...args: any[] +) => infer TResult + ? EffectRequirements + : never; + +type CoreEffectAction = TAction extends (...args: infer TArgs) => any + ? ((...args: TArgs) => void) & { + readonly [effectActionBrand]?: EffectActionRequirements; + } + : never; + +type CoreEffectActionMap = { + [K in keyof TActionMap]: CoreEffectAction; +}; + +type EffectSetupConfig< + TSchemas extends EffectSetupSchemas, + TStates extends Record, + TActionMap extends Record, + TActorMap extends Sources['actors'], + TGuardMap extends Sources['guards'], + TDelayMap extends Sources['delays'], + TValidator extends ActorLogicValidator | undefined, + TSourceSchemas extends SetupSchemas = ToStandardSetupSchemas +> = { + validator?: TValidator; + actions?: TActionMap & Record; + actors?: TActorMap; + guards?: NonNullable< + SetupConfig< + TSourceSchemas, + ToStandardSetupStates, + CoreEffectActionMap, + TActorMap, + TGuardMap, + TDelayMap, + TValidator + >['guards'] + >; + delays?: NonNullable< + SetupConfig< + TSourceSchemas, + ToStandardSetupStates, + CoreEffectActionMap, + TActorMap, + TGuardMap, + TDelayMap, + TValidator + >['delays'] + >; + schemas?: TSchemas & + ([TValidator] extends [ActorLogicValidator] + ? ValidateEffectSetupSchemas + : unknown); + states?: TStates & + ([TValidator] extends [ActorLogicValidator] + ? ValidateEffectSetupStates + : unknown); +}; + +type MergeRecord = Omit & + TExtension; + +type MergeSetupSchemas< + TBaseSchemas extends SetupSchemas, + TExtensionSchemas extends SetupSchemas +> = { + [K in keyof TBaseSchemas | keyof TExtensionSchemas]: K extends + | 'events' + | 'internalEvents' + | 'emitted' + | 'children' + | 'actions' + | 'guards' + ? MergeRecord< + K extends keyof TBaseSchemas ? NonNullable : {}, + K extends keyof TExtensionSchemas + ? NonNullable + : {} + > + : K extends keyof TExtensionSchemas + ? TExtensionSchemas[K] + : K extends keyof TBaseSchemas + ? TBaseSchemas[K] + : never; +} extends infer TMergedSchemas extends SetupSchemas + ? TMergedSchemas + : never; + +interface RuntimeValidationDoesNotSupportTransformingSchemas { + readonly __xstate_effect_error: 'Runtime validation does not support schemas with different encoded and decoded types'; +} + +type RuntimeValidationCompatibility = [ + TValidator +] extends [ActorLogicValidator] + ? [TSchemas] extends [ValidateEffectSetupSchemas] + ? [TStates] extends [ValidateEffectSetupStates] + ? unknown + : RuntimeValidationDoesNotSupportTransformingSchemas + : RuntimeValidationDoesNotSupportTransformingSchemas + : unknown; + +declare const inheritedEffectValidator: unique symbol; +type InheritedEffectValidator = typeof inheritedEffectValidator; + +type ResolveExtendedValidator = [TExtension] extends [ + InheritedEffectValidator +] + ? TBase + : Exclude; + +type ExtendValidatorConfig = [TExtension] extends [ + InheritedEffectValidator +] + ? { validator?: never } + : { validator: TExtension }; + +type EffectSetupExtensionConfig< + TBaseSchemas extends SetupSchemas, + TBaseStates extends Record, + TBaseValidator extends ActorLogicValidator | undefined, + TExtensionSchemas extends EffectSetupSchemas, + TExtensionStates extends Record, + TExtensionActionMap extends Record, + TExtensionActorMap extends Sources['actors'], + TExtensionGuardMap extends Sources['guards'], + TExtensionDelayMap extends Sources['delays'], + TExtensionValidator extends + | ActorLogicValidator + | undefined + | InheritedEffectValidator +> = EffectSetupConfig< + TExtensionSchemas, + TExtensionStates, + TExtensionActionMap, + TExtensionActorMap, + TExtensionGuardMap, + TExtensionDelayMap, + ResolveExtendedValidator, + MergeSetupSchemas> +> & + ExtendValidatorConfig & + RuntimeValidationCompatibility< + NoInfer, + NoInfer, + ResolveExtendedValidator + >; + +/** + * What `setupEffect` returns: the XState `SetupReturn` with an `extend` method + * that also accepts Effect schemas and Effect-returning actions. Call + * `createMachine` on it to build a machine whose registered actions and actors + * contribute to `RequirementsFrom`. + */ +export type EffectSetupReturn< + TStates extends Record = Record< + string, + SetupStateSchema + >, + TSchemas extends SetupSchemas = {}, + TSetupActionMap extends Sources['actions'] = {}, + TSetupActorMap extends Sources['actors'] = {}, + TSetupGuardMap extends Sources['guards'] = {}, + TSetupDelayMap extends Sources['delays'] = {}, + TSetupDelays extends string = Extract, + TValidator extends ActorLogicValidator | undefined = undefined +> = Omit< + SetupReturn< + TStates, + TSchemas, + TSetupActionMap, + TSetupActorMap, + TSetupGuardMap, + TSetupDelayMap, + TSetupDelays, + SystemRegistry, + TValidator + >, + 'extend' +> & { + extend< + const TExtensionSchemas extends EffectSetupSchemas = {}, + const TExtensionStates extends Record = {}, + TExtensionActionMap extends Record = {}, + TExtensionActorMap extends Sources['actors'] = {}, + TExtensionGuardMap extends Sources['guards'] = {}, + TExtensionDelayMap extends Sources['delays'] = {}, + const TExtensionValidator extends + | ActorLogicValidator + | undefined + | InheritedEffectValidator = InheritedEffectValidator + >( + config: EffectSetupExtensionConfig< + TSchemas, + TStates, + TValidator, + TExtensionSchemas, + TExtensionStates, + TExtensionActionMap, + TExtensionActorMap, + TExtensionGuardMap, + TExtensionDelayMap, + TExtensionValidator + > + ): EffectSetupReturn< + MergeRecord>, + MergeSetupSchemas>, + MergeRecord>, + MergeRecord, + MergeRecord, + MergeRecord, + TSetupDelays | Extract, + ResolveExtendedValidator + >; +}; + +type AnyEffectSetupConfig = Omit< + AnySetupConfig, + 'actions' | 'schemas' | 'states' +> & { + actions?: Record; + schemas?: EffectSetupSchemas; + states?: Record; +}; + +function wrapActions( + actions: Record | undefined +): Record void | PromiseLike> | undefined { + if (!actions) { + return undefined; + } + + const wrapped: Record void | PromiseLike> = + {}; + for (const key of Object.keys(actions)) { + const action = actions[key]; + wrapped[key] = (args) => { + // machine.provide can replace Effect actions with plain actions. + const result: unknown = action(args); + return Effect.isEffect(result) + ? runHostedEffect( + args.self, + result as Effect.Effect, + `action.${key}` + ) + : (result as void | PromiseLike); + }; + } + return wrapped; +} + +/** + * Makes `machine.provide` host Effect-returning action overrides the same way + * `setupEffect` hosts declared actions. + */ +function decorateMachine( + machine: TMachine +): TMachine { + const provide = machine.provide.bind(machine) as ( + sources: Record + ) => AnyStateMachine; + machine.provide = ((sources: Record) => + decorateMachine( + provide({ + ...sources, + actions: wrapActions( + sources.actions as Record | undefined + ) + }) + )) as TMachine['provide']; + return machine; +} + +function decorateEffectSetup(effectSetup: SetupReturn): SetupReturn { + const createMachine = effectSetup.createMachine.bind(effectSetup) as ( + config: unknown + ) => AnyStateMachine; + effectSetup.createMachine = ((config: unknown) => + decorateMachine(createMachine(config))) as typeof effectSetup.createMachine; + const extend = effectSetup.extend; + const extendAny = extend as (extension: any) => SetupReturn; + effectSetup.extend = ((extension: AnySetupConfig) => + decorateEffectSetup( + extendAny({ + ...extension, + schemas: toStandardSetupSchemas(extension.schemas), + states: toStandardSetupStates(extension.states), + actions: wrapActions( + extension.actions as Record | undefined + ) + }) + )) as typeof effectSetup.extend; + return effectSetup; +} + +/** + * The Effect-aware form of XState's `setup`. It accepts Effect `Schema` values + * wherever `setup` accepts Standard Schemas, and actions that return an + * Effect, which it wraps so the transition stays synchronous while the Effect + * runs in the actor's Effect context. Everything else, including `actors`, + * `guards`, `delays` and `extend`, behaves as in `setup`. Machines built from + * it must be started with `createEffectActor`. + */ +export function setupEffect(): EffectSetupReturn; +export function setupEffect< + const TSchemas extends EffectSetupSchemas = {}, + const TStates extends Record = Record< + string, + EffectSetupStateSchema + >, + TActionMap extends Record = {}, + TActorMap extends Sources['actors'] = {}, + TGuardMap extends Sources['guards'] = {}, + TDelayMap extends Sources['delays'] = {}, + const TValidator extends ActorLogicValidator | undefined = undefined +>( + config: EffectSetupConfig< + TSchemas, + TStates, + TActionMap, + TActorMap, + TGuardMap, + TDelayMap, + TValidator + > +): EffectSetupReturn< + ToStandardSetupStates, + ToStandardSetupSchemas, + CoreEffectActionMap, + TActorMap, + TGuardMap, + TDelayMap, + Extract, + TValidator +>; +export function setupEffect( + config: AnyEffectSetupConfig = {} +): EffectSetupReturn { + return decorateEffectSetup( + setup({ + ...config, + schemas: toStandardSetupSchemas(config.schemas), + states: toStandardSetupStates(config.states), + actions: wrapActions(config.actions) + } as AnySetupConfig) as SetupReturn + ) as EffectSetupReturn; +} diff --git a/xstate-effect/src/state.test.ts b/xstate-effect/src/state.test.ts new file mode 100644 index 00000000..0c3d5706 --- /dev/null +++ b/xstate-effect/src/state.test.ts @@ -0,0 +1,154 @@ +import { Effect, Match, Schema, Stream } from 'effect'; +import { createActor, createMachine } from 'xstate'; +import { + createEffectActor, + send, + setupEffect, + snapshots, + taggedState, + type TaggedState, + type TaggedStateFrom +} from './index.ts'; + +const machine = setupEffect({ + schemas: { + context: Schema.Struct({ id: Schema.String }), + events: { + START: Schema.Struct({}), + DONE: Schema.Struct({}), + FAIL: Schema.Struct({}) + } + }, + states: { + idle: {}, + loading: { + schemas: { + context: Schema.Struct({ startedAt: Schema.Number }) + } + }, + done: { + states: { + success: {}, + failure: {} + } + }, + failed: {} + } +}).createMachine({ + context: { id: 'a' }, + initial: 'idle', + states: { + idle: { + on: { + START: ({ context }) => ({ + target: 'loading', + context: { ...context, startedAt: 1 } + }) + } + }, + loading: { + on: { DONE: { target: 'done' }, FAIL: { target: 'failed' } } + }, + done: { + initial: 'success', + states: { + success: {}, + failure: {} + } + }, + failed: {} + } +}); + +const parallelMachine = createMachine({ + type: 'parallel', + states: { + a: { initial: 'a1', states: { a1: {}, a2: {} } }, + b: { initial: 'b1', states: { b1: {} } } + } +}); + +const describeState = Match.type>().pipe( + Match.tag('idle', () => 'idle'), + Match.tag('loading', ({ context }) => `loading since ${context.startedAt}`), + Match.tag('done.success', 'done.failure', 'failed', ({ _tag }) => _tag), + Match.exhaustive +); + +describe('taggedState', () => { + it('tags the state path and keeps the per-state context', () => { + const actor = createActor(machine).start(); + const idle = taggedState(actor.getSnapshot()); + expect(idle._tag).toBe('idle'); + expect(idle.value).toBe('idle'); + + actor.send({ type: 'START' }); + const loading = taggedState(actor.getSnapshot()); + expect(loading._tag).toBe('loading'); + expect(loading.context).toEqual({ id: 'a', startedAt: 1 }); + + actor.send({ type: 'DONE' }); + const done = taggedState(actor.getSnapshot()); + expect(done._tag).toBe('done.success'); + expect(done.value).toEqual({ done: 'success' }); + expect(done.snapshot).toBe(actor.getSnapshot()); + }); + + it('stops at a parallel state', () => { + const actor = createActor(parallelMachine).start(); + const tagged = taggedState(actor.getSnapshot()); + expect(tagged._tag).toBe('(machine)'); + expect(tagged.value).toEqual({ a: 'a1', b: 'b1' }); + }); + + it('matches exhaustively over snapshots of an Effect actor', async () => { + const program = Effect.gen(function* () { + const actor = yield* createEffectActor(machine); + const seen = yield* snapshots(actor).pipe( + Stream.map(taggedState), + Stream.tap(({ _tag }) => + _tag === 'idle' + ? send(actor, { type: 'START' }) + : _tag === 'loading' + ? send(actor, { type: 'FAIL' }) + : Effect.void + ), + Stream.map(describeState), + Stream.take(3), + Stream.runCollect + ); + return [...seen]; + }); + + await expect(Effect.runPromise(Effect.scoped(program))).resolves.toEqual([ + 'idle', + 'loading since 1', + 'failed' + ]); + }); + + it('types the tag union and per-state context', () => { + type Tagged = TaggedState; + type Tags = Tagged['_tag']; + 'idle' satisfies Tags; + 'loading' satisfies Tags; + 'done.success' satisfies Tags; + 'done.failure' satisfies Tags; + 'failed' satisfies Tags; + // @ts-expect-error - not a leaf state of this machine + 'done' satisfies Tags; + + const check = (tagged: Tagged) => { + if (tagged._tag === 'loading') { + tagged.context.startedAt satisfies number; + tagged.value satisfies 'loading'; + } + }; + check(taggedState(createActor(machine).getSnapshot())); + + type Parallel = TaggedStateFrom< + ReturnType + >; + '(machine)' satisfies Parallel['_tag']; + }); +}); diff --git a/xstate-effect/src/state.ts b/xstate-effect/src/state.ts new file mode 100644 index 00000000..7c5e4793 --- /dev/null +++ b/xstate-effect/src/state.ts @@ -0,0 +1,133 @@ +import type { + AnyMachineSnapshot, + AnyStateMachine, + MachineContext, + MachineSnapshot, + SnapshotFrom, + StateContextFromStateValue, + StateSchema, + StateValue, + StateValueFromStateSchema +} from 'xstate'; + +type IsUnion = T extends unknown + ? [U] extends [T] + ? false + : true + : never; + +type Join = TPrefix extends '' + ? TKey + : `${TPrefix}.${TKey}`; + +/** The tag of the machine itself, used when the root state is parallel. */ +const MACHINE_TAG = '(machine)'; + +/** + * The dotted path of a state value: `'idle'`, `'form.editing'`. A parallel + * state has no single path, so its tag stops at the parallel state, or is + * `'(machine)'` when the machine itself is parallel. + */ +export type StateTag< + TValue, + TPrefix extends string = '' +> = string extends TValue + ? string + : TValue extends string + ? Join + : TValue extends object + ? string extends keyof TValue + ? string + : IsUnion extends true + ? TPrefix extends '' + ? typeof MACHINE_TAG + : TPrefix + : { + [K in keyof TValue & string]: StateTag< + TValue[K], + Join + >; + }[keyof TValue & string] + : never; + +type TaggedStateOf< + TSnapshot, + TValue, + TContext extends MachineContext, + TSchema extends StateSchema +> = TValue extends unknown + ? { + readonly _tag: StateTag; + readonly value: TValue; + readonly context: StateContextFromStateValue; + readonly snapshot: TSnapshot; + } + : never; + +/** + * A machine snapshot as a tagged union over its states. `_tag` is the state's + * dotted path and `context` is the context of that state, including any + * per-state context schema, so `Match.tag` narrows both. + */ +export type TaggedStateFrom = + TSnapshot extends MachineSnapshot< + infer TContext, + infer _TEvent, + infer _TChildren, + infer _TStateValue, + infer _TTag, + infer _TOutput, + infer _TMeta, + infer TSchema + > + ? TaggedStateOf< + TSnapshot, + StateValueFromStateSchema, + TContext, + TSchema + > + : never; + +/** The tagged state union of a machine. */ +export type TaggedState = TaggedStateFrom< + SnapshotFrom +>; + +/** Computes the dotted path tag of a state value. */ +function stateTag(value: StateValue, prefix = ''): string { + if (typeof value === 'string') { + return prefix ? `${prefix}.${value}` : value; + } + const keys = Object.keys(value); + if (keys.length !== 1) { + return prefix || MACHINE_TAG; + } + const key = keys[0]!; + return stateTag(value[key]!, prefix ? `${prefix}.${key}` : key); +} + +/** + * Views a machine snapshot as a tagged union member for `Match.tag`, + * `Match.tags` or a `switch` on `_tag`. + * + * @example + * + * ```ts + * const view = Match.type>().pipe( + * Match.tag('loading', ({ context }) => `Loading ${context.id}`), + * Match.tag('done', () => 'Done'), + * Match.exhaustive + * ); + * view(taggedState(snapshot)); + * ``` + */ +export function taggedState( + snapshot: TSnapshot +): TaggedStateFrom { + return { + _tag: stateTag(snapshot.value), + value: snapshot.value, + context: snapshot.context, + snapshot + } as unknown as TaggedStateFrom; +} diff --git a/xstate-effect/src/types.ts b/xstate-effect/src/types.ts new file mode 100644 index 00000000..02adadbf --- /dev/null +++ b/xstate-effect/src/types.ts @@ -0,0 +1,111 @@ +import type { Effect, Scope } from 'effect'; +import type { EffectLogicBrand } from './fromEffect.ts'; +import { effectActionBrand } from './brands.ts'; +import type { ActorScope } from './actorScope.ts'; + +/** The `R` channel of an Effect type, or `never` for anything else. */ +export type EffectRequirements = + T extends Effect.Effect ? R : never; + +type RequirementsFromActions = + T extends Record any> + ? T[keyof T] extends infer TAction + ? TAction extends { + readonly [effectActionBrand]?: infer R; + } + ? unknown extends R + ? EffectRequirements< + TAction extends (...args: any[]) => infer TResult + ? TResult + : never + > + : Exclude + : EffectRequirements< + TAction extends (...args: any[]) => infer TResult ? TResult : never + > + : never + : never; + +/** + * Recursion budget for walking registered child machines. A machine cannot + * contain itself as a registered actor type, but deeply nested machine trees + * are capped at this depth to keep the conditional type finite. + */ +type MaxDepth = 10; + +type PrevDepth = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + +type Depth = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10; + +type RequirementsFromActors = + T extends Record + ? // `T[keyof T]` is the union of every registered actor logic; the naked + // type parameter in `RequirementsFrom` distributes over it, so mixed + // maps (Effect logic + child machines + plain logic) all contribute. + RequirementsFrom + : never; + +/** `invoke` accepts a single config or an array of them. */ +type InvokeEntry = TInvoke extends readonly (infer U)[] ? U : TInvoke; + +/** + * Requirements of the logic passed inline as `invoke.src`. A string `src` + * names an actor registered in `setup({ actors })`, whose requirements are + * already collected from the actor map, so it contributes nothing here. + */ +type RequirementsFromInvoke = + InvokeEntry extends infer TEntry + ? TEntry extends { src: infer TSrc } + ? TSrc extends string + ? never + : RequirementsFrom + : never + : never; + +/** + * Walks the machine's literal config tree (the state schema) collecting + * requirements from inline `invoke.src` logic at the root and in every + * descendant state node. + */ +type RequirementsFromStateSchema = + | (TSchema extends { invoke: infer TInvoke } + ? RequirementsFromInvoke + : never) + | (TSchema extends { states: infer TStates } + ? TStates extends Record + ? RequirementsFromStateSchema + : never + : never); + +/** + * Collects the Effect service requirements of an actor logic. + * + * Actor and invocation scopes are supplied by the host and excluded here. + * For Effect logic this is the remaining `R`. For a state machine it is the + * union of the requirements of its registered Effect actions, its registered + * Effect actors, the Effect logic passed inline as `invoke.src` anywhere in + * its state tree, and — recursively — the requirements of any child machine + * reached either way (capped at {@link MaxDepth} levels of machine nesting). + */ +export type RequirementsFrom = + T extends EffectLogicBrand + ? Exclude + : T extends { + readonly _actionMap: infer TActionMap; + readonly _actorMap: infer TActorMap; + readonly _stateSchema: infer TStateSchema; + } + ? + | Exclude< + RequirementsFromActions, + ActorScope | Scope.Scope + > + | ([TDepth] extends [0] + ? never + : + | RequirementsFromActors + | RequirementsFromStateSchema< + TStateSchema, + PrevDepth[TDepth] + >) + : never; diff --git a/xstate-effect/test/lint-fixtures/declared-effect.ts b/xstate-effect/test/lint-fixtures/declared-effect.ts new file mode 100644 index 00000000..d1941cb9 --- /dev/null +++ b/xstate-effect/test/lint-fixtures/declared-effect.ts @@ -0,0 +1,26 @@ +// Negative fixture: nothing here may be reported. +import { Effect } from 'effect'; + +declare const enq: any; +declare const enqueue: any; +declare const args: any; +declare const track: (value: string) => void; + +export function declaredAction() { + enq(args.actions.audit, args); +} + +export function declaredSpawn() { + enq.spawn(args.actors.leaf); + enqueue.spawn(args.actors.leaf); +} + +export function inlineActionWithoutEffect() { + enq(() => { + track('saved'); + }); +} + +export function inlineActionReturningNonEffect() { + enqueue(() => Promise.resolve('ok')); +} diff --git a/xstate-effect/test/lint-fixtures/inline-effect.ts b/xstate-effect/test/lint-fixtures/inline-effect.ts new file mode 100644 index 00000000..875f3a5f --- /dev/null +++ b/xstate-effect/test/lint-fixtures/inline-effect.ts @@ -0,0 +1,28 @@ +// Positive fixture: every `enq`/`enqueue` call below must be reported. +import { Effect } from 'effect'; +import { fromEffect, fromEffectStream } from '../../src/index.ts'; + +declare const enq: any; +declare const enqueue: any; + +export function inlineActionArrow() { + enq(() => Effect.log('saved')); +} + +export function inlineActionBlock() { + enqueue(() => { + return Effect.sync(() => {}); + }); +} + +export function inlineActionPromiseWrapped() { + enqueue(() => Promise.resolve(Effect.succeed('ok'))); +} + +export function inlineSpawnEnq() { + enq.spawn(fromEffect(Effect.succeed('inline'))); +} + +export function inlineSpawnEnqueue() { + enqueue.spawn(fromEffectStream(Effect.succeed('inline') as any)); +} diff --git a/xstate-effect/test/lint-fixtures/oxlintrc.fixtures.json b/xstate-effect/test/lint-fixtures/oxlintrc.fixtures.json new file mode 100644 index 00000000..cb39677b --- /dev/null +++ b/xstate-effect/test/lint-fixtures/oxlintrc.fixtures.json @@ -0,0 +1,10 @@ +{ + "$schema": "../../../../node_modules/oxlint/configuration_schema.json", + "jsPlugins": ["../../../../scripts/oxlint-plugin-xstate-effect.ts"], + "categories": { + "correctness": "off" + }, + "rules": { + "xstate-effect/no-inline-effect": "error" + } +} diff --git a/xstate-react/CHANGELOG.md b/xstate-react/CHANGELOG.md new file mode 100644 index 00000000..fd2941f7 --- /dev/null +++ b/xstate-react/CHANGELOG.md @@ -0,0 +1,1067 @@ +# Changelog + +## 7.0.0-alpha.4 + +### Minor Changes + +- 0fe9afe: `useActorRef()`, `useActor()` and `useMachine()` now use the machine passed on the first render for the lifetime of the component, like a `useState` initializer. Passing a different machine object on a later render no longer stops the actor and starts a new one from its persisted snapshot. + + Creating the machine inside the component no longer resets state or causes render loops, so wrapping it in `useMemo` is no longer needed: + + ```tsx + function Toggle() { + // Created on every render; only the first one is used. + const [snapshot, send] = useMachine(createMachine({ /* ... */ })); + // ... + } + ``` + + Vary a running machine with `input` or `machine.provide()` (provided implementations are still picked up on every render). To switch to a different machine, change the component's `key`: + + ```tsx + + ``` + +### Patch Changes + +- 0fe9afe: React Fast Refresh keeps the running actor and its state when you edit a machine. In development builds, `useActorRef()`, `useActor()` and `useMachine()` switch the running actor to the edited machine, so the current state and context are kept, including context that holds DOM elements or cyclic objects. If the edited machine cannot represent the current state, the actor restarts from the edited machine. Production builds are unaffected. +- 73fa80b: `useActor`, `useActorRef` and `useMachine` now require `input` for machines that declare a required input schema, matching `createActor`. Passing a persisted `snapshot` instead of `input` is allowed. + +## 7.0.0-alpha.3 + +### Patch Changes + +- 69b6663: Stop child actors and their timers and subscriptions when an unhandled parent error occurs, including when a stop action has not executed yet. + + Keep `useActorRef` observers subscribed when the actor is replaced, and subscribe before the replacement starts. + +## 7.0.0-alpha.2 + +### Patch Changes + +- 069aadf: Fixed delayed transitions and other built-in effects in minified bundles, preserved hook-owned actors across React StrictMode effect reconnects, and allowed graph utilities to accept machines from duplicate XState package copies. + +## 7.0.0-alpha.1 + +### Major Changes + +- [#5543](https://github.com/statelyai/xstate/pull/5543) [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Updated `@xstate/react` for XState v6. The internal Strict-Mode rehydration mechanism (`stopRootWithRehydration`) has been removed: on a Strict-Mode (or Offscreen/Activity) remount, the actor is now recreated and restarted rather than rehydrated, consistent with v6 actors no longer auto-starting children on `start()`. + + In production this changes nothing — there's no throwaway double-mount, so the actor is created once and runs normally. In development, the recreated actor starts from the same logic and `input`, so it lands on the same initial snapshot; the only observable difference is for actors that accumulated child state during Strict Mode's discarded first mount, which was itself a dev-only artifact. In exchange, the package sheds a fragile, hard-to-reason-about mechanism (root-stop-with-child-snapshot-preservation plus observer muting) that existed solely to paper over Strict Mode. + +### Patch Changes + +- Updated dependencies [[`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`021cc56`](https://github.com/statelyai/xstate/commit/021cc563e75d2e4d130c34e2d274565c2df6ec76), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`d9079cd`](https://github.com/statelyai/xstate/commit/d9079cd8586b4be4154dbfc296219b391f1cd85c), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`96aee67`](https://github.com/statelyai/xstate/commit/96aee679d4bd8041eb25df6bda2d9eef2ab7169f), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925), [`021cc56`](https://github.com/statelyai/xstate/commit/021cc563e75d2e4d130c34e2d274565c2df6ec76), [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925)]: + - xstate@6.0.0-alpha.1 + +## 7.0.0-alpha.0 + +### Patch Changes + +- Updated dependencies [[`54b0f8b`](https://github.com/statelyai/xstate/commit/54b0f8b22679721d567ca7e2b7074e86a41de6ef), [`8b309a1`](https://github.com/statelyai/xstate/commit/8b309a17415b4522a99a374753731471b8784dd5), [`6031736`](https://github.com/statelyai/xstate/commit/6031736fb13fee88439cdbbc329f7b23f7387a63), [`54b0f8b`](https://github.com/statelyai/xstate/commit/54b0f8b22679721d567ca7e2b7074e86a41de6ef), [`8b309a1`](https://github.com/statelyai/xstate/commit/8b309a17415b4522a99a374753731471b8784dd5), [`d11c72d`](https://github.com/statelyai/xstate/commit/d11c72df0d83cfa5fc4445995b85e79a601c1c9e), [`46692e3`](https://github.com/statelyai/xstate/commit/46692e3c51ed6c830a01361ef74653949d5259d6), [`46692e3`](https://github.com/statelyai/xstate/commit/46692e3c51ed6c830a01361ef74653949d5259d6)]: + - xstate@6.0.0-alpha.0 + +## 6.1.0 + +### Minor Changes + +- [#5470](https://github.com/statelyai/xstate/pull/5470) [`3e03427`](https://github.com/statelyai/xstate/commit/3e03427639154a021c85e99e0518ab92cc42dc6d) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `useActor` and `useSelector` now throw when the actor reaches an error state, allowing errors to be caught by React error boundaries. + + ```tsx + import { createMachine } from 'xstate'; + import { useActor } from '@xstate/react'; + import { ErrorBoundary } from 'react-error-boundary'; + + const machine = createMachine({ + initial: 'idle', + states: { + idle: { + on: { + fetch: 'loading' + } + }, + loading: { + invoke: { + src: fromPromise(async () => { + throw new Error('Network error'); + }), + onDone: 'success' + // Without onError, the actor enters an error state + } + }, + success: {} + } + }); + + function App() { + return ( + Something went wrong

}> + +
+ ); + } + + function ActorComponent() { + // If the actor errors, the error will be thrown + // and caught by the nearest error boundary + const [snapshot, send] = useActor(machine); + + return
{snapshot.value}
; + } + ``` + +## 6.0.0 + +### Patch Changes + +- Updated dependencies [[`e07a7cd8462473188a0fb646a965e61be1ce6ae3`](https://github.com/statelyai/xstate/commit/e07a7cd8462473188a0fb646a965e61be1ce6ae3)]: + - xstate@5.20.0 + +## 5.0.5 + +### Patch Changes + +- Updated dependencies [[`479c74b83fa77c57c48f54cf0e9dcfab5fe6cae5`](https://github.com/statelyai/xstate/commit/479c74b83fa77c57c48f54cf0e9dcfab5fe6cae5)]: + - xstate@5.19.4 + +## 5.0.4 + +### Patch Changes + +- Updated dependencies [[`b453b2d72ba12d0fe46a995f9ccced8000fd0cc9`](https://github.com/statelyai/xstate/commit/b453b2d72ba12d0fe46a995f9ccced8000fd0cc9)]: + - xstate@5.19.3 + +## 5.0.3 + +### Patch Changes + +- [#5223](https://github.com/statelyai/xstate/pull/5223) [`9e1de554c4ebf49997b717fada540951d01f511c`](https://github.com/statelyai/xstate/commit/9e1de554c4ebf49997b717fada540951d01f511c) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added React 19 as a peer dependency. + +## 5.0.2 + +### Patch Changes + +- Updated dependencies [[`d99df1d8f4fe49145c9974465b65028bf19b365f`](https://github.com/statelyai/xstate/commit/d99df1d8f4fe49145c9974465b65028bf19b365f)]: + - xstate@5.19.2 + +## 5.0.1 + +### Patch Changes + +- Updated dependencies [[`bf6119a7310a878afbf4f5b01f5e24288f9a0f16`](https://github.com/statelyai/xstate/commit/bf6119a7310a878afbf4f5b01f5e24288f9a0f16)]: + - xstate@5.19.1 + +## 5.0.0 + +### Patch Changes + +- [#5109](https://github.com/statelyai/xstate/pull/5109) [`d67b71dd25d457a2a59f2c943db13f50fab7ec3d`](https://github.com/statelyai/xstate/commit/d67b71dd25d457a2a59f2c943db13f50fab7ec3d) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add React 19 as a peer dependency + +- Updated dependencies [[`8c4b70652acaef2702f32435362e4755679a516d`](https://github.com/statelyai/xstate/commit/8c4b70652acaef2702f32435362e4755679a516d)]: + - xstate@5.19.0 + +## 4.1.3 + +### Patch Changes + +- Updated dependencies [[`25963966c394fc904dc9b701a420b6e204ebe7f7`](https://github.com/statelyai/xstate/commit/25963966c394fc904dc9b701a420b6e204ebe7f7)]: + - xstate@5.18.2 + +## 4.1.2 + +### Patch Changes + +- [#5055](https://github.com/statelyai/xstate/pull/5055) [`ad38c35c37`](https://github.com/statelyai/xstate/commit/ad38c35c377d4ec5c97710fda12512abbe5f7140) Thanks [@SandroMaglione](https://github.com/SandroMaglione)! - Updated types of `useActor`, `useMachine`, and `useActorRef` to require `input` when defined inside `types/input`. + + Previously even when `input` was defined inside `types`, `useActor`, `useMachine`, and `useActorRef` would **not** make the input required: + + ```tsx + const machine = setup({ + types: { + input: {} as { value: number } + } + }).createMachine({}); + + function App() { + // Event if `input` is not defined, `useMachine` works at compile time, but risks crashing at runtime + const _ = useMachine(machine); + return <>; + } + ``` + + With this change the above code will show a type error, since `input` is now required: + + ```tsx + const machine = setup({ + types: { + input: {} as { value: number } + } + }).createMachine({}); + + function App() { + const _ = useMachine(machine, { + input: { value: 1 } // Now input is required at compile time! + }); + return <>; + } + ``` + + This avoids runtime errors when forgetting to pass `input` when defined inside `types`. + +## 4.1.1 + +### Patch Changes + +- [#4844](https://github.com/statelyai/xstate/pull/4844) [`5aa6eb05c`](https://github.com/statelyai/xstate/commit/5aa6eb05c4d79a7efda9895b212fdb45a638f31f) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `useSelector(…)` hook from `@xstate/react` is now compatible with stores from `@xstate/store`. + + ```tsx + import { createStore } from '@xstate/store'; + import { useSelector } from '@xstate/react'; + + const store = createStore( + { + count: 0 + }, + { + inc: { + count: (context) => context.count + 1 + } + } + ); + + function Counter() { + // Note that this `useSelector` is from `@xstate/react`, + // not `@xstate/store/react` + const count = useSelector(store, (state) => state.context.count); + + return ( +
+ +
+ ); + } + ``` + +## 4.1.0 + +### Minor Changes + +- [#4231](https://github.com/statelyai/xstate/pull/4231) [`c2402e7bc`](https://github.com/statelyai/xstate/commit/c2402e7bc269dd1f1a9eca0d3e4484ad5a4cfadb) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `actor` passed to `useSelector(actor, selector)` is now allowed to be `undefined` for an actor that may not exist yet. For actors that may be `undefined`, the `snapshot` provided to the `selector` function can also be `undefined`: + + ```ts + const count = useSelector(maybeActor, (snapshot) => { + // `snapshot` may be undefined + return snapshot?.context.count; + }); + + count; // number | undefined + ``` + +## 4.0.3 + +### Patch Changes + +- [#4695](https://github.com/statelyai/xstate/pull/4695) [`52900a084`](https://github.com/statelyai/xstate/commit/52900a084712755b00e6c38eb9aa2c3b290259b5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Options in `createActorContext` are now properly merged with provider options. Previously, provider options replaced the actor options. + + ```tsx + const { inspect } = createBrowserInspector(); + + const SomeContext = createActorContext(someMachine, { inspect }); + + // ... + // Options are now merged: + // { inspect: inspect, input: 10 } + + {/* ... */} + ; + ``` + +## 4.0.2 + +### Patch Changes + +- [#4600](https://github.com/statelyai/xstate/pull/4600) [`1f2ccb97c`](https://github.com/statelyai/xstate/commit/1f2ccb97ca00ff2d2ec1c9996f8205dbe656602b) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Typegen-based types for detecting missing implementations have been removed internally. + +## 4.0.1 + +### Patch Changes + +- [#4497](https://github.com/statelyai/xstate/pull/4497) [`d7f220225`](https://github.com/statelyai/xstate/commit/d7f220225c34808a96383099e1f9bfd3abd13962) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix an issue where `after` transitions do not work in React strict mode. Delayed events (including from `after` transitions) should now work as expected in all React modes. + +## 4.0.0 + +### Major Changes + +- [#3947](https://github.com/statelyai/xstate/pull/3947) [`5fa3a0c74`](https://github.com/statelyai/xstate/commit/5fa3a0c74343e400871473d375f02d3d918d1f4e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Removed the ability to pass a factory function as argument to `useMachine`. +- [#4006](https://github.com/statelyai/xstate/pull/4006) [`42df9a536`](https://github.com/statelyai/xstate/commit/42df9a5360ec776ca3ce8bcd0f90873a79125bf2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `useActorRef` is introduced, which returns an `ActorRef` from actor logic: + + ```ts + const actorRef = useActorRef(machine, { ... }); + const anotherActorRef = useActorRef(fromPromise(...)); + ``` + + ~~`useMachine`~~ is deprecated in favor of `useActor`, which works with machines and any other kind of logic + + ```diff + -const [state, send] = useMachine(machine); + +const [state, send] = useActor(machine); + const [state, send] = useActor(fromTransition(...)); + ``` + + ~~`useSpawn`~~ is removed in favor of `useActorRef` + + ````diff + -const actorRef = useSpawn(machine); + +const actorRef = useActorRef(machine); + + The previous use of `useActor(actorRef)` is now replaced with just using the `actorRef` directly, and with `useSelector`: + + ```diff + -const [state, send] = useActor(actorRef); + +const state = useSelector(actorRef, s => s); + // actorRef.send(...) + ```` + +- [#4050](https://github.com/statelyai/xstate/pull/4050) [`fc88dc8e6`](https://github.com/statelyai/xstate/commit/fc88dc8e6d3fbc4ee8a1e0bdb538bab560b7a695) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `options` prop has been added (back) to the `Context.Provider` component returned from `createActorContext`: + + ```tsx + const SomeContext = createActorContext(someMachine); + + // ... + + + {/* ... */} + ; + ``` + +- [#4006](https://github.com/statelyai/xstate/pull/4006) [`42df9a536`](https://github.com/statelyai/xstate/commit/42df9a5360ec776ca3ce8bcd0f90873a79125bf2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `useActor` has been removed from the created actor context, you should be able to replace its usage with `MyCtx.useSelector` and `MyCtx.useActorRef`. +- [#4265](https://github.com/statelyai/xstate/pull/4265) [`1153b3f9a`](https://github.com/statelyai/xstate/commit/1153b3f9a95b4d76ff5408be8bd03a66f884b9cb) Thanks [@davidkpiano](https://github.com/davidkpiano)! - FSM-related functions have been removed. +- [#3947](https://github.com/statelyai/xstate/pull/3947) [`5fa3a0c74`](https://github.com/statelyai/xstate/commit/5fa3a0c74343e400871473d375f02d3d918d1f4e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Implementations for machines on `useMachine` hooks should go directly on the machine via `machine.provide(...)`, and are no longer allowed to be passed in as options. + + ```diff + -const [state, send] = useMachine(machine, { + - actions: { + - // ... + - } + -}); + +const [state, send] = useMachine(machine.provide({ + + actions: { + + // ... + + } + +})); + ``` + +- [#3148](https://github.com/statelyai/xstate/pull/3148) [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Removed `getSnapshot` parameter from hooks. It is expected that the received `actorRef` has to have a `getSnapshot` method on it that can be used internally. + +### Minor Changes + +- [#3727](https://github.com/statelyai/xstate/pull/3727) [`5fb3c683d`](https://github.com/statelyai/xstate/commit/5fb3c683d9a9bdc06637b3a13a5b575059aebadd) Thanks [@Andarist](https://github.com/Andarist)! - `exports` field has been added to the `package.json` manifest. It limits what files can be imported from a package - it's no longer possible to import from files that are not considered to be a part of the public API. +- [#4240](https://github.com/statelyai/xstate/pull/4240) [`409552cf8`](https://github.com/statelyai/xstate/commit/409552cf8578dc517cca4e6eaeb652a33f49c06c) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `useMachine` function is an alias of `useActor`. +- [#4436](https://github.com/statelyai/xstate/pull/4436) [`340aee643`](https://github.com/statelyai/xstate/commit/340aee6437767fa3dc5cef6e991cf975fe27467a) Thanks [@Andarist](https://github.com/Andarist)! - Fast refresh now works as expected for most use-cases. +- [#4050](https://github.com/statelyai/xstate/pull/4050) [`fc88dc8e6`](https://github.com/statelyai/xstate/commit/fc88dc8e6d3fbc4ee8a1e0bdb538bab560b7a695) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `observerOrListener` argument has been removed from the 3rd argument of `createActorContext(logic, options)`. + +## 4.0.0-beta.11 + +### Minor Changes + +- [#4436](https://github.com/statelyai/xstate/pull/4436) [`340aee643`](https://github.com/statelyai/xstate/commit/340aee6437767fa3dc5cef6e991cf975fe27467a) Thanks [@Andarist](https://github.com/Andarist)! - Fast refresh now works as expected for most use-cases. + +## 4.0.0-beta.10 + +### Minor Changes + +- [#4240](https://github.com/statelyai/xstate/pull/4240) [`409552cf8`](https://github.com/statelyai/xstate/commit/409552cf8578dc517cca4e6eaeb652a33f49c06c) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `useMachine` function is aliased to `useActor` and not shown as visually deprecated. + +## 4.0.0-beta.9 + +### Major Changes + +- [#4265](https://github.com/statelyai/xstate/pull/4265) [`1153b3f9a`](https://github.com/statelyai/xstate/commit/1153b3f9a95b4d76ff5408be8bd03a66f884b9cb) Thanks [@davidkpiano](https://github.com/davidkpiano)! - FSM-related functions have been removed. + +## 4.0.0-beta.8 + +### Patch Changes + +- [#4138](https://github.com/statelyai/xstate/pull/4138) [`461e3983a`](https://github.com/statelyai/xstate/commit/461e3983a0e9d51c43a4b0e7370354b7dea24e5f) Thanks [@Andarist](https://github.com/Andarist)! - Fixed missing `.mjs` proxy files for condition-based builds. + +## 4.0.0-beta.7 + +### Major Changes + +- [#4050](https://github.com/statelyai/xstate/pull/4050) [`fc88dc8e6`](https://github.com/statelyai/xstate/commit/fc88dc8e6d3fbc4ee8a1e0bdb538bab560b7a695) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `options` prop has been added (back) to the `Context.Provider` component returned from `createActorContext`: + + ```tsx + const SomeContext = createActorContext(someMachine); + + // ... + + + {/* ... */} + ; + ``` + +### Minor Changes + +- [#4050](https://github.com/statelyai/xstate/pull/4050) [`fc88dc8e6`](https://github.com/statelyai/xstate/commit/fc88dc8e6d3fbc4ee8a1e0bdb538bab560b7a695) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `observerOrListener` argument has been removed from the 3rd argument of `createActorContext(logic, options)`. + +## 4.0.0-beta.6 + +### Major Changes + +- [#4041](https://github.com/statelyai/xstate/pull/4041) [`50fe8cdd4`](https://github.com/statelyai/xstate/commit/50fe8cdd4114e77c104520f9c89d471cf2173dfb) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Instances of "behavior" in the codebase have been replaced with "actor logic". + +## 4.0.0-beta.5 + +### Patch Changes + +- [#4033](https://github.com/statelyai/xstate/pull/4033) [`9cb7cb51a`](https://github.com/statelyai/xstate/commit/9cb7cb51a0ce577d2de508aedf3773d4f80f9d46) Thanks [@Andarist](https://github.com/Andarist)! - Fixed generated TS declaration files to not include `.ts` extensions in the import/export statements. + +## 4.0.0-beta.4 + +### Major Changes + +- [#3947](https://github.com/statelyai/xstate/pull/3947) [`5fa3a0c74`](https://github.com/statelyai/xstate/commit/5fa3a0c74343e400871473d375f02d3d918d1f4e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Removed the ability to pass a factory function as argument to `useMachine` and `useInterpret`. + +- [#4006](https://github.com/statelyai/xstate/pull/4006) [`42df9a536`](https://github.com/statelyai/xstate/commit/42df9a5360ec776ca3ce8bcd0f90873a79125bf2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `useActorRef` is introduced, which returns an `ActorRef` from actor logic: + + ```ts + const actorRef = useActorRef(machine, { ... }); + const anotherActorRef = useActorRef(fromPromise(...)); + ``` + + ~~`useMachine`~~ is deprecated in favor of `useActor`, which works with machines and any other kind of logic + + ```diff + -const [state, send] = useMachine(machine); + +const [state, send] = useActor(machine); + const [state, send] = useActor(fromTransition(...)); + ``` + + ~~`useSpawn`~~ is removed in favor of `useActorRef` + + ````diff + -const actorRef = useSpawn(machine); + +const actorRef = useActorRef(machine); + + The previous use of `useActor(actorRef)` is now replaced with just using the `actorRef` directly, and with `useSelector`: + + ```diff + -const [state, send] = useActor(actorRef); + +const state = useSelector(actorRef, s => s); + // actorRef.send(...) + ```` + +- [#4006](https://github.com/statelyai/xstate/pull/4006) [`42df9a536`](https://github.com/statelyai/xstate/commit/42df9a5360ec776ca3ce8bcd0f90873a79125bf2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - `useActor` has been removed from the created actor context, you should be able to replace its usage with `MyCtx.useSelector` and `MyCtx.useActorRef`. + +- [#3947](https://github.com/statelyai/xstate/pull/3947) [`5fa3a0c74`](https://github.com/statelyai/xstate/commit/5fa3a0c74343e400871473d375f02d3d918d1f4e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Implementations for machines on `useMachine` and `useInterpret` hooks should go directly on the machine via `machine.provide(...)`, and are no longer allowed to be passed in as options. + + ```diff + -const [state, send] = useMachine(machine, { + - actions: { + - // ... + - } + -}); + +const [state, send] = useMachine(machine.provide({ + + actions: { + + // ... + + } + +})); + ``` + + `@xstate/react` will detect that the machine's config is still the same, and will not produce the "machine has changed" warning. + +## 3.2.2 + +### Patch Changes + +- [#3919](https://github.com/statelyai/xstate/pull/3919) [`6665f0a32`](https://github.com/statelyai/xstate/commit/6665f0a32327407e8fec12240383f211094d929c) Thanks [@c-w](https://github.com/c-w)! - Updated the allowed range for the `use-isomorphic-layout-effect` dependency. + +## 4.0.0-beta.3 + +## 4.0.0-alpha.2 + +### Patch Changes + +- [#3944](https://github.com/statelyai/xstate/pull/3944) [`305a89001`](https://github.com/statelyai/xstate/commit/305a89001d229f43eb85cd7bd06e797c3fb4f78a) Thanks [@Andarist](https://github.com/Andarist)! - Releasing adjusted internals to make the alpha version of this module compatible with the current version of `xstate@alpha` + +## 3.2.1 + +### Patch Changes + +- [#3829](https://github.com/statelyai/xstate/pull/3829) [`c110c429d`](https://github.com/statelyai/xstate/commit/c110c429d33cb724242ff65136de3ebe408eab97) Thanks [@Andarist](https://github.com/Andarist)! - Fixed compatibility of the generated TS types for `createActorContext` with pre-4.7. + +## 3.2.0 + +### Minor Changes + +- [#3814](https://github.com/statelyai/xstate/pull/3814) [`494203b3d`](https://github.com/statelyai/xstate/commit/494203b3dc358807e96cf1368f1347ff8e1d14e3) Thanks [@Andarist](https://github.com/Andarist)! - The `Provider` from `createActorContext(...)` now accepts the `options={{...}}` prop that takes the same object as the second argument to the `useMachine(machine, options)` hook. + + These options are no longer passed as the second argument to the `createActorContext(machine)` function: + + ```diff + + -const SomeContext = createActorContext(someMachine, + - { actions: { ... } }); + +const SomeContext = createActorContext(someMachine); + + // ... + + - + + + + // ... + ``` + +## 3.1.2 + +### Patch Changes + +- [#3804](https://github.com/statelyai/xstate/pull/3804) [`b53856d28`](https://github.com/statelyai/xstate/commit/b53856d28da4ecbba7d4393f72aa38894fd523d9) Thanks [@farskid](https://github.com/farskid)! - Interpreter options can now be specified in the second argument of createActorContext(machine, options). + +## 3.1.1 + +### Patch Changes + +- [#3799](https://github.com/statelyai/xstate/pull/3799) [`51d254692`](https://github.com/statelyai/xstate/commit/51d254692c2d267c24c65fc5802461540c012393) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue that caused the internally used `useSyncExternalStore` to warn about the computed snapshot not being cached when a not-started machine service was passed to `useActor`. + +## 3.1.0 + +### Minor Changes + +- [#3778](https://github.com/statelyai/xstate/pull/3778) [`f12248b23`](https://github.com/statelyai/xstate/commit/f12248b2379e4e554d69a238019216feea5211f6) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createActorContext(...)` helper has been introduced to make global actors easier to use with React. It outputs a React Context object with the following properties: + - `.Provider` - The React Context provider + - `.useActor(...)` - A hook that can be used to get the current state and send events to the actor + - `.useSelector(...)` - A hook that can be used to select some derived state from the actor's state + - `.useActorRef()` - A hook that can be used to get a reference to the actor that can be passed to other components + + Usage: + + ```jsx + import { createActorContext } from '@xstate/react'; + import { someMachine } from './someMachine'; + + // Create a React Context object that will interpret the machine + const SomeContext = createActorContext(someMachine); + + function SomeComponent() { + // Get the current state and `send` function + const [state, send] = SomeContext.useActor(); + + // Or select some derived state + const someValue = SomeContext.useSelector((state) => state.context.someValue); + + // Or get a reference to the actor + const actorRef = SomeContext.useActorRef(); + + return (/* ... */); + } + + function App() { + return ( + + + + ); + } + ``` + +## 3.0.2 + +### Patch Changes + +- [#3752](https://github.com/statelyai/xstate/pull/3752) [`4190c3fd6`](https://github.com/statelyai/xstate/commit/4190c3fd6d9bb6e7fca5c01cc1722f40e7e63399) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Computing the initial state is now consistent with `useMachine` and `useActor`, avoiding stale initial state problems with nested machines + +## 4.0.0-alpha.1 + +### Minor Changes + +- [#3727](https://github.com/statelyai/xstate/pull/3727) [`5fb3c683d`](https://github.com/statelyai/xstate/commit/5fb3c683d9a9bdc06637b3a13a5b575059aebadd) Thanks [@Andarist](https://github.com/Andarist)! - `exports` field has been added to the `package.json` manifest. It limits what files can be imported from a package - it's no longer possible to import from files that are not considered to be a part of the public API. + +### Patch Changes + +- Updated dependencies [[`5fb3c683d`](https://github.com/statelyai/xstate/commit/5fb3c683d9a9bdc06637b3a13a5b575059aebadd), [`ec39214c8`](https://github.com/statelyai/xstate/commit/ec39214c8eba11d75f6af72bae51ddb65ce003a0)]: + - @xstate/fsm@3.0.0-alpha.0 + +## 3.0.1 + +### Patch Changes + +- [#3456](https://github.com/statelyai/xstate/pull/3456) [`131d429ab`](https://github.com/statelyai/xstate/commit/131d429ab350aaca371c4c7974829c621a50c024) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `shallowEqual` helper comparator function. + +- [#3500](https://github.com/statelyai/xstate/pull/3500) [`0dfc6d92f`](https://github.com/statelyai/xstate/commit/0dfc6d92f6950b3eb78e0693ae3b0abe5751bf42) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with `useSelector` always computing fresh snapshots internally for uninitialized services. This avoids the internal `useSyncExternalStore` from warning about the snapshot value not being cached properly. + +## 4.0.0-alpha.0 + +### Major Changes + +- [#3148](https://github.com/statelyai/xstate/pull/3148) [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Removed `getSnapshot` parameter from hooks. It is expected that the received `actorRef` has to have a `getSnapshot` method on it that can be used internally. + +### Patch Changes + +- Updated dependencies [[`7f3b84816`](https://github.com/statelyai/xstate/commit/7f3b84816564d951b6b29afdd7075256f1f59501), [`969a2f4fc`](https://github.com/statelyai/xstate/commit/969a2f4fc0bc9147b9a52da25306e5c13b97f159), [`c0a6dcafa`](https://github.com/statelyai/xstate/commit/c0a6dcafa1a11a5ff1660b57e0728675f155c292), [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117), [`172d6a7e1`](https://github.com/statelyai/xstate/commit/172d6a7e1e4ab0fa73485f76c52675be8a1f3362), [`31bc73e05`](https://github.com/statelyai/xstate/commit/31bc73e05692f29301f5bb5cb4b87b90773e0ef2), [`e09efc720`](https://github.com/statelyai/xstate/commit/e09efc720f05246b692d0fdf17cf5d8ac0344ee6), [`145539c4c`](https://github.com/statelyai/xstate/commit/145539c4cfe1bde5aac247792622428e44342dd6), [`3de36bb24`](https://github.com/statelyai/xstate/commit/3de36bb24e8f59f54d571bf587407b1b6a9856e0), [`9e10660ec`](https://github.com/statelyai/xstate/commit/9e10660ec2f1e89cbb09a1094edb4f6b8a273a99), [`8fcbddd51`](https://github.com/statelyai/xstate/commit/8fcbddd51d66716ab1d326d934566a7664a4e175), [`515cdc9c1`](https://github.com/statelyai/xstate/commit/515cdc9c148a3a1b558120c309080e9a21e876bc), [`6043a1c28`](https://github.com/statelyai/xstate/commit/6043a1c28d21ff8cbabc420a6817a02a1a54fcc8), [`6a6b2b869`](https://github.com/statelyai/xstate/commit/6a6b2b8691626112d1d9dbf23d0a0e80ff7130a8), [`0b49437b1`](https://github.com/statelyai/xstate/commit/0b49437b1be3e6d9bc61304711b83300cba88dc4), [`0e24ea6d6`](https://github.com/statelyai/xstate/commit/0e24ea6d62a5c1a8b7e365f2252dc930d94997c4), [`04e89f90f`](https://github.com/statelyai/xstate/commit/04e89f90f97fe25a45b5908c45f25a513f0fd70f), [`0096d9f7a`](https://github.com/statelyai/xstate/commit/0096d9f7afda7546fc7b1d5fdd1546f55c32bfe4), [`8fcbddd51`](https://github.com/statelyai/xstate/commit/8fcbddd51d66716ab1d326d934566a7664a4e175), [`b200e0e0b`](https://github.com/statelyai/xstate/commit/b200e0e0b7123797086080b75abdfcf2fce45253), [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117), [`9437c3de9`](https://github.com/statelyai/xstate/commit/9437c3de912c2a38c04798cbb94f267a1e5db3f8), [`0038c7b1e`](https://github.com/statelyai/xstate/commit/0038c7b1e2050fe7262849aab8fdff4a7ce7cf92), [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117), [`b24e47b9e`](https://github.com/statelyai/xstate/commit/b24e47b9e7a59a5b0527d4386cea3af16c84ca7a), [`390eaaa52`](https://github.com/statelyai/xstate/commit/390eaaa523cb0dd243e39c6300e671606c1e45fc), [`7a68cbb61`](https://github.com/statelyai/xstate/commit/7a68cbb615afb6556c83868535dae67af366a117), [`0c6cfee9a`](https://github.com/statelyai/xstate/commit/0c6cfee9a6d603aa1756e3a6d0f76d4da1486caf), [`e09efc720`](https://github.com/statelyai/xstate/commit/e09efc720f05246b692d0fdf17cf5d8ac0344ee6), [`025a2d6a2`](https://github.com/statelyai/xstate/commit/025a2d6a295359a746bee6ffc2953ccc51a6aaad), [`e09efc720`](https://github.com/statelyai/xstate/commit/e09efc720f05246b692d0fdf17cf5d8ac0344ee6), [`c99bb43af`](https://github.com/statelyai/xstate/commit/c99bb43afec01ddee86fc746c346ea1aeeca687d), [`fc5ca7b7f`](https://github.com/statelyai/xstate/commit/fc5ca7b7fcd2d7821ce2409743c50505529104e7), [`c9cda27cb`](https://github.com/statelyai/xstate/commit/c9cda27cbe52b9c706ccb63b709d22d049be31e3), [`5d16a7365`](https://github.com/statelyai/xstate/commit/5d16a73651e97dd0228c5215cb2452a4d9951118), [`8fcbddd51`](https://github.com/statelyai/xstate/commit/8fcbddd51d66716ab1d326d934566a7664a4e175), [`53a594e9a`](https://github.com/statelyai/xstate/commit/53a594e9a1b49ccb1121048a5784676f83950024), [`31a0d890f`](https://github.com/statelyai/xstate/commit/31a0d890f55d8f0b06772c9fd510b18302b76ebb)]: + - xstate@5.0.0-alpha.0 + +## 3.0.0 + +### Major Changes + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - This package now accepts React 18 as a peer dep and the implementation has been rewritten to use [`use-sync-external-store`](https://www.npmjs.com/package/use-sync-external-store) package. This doesn't break compatibility with older versions of React since we are using the shim to keep compatibility with those older versions. + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `asEffect` and `asLayoutEffect` action creators were removed. They were not fitting the React model that well and could lead to issues as their existence suggested that they are easy to use. + + To execute actions at those exact times you can always either just call your stuff directly from those effects or send events to the machine from those effects and execute explicit actions in response to said events. + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - The signatures of `useMachine` and `useService` integrating with `@xstate/fsm` were changed. They now only accept a single generic each (`TMachine` and `TService` respectively). This has been done to match their signatures with the related hooks that integrate with `xstate` itself. + +### Patch Changes + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - In v2 we have changed signatures of `useMachine` and `useInterpret`. Instead of accepting a list of generics they now only support a single generic: `TMachine`. This change, erroneously, was only introduced to types targeting TS@4.x but the types targeting previous TS releases were still using the older signatures. This has now been fixed and users of older TS versions should now be able to leverage typegen with `@xstate/react`. + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `useMachine` for `xstate` now correctly rerenders with the initial state when the internal service is being restarted. This might happen during Fast Refresh and now you shouldn't be able to observe this stale state that didn't match the actual state of the service. + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - `useMachine` for `@xstate/fsm` now starts the service in an effect. This avoids side-effects in render and improves the compatibility with `StrictMode`. + +- [#2939](https://github.com/statelyai/xstate/pull/2939) [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf) Thanks [@Andarist](https://github.com/Andarist)! - Implementations given to `useMachine` targeting `@xstate/fsm` are now updated in a layout effect. This avoid some stale closure problems for actions that are executed in response to events sent from layout effects. + +* Updated dependencies [[`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf), [`360e85462`](https://github.com/statelyai/xstate/commit/360e8546298c4a06b6d51d8f12c0563672dd7acf)]: + - @xstate/fsm@2.0.0 + +## 2.0.1 + +### Patch Changes + +- [#3089](https://github.com/statelyai/xstate/pull/3089) [`862697e29`](https://github.com/statelyai/xstate/commit/862697e2990934d46050580d7e09c749d09d8426) Thanks [@Andarist](https://github.com/Andarist)! - Fixed compatibility with Skypack by exporting some shared utilities from root entry of XState and consuming them directly in other packages (this avoids accessing those things using deep imports and thus it avoids creating those compatibility problems). + +## 2.0.0 + +### Major Changes + +- [#2674](https://github.com/statelyai/xstate/pull/2674) [`e5a8b8dff`](https://github.com/statelyai/xstate/commit/e5a8b8dffb88cffbdca26683099ffdf5f1b01c8d) Thanks [@Andarist](https://github.com/Andarist), [@mattpocock](https://github.com/mattpocock)! - To avoid breaking any consumers and to leverage the newly introduced typegen support, the major version of this package had to be bumped. While you can still use it with older versions of TS, the typegen support in this package requires TS version 4.0 or greater. + + When using hooks from `@xstate/react` it's recommended to skip providing explicit generics to them. Note that that generics list has changed since v1 and we now only accept a single generic, `TMachine`. + +- [#2674](https://github.com/statelyai/xstate/pull/2674) [`ab919d300`](https://github.com/statelyai/xstate/commit/ab919d300f6d2b78871d3399ec58a697c4268d9b) Thanks [@Andarist](https://github.com/Andarist)! - Removed already deprecated `useService` from `@xstate/react`. You can replace its usage with `useActor`. + +### Patch Changes + +- [#2957](https://github.com/statelyai/xstate/pull/2957) [`8550ddda7`](https://github.com/statelyai/xstate/commit/8550ddda73e2ad291e19173d7fa8d13e3336fbb9) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The repository links have been updated from `github.com/davidkpiano` to `github.com/statelyai`. + +## 1.6.3 + +### Patch Changes + +- [#2767](https://github.com/statelyai/xstate/pull/2767) [`c1503b121`](https://github.com/statelyai/xstate/commit/c1503b1219d995ebf0f45de46036c5a1d7e6442f) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an over-rendering issue in the `useSelector`. + +## 1.6.2 + +### Patch Changes + +- [#2736](https://github.com/statelyai/xstate/pull/2736) [`2246ae051`](https://github.com/statelyai/xstate/commit/2246ae051663f261b4750d7adba57f008ec28f1d) Thanks [@Andarist](https://github.com/Andarist), [@davidkpiano](https://github.com/statelyai), [@VanTanev](https://github.com/VanTanev)! - The `useSelector(...)` hook now works as expected when the `actor` passed in changes. The hook will properly subscribe to the new `actor` and select the desired value. See [#2702](https://github.com/statelyai/xstate/issues/2702) + +- [#2685](https://github.com/statelyai/xstate/pull/2685) [`469268d39`](https://github.com/statelyai/xstate/commit/469268d39fbc23996599773adfc4ca824b48585f) Thanks [@farskid](https://github.com/farskid), [@Andarist](https://github.com/Andarist)! - Fixed a regression with a development-only warning not being shown when a machine reference is updated during the hook lifecycle. This usually happens when machine options are dependent on external values and they're passed via `withConfig`. + + ```js + const machine = createMachine({ + initial: 'foo', + context: { id: 1 }, + states: { + foo: { + on: { + CHECK: { + target: 'bar', + cond: 'hasOverflown' + } + } + }, + bar: {} + } + }); + + const [id, setId] = useState(1); + const [current, send] = useMachine( + machine.withConfig({ + guards: { + hasOverflown: () => id > 1 // id is a reference to an outside value + } + }) + ); + + // later when id updates + setId(2); + // Now the reference passed to `useMachine` (the result of `machine.withConfig`) is updated but the interpreted machine stays the same. So the guard is still the previous one that got passed to the `useMachine` initially, and it closes over the stale `id`. + ``` + +## 1.6.1 + +### Patch Changes + +- [#2587](https://github.com/statelyai/xstate/pull/2587) [`5aaa8445c`](https://github.com/statelyai/xstate/commit/5aaa8445c0041c6e9c47285c18e8b71cb2d805a7) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with implementations provided outside of React being wiped out and unusable. + +## 1.6.0 + +### Minor Changes + +- [`4b4872ca`](https://github.com/statelyai/xstate/commit/4b4872cafd63f825f3918c6eb6fa84642d45e3e0) [#2241](https://github.com/statelyai/xstate/pull/2241) Thanks [@mattpocock](https://github.com/mattpocock)! - Changed the behaviour of guards, delays and activities when declared as options in `useMachine`/`useInterpret`. + + Previously, guards could not reference external props, because they would not be updated when the props changed. For instance: + + ```tsx + const Modal = (props) => { + useMachine(modalMachine, { + guards: { + isModalOpen: () => props.isOpen + } + }); + }; + ``` + + When the component is created, `props.isOpen` would be checked and evaluated to the initial value. But if the guard is evaluated at any other time, it will not respond to the props' changed value. + + This is not true of actions/services. This will work as expected: + + ```tsx + const Modal = (props) => { + useMachine(modalMachine, { + actions: { + consoleLogModalOpen: () => { + console.log(props.isOpen); + } + } + }); + }; + ``` + + This change brings guards and delays into line with actions and services. + + ⚠️ **NOTE:** Whenever possible, use data from within `context` rather than external data in your guards and delays. + +### Patch Changes + +- [`fe3e859f`](https://github.com/statelyai/xstate/commit/fe3e859f5c53813307bacad915bebc8d1f3a982c) [#2522](https://github.com/statelyai/xstate/pull/2522) Thanks [@farskid](https://github.com/farskid), [@Andarist](https://github.com/Andarist)! - Fixed an issue with actors not being spawned correctly by `useMachine` and `useInterpret` when they were defined a lazily evaluated context, like for example here: + + ```js + createMachine({ + // lazy context + context: () => ({ + ref: spawn(() => {}) + }) + }); + ``` + +## 1.5.1 + +### Patch Changes + +- [`453acacb`](https://github.com/statelyai/xstate/commit/453acacbec364531a2851f183c3ab446d7db0e84) [#2389](https://github.com/statelyai/xstate/pull/2389) Thanks [@davidkpiano](https://github.com/statelyai)! - An internal issue where the `spawnBehavior` import for the `useSpawn(...)` hook was broken internally has been fixed. + +## 1.5.0 + +### Minor Changes + +- [`432b60f7`](https://github.com/statelyai/xstate/commit/432b60f7bcbcee9510e0d86311abbfd75b1a674e) [#2280](https://github.com/statelyai/xstate/pull/2280) Thanks [@davidkpiano](https://github.com/statelyai)! - Just like `useInvoke(...)`, other types of actors can now be spawned from _behaviors_ using `useSpawn(...)`: + + ```tsx + import { fromReducer } from 'xstate/lib/behaviors'; + import { useActor, useSpawn } from '@xstate/react'; + + type CountEvent = { type: 'INC' } | { type: 'DEC' }; + + const countBehavior = fromReducer( + (count: number, event: CountEvent): number => { + if (event.type === 'INC') { + return count + 1; + } else if (event.type === 'DEC') { + return count - 1; + } + + return count; + }, + 0 // initial state + ); + + const countMachine = createMachine({ + invoke: { + id: 'count', + src: () => fromReducer(countReducer, 0) + }, + on: { + INC: { + actions: forwardTo('count') + }, + DEC: { + actions: forwardTo('count') + } + } + }); + + const Component = () => { + const countActorRef = useSpawn(countBehavior); + const [count, send] = useActor(countActorRef); + + return ( +
+ Count: {count} + + +
+ ); + }; + ``` + +## 1.4.0 + +### Minor Changes + +- [`849ec56c`](https://github.com/statelyai/xstate/commit/849ec56c2a9db34e65a30af94e68a7a7a50b4158) [#2286](https://github.com/statelyai/xstate/pull/2286) Thanks [@davidkpiano](https://github.com/statelyai)! - The `useService(...)` hook will be deprecated, since services are also actors. In future versions, the `useActor(...)` hook should be used instead: + + ```diff + -const [state, send] = useService(service); + +const [state, send] = useActor(service); + ``` + +### Patch Changes + +- [`ea3aaffb`](https://github.com/statelyai/xstate/commit/ea3aaffb906b34a42bb2736c7b91d54ffe9ed882) [#2326](https://github.com/statelyai/xstate/pull/2326) Thanks [@davidkpiano](https://github.com/statelyai)! - The `send` type returned in the tuple from `useActor(someService)` was an incorrect `never` type; this has been fixed. + +## 1.3.4 + +### Patch Changes + +- [`aa3c2991`](https://github.com/statelyai/xstate/commit/aa3c29916b7382fbcf1a3efb183ca1e8eb625480) [#2223](https://github.com/statelyai/xstate/pull/2223) Thanks [@davidkpiano](https://github.com/statelyai)! - Support for actor refs with the `.getSnapshot()` method (added for spawned actors in XState version 4.19) is now supported in the `useActor(...)` hook. + +## 1.3.3 + +### Patch Changes + +- [`27e7242c`](https://github.com/statelyai/xstate/commit/27e7242c24146de85cf618a658b400a3241fa7d7) [#2112](https://github.com/statelyai/xstate/pull/2112) Thanks [@davidkpiano](https://github.com/statelyai)! - The `executeEffect` function is no longer exported (was meant to be internal and is useless as a public function anyway). This also fixes a circular dependency issue. + +## 1.3.2 + +### Patch Changes + +- [`bb5e81ea`](https://github.com/statelyai/xstate/commit/bb5e81eaa1ecba1fd54a7677ce9eaee9bd695964) [#2050](https://github.com/statelyai/xstate/pull/2050) Thanks [@theKashey](https://github.com/theKashey)! - Added an explicit entrypoint for `@xstate/react/fsm` which you can use instead of `@xstate/react/lib/fsm`. This is the only specifier that will be supported in the future - the other one will be dropped in the next major version. + + ```diff + -import { useMachine } from '@xstate/react/lib/fsm' + +import { useMachine } from '@xstate/react/fsm' + ``` + +## 1.3.1 + +### Patch Changes + +- [`b076b253`](https://github.com/statelyai/xstate/commit/b076b25364224874f62e8065892be40dfbb28030) [#1947](https://github.com/statelyai/xstate/pull/1947) Thanks [@lukekarrys](https://github.com/lukekarrys)! - Fix typing of the service returned from the fsm useMachine hook by passing it Typestate + +- [`9b5dc784`](https://github.com/statelyai/xstate/commit/9b5dc7843c44f50bcca0ffccb843b3d50cef6ddc) [#1950](https://github.com/statelyai/xstate/pull/1950) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with `toObserver` being internally imported from `xstate/lib/utils` which has broken UMD build and the declared peer dep contract. + +## 1.3.0 + +### Minor Changes + +- [`577ae023`](https://github.com/statelyai/xstate/commit/577ae02384926b49e876011c4393f212b49066f8) [#1915](https://github.com/statelyai/xstate/pull/1915) Thanks [@davidkpiano](https://github.com/statelyai)! - New hook: `useInterpret(machine)`, which is a low-level hook that interprets the `machine` and returns the `service`: + + ```js + import { useInterpret } from '@xstate/react'; + import { someMachine } from '../path/to/someMachine'; + + const App = () => { + const service = useInterpret(someMachine); + + // ... + }; + ``` + +- [`577ae023`](https://github.com/statelyai/xstate/commit/577ae02384926b49e876011c4393f212b49066f8) [#1915](https://github.com/statelyai/xstate/pull/1915) Thanks [@davidkpiano](https://github.com/statelyai)! - New hook: `useSelector(actor, selector)`, which subscribes to `actor` and returns the selected state derived from `selector(snapshot)`: + + ```js + import { useSelector } from '@xstate/react'; + + const App = ({ someActor }) => { + const count = useSelector(someActor, (state) => state.context.count); + + // ... + }; + ``` + +## 1.2.2 + +### Patch Changes + +- [`4b31cefb`](https://github.com/statelyai/xstate/commit/4b31cefb3d3497e5515314046639df7e27dbe9e8) [#1780](https://github.com/statelyai/xstate/pull/1780) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with some external packages not being bundled correctly into the UMD bundles. + +## 1.2.1 + +### Patch Changes + +- [`a16a5f2f`](https://github.com/statelyai/xstate/commit/a16a5f2ff5ba9d4d7834ec3ca2d0adecf5d6a870) [#1756](https://github.com/statelyai/xstate/pull/1756) Thanks [@dimitardanailov](https://github.com/dimitardanailov)! - Fixed an issue with `process` references not being removed correctly from the UMD bundles. + +## 1.2.0 + +### Minor Changes + +- [`dd98296e`](https://github.com/statelyai/xstate/commit/dd98296e9fcbae905da2395e67e876e28be7c774) [#1738](https://github.com/statelyai/xstate/pull/1738) Thanks [@dimitardanailov](https://github.com/dimitardanailov)! - Added UMD bundle. + +## 1.1.0 + +### Minor Changes + +- [`89f9c27c`](https://github.com/statelyai/xstate/commit/89f9c27c453dc56bdfdf49c8ea1f0f87ff1f9b67) [#1622](https://github.com/statelyai/xstate/pull/1622) Thanks [@davidkpiano](https://github.com/statelyai)! - Spawned/invoked actors and interpreters are now typed as extending `ActorRef` rather than `Actor` or `Interpreter`. This unification of types should make it more straightforward to provide actor types in React: + + ```ts + import { ActorRef } from 'xstate'; + import { useActor } from '@xstate/react'; + + const Child: React.FC<{ actorRef: ActorRef }> = ({ + actorRef + }) => { + // `state` is typed as `SomeEmitted` + // `send` can be called with `SomeEvent` values + const [state, send] = useActor(actorRef); + + // . .. + }; + ``` + + It's also easier to specify the type of a spawned/invoked machine with `ActorRefFrom`: + + ```ts + import { createMachine, ActorRefFrom } from 'xstate'; + import { useActor } from '@xstate/react'; + + const someMachine = createMachine({ + // ... + }); + + const Child: React.FC<{ someRef: ActorRefFrom }> = ({ + someRef + }) => { + // `state` is typed as `State` + // `send` can be called with `SomeEvent` values + const [state, send] = useActor(someRef); + + // . .. + }; + ``` + +## 1.0.3 + +### Patch Changes + +- [`27db2950`](https://github.com/statelyai/xstate/commit/27db295064d42cacb89ff10d55f39eb7609148e1) [#1636](https://github.com/statelyai/xstate/pull/1636) Thanks [@Andarist](https://github.com/Andarist)! - Allow React 17 in the specified peer dependency range. + +## 1.0.2 + +### Patch Changes + +- [`c7927083`](https://github.com/statelyai/xstate/commit/c7927083a651e3c51952ade2ffda793df0391bf6) [#1516](https://github.com/statelyai/xstate/pull/1516) Thanks [@davidkpiano](https://github.com/statelyai)! - The `send` function returned from the `useService()` now can take two arguments (an event type and payload), to match the behavior of `@xstate/react` version 0.x. + +- [`db77623a`](https://github.com/statelyai/xstate/commit/db77623a48955d762cffa9b624f438220add5eed) [#1516](https://github.com/statelyai/xstate/pull/1516) Thanks [@davidkpiano](https://github.com/statelyai)! - The `send` value returned from the `useService()` hook will now accept a payload, which matches the signature of the `send` value returned from the `useMachine()` hook: + + ```js + const [state, send] = useService(someService); + + // ... + + // this is OK: + send('ADD', { value: 3 }); + + // which is equivalent to: + send({ type: 'ADD', value: 3 }); + ``` + +- [`93f6db02`](https://github.com/statelyai/xstate/commit/93f6db02a2d56ec997198ddef0af3d7730bb79bb) [#1594](https://github.com/statelyai/xstate/pull/1594) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an issue with internal `setState` in `useService` being called with 2 arguments instead of 1. + +- [`72b0880e`](https://github.com/statelyai/xstate/commit/72b0880e6444ae009adca72088872bb5c0760ce3) [#1504](https://github.com/statelyai/xstate/pull/1504) Thanks [@Andarist](https://github.com/Andarist)! - Fixed issue with `useService` returning an initial state for services in their final states. + +## 1.0.1 + +### Patch Changes + +- [`c0bd0407`](https://github.com/statelyai/xstate/commit/c0bd040767dcac20ed690e49a8725b4f1011dd5d) [#1493](https://github.com/statelyai/xstate/pull/1493) Thanks [@davidkpiano](https://github.com/statelyai)! - There will now be a descriptive error when trying to use an actor-like object in the `useService()` hook, where `useActor()` should be preferred: + + > Attempted to use an actor-like object instead of a service in the useService() hook. Please use the useActor() hook instead. + +All notable changes to this project will be documented in this file. + +## [1.0.0-rc.7] + +- The `machine` passed into `useMachine(machine)` can now be passed in lazily: + + ```js + const [state, send] = useMachine(() => createMachine(/* ... */)); + + // ... + ``` + + This has the benefit of avoiding unnecessary machine initializations whenever the component rerenders. + +- The `useActor` hook now takes a second argument: `getSnapshot` which is a function that should return the last emitted value: + + ```js + const [state, send] = useActor(someActor, (actor) => actor.current); + ``` + +## [1.0.0-rc.6] + +## [1.0.0-rc.5] + +- You can now schedule actions in `useEffect` or `useLayoutEffect` via: + - `asEffect` - queues the action to be executed in `useEffect` + - `asLayoutEffect` - queues the action to be executed in `useLayoutEffect` + +```jsx +import { createMachine } from 'xstate'; +import { useMachine, asEffect } from '@xstate/react'; + +const machine = createMachine({ + initial: 'focused', + states: { + focused: { + entry: 'focus' + } + } +}); + +const Input = () => { + const inputRef = useRef(null); + const [state, send] = useMachine(machine, { + actions: { + focus: asEffect(() => { + inputRef.current && inputRef.current.focus(); + }) + } + }); + + return ; +}; +``` + +## [0.8.1] + +- Services are now kept up to date + +## [0.8.0] + +- The `useActor()` hook is now available. +- Support for persisted states + +## [0.7.1] + +- Actions passed into `useMachine(..., { actions: { ... } })` will now be kept up-to-date and no longer reference stale data. + +## [0.7.0] + +### Added + +- Machine configuration can now be merged into the options argument of `useMachine(machine, options)`. The following Machine Config options are available: `guards`, `actions`, `activities`, `services`, `delays` and `updates` (NOTE: `context` option is not implemented yet, use `withContext` or `withConfig` instead for the meantime) + +```js +const [current, send] = useMachine(someMachine, { + actions: { + doThing: doTheThing + }, + services: {/* ... */}, + guards: {/* ... */} + // ... etc. +}); +``` diff --git a/xstate-react/LICENSE b/xstate-react/LICENSE new file mode 100644 index 00000000..fc1fe941 --- /dev/null +++ b/xstate-react/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Khourshid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/xstate-react/README.md b/xstate-react/README.md new file mode 100644 index 00000000..ed8a00ae --- /dev/null +++ b/xstate-react/README.md @@ -0,0 +1,52 @@ +# @xstate/react + +This package contains utilities for using [XState](https://github.com/statelyai/xstate) with [React](https://github.com/facebook/react/). + +- [Read the full documentation in the XState docs](https://stately.ai/docs/xstate-react). +- [Read our contribution guidelines](https://github.com/statelyai/xstate/blob/main/CONTRIBUTING.md). + +## Quick start + +1. Install `xstate` and `@xstate/react`: + +```bash +npm i xstate @xstate/react +``` + +2. Import the `useMachine` hook: + +```tsx +import { useMachine } from '@xstate/react'; +import { createMachine } from 'xstate'; + +const toggleMachine = createMachine({ + id: 'toggle', + initial: 'inactive', + states: { + inactive: { + on: { TOGGLE: { target: 'active' } } + }, + active: { + on: { TOGGLE: { target: 'inactive' } } + } + } +}); + +export const Toggler = () => { + const [state, send] = useMachine(toggleMachine); + + return ( + + ); +}; +``` + +## Observing an actor + + + +Pass a snapshot listener or observer as the third argument to `useActorRef(logic, options, observer)`. It subscribes before the actor starts. When the hook replaces the actor (after an external stop, or a Fast Refresh that cannot keep it), the observer follows the replacement, even when the callback identity stays the same. Unmounting unsubscribes the observer and stops the actor. diff --git a/xstate-react/docs/global-state.md b/xstate-react/docs/global-state.md new file mode 100644 index 00000000..bd244c4f --- /dev/null +++ b/xstate-react/docs/global-state.md @@ -0,0 +1,108 @@ +--- +title: Global state +description: Run one application-wide actor and read it from any component. +--- + +Some state belongs to the application rather than to a piece of the UI: the signed-in session, a notification queue, a media player that keeps playing while the user navigates. Create that actor once at module scope and read it with [`useSelector`](selectors.md). + +```tsx +// player.ts +import { createActor } from 'xstate'; + +export const playerActor = createActor(playerMachine).start(); +``` + +```tsx +// TransportControls.tsx +import { useSelector } from '@xstate/react'; +import { playerActor } from './player'; + +export function TransportControls() { + const isPlaying = useSelector(playerActor, (s) => s.matches('playing')); + + return ( + + ); +} +``` + +There is no provider and no hook that owns the actor. Any module can import the actor and send to it, including code outside React such as a router guard or a service worker message handler. + +The actor is started at import time and never stopped, so it survives every unmount. That is the intended behavior for a media player. For state scoped to a screen, it is a leak. + +## Module scope or provider? + +| | Module-scope actor | [`createActorContext`](shared-actors.md) | +| --- | --- | --- | +| Lifetime | The page session | The provider's mount | +| Instances | Exactly one | One per rendered provider | +| Input | Fixed at module load | Per provider, via `options.input` | +| Server rendering | Unsafe — shared between requests | Safe — one actor per render | +| Reset | Manual, via an event | Unmount and remount | + +Choose a module-scope actor when there is exactly one of the thing and it should outlive any component. Choose a provider when the actor is scoped to a screen, a route, a dialog, or an item, or when it needs input that only a component knows. + +> **Warning:** Never create a module-scope actor in code that runs on the server. The module is shared by every request, so one user's state leaks into another's response. See [server rendering](server-rendering.md). + +## Several global actors + +Independent concerns get independent actors. A session actor, a notification actor and a player actor are three module-scope actors, each with its own file and its own selectors. + +```tsx +const unread = useSelector(notificationsActor, (s) => s.context.unread.length); +const userName = useSelector(sessionActor, (s) => s.context.user?.name); +``` + +When those actors must reach each other, put them in one [actor system](../systems.md) instead of importing one into the other. Declare the registry up front and look actors up by key from inside machine logic. + +```tsx +// system.ts +import { createSystem } from 'xstate'; + +export const appSystem = createSystem({ + registry: { notifications: notificationsMachine } +}); + +export const appActor = appSystem.createActor(appMachine).start(); +``` + +```ts +// inside appMachine +on: { + 'order.placed': ({ system }, enq) => { + enq.sendTo(system.get('notifications'), { + type: 'notify', + message: 'Order placed' + }); + } +} +``` + +Components still read whichever actor holds the value they render: + +```tsx +const notifications = appActor.system.get('notifications'); +const unread = useSelector(notifications, (s) => s?.context.unread.length ?? 0); +``` + +Registry entries are removed when their actor stops, so handle `undefined`. + +A single root actor that [invokes](../invoke.md) or [spawns](../spawn.md) its children is usually clearer than several independent roots. Children then persist together in one `getPersistedSnapshot()` call, and one `appActor.stop()` tears everything down. + +## Global state cheatsheet + +```tsx +// module scope +export const appActor = createActor(appMachine, { input }).start(); + +// in a component +const value = useSelector(appActor, (snapshot) => snapshot.context.value); +appActor.trigger.refresh(); + +// systems +const system = createSystem({ registry: { notifications: notificationsMachine } }); +const actor = system.createActor(appMachine).start(); +system.get('notifications'); +``` diff --git a/xstate-react/docs/input-and-snapshots.md b/xstate-react/docs/input-and-snapshots.md new file mode 100644 index 00000000..3d5ee631 --- /dev/null +++ b/xstate-react/docs/input-and-snapshots.md @@ -0,0 +1,118 @@ +--- +title: Input and restored snapshots +description: Start React actors with input or persisted state. +--- + +`input` gives an actor the data it needs to compute its initial state. `snapshot` restores an actor to a state it already reached. Both are [actor options](../create-actor.md#actor-options), passed as the second argument to the hook. + +```tsx +const [snapshot, send] = useActor(uploadMachine, { + input: { fileName: 'report.pdf' } +}); +``` + +The same options work on `useActorRef` and on a provider. + +```tsx + + + +``` + +When the logic requires input, the options argument is required and TypeScript reports a missing `input`. See [input and output](../input-output.md). + +## Input is read once + +Options are read when the actor is created: on the first render of the component, or the first render of the provider. Changing `input` on a later render does not restart the actor and does not update its context. + +```tsx +// userId changes on a later render: the actor keeps the original one +const [snapshot] = useActor(profileMachine, { input: { userId } }); +``` + +Two ways to handle changing input, in order of preference: + +- Send an event. `send({ type: 'user.changed', userId })` keeps one actor and lets the machine decide what a change means: cancel the in-flight request, reset the form, or keep the draft. +- Remount the component with a `key`. `` stops the old actor and creates a new one with the new input. Use this when the previous state has no meaning for the new input. + +Input itself can be computed at render time, but only the first value is used. + +```tsx +const [snapshot] = useActor(searchMachine, { + input: { query: searchParams.get('q') ?? '' } +}); +``` + +## Restoring a persisted snapshot + +Pass a snapshot from [`actor.getPersistedSnapshot()`](../persistence.md) to resume where the user left off. The actor starts in that state rather than its initial state; entry actions are not re-run, and invoked children are restored. + +```tsx +import { useActor } from '@xstate/react'; +import type { Snapshot } from 'xstate'; + +function Checkout({ + orderId, + persisted +}: { + orderId: string; + persisted?: Snapshot; +}) { + const [snapshot, send] = useActor( + checkoutMachine, + persisted ? { snapshot: persisted } : { input: { orderId } } + ); + + return send({ type: 'next' })} />; +} +``` + +When the logic requires input, a snapshot that may be missing (an optional prop, or a `localStorage` read that finds nothing) needs a branch that passes `input` instead. Logic without required input accepts `snapshot: undefined`, which is the same as passing nothing. + +Save as the actor changes by subscribing to the actor reference. `getPersistedSnapshot()` is a method on the actor, not on the snapshot the subscriber receives. + +```tsx +const actorRef = useActorRef( + checkoutMachine, + persisted ? { snapshot: persisted } : { input: { orderId } } +); + +useEffect(() => { + const sub = actorRef.subscribe(() => { + localStorage.setItem( + 'checkout', + JSON.stringify(actorRef.getPersistedSnapshot()) + ); + }); + + return () => sub.unsubscribe(); +}, [actorRef]); +``` + +> **Warning:** Stored snapshots are untrusted input. Validate and version them before restoring. A malformed snapshot starts an actor in an unusable state rather than throwing. See [persist and restore actors](../persist-and-restore-actors.md). + +`input` and `snapshot` can be passed together, but the restored snapshot already carries the context that input produced. Pass `input` alongside `snapshot` only for logic that reads `input` after restoring. + +## TypeScript + +`input` is typed from the logic's input schema, and the options argument becomes required when the logic requires input. Restored snapshots are typed as `Snapshot` because they come from outside the type system. + +```tsx +import type { Snapshot } from 'xstate'; + +const persisted = JSON.parse(stored) as Snapshot; +useActor(checkoutMachine, { snapshot: persisted }); +``` + +## Input and snapshots cheatsheet + +```tsx +useActor(logic, { input: { userId } }); +useActor(logic, { snapshot: persisted }); +useActorRef(logic, { input, snapshot }); + +; + +// new input, new actor +; +``` diff --git a/xstate-react/docs/meta.json b/xstate-react/docs/meta.json new file mode 100644 index 00000000..24558c6e --- /dev/null +++ b/xstate-react/docs/meta.json @@ -0,0 +1,12 @@ +{ + "title": "XState React", + "pages": [ + "use-machine", + "selectors", + "shared-actors", + "global-state", + "input-and-snapshots", + "server-rendering", + "testing" + ] +} diff --git a/xstate-react/docs/selectors.md b/xstate-react/docs/selectors.md new file mode 100644 index 00000000..9983c757 --- /dev/null +++ b/xstate-react/docs/selectors.md @@ -0,0 +1,118 @@ +--- +title: Select actor data +description: Re-render a component only when selected actor data changes. +--- + +`useSelector(actorRef, selector, compare?)` reads one derived value from an actor's [snapshot](../snapshots.md) and re-renders the component only when that value changes. + +```tsx +import { useActorRef, useSelector } from '@xstate/react'; + +function Cart() { + const actorRef = useActorRef(checkoutMachine); + const total = useSelector(actorRef, (snapshot) => snapshot.context.total); + + return {total}; +} +``` + +The selector runs on every snapshot. The component re-renders only when the selected value differs from the previous one, compared with `===` by default. + +Select the smallest value the component actually renders: a count, a label, or `snapshot.matches('loading')`. Selecting `snapshot.context` re-renders the component on any context change. + +```tsx +const isUploading = useSelector(actorRef, (s) => s.matches('uploading')); +const percent = useSelector(actorRef, (s) => s.context.percent); +``` + +Two selectors on the same actor are independent. A progress bar and a status label can each update only when their own value changes. + +## Custom equality + +Pass a comparison function as the third argument when the selector returns a new object or array each time. Without it, every snapshot produces a new reference and the component re-renders every time. + +```tsx +const summary = useSelector( + actorRef, + (s) => ({ step: s.value, itemCount: s.context.items.length }), + (a, b) => a.step === b.step && a.itemCount === b.itemCount +); +``` + +`shallowEqual` covers the common case of a flat object or array. + +```tsx +import { shallowEqual, useSelector } from '@xstate/react'; + +const { step, itemCount } = useSelector( + actorRef, + (s) => ({ step: s.value, itemCount: s.context.items.length }), + shallowEqual +); +``` + +`shallowEqual` compares own enumerable keys one level deep with `Object.is`. It does not recurse, so a selector returning nested objects still re-renders. + +## Child actors + +`useSelector` works with any actor reference, including [invoked](../invoke.md) and [spawned](../spawn.md) children. Pass the child reference down and let the child component subscribe to it directly, so the parent does not re-render for the child's updates. + +```tsx +function TodoList() { + const [snapshot] = useActor(todosMachine); + + return snapshot.context.todos.map((todo) => ( + + )); +} + +type TodoActor = ActorFromLogic; + +function TodoItem({ actor }: { actor: TodoActor }) { + const label = useSelector(actor, (s) => s.context.label); + + return ( + + ); +} +``` + +Children read from `snapshot.children` may be absent while their state is inactive. `useSelector` accepts `undefined` as the actor, in which case the selector receives `undefined` and no subscription is made. + +```tsx +const progress = useSelector( + snapshot.children.upload, + (s) => s?.context.percent ?? 0 +); +``` + +If the selected actor is in an `error` snapshot, `useSelector` throws the error during render so an error boundary can catch it. + +## Compared with `actor.select` + +[`actor.select(...)`](../selectors.md) is the framework-agnostic API. It returns a readable with `get()` and `subscribe(...)`, and is the API to use outside components: in machine logic, tests, or imperative code that syncs a media element. + +Inside a component, use `useSelector`. It handles subscription, cleanup and concurrent rendering through `useSyncExternalStore`. + +## TypeScript + +The selector's argument is typed from the actor reference's snapshot, and the return type is inferred from the selector. Annotate the parameter when the selector is defined outside the call. + +```tsx +import type { SnapshotFrom } from 'xstate'; + +const selectTotal = (snapshot: SnapshotFrom) => + snapshot.context.total; + +const total = useSelector(actorRef, selectTotal); // number +``` + +## Selectors cheatsheet + +```tsx +useSelector(actorRef, (snapshot) => snapshot.context.count); +useSelector(actorRef, (snapshot) => snapshot.matches('loading')); +useSelector(actorRef, selector, compare); +useSelector(actorRef, selector, shallowEqual); +useSelector(snapshot.children.upload, (s) => s?.context.percent ?? 0); +``` diff --git a/xstate-react/docs/server-rendering.md b/xstate-react/docs/server-rendering.md new file mode 100644 index 00000000..a6577ed4 --- /dev/null +++ b/xstate-react/docs/server-rendering.md @@ -0,0 +1,102 @@ +--- +title: Server rendering +description: Render XState actors on the server and hydrate them on the client. +--- + +Two rules cover most cases: never share a running actor between requests, and make the first client render produce the same markup the server produced. + +`useActor`, `useActorRef` and `useSelector` all render on the server. They create the actor, read its initial snapshot and return it. The effect that starts the actor never runs, so no transitions, entry actions or invoked children execute on the server. + +## One actor per request + +A module-scope actor is created once per process and shared by every request, so one user's checkout state is rendered into another user's page. Create actors inside the request or inside the component tree instead. + +```tsx +// Wrong on the server: one actor for every visitor +export const cartActor = createActor(cartMachine).start(); +``` + +```tsx +// Right: one actor per rendered tree + + + +``` + +The same applies to actors created in a request handler: stop them when the request finishes, or let them go out of scope. See [run backend workflows](../backend-workflows.md). + +> **Warning:** [Module-scope actors](global-state.md) are a client-only pattern. In a server-rendered app, put the module that creates them behind a client entry point so it never loads during a request. + +## Render-only initial state + +When the server only needs to render markup and will not run the machine, `initialTransition(logic, input?)` computes the initial snapshot without creating an actor. + +```tsx +import { initialTransition } from 'xstate'; + +const [snapshot] = initialTransition(checkoutMachine, { orderId }); +const heading = snapshot.matches('review') ? 'Review order' : 'Checkout'; +``` + +This is the cheapest option for a route that renders a heading, a title or a redirect decision from the machine's initial state. + +## Hydration with a persisted snapshot + +When the server advanced the machine (loading data, validating a session, resuming a saved flow), serialize the result and restore it on the client so the first client render matches. + +On the server, run the actor and take a persisted snapshot: + +```tsx +const actor = createActor(checkoutMachine, { input: { orderId } }).start(); +await waitFor(actor, (snapshot) => snapshot.matches('ready')); + +const persisted = actor.getPersistedSnapshot(); +actor.stop(); +``` + +Send `persisted` to the client with the page, then pass it to the hook: + +```tsx +function Checkout({ persisted }: { persisted: Snapshot }) { + const [snapshot, send] = useActor(checkoutMachine, { snapshot: persisted }); + + return send({ type: 'next' })} />; +} +``` + +Both renders now start from the same snapshot, so there is no hydration mismatch. See [input and snapshots](input-and-snapshots.md) and [persistence](../persistence.md). + +Anything in context must survive `JSON.stringify`. Store an id and look the resource up again on the client rather than putting a client, socket or DOM node in context. See [serialization](../serialization.md). + +## Next.js App Router + +Hooks are client-only. A component that calls `useActor`, `useActorRef` or `useSelector` needs `'use client'`, as does the module that calls `createActorContext(...)`. + +```tsx +'use client'; + +import { createActorContext } from '@xstate/react'; + +export const CheckoutContext = createActorContext(checkoutMachine); +``` + +Server components can still do machine work, such as computing a snapshot with `initialTransition(...)` or running an actor to completion, and pass the result down as a serializable prop: + +```tsx +// app/checkout/page.tsx — server component +export default async function Page({ params }) { + const persisted = await loadCheckoutSnapshot(params.orderId); + + return ( + + + + ); +} +``` + +Only serializable values cross that boundary, which is what `getPersistedSnapshot()` returns. + +## Browser-only effects + +Effects that touch `window`, `localStorage` or media APIs must not run during a server render. Nothing in a machine runs on the server, so put them where they belong: in an [invoked actor](../invoke.md) owned by a state the machine only reaches after hydration, or in an effect queued with `enq(...)`, which is executed by a started actor and therefore only in the browser. diff --git a/xstate-react/docs/shared-actors.md b/xstate-react/docs/shared-actors.md new file mode 100644 index 00000000..a3ae305e --- /dev/null +++ b/xstate-react/docs/shared-actors.md @@ -0,0 +1,161 @@ +--- +title: Share actors +description: Provide one actor to a React subtree. +--- + +`createActorContext(logic, options?)` builds a React context around actor logic. Every component under the provider reads and sends to the same actor. + +```tsx +import { createActorContext } from '@xstate/react'; + +export const CheckoutContext = createActorContext(checkoutMachine); + +function App() { + return ( + + + + + ); +} + +function Cart() { + const total = CheckoutContext.useSelector((snapshot) => snapshot.context.total); + const actorRef = CheckoutContext.useActorRef(); + + return ; +} +``` + +The returned object has three members. + +| Member | Description | +| --- | --- | +| `Provider` | Creates one actor and provides it to its subtree. | +| `useSelector(selector, compare?)` | Reads a derived value from the provided actor. Same semantics as [`useSelector`](selectors.md). | +| `useActorRef()` | Returns the provided [actor reference](../create-actor.md). Does not re-render. | + +Each rendered `Provider` creates its own actor, with the same lifecycle as [`useActorRef`](use-machine.md#actor-lifecycle): started on mount, stopped on unmount, recreated if it was stopped while the component stayed mounted. + +Calling `useSelector` or `useActorRef` outside the provider throws: *You used a hook from "ActorProvider" but it's not inside a `` component.* + +## Provider options + +`Provider` takes an `options` prop with the same [actor options](../create-actor.md#actor-options) as `createActor(...)`: `input`, `snapshot`, `id`, `inspect`, and the rest. + +```tsx + + + +``` + +Options passed to `createActorContext(logic, options)` are defaults. The `options` prop is merged over them, key by key. + +```tsx +const CheckoutContext = createActorContext(checkoutMachine, { + inspect: inspector +}); + +// inspect is kept, input is added +; +``` + +`logic` overrides the logic for one provider, which is how a test swaps in [`machine.provide({ ... })`](../setup-and-provide.md). + +```tsx + + + +``` + +> **Warning:** The `machine` prop was removed. Passing it throws. Use `logic`. + +## Provide implementations + +A provider component can take implementations as props and pass them to the shared actor. Build the logic with [`machine.provide({ ... })`](../setup-and-provide.md) and pass it as `logic`; pass input through `options`. + +```tsx +import * as React from 'react'; +import { createActorContext } from '@xstate/react'; +import { checkoutMachine } from './checkoutMachine'; +import type { authorize } from './authorize'; + +export const CheckoutContext = createActorContext(checkoutMachine); + +export function CheckoutProvider({ + orderId, + authorizeLogic, + track, + children +}: { + orderId: string; + authorizeLogic: typeof authorize; + track: (params: { name: string }) => void; + children: React.ReactNode; +}) { + const [logic] = React.useState(() => + checkoutMachine.provide({ + actors: { authorize: authorizeLogic }, + actions: { track } + }) + ); + + return ( + + {children} + + ); +} +``` + +The logic is created once, on the first render, and the actor runs with those implementations for the provider's lifetime. To switch to different implementations, change the provider's `key`. React unmounts the old provider, which stops its actor, and mounts a new provider with a new actor. + +```tsx + + + +``` + +The new actor starts from the machine's initial state. Consumers keep calling `CheckoutContext.useSelector(...)` and `CheckoutContext.useActorRef()` unchanged. + +## When to use it + +Use a provider when several components in one subtree need the same actor and the actor's lifetime matches a piece of the UI: a cart shared across checkout steps, a wizard shared across its steps, a media player shared by transport controls and a timeline. + +Prefer passing the actor reference as a prop when only one or two components need it. `useActorRef` in a parent plus [`useSelector`](selectors.md) in a child is simpler and more explicit than a context. + +Place the provider close to the feature it belongs to. A provider at the application root gives every instance of that feature the same actor, which is rarely what you want for per-item state. For state that belongs to the whole application, see [global state](global-state.md). + +## TypeScript + +Snapshot, event and actor reference types come from the logic. + +`input` stays optional on `createActorContext` and on the `Provider` `options` prop, even when the logic requires input, because the actor's options are merged from the `createActorContext(logic, options)` defaults and the `` prop. A missing required input is not a type error; when initialization reads it, the actor starts with an error snapshot. + +```tsx +const CheckoutContext = createActorContext(checkoutMachine); + +const total = CheckoutContext.useSelector((s) => s.context.total); // number +const actorRef = CheckoutContext.useActorRef(); // Actor +``` + +## Shared actors cheatsheet + +```tsx +const Ctx = createActorContext(logic, defaultOptions); + + + {children} +; + +Ctx.useSelector((snapshot) => snapshot.context.value); +Ctx.useSelector((snapshot) => snapshot.context.user, shallowEqual); +Ctx.useActorRef(); +``` diff --git a/xstate-react/docs/testing.md b/xstate-react/docs/testing.md new file mode 100644 index 00000000..63f565f0 --- /dev/null +++ b/xstate-react/docs/testing.md @@ -0,0 +1,143 @@ +--- +title: Test React components +description: Test components that run XState actors. +--- + +Test a component the way a user uses it: render it, fire events, assert on what is on screen. The actor is an implementation detail. Assert on rendered output, not on `snapshot.value`. + +```tsx +import { fireEvent, render, screen } from '@testing-library/react'; + +test('plays and pauses', () => { + render(); + + fireEvent.click(screen.getByRole('button', { name: 'Play' })); + expect(screen.getByRole('button').textContent).toBe('Pause'); +}); +``` + +Test machine logic without React wherever you can. A transition, a guard or a retry policy is faster and clearer to test against a bare actor. See [test XState logic](../testing.md). Reserve component tests for what only React can break: rendering, events, and effects tied to mount and unmount. + +## Replacing implementations + +`machine.provide({ ... })` returns new logic with implementations swapped, leaving the machine's structure alone. Use it to stand in for network calls, timers and analytics. + +```tsx +import { createAsyncLogic } from 'xstate'; + +const testMachine = checkoutMachine.provide({ + actors: { + authorize: createAsyncLogic({ run: async () => ({ status: 'approved' }) }) + } +}); + +render(); +``` + +Accept the logic as a prop, or render it through a provider. Do not reach into a running actor from a test. + +```tsx +await screen.findByText('Payment approved'); +``` + +For a failure path, provide logic that throws. Guards and actions swap the same way, which is how you test a branch without constructing the state that would reach it naturally. + +```tsx +playerMachine.provide({ + guards: { hasSubscription: () => false }, + actions: { track: analyticsSpy } +}); +``` + +## Testing a `createActorContext` consumer + +Components that use `Ctx.useSelector` or `Ctx.useActorRef` must render inside the provider, or the hook throws. Wrap them in the test, and use the `logic` prop to inject test logic. + +```tsx +function renderWithProvider(ui: React.ReactNode, logic = checkoutMachine) { + return render( + {ui} + ); +} + +test('shows the cart total', () => { + renderWithProvider(, testMachine); + + expect(screen.getByTestId('total').textContent).toBe('42'); +}); +``` + +Use `options` to start the provider's actor at a specific point instead of clicking through the flow. + +```tsx +const actor = createActor(checkoutMachine).start(); +actor.send({ type: 'next' }); +const persisted = actor.getPersistedSnapshot(); + +render( + + + +); +``` + +`options={{ input }}` does the same for logic whose starting state is derived from input. + +## Time + +Delays and [timeouts](../timeouts.md) go through the actor's clock. Fake timers are the simplest way to control them, because they also cover timers React itself uses. Advance them inside `act(...)` so React flushes the resulting renders. + +```tsx +import { act } from '@testing-library/react'; + +beforeEach(() => vi.useFakeTimers()); +afterEach(() => vi.useRealTimers()); + +test('retries after the backoff', () => { + render(); + + act(() => { + vi.advanceTimersByTime(310); + }); + + expect(screen.getByText('Retrying')).toBeTruthy(); +}); +``` + +`SimulatedClock` is the alternative when only one actor's time should move. Pass it as the `clock` [actor option](../create-actor.md#actor-options) and call `clock.increment(ms)` inside `act(...)`. + +```tsx +const clock = new SimulatedClock(); + +render(); +act(() => clock.increment(5_000)); +``` + +## Async and StrictMode + +Anything that sends events from outside React (a resolved promise, a subscription, a direct `actor.send(...)`) must be wrapped in `act(...)` so React can flush. For work that settles on its own, prefer `findBy*` queries, which retry until the element appears. + +```tsx +act(() => actorRef.send({ type: 'increment' })); + +expect(await screen.findByText('Upload complete')).toBeTruthy(); +``` + +Run component tests under `React.StrictMode` as well as without it. StrictMode double-mounts, which surfaces actors that do not survive a stop and restart, and effects that assume they run once. + +> **Warning:** Errors from an `error` snapshot are thrown during render by `useActor` and `useSelector`. Wrap the component in an error boundary in the test, or the failure surfaces as an unhandled render error instead of the assertion you wrote. + +## Testing cheatsheet + +```tsx +render(); +render({ui}); +render({ui}); + +machine.provide({ actors, guards, actions, delays }); + +fireEvent.click(screen.getByTestId('submit')); +await screen.findByText('Done'); +act(() => vi.advanceTimersByTime(1_000)); +act(() => actorRef.send({ type: 'next' })); +``` diff --git a/xstate-react/docs/use-machine.md b/xstate-react/docs/use-machine.md new file mode 100644 index 00000000..fd7a8a7e --- /dev/null +++ b/xstate-react/docs/use-machine.md @@ -0,0 +1,140 @@ +--- +title: Use a machine in React +description: Run XState actor logic in a React component. +--- + +Install XState and the React package. + +```bash +npm install xstate@alpha @xstate/react@alpha +``` + +`useActor(logic, options?)` creates an actor for the component, starts it, and re-renders when it produces a new snapshot. + +```tsx +import { useActor } from '@xstate/react'; +import { createMachine } from 'xstate'; + +const playerMachine = createMachine({ + initial: 'paused', + states: { + paused: { on: { play: { target: 'playing' } } }, + playing: { on: { pause: { target: 'paused' } } } + } +}); + +export function Player() { + const [snapshot, send] = useActor(playerMachine); + + return ( + + ); +} +``` + +The returned tuple is `[snapshot, send, actorRef]`. The third member is the full [actor](../create-actor.md), useful for `actorRef.trigger`, `actorRef.on(...)` and passing a reference to children. + +```tsx +const [snapshot, send, actorRef] = useActor(playerMachine); + +; +``` + +`actorRef.trigger` is typed from the machine's `schemas.events`. See [TypeScript](../typescript.md). + +## Options + +The second argument accepts the same [actor options](../create-actor.md#actor-options) as `createActor(...)`: `input`, `snapshot`, `id`, `inspect`, `clock`, `logger` and `registryKey`. It is required when the logic requires input. + +```tsx +const [snapshot, send] = useActor(uploadMachine, { + input: { fileId }, + inspect: (event) => console.log(event) +}); +``` + +Options are read when the actor is created. Changing `input` on a later render does not restart the actor — see [input and snapshots](input-and-snapshots.md). + +## Re-render semantics + +`useActor` subscribes with `useSyncExternalStore`, so the component re-renders whenever the actor produces a new snapshot object. An event that takes no transition produces the same snapshot reference, and React bails out of the render. + +That still means every state or context change re-renders the component. When a component only needs one value from a long-lived actor, use `useActorRef(...)` with [`useSelector(...)`](selectors.md) instead. + +```tsx +const actorRef = useActorRef(playerMachine); +const isPlaying = useSelector(actorRef, (s) => s.matches('playing')); +``` + +`useActorRef(logic, options?, observerOrListener?)` creates and starts an actor without subscribing to it, so it never re-renders on its own. The optional third argument is a snapshot listener function or an [observer object](../create-actor.md#subscribing), subscribed for as long as it is provided. Memoize it with `useCallback`; a new function identity re-subscribes. + +```tsx +const onSnapshot = useCallback( + (snapshot) => { + if (snapshot.status === 'done') navigate('/receipt'); + }, + [navigate] +); + +const actorRef = useActorRef(checkoutMachine, undefined, onSnapshot); +``` + +If the actor reaches an `error` snapshot, `useActor` throws the error during render, so an error boundary can catch it. `useActorRef` does not. + +> **Warning:** `useActor` takes actor *logic*, not an actor reference. Passing an existing `actorRef` throws in development. Read from an existing actor with [`useSelector`](selectors.md). + +## Actor lifecycle + +One actor is created per component instance. It starts in an effect after mount and is stopped on unmount. + +React StrictMode disconnects and immediately reconnects effects in development. `useActor` and `useActorRef` defer cleanup by one microtask, so that immediate reconnect cancels the pending stop and preserves the actor and its children. A real unmount still stops the actor. If an actor was stopped externally before an effect reconnects, the hooks create a fresh actor from the same logic and options; an actor that completed naturally (`done` or `error`) is left alone. + +The logic passed on the first render is used for the component's lifetime, like a `useState` initializer. Passing a different machine on a later render does not replace the actor, so a machine created in the component body needs no `useMemo`. Implementations swapped with `machine.provide({ ... })` in the component body keep the same config and update the running actor in place, so a guard or action defined in render always sees the latest props. To vary a running actor, pass `input` or send an event. To switch to a different machine, remount the component with a `key`: + +```tsx + +``` + +### Hot reloading + +In development builds, when React Fast Refresh re-renders a component after the machine's module was edited, the hooks keep the running actor and switch it to the edited machine. The current state and context carry over in memory, without serializing, so context that holds DOM elements or cyclic objects is kept. If an active state gained child states, their initial states become active. Invoked and spawned actors whose logic did not change keep running; the others restart. + +The hooks start a fresh actor from the edited machine instead when: + +- the current state no longer exists in it, or its `id` changed +- a remembered history state no longer exists in it +- an invoked actor's `src` is a function, or names an actor it does not provide +- context or a pending delayed event refers to an actor that would restart +- its configured validator rejects the current context + +Production builds never switch machines. + +`useMachine(...)` is a deprecated alias for `useActor(machine, options)`. It accepts state machines only. Use `useActor(...)`. + +## TypeScript + +Snapshot, event and actor reference types are inferred from the actor logic. `options` becomes a required argument when the logic requires input. + +```tsx +import type { SnapshotFrom } from 'xstate'; + +const [snapshot, send] = useActor(playerMachine); +snapshot.context; // typed +send({ type: 'play' }); // typed + +type PlayerSnapshot = SnapshotFrom; +``` + +## React hooks cheatsheet + +```tsx +const [snapshot, send, actorRef] = useActor(logic, options); +const actorRef = useActorRef(logic, options, observerOrListener); +const value = useSelector(actorRef, (snapshot) => snapshot.context.value); + +send({ type: 'play' }); +actorRef.trigger.play(); +actorRef.on('played', (event) => analytics.track(event)); +``` diff --git a/xstate-react/package.json b/xstate-react/package.json new file mode 100644 index 00000000..08e47b35 --- /dev/null +++ b/xstate-react/package.json @@ -0,0 +1,80 @@ +{ + "name": "@xstate/react", + "version": "7.0.0-alpha.4", + "description": "XState tools for React", + "keywords": [ + "state", + "machine", + "statechart", + "scxml", + "state", + "graph", + "react", + "hook" + ], + "author": "David Khourshid ", + "homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-react#readme", + "license": "MIT", + "main": "dist/xstate-react.cjs.js", + "module": "dist/xstate-react.esm.js", + "exports": { + ".": { + "types": { + "import": "./dist/xstate-react.cjs.mjs", + "default": "./dist/xstate-react.cjs.js" + }, + "development": { + "module": "./dist/xstate-react.development.esm.js", + "import": "./dist/xstate-react.development.cjs.mjs", + "default": "./dist/xstate-react.development.cjs.js" + }, + "module": "./dist/xstate-react.esm.js", + "import": "./dist/xstate-react.cjs.mjs", + "default": "./dist/xstate-react.cjs.js" + }, + "./package.json": "./package.json" + }, + "imports": { + "#is-development": { + "development": "./src/true.ts", + "default": "./src/false.ts" + } + }, + "types": "dist/xstate-react.cjs.d.ts", + "sideEffects": false, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/statelyai/xstate.git" + }, + "scripts": {}, + "bugs": { + "url": "https://github.com/statelyai/xstate/issues" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", + "xstate": "workspace:^" + }, + "peerDependenciesMeta": { + "xstate": { + "optional": true + } + }, + "dependencies": { + "use-isomorphic-layout-effect": "^1.1.2", + "use-sync-external-store": "^1.2.0" + }, + "devDependencies": { + "@testing-library/react": "^16.2.0", + "@types/react": "^19.0.10", + "@types/react-dom": "^19.0.4", + "@types/use-sync-external-store": "^0.0.3", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "rxjs": "^7.8.1", + "xstate": "workspace:^", + "zod": "^3.25.51" + } +} diff --git a/xstate-react/src/createActorContext.ts b/xstate-react/src/createActorContext.ts new file mode 100644 index 00000000..e5e8a02b --- /dev/null +++ b/xstate-react/src/createActorContext.ts @@ -0,0 +1,84 @@ +import * as React from 'react'; +import { Actor, ActorOptions, AnyActorLogic, SnapshotFrom } from 'xstate'; +import { useActorRef } from './useActorRef'; +import { useSelector as useSelectorUnbound } from './useSelector'; + +export function createActorContext( + actorLogic: TLogic, + actorOptions?: ActorOptions +): { + useSelector: ( + selector: (snapshot: SnapshotFrom) => T, + compare?: (a: T, b: T) => boolean + ) => T; + useActorRef: () => Actor; + Provider: (props: { + children: React.ReactNode; + options?: ActorOptions; + /** @deprecated Use `logic` instead. */ + machine?: never; + logic?: TLogic; + }) => React.ReactElement; +} { + const ReactContext = React.createContext | null>(null); + + const OriginalProvider = ReactContext.Provider; + + function Provider({ + children, + logic: providedLogic = actorLogic, + machine, + options: providedOptions + }: { + children: React.ReactNode; + logic: TLogic; + /** @deprecated Use `logic` instead. */ + machine?: never; + options?: ActorOptions; + }) { + if (machine) { + throw new Error( + `The "machine" prop has been deprecated. Please use "logic" instead.` + ); + } + + const actor = useActorRef(providedLogic, { + ...actorOptions, + ...providedOptions + }); + + return React.createElement(OriginalProvider, { + value: actor, + children + }); + } + + // TODO: add properties to actor ref to make more descriptive + Provider.displayName = `ActorProvider`; + + function useContext(): Actor { + const actor = React.useContext(ReactContext); + + if (!actor) { + throw new Error( + `You used a hook from "${Provider.displayName}" but it's not inside a <${Provider.displayName}> component.` + ); + } + + return actor; + } + + function useSelector( + selector: (snapshot: SnapshotFrom) => T, + compare?: (a: T, b: T) => boolean + ): T { + const actor = useContext(); + return useSelectorUnbound(actor, selector, compare); + } + + return { + Provider: Provider as any, + useActorRef: useContext, + useSelector + }; +} diff --git a/xstate-react/src/false.ts b/xstate-react/src/false.ts new file mode 100644 index 00000000..33136544 --- /dev/null +++ b/xstate-react/src/false.ts @@ -0,0 +1 @@ +export default false; diff --git a/xstate-react/src/index.ts b/xstate-react/src/index.ts new file mode 100644 index 00000000..2e8df985 --- /dev/null +++ b/xstate-react/src/index.ts @@ -0,0 +1,8 @@ +export { createActorContext } from './createActorContext.ts'; +export { shallowEqual } from './shallowEqual.ts'; +export { useActor } from './useActor.ts'; +export { useActorRef } from './useActorRef.ts'; +export { useSelector } from './useSelector.ts'; + +// deprecated +export { useMachine } from './useMachine.ts'; diff --git a/xstate-react/src/shallowEqual.ts b/xstate-react/src/shallowEqual.ts new file mode 100644 index 00000000..1eedb165 --- /dev/null +++ b/xstate-react/src/shallowEqual.ts @@ -0,0 +1,37 @@ +// From https://github.com/reduxjs/react-redux/blob/720f0ba79236cdc3e1115f4ef9a7760a21784b48/src/utils/shallowEqual.ts +function is(x: unknown, y: unknown) { + if (x === y) { + return x !== 0 || y !== 0 || 1 / x === 1 / y; + } else { + return x !== x && y !== y; + } +} + +export function shallowEqual(objA: any, objB: any) { + if (is(objA, objB)) return true; + + if ( + typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null + ) { + return false; + } + + const keysA = Object.keys(objA); + const keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) return false; + + for (let i = 0; i < keysA.length; i++) { + if ( + !Object.prototype.hasOwnProperty.call(objB, keysA[i]) || + !is(objA[keysA[i]], objB[keysA[i]]) + ) { + return false; + } + } + + return true; +} diff --git a/xstate-react/src/true.ts b/xstate-react/src/true.ts new file mode 100644 index 00000000..ff3177ba --- /dev/null +++ b/xstate-react/src/true.ts @@ -0,0 +1 @@ +export default true; diff --git a/xstate-react/src/useActor.ts b/xstate-react/src/useActor.ts new file mode 100644 index 00000000..c8de6d25 --- /dev/null +++ b/xstate-react/src/useActor.ts @@ -0,0 +1,72 @@ +import isDevelopment from '#is-development'; +import { useCallback } from 'react'; +import { useSyncExternalStore } from 'use-sync-external-store/shim'; +import { + Actor, + ActorOptions, + AnyActorLogic, + Snapshot, + SnapshotFrom, + createActor, + type ConditionalRequired, + type IsNotNever, + type RequiredActorOptionsKeys, + type RequiredActorOptionsFor +} from 'xstate'; +import { useActorLifecycle, useIdleActorRef } from './useActorRef.ts'; + +export function useActor( + logic: TLogic, + ...[options]: ConditionalRequired< + [options?: ActorOptions & RequiredActorOptionsFor], + IsNotNever> + > +): [SnapshotFrom, Actor['send'], Actor] { + if ( + isDevelopment && + !!logic && + 'send' in logic && + typeof logic.send === 'function' + ) { + throw new Error( + `useActor() expects actor logic (e.g. a machine), but received an ActorRef. Use the useSelector(actorRef, ...) hook instead to read the ActorRef's snapshot.` + ); + } + + const [actorRef, setActorRef] = useIdleActorRef(logic, options); + + const getSnapshot = useCallback(() => { + return actorRef.getSnapshot(); + }, [actorRef]); + + const subscribe = useCallback( + (handleStoreChange: () => void) => { + const { unsubscribe } = actorRef.subscribe({ + next: handleStoreChange, + error: handleStoreChange + }); + return unsubscribe; + }, + [actorRef] + ); + + const actorSnapshot = useSyncExternalStore( + subscribe, + getSnapshot, + getSnapshot + ); + + const snapshotWithStatus = + 'status' in actorSnapshot + ? (actorSnapshot as Snapshot) + : undefined; + if (snapshotWithStatus?.status === 'error') { + throw snapshotWithStatus.error; + } + + useActorLifecycle(actorRef, setActorRef, () => + createActor(actorRef.logic, options as ActorOptions) + ); + + return [actorSnapshot, actorRef.send, actorRef]; +} diff --git a/xstate-react/src/useActorRef.ts b/xstate-react/src/useActorRef.ts new file mode 100644 index 00000000..96653f78 --- /dev/null +++ b/xstate-react/src/useActorRef.ts @@ -0,0 +1,144 @@ +import isDevelopment from '#is-development'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import useIsomorphicLayoutEffect from 'use-isomorphic-layout-effect'; +import { + Actor, + ActorOptions, + AnyActorLogic, + AnyStateMachine, + Observer, + SnapshotFrom, + _hotSwapActorLogic as hotSwapActorLogic, + createActor, + toObserver, + type ConditionalRequired, + type IsNotNever, + type RequiredActorOptionsKeys, + type RequiredActorOptionsFor +} from 'xstate'; +export function useIdleActorRef( + logic: TLogic, + ...[options]: ConditionalRequired< + [options?: ActorOptions & RequiredActorOptionsFor], + IsNotNever> + > +): [Actor, (actorRef: Actor) => void] { + const [actorRef, setActorRef] = useState(() => { + return createActor(logic, options as ActorOptions); + }); + // An object whose identity changes only when React Fast Refresh re-renders + // this component. Fast Refresh ignores dependency lists while it applies an + // update, so a `useMemo` with no dependencies recomputes during a refresh + // and at no other time. + const refreshSignal = useMemo(() => ({}), []); + const refreshSignalRef = useRef(refreshSignal); + + // The logic passed on the first render is used for the hook's lifetime. + // Later renders only contribute implementations provided with + // `machine.provide()` for the same machine config. + // TODO: consider using `useAsapEffect` that would do this in `useInsertionEffect` is that's available + useIsomorphicLayoutEffect(() => { + const currentLogic = actorRef.logic as any as AnyStateMachine; + const refreshed = refreshSignalRef.current !== refreshSignal; + refreshSignalRef.current = refreshSignal; + + if (logic.config === currentLogic.config) { + currentLogic.sources = (logic as any as AnyStateMachine).sources; + return; + } + + // Development hot reloading: Fast Refresh re-evaluated the module that + // defines the machine. Keep the running actor and carry its live snapshot + // over to the new machine; start a fresh actor if it cannot be carried. + if (isDevelopment && refreshed) { + if (!hotSwapActorLogic(actorRef, logic as any as AnyStateMachine)) { + setActorRef(createActor(logic, options as ActorOptions)); + } + } + }); + + return [actorRef, setActorRef]; +} + +export function useActorLifecycle( + actorRef: Actor, + setActorRef: (actorRef: Actor) => void, + createReplacement: () => Actor +): void { + const pendingStopsRef = useRef(new Map, () => void>()); + + useEffect(() => { + const cancelPendingStop = pendingStopsRef.current.get(actorRef); + if (cancelPendingStop) { + cancelPendingStop(); + pendingStopsRef.current.delete(actorRef); + } + + // If the actor was stopped before this effect reconnected, create a fresh + // actor. A stopped actor cannot be restarted. + if ( + (actorRef as any)._processingStatus === + 2 /* ProcessingStatus.Stopped */ && + (actorRef.getSnapshot() as any)?.status === 'stopped' + ) { + const newActor = createReplacement(); + setActorRef(newActor); + return; + } + + actorRef.start(); + return () => { + let canceled = false; + const cancel = () => { + canceled = true; + }; + pendingStopsRef.current.set(actorRef, cancel); + + queueMicrotask(() => { + if (!canceled) { + actorRef.stop(); + } + if (pendingStopsRef.current.get(actorRef) === cancel) { + pendingStopsRef.current.delete(actorRef); + } + }); + }; + }, [actorRef]); +} + +export function useActorRef( + machine: TLogic, + ...[options, observerOrListener]: IsNotNever< + RequiredActorOptionsKeys + > extends true + ? [ + options: ActorOptions & RequiredActorOptionsFor, + observerOrListener?: + | Observer> + | ((value: SnapshotFrom) => void) + ] + : [ + options?: ActorOptions, + observerOrListener?: + | Observer> + | ((value: SnapshotFrom) => void) + ] +): Actor { + const [actorRef, setActorRef] = useIdleActorRef(machine, options); + + useEffect(() => { + if (!observerOrListener) { + return; + } + const sub = actorRef.subscribe(toObserver(observerOrListener)); + return () => { + sub.unsubscribe(); + }; + }, [actorRef, observerOrListener]); + + useActorLifecycle(actorRef, setActorRef, () => + createActor(actorRef.logic, actorRef.options) + ); + + return actorRef; +} diff --git a/xstate-react/src/useMachine.ts b/xstate-react/src/useMachine.ts new file mode 100644 index 00000000..a0ac8975 --- /dev/null +++ b/xstate-react/src/useMachine.ts @@ -0,0 +1,22 @@ +import { + Actor, + ActorOptions, + AnyStateMachine, + StateFrom, + type ConditionalRequired, + type IsNotNever, + type RequiredActorOptionsKeys, + type RequiredActorOptionsFor +} from 'xstate'; +import { useActor } from './useActor.ts'; + +/** @alias useActor */ +export function useMachine( + machine: TMachine, + ...[options]: ConditionalRequired< + [options?: ActorOptions & RequiredActorOptionsFor], + IsNotNever> + > +): [StateFrom, Actor['send'], Actor] { + return useActor(machine, options); +} diff --git a/xstate-react/src/useSelector.ts b/xstate-react/src/useSelector.ts new file mode 100644 index 00000000..1d5fb196 --- /dev/null +++ b/xstate-react/src/useSelector.ts @@ -0,0 +1,56 @@ +import { useCallback } from 'react'; +import { useSyncExternalStoreWithSelector } from 'use-sync-external-store/shim/with-selector'; +import { AnyActorRef } from 'xstate'; + +type SyncExternalStoreSubscribe = Parameters< + typeof useSyncExternalStoreWithSelector +>[0]; + +function defaultCompare(a: T, b: T) { + return a === b; +} + +export function useSelector< + TActor extends Pick | undefined, + T +>( + actor: TActor, + selector: ( + snapshot: TActor extends { getSnapshot(): infer TSnapshot } + ? TSnapshot + : undefined + ) => T, + compare: (a: T, b: T) => boolean = defaultCompare +): T { + const subscribe: SyncExternalStoreSubscribe = useCallback( + (handleStoreChange) => { + if (!actor) { + return () => {}; + } + const { unsubscribe } = actor.subscribe({ + next: handleStoreChange, + error: handleStoreChange + }); + return unsubscribe; + }, + [actor] + ); + + const boundGetSnapshot = useCallback(() => { + const snapshot = actor?.getSnapshot(); + if (snapshot && 'status' in snapshot && snapshot.status === 'error') { + throw snapshot.error; + } + return snapshot; + }, [actor]); + + const selectedSnapshot = useSyncExternalStoreWithSelector( + subscribe, + boundGetSnapshot, + boundGetSnapshot, + selector, + compare + ); + + return selectedSnapshot; +} diff --git a/xstate-react/test/createActorContext.test.tsx b/xstate-react/test/createActorContext.test.tsx new file mode 100644 index 00000000..850643b3 --- /dev/null +++ b/xstate-react/test/createActorContext.test.tsx @@ -0,0 +1,545 @@ +import { + createMachine, + createAsyncLogic, + Snapshot, + InspectionEvent +} from 'xstate'; +import { fireEvent, screen, render, waitFor } from '@testing-library/react'; +import { useSelector, createActorContext, shallowEqual } from '../src'; +import { z } from 'zod'; + +describe('createActorContext', () => { + it('should work with useSelector', () => { + const someMachine = createMachine({ + initial: 'a', + states: { a: {} } + }); + + const SomeContext = createActorContext(someMachine); + + const Component = () => { + const value = SomeContext.useSelector((state) => state.value as string); + + return
{value}
; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('a'); + }); + + it('the actor should be able to receive events', () => { + const someMachine = createMachine({ + initial: 'a', + states: { + a: { + on: { + NEXT: { target: 'b' } + } + }, + b: {} + } + }); + + const SomeContext = createActorContext(someMachine); + + const Component = () => { + const actorRef = SomeContext.useActorRef(); + const state = SomeContext.useSelector((s) => s); + + return ( + <> +
{state.value as string}
+ + + ); + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('a'); + + fireEvent.click(screen.getByTestId('next')); + + expect(screen.getByTestId('value').textContent).toBe('b'); + }); + + it('should work with useSelector and a custom comparator', async () => { + const someMachine = createMachine({ + schemas: { + context: z.object({ + obj: z.object({ + counter: z.number() + }), + arr: z.array(z.string()) + }) + }, + context: { + obj: { + counter: 0 + }, + arr: [] as string[] + }, + on: { + // INC: { + // actions: assign(({ context }) => ({ + // obj: { + // counter: context.obj.counter + 1 + // } + // })) + // }, + INC: ({ context }) => ({ + context: { + obj: { + counter: context.obj.counter + 1 + } + } + }), + PUSH: ({ context }) => ({ + context: { + arr: [...context.arr, Math.random().toString(36).slice(2)] + } + }) + } + }); + + const SomeContext = createActorContext(someMachine); + + let rerenders = 0; + + const Component = () => { + const actor = SomeContext.useActorRef(); + const value = SomeContext.useSelector( + (state) => state.context.obj, + shallowEqual + ); + + rerenders += 1; + + return ( + <> + + +
{value.counter}
; + + ); + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('0'); + expect(rerenders).toBe(1); + + fireEvent.click(screen.getByText('Inc')); + + expect(screen.getByTestId('value').textContent).toBe('1'); + expect(rerenders).toBe(2); + + fireEvent.click(screen.getByText('Push')); + + expect(rerenders).toBe(2); + + fireEvent.click(screen.getByText('Inc')); + + expect(screen.getByTestId('value').textContent).toBe('2'); + expect(rerenders).toBe(3); + }); + + it('should work with useActorRef', () => { + const someMachine = createMachine({ + initial: 'a', + states: { a: {} } + }); + + const SomeContext = createActorContext(someMachine); + + const Component = () => { + const actor = SomeContext.useActorRef(); + const value = useSelector(actor, (state) => state.value); + + return
{value as string}
; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('a'); + }); + + it('should work with a provided machine', () => { + const createSomeMachine = (context: { count: number }) => + createMachine({ + schemas: { + context: z.object({ + count: z.number() + }) + }, + context + }); + + const SomeContext = createActorContext(createSomeMachine({ count: 0 })); + + const Component = () => { + const actor = SomeContext.useActorRef(); + const count = useSelector(actor, (state) => state.context.count); + + return
{count}
; + }; + + const otherMachine = createSomeMachine({ count: 42 }); + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('42'); + }); + + it('useActorRef should throw when the actor was not provided', () => { + const SomeContext = createActorContext(createMachine({})); + + const App = () => { + SomeContext.useActorRef(); + return null; + }; + + expect(() => render()).toThrowErrorMatchingInlineSnapshot( + `[Error: You used a hook from "ActorProvider" but it's not inside a component.]` + ); + }); + + it('useSelector should throw when the actor was not provided', () => { + const SomeContext = createActorContext(createMachine({})); + + const App = () => { + SomeContext.useSelector((a) => a); + return null; + }; + + expect(() => render()).toThrowErrorMatchingInlineSnapshot( + `[Error: You used a hook from "ActorProvider" but it's not inside a component.]` + ); + }); + + it('should be able to pass interpreter options to the provider', () => { + const someMachine = createMachine({ + initial: 'a', + actions: { + testAction: () => {} + }, + states: { + a: { + // entry: ['testAction'] + entry: ({ actions }, enq) => { + enq(actions.testAction); + } + } + } + }); + const stubFn = vi.fn(); + const SomeContext = createActorContext(someMachine); + + const Component = () => { + return null; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(stubFn).toHaveBeenCalledTimes(1); + }); + + it('should work with other types of logic', async () => { + const PromiseContext = createActorContext( + createAsyncLogic({ run: () => Promise.resolve(42) }) + ); + + const Component = () => { + const value = PromiseContext.useSelector((data) => data); + + return
{value.output}
; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + await waitFor(() => { + expect(screen.getByTestId('value').textContent).toBe('42'); + }); + }); + + it("should preserve machine's identity when swapping options using in-render `.provide`", () => { + const someMachine = createMachine({ + schemas: { + context: z.object({ + count: z.number() + }) + }, + context: { count: 0 }, + on: { + // inc: { + // actions: assign({ count: ({ context }) => context.count + 1 }) + // } + inc: ({ context }) => ({ + context: { + count: context.count + 1 + } + }) + } + }); + const stubFn = vi.fn(); + const SomeContext = createActorContext(someMachine); + + const Component = () => { + const { send } = SomeContext.useActorRef(); + const count = SomeContext.useSelector((state) => state.context.count); + return ( + <> + {count} + + + ); + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('count').textContent).toBe('0'); + fireEvent.click(screen.getByTestId('button')); + + expect(screen.getByTestId('count').textContent).toBe('1'); + + fireEvent.click(screen.getByTestId('button')); + + expect(screen.getByTestId('count').textContent).toBe('2'); + }); + + it('options can be passed to the provider', () => { + const machine = createMachine({ + initial: 'a', + states: { + a: { + on: { + next: { target: 'b' } + } + }, + b: {} + } + }); + const SomeContext = createActorContext(machine); + let persistedState: Snapshot | undefined = undefined; + + const Component = () => { + const actorRef = SomeContext.useActorRef(); + const state = SomeContext.useSelector((state) => state); + + persistedState = actorRef.getPersistedSnapshot(); + + return ( +
{ + actorRef.send({ type: 'next' }); + }} + > + {state.value as string} +
+ ); + }; + + const App = () => { + return ( + + + + ); + }; + + const { unmount } = render(); + + expect(screen.getByTestId('value').textContent).toBe('a'); + + fireEvent.click(screen.getByTestId('value')); + + // Ensure that the state machine without restored state functions as normal + expect(screen.getByTestId('value').textContent).toBe('b'); + + // unrender app + unmount(); + + // At this point, `state` should be `{ value: 'b' }` + + // re-render app + render(); + + // Ensure that the state machine is restored to the persisted state + expect(screen.getByTestId('value').textContent).toBe('b'); + }); + + it('input can be passed to the provider', () => { + const SomeContext = createActorContext( + createMachine({ + // types: {} as { + // context: { doubled: number }; + // }, + schemas: { + context: z.object({ + doubled: z.number() + }), + input: z.number() + }, + context: ({ input }) => ({ + doubled: input * 2 + }) + }) + ); + + const Component = () => { + const doubled = SomeContext.useSelector((state) => state.context.doubled); + + return
{doubled}
; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(screen.getByTestId('value').textContent).toBe('84'); + }); + + it('should merge createActorContext options with options passed to the provider', () => { + const events: InspectionEvent[] = []; + const SomeContext = createActorContext( + createMachine({ + // types: { + // context: {} as { count: number }, + // input: {} as number + // }, + schemas: { + context: z.object({ + count: z.number() + }), + input: z.number() + }, + context: ({ input }) => ({ count: input }) + }), + { + inspect: (ev) => { + events.push(ev); + } + } + ); + + const Component = () => { + const count = SomeContext.useSelector((state) => state.context.count); + + return
{count}
; + }; + + const App = () => { + return ( + + + + ); + }; + + render(); + + expect(events.length).toBeGreaterThan(0); + expect(events).toContainEqual( + expect.objectContaining({ + snapshot: expect.objectContaining({ + context: { count: 10 } + }) + }) + ); + }); +}); diff --git a/xstate-react/test/fastRefresh.production.test.tsx b/xstate-react/test/fastRefresh.production.test.tsx new file mode 100644 index 00000000..a9d4a457 --- /dev/null +++ b/xstate-react/test/fastRefresh.production.test.tsx @@ -0,0 +1,47 @@ +import { act, render } from '@testing-library/react'; +import * as React from 'react'; +import { createMachine } from 'xstate'; +import { useActorRef } from '../src/index.ts'; + +const refresh = vi.hoisted(() => ({ signal: {} as object })); +// `useActorRef` detects a refresh through its only zero-dependency `useMemo`. +vi.mock('react', async (importOriginal) => { + const React = await importOriginal(); + return { + ...React, + useMemo: (factory: () => unknown, deps: unknown[]) => + deps.length === 0 ? refresh.signal : React.useMemo(factory, deps) + }; +}); +vi.mock('#is-development', () => ({ default: false })); + +const createToggle = (extra: Record = {}) => + createMachine({ + id: 'toggle', + initial: 'off', + states: { + off: { on: { TOGGLE: { target: 'on' } } }, + on: { on: { ...extra } }, + ...(extra.RESET ? { reset: {} } : {}) + } + } as any); + +it('keeps the first machine on a refresh signal in production builds', () => { + const v1 = createToggle(); + let actorRef!: any; + const App = ({ machine }: { machine: any }) => { + actorRef = useActorRef(machine); + return null; + }; + const { rerender } = render(); + const original = actorRef; + act(() => original.send({ type: 'TOGGLE' })); + + refresh.signal = {}; + rerender(); + + expect(actorRef).toBe(original); + expect(actorRef.logic).toBe(v1); + act(() => actorRef.send({ type: 'RESET' })); + expect(actorRef.getSnapshot().value).toBe('on'); +}); diff --git a/xstate-react/test/fastRefresh.test.tsx b/xstate-react/test/fastRefresh.test.tsx new file mode 100644 index 00000000..5cc85cc5 --- /dev/null +++ b/xstate-react/test/fastRefresh.test.tsx @@ -0,0 +1,285 @@ +import { act, render } from '@testing-library/react'; +import * as React from 'react'; +import { createLogic, createMachine, setup } from 'xstate'; +import { standardSchemaValidator } from 'xstate/validation'; +import { z } from 'zod'; +import { useActorRef } from '../src/index.ts'; + +// Stands in for React Fast Refresh: replacing `refresh.signal` makes the next +// render look like a refresh re-render. +const refresh = vi.hoisted(() => ({ signal: {} as object })); +// `useActorRef` detects a refresh through its only zero-dependency `useMemo`. +vi.mock('react', async (importOriginal) => { + const React = await importOriginal(); + return { + ...React, + useMemo: (factory: () => unknown, deps: unknown[]) => + deps.length === 0 ? refresh.signal : React.useMemo(factory, deps) + }; +}); + +function simulateRefresh() { + refresh.signal = {}; +} + +function mount(machine: any) { + let actorRef!: any; + const App = ({ machine }: { machine: any }) => { + actorRef = useActorRef(machine); + return null; + }; + const utils = render(); + return { + get actorRef() { + return actorRef; + }, + refreshTo(next: any) { + simulateRefresh(); + act(() => { + utils.rerender(); + }); + } + }; +} + +const createEditor = (extra: Record = {}) => + createMachine({ + id: 'editor', + context: () => { + const cyclic: Record = {}; + cyclic.self = cyclic; + return { el: document.createElement('div'), cyclic }; + }, + initial: 'idle', + states: { + idle: { on: { NEXT: { target: 'editing' } } }, + editing: { on: { ...extra } }, + ...(extra.DONE ? { done: {} } : {}) + } + } as any); + +describe('Fast Refresh', () => { + it('keeps the running actor and its live context across a refresh', () => { + const v1 = createEditor(); + const app = mount(v1); + const original = app.actorRef; + act(() => original.send({ type: 'NEXT' })); + const { el, cyclic } = original.getSnapshot().context; + + const v2 = createEditor({ DONE: { target: 'done' } }); + expect(() => app.refreshTo(v2)).not.toThrow(); + + expect(app.actorRef).toBe(original); + expect(app.actorRef.logic).toBe(v2); + const snapshot = app.actorRef.getSnapshot(); + expect(snapshot.value).toBe('editing'); + expect(snapshot.context.el).toBe(el); + expect(snapshot.context.cyclic).toBe(cyclic); + + // The new machine's transitions apply. + act(() => app.actorRef.send({ type: 'DONE' })); + expect(app.actorRef.getSnapshot().value).toBe('done'); + }); + + it('starts a fresh actor when the current state no longer exists', () => { + const v1 = createEditor(); + const app = mount(v1); + const original = app.actorRef; + act(() => original.send({ type: 'NEXT' })); + + const v2 = createMachine({ + id: 'editor', + initial: 'idle', + states: { idle: {} } + }); + app.refreshTo(v2); + + expect(app.actorRef).not.toBe(original); + expect(app.actorRef.logic).toBe(v2); + expect(app.actorRef.getSnapshot().value).toBe('idle'); + }); + + it('starts a fresh actor when the context validator rejects the context', () => { + const v1 = createEditor(); + const app = mount(v1); + const original = app.actorRef; + act(() => original.send({ type: 'NEXT' })); + + const v2 = setup({ + validator: standardSchemaValidator(), + schemas: { context: z.object({ count: z.number() }) } + }).createMachine({ + id: 'editor', + context: { count: 0 }, + initial: 'idle', + states: { + idle: { on: { NEXT: { target: 'editing' } } }, + editing: {} + } + }); + app.refreshTo(v2); + + expect(app.actorRef).not.toBe(original); + expect(app.actorRef.getSnapshot().value).toBe('idle'); + expect(app.actorRef.getSnapshot().context).toEqual({ count: 0 }); + }); + + it('keeps children whose logic is unchanged and restarts the others', () => { + const stable = createLogic({ context: 0, run: () => undefined }); + const createParent = (other: any) => + createMachine({ + id: 'parent', + actors: { stable, other }, + invoke: [ + { id: 'stable', src: 'stable' }, + { id: 'other', src: 'other' } + ] + }); + + const app = mount( + createParent(createLogic({ context: 0, run: () => undefined })) + ); + const before = app.actorRef.getSnapshot().children; + + app.refreshTo( + createParent(createLogic({ context: 0, run: () => undefined })) + ); + + const after = app.actorRef.getSnapshot().children; + expect(after.stable).toBe(before.stable); + expect(after.other).not.toBe(before.other); + expect(after.other.getSnapshot().status).toBe('active'); + expect(before.other.getSnapshot().status).toBe('stopped'); + }); + + it('starts a fresh actor when context holds a child that would restart', () => { + const createParent = (worker: any) => + createMachine({ + id: 'parent', + actors: { worker }, + context: { ref: undefined as any }, + entry: ({ actors }: any, enq: any) => ({ + context: { ref: enq.spawn(actors.worker, { id: 'worker' }) } + }) + } as any); + + const app = mount( + createParent(createLogic({ context: 0, run: () => undefined })) + ); + const original = app.actorRef; + expect(original.getSnapshot().context.ref).toBe( + original.getSnapshot().children.worker + ); + + app.refreshTo( + createParent(createLogic({ context: 1, run: () => undefined })) + ); + + expect(app.actorRef).not.toBe(original); + const snapshot = app.actorRef.getSnapshot(); + expect(snapshot.context.ref).toBe(snapshot.children.worker); + expect(snapshot.children.worker.getSnapshot().context).toBe(1); + }); + + it('delivers snapshots a restarted child emits while starting', () => { + const seen: unknown[] = []; + const createParent = (child: any) => + createMachine({ + id: 'parent', + actors: { child }, + invoke: { + id: 'child', + src: 'child', + onSnapshot: ({ event }: any) => { + seen.push(event.snapshot.context); + } + } + } as any); + + const app = mount( + createParent(createLogic({ context: 'v1', run: () => undefined })) + ); + const original = app.actorRef; + seen.length = 0; + + app.refreshTo( + createParent(createLogic({ context: 'v2', run: () => undefined })) + ); + + expect(app.actorRef).toBe(original); + expect(seen).toEqual(['v2']); + }); + + it('starts a fresh actor when a remembered history state was removed', () => { + const createHistoryMachine = (withHistory: boolean) => + createMachine({ + id: 'player', + initial: 'on', + states: { + on: { + initial: 'a', + states: { + a: { on: { NEXT: { target: 'b' } } }, + b: {}, + ...(withHistory ? { hist: { type: 'history', target: 'a' } } : {}) + }, + on: { OFF: { target: 'off' } } + }, + off: { + on: { + ON: { target: withHistory ? 'on.hist' : 'on' }, + NOOP: {} + } + } + } + } as any); + + const app = mount(createHistoryMachine(true)); + const original = app.actorRef; + act(() => original.send({ type: 'NEXT' })); + act(() => original.send({ type: 'OFF' })); + expect(Object.keys(original.getSnapshot().historyValue)).toHaveLength(1); + + app.refreshTo(createHistoryMachine(false)); + + expect(app.actorRef).not.toBe(original); + expect(app.actorRef.getSnapshot().value).toEqual({ on: 'a' }); + }); + + it('derives the state value when an active state gains substates', () => { + const v1 = createEditor(); + const app = mount(v1); + const original = app.actorRef; + act(() => original.send({ type: 'NEXT' })); + + const v2 = createMachine({ + id: 'editor', + initial: 'idle', + states: { + idle: { on: { NEXT: { target: 'editing' } } }, + editing: { initial: 'typing', states: { typing: {} } } + } + }); + app.refreshTo(v2); + + expect(app.actorRef).toBe(original); + const snapshot = app.actorRef.getSnapshot(); + expect(snapshot.value).toEqual({ editing: 'typing' }); + expect(snapshot.matches({ editing: 'typing' })).toBe(true); + }); + + it('keeps the first machine when the machine changes without a refresh', () => { + const v1 = createEditor(); + let actorRef!: any; + const App = ({ machine }: { machine: any }) => { + actorRef = useActorRef(machine); + return null; + }; + const { rerender } = render(); + const original = actorRef; + rerender(); + + expect(actorRef).toBe(original); + expect(actorRef.logic).toBe(v1); + }); +}); diff --git a/xstate-react/test/issueRegressions.test.tsx b/xstate-react/test/issueRegressions.test.tsx new file mode 100644 index 00000000..0a2174be --- /dev/null +++ b/xstate-react/test/issueRegressions.test.tsx @@ -0,0 +1,137 @@ +/** + * Regression tests for open @xstate/react issues that are fixed in v6. Each + * test reproduces the issue as originally reported with v6 APIs. + */ +import { render, screen } from '@testing-library/react'; +import * as React from 'react'; +import { + createActor, + createCallbackLogic, + createMachine, + setup, + types +} from 'xstate'; +import { useMachine } from '../src/index.ts'; + +describe('lifecycle', () => { + it('#5272 an invoked callback starts once under StrictMode', () => { + let starts = 0; + let cleanups = 0; + const appMachine = createMachine({ + invoke: { + src: createCallbackLogic(() => { + starts++; + return () => { + cleanups++; + }; + }) + } + }); + + function App() { + useMachine(appMachine); + return null; + } + + render( + + + + ); + + expect(starts).toBe(1); + expect(cleanups).toBe(0); + }); + + it('#5074 system.get resolves a sibling invoked actor under StrictMode', () => { + const results: string[] = []; + const feedbackMachine = createMachine({}); + const rootMachine = setup({ + actors: { + feedback: feedbackMachine, + alert: createCallbackLogic(({ system }) => { + results.push(system.get('feedback') ? 'ok' : 'missing'); + }) + } + }).createMachine({ + invoke: [{ src: 'feedback', registryKey: 'feedback' }, { src: 'alert' }] + }); + + function App() { + useMachine(rootMachine); + return null; + } + + render( + + + + ); + + expect(results.length).toBeGreaterThan(0); + expect(results).not.toContain('missing'); + }); + + it('#3270 an event sent from a callback ref survives the StrictMode remount', () => { + const counterMachine = createMachine({ + schemas: { + events: { INCREMENT: types<{}>() } + }, + context: { count: 0 }, + on: { + INCREMENT: ({ context }) => ({ + context: { count: context.count + 1 } + }) + } + }); + + function Counter() { + const [current, send] = useMachine(counterMachine); + const ref = React.useCallback( + (node: HTMLElement | null) => { + if (node) { + send({ type: 'INCREMENT' }); + } + }, + [send] + ); + return
count: {current.context.count}
; + } + + render( + + + + ); + + // React 19 invokes the callback ref twice under StrictMode + expect(screen.getByText(/count:/).textContent).toBe('count: 2'); + }); +}); + +describe('types', () => { + it('#5480 useMachine accepts persisted and live snapshots', () => { + const machine = createMachine({ + initial: 'a', + states: { a: { on: { NEXT: { target: 'b' } } }, b: {} } + }); + const actor = createActor(machine).start(); + actor.send({ type: 'NEXT' }); + const persisted = actor.getPersistedSnapshot(); + const live = actor.getSnapshot(); + const fromStorage = JSON.parse(JSON.stringify(persisted)); + + function App() { + const [a] = useMachine(machine, { snapshot: persisted }); + const [b] = useMachine(machine, { snapshot: live }); + const [c] = useMachine(machine, { snapshot: fromStorage }); + return ( +
{[a.value, b.value, c.value].join(',')}
+ ); + } + + render(); + + expect(screen.getByTestId('values').textContent).toBe('b,b,b'); + }); +}); diff --git a/xstate-react/test/lint-fixtures/machine-in-component.tsx b/xstate-react/test/lint-fixtures/machine-in-component.tsx new file mode 100644 index 00000000..3a160a1d --- /dev/null +++ b/xstate-react/test/lint-fixtures/machine-in-component.tsx @@ -0,0 +1,45 @@ +import { useMachine } from '@xstate/react'; +import { createStore } from '@xstate/store'; +import * as React from 'react'; +import { forwardRef, memo } from 'react'; +import { createMachine, setup } from 'xstate'; + +export function Counter() { + const [snapshot] = useMachine(createMachine({})); + return

{String(snapshot.value)}

; +} + +export const Toggle = () => { + const machine = setup({}).createMachine({}); + const [snapshot] = useMachine(machine); + return

{String(snapshot.value)}

; +}; + +export function useCounterStore() { + return createStore({ context: { count: 0 }, on: {} }); +} + +export const Form = function () { + const onSubmit = () => createMachine({}); + return
; +}; + +export const Memoized = memo(() => { + const [snapshot] = useMachine(createMachine({})); + return

{String(snapshot.value)}

; +}); + +export const Wrapped = React.memo(() => { + const [snapshot] = useMachine(createMachine({})); + return

{String(snapshot.value)}

; +}); + +export const Field = forwardRef(function (_props, ref) { + const [snapshot] = useMachine(setup({}).createMachine({})); + return ; +}); + +export const Input = React.forwardRef((_props, ref) => { + const [snapshot] = useMachine(createMachine({})); + return ; +}); diff --git a/xstate-react/test/lint-fixtures/machine-outside-component.tsx b/xstate-react/test/lint-fixtures/machine-outside-component.tsx new file mode 100644 index 00000000..6ad43636 --- /dev/null +++ b/xstate-react/test/lint-fixtures/machine-outside-component.tsx @@ -0,0 +1,21 @@ +import { useMachine } from '@xstate/react'; +import { useMemo, useState } from 'react'; +import { createMachine, setup } from 'xstate'; + +const counterMachine = createMachine({}); + +export function createCounterMachine() { + return setup({}).createMachine({}); +} + +export function Counter() { + const [snapshot] = useMachine(counterMachine); + return

{String(snapshot.value)}

; +} + +export function Memoized() { + const machine = useMemo(() => createMachine({}), []); + const [lazy] = useState(() => setup({}).createMachine({})); + const [snapshot] = useMachine(machine); + return

{String(snapshot.value) + String(lazy.id)}

; +} diff --git a/xstate-react/test/lint-fixtures/oxlintrc.fixtures.json b/xstate-react/test/lint-fixtures/oxlintrc.fixtures.json new file mode 100644 index 00000000..55afe3d8 --- /dev/null +++ b/xstate-react/test/lint-fixtures/oxlintrc.fixtures.json @@ -0,0 +1,10 @@ +{ + "$schema": "../../../../node_modules/oxlint/configuration_schema.json", + "jsPlugins": ["../../../../scripts/oxlint-plugin-xstate-react.ts"], + "categories": { + "correctness": "off" + }, + "rules": { + "xstate/no-machine-in-component": "error" + } +} diff --git a/xstate-react/test/lint.test.ts b/xstate-react/test/lint.test.ts new file mode 100644 index 00000000..584000ad --- /dev/null +++ b/xstate-react/test/lint.test.ts @@ -0,0 +1,92 @@ +import { spawnSync } from 'node:child_process'; +import path from 'node:path'; + +const repoRoot = path.resolve(__dirname, '../../..'); +const fixtureDir = path.join( + repoRoot, + 'packages/xstate-react/test/lint-fixtures' +); +const fixtureConfig = path.join(fixtureDir, 'oxlintrc.fixtures.json'); +const pluginPath = 'scripts/oxlint-plugin-xstate-react.ts'; + +interface OxlintDiagnostic { + message: string; + code: string; +} + +/** + * Lints one fixture with a config that enables only + * `xstate/no-machine-in-component`, so the result is unaffected by the rest of + * the repository's lint configuration. + */ +const lint = (fixture: string): OxlintDiagnostic[] => { + const result = spawnSync( + 'pnpm', + [ + 'exec', + 'oxlint', + '-c', + path.relative(repoRoot, fixtureConfig), + '--format', + 'json', + path.relative(repoRoot, path.join(fixtureDir, fixture)) + ], + { cwd: repoRoot, encoding: 'utf8' } + ); + + if (result.error) { + throw result.error; + } + const stdout = result.stdout ?? ''; + const start = stdout.indexOf('{'); + if (start === -1) { + throw new Error(`oxlint produced no report:\n${stdout}\n${result.stderr}`); + } + return ( + JSON.parse(stdout.slice(start)) as { diagnostics: OxlintDiagnostic[] } + ).diagnostics; +}; + +describe('xstate/no-machine-in-component', () => { + it('supports strict type-aware linting of the plugin itself', () => { + const result = spawnSync( + 'pnpm', + [ + 'exec', + 'oxlint', + '--type-aware', + ...[ + 'no-unsafe-assignment', + 'no-unsafe-call', + 'no-unsafe-member-access', + 'no-unsafe-argument', + 'no-unsafe-return', + 'strict-boolean-expressions' + ].flatMap((rule) => ['--deny', `typescript/${rule}`]), + pluginPath + ], + { cwd: repoRoot, encoding: 'utf8' } + ); + + expect(result.error).toBeUndefined(); + expect(result.status, result.stdout + result.stderr).toBe(0); + }, 60_000); + + it('reports machines and stores created in component and hook bodies, including memo and forwardRef components', () => { + const diagnostics = lint('machine-in-component.tsx'); + + expect(diagnostics).toHaveLength(8); + expect( + diagnostics.every( + (diagnostic) => + diagnostic.code === 'xstate(no-machine-in-component)' && + diagnostic.message === + 'Create machines at module scope, or memoize with useMemo; useActorRef keeps the first machine it receives.' + ) + ).toBe(true); + }, 60_000); + + it('reports nothing at module scope or in useMemo/useState initializers', () => { + expect(lint('machine-outside-component.tsx')).toEqual([]); + }, 60_000); +}); diff --git a/xstate-react/test/types.test.tsx b/xstate-react/test/types.test.tsx new file mode 100644 index 00000000..114a7f37 --- /dev/null +++ b/xstate-react/test/types.test.tsx @@ -0,0 +1,270 @@ +import { render } from '@testing-library/react'; +import { ActorRefFrom, createActor, createMachine } from 'xstate'; +import { + useActor, + useActorRef, + useMachine, + useSelector +} from '../src/index.ts'; +import z from 'zod'; + +describe('useMachine', () => { + interface YesNoContext { + value?: number; + } + + interface YesNoEvent { + type: 'YES'; + } + + const yesNoMachine = createMachine({ + // types: {} as { context: YesNoContext; events: YesNoEvent }, + schemas: { + context: z.object({ + value: z.number().optional() + }), + events: z.object({ + type: z.literal('YES') + }) as any + }, + context: { + value: undefined + }, + initial: 'no', + states: { + no: { + on: { + YES: { target: 'yes' } + } + }, + yes: { + type: 'final' + } + } + }); + + it('state should not become never after checking state with matches', () => { + const YesNo = () => { + const [state] = useMachine(yesNoMachine); + + if (state.matches('no')) { + return No; + } + + return Yes: {state.context.value}; + }; + + render(); + }); + + // Example from: https://github.com/statelyai/xstate/discussions/1534 + it('spawned actors should be typed correctly', () => { + const child = createMachine({ + // types: {} as { + // context: { bar: number }; + // events: { type: 'FOO'; data: number }; + // }, + schemas: { + context: z.object({ + bar: z.number() + }), + events: z.object({ + type: z.literal('FOO'), + data: z.number() + }) as any + }, + id: 'myActor', + context: { + bar: 1 + }, + initial: 'ready', + states: { + ready: {} + } + }); + + const m = createMachine({ + initial: 'ready', + schemas: { + context: z.object({ + actor: z.custom>().nullable() + }) + }, + context: { + actor: null + }, + states: { + ready: { + entry: (_, enq) => ({ + context: { + actor: enq.spawn(child) + } + }) + } + } + }); + + interface Props { + myActor: ActorRefFrom; + } + + function Element({ myActor }: Props) { + const current = useSelector(myActor, (state) => state); + const bar: number = current.context.bar; + + // @ts-expect-error + send({ type: 'WHATEVER' }); + + return ( + <> + {bar} +
myActor.send({ type: 'FOO', data: 1 } as any)}> + click +
+ + ); + } + + function App() { + const [current] = useMachine(m); + + if (!current.context.actor) { + return null; + } + + return ; + } + + const noop = (_val: any) => { + /* ... */ + }; + + noop(App); + }); +}); + +describe('useActor', () => { + it('should require input to be specified when defined', () => { + const withInputMachine = createMachine({ + // types: {} as { input: { value: number } }, + schemas: { + input: z.object({ + value: z.number() + }) + }, + initial: 'idle', + states: { + idle: {} + } + }); + + const Component = () => { + // @ts-expect-error input is required + const _ = useActor(withInputMachine); + return <>; + }; + + render(); + }); + + it('should not require input when not defined', () => { + const noInputMachine = createMachine({ + // types: {} as {}, + initial: 'idle', + states: { + idle: {} + } + }); + const Component = () => { + const _ = useActor(noInputMachine); + return <>; + }; + + render(); + }); +}); + +describe('useActorRef', () => { + it('should not require input when restoring a snapshot', () => { + const machine = createMachine({ + schemas: { input: z.object({ value: z.number() }) } + }); + const snapshot = createActor(machine, { + input: { value: 1 } + }).getPersistedSnapshot(); + + // Type-only checks: the hooks need a component to run. + const check = () => { + useActorRef(machine, { snapshot }); + useActor(machine, { snapshot }); + useMachine(machine, { snapshot }); + // @ts-expect-error input or snapshot is required + useActorRef(machine); + // @ts-expect-error input or snapshot is required + useActorRef(machine, {}); + }; + + expect(check).toBeTypeOf('function'); + }); + + it('should require input to be specified when defined', () => { + const withInputMachine = createMachine({ + // types: {} as { input: { value: number } }, + schemas: { + input: z.object({ + value: z.number() + }) + }, + initial: 'idle', + states: { + idle: {} + } + }); + + const Component = () => { + // @ts-expect-error input is required + const _ = useActorRef(withInputMachine); + return <>; + }; + + render(); + }); + + it('should not require input when not defined', () => { + const noInputMachine = createMachine({ + // types: {} as {}, + initial: 'idle', + states: { + idle: {} + } + }); + + const Component = () => { + const _ = useActorRef(noInputMachine); + return <>; + }; + + render(); + }); +}); + +it('useMachine types work for machines with a specified id and state with an after property #5008', () => { + // https://github.com/statelyai/xstate/issues/5008 + const cheatCodeMachine = createMachine({ + id: 'cheatCodeMachine', + initial: 'disabled', + states: { + disabled: { + after: {} + }, + enabled: {} + } + }); + + function _useCheatCode(): boolean { + // This should typecheck without errors + const [state] = useMachine(cheatCodeMachine); + + return state.matches('enabled'); + } +}); diff --git a/xstate-react/test/useActor.test.tsx b/xstate-react/test/useActor.test.tsx new file mode 100644 index 00000000..c7a62f4f --- /dev/null +++ b/xstate-react/test/useActor.test.tsx @@ -0,0 +1,1019 @@ +import { act, fireEvent, screen } from '@testing-library/react'; +import { setTimeout as sleep } from 'node:timers/promises'; +import * as React from 'react'; +import { useState } from 'react'; +import { BehaviorSubject } from 'rxjs'; +import { + Actor, + Snapshot, + SnapshotFrom, + createActor, + createMachine +} from 'xstate'; +import { + createCallbackLogic, + createObservableLogic, + createAsyncLogic +} from 'xstate'; +import { useActor, useSelector } from '../src/index.ts'; +import { describeEachReactMode } from './utils.tsx'; +import z from 'zod'; + +afterEach(() => { + vi.useRealTimers(); +}); + +describeEachReactMode('useActor (%s)', ({ suiteKey, render }) => { + const context = { + data: undefined as undefined | string + }; + const fetchMachine = createMachine({ + id: 'fetch', + // types: {} as { + // context: typeof context; + // events: { type: 'FETCH' } | DoneActorEvent; + // actors: { + // src: 'fetchData'; + // logic: ActorLogicFrom>; + // }; + // }, + schemas: { + context: z.object({ + data: z.string().optional() + }), + events: z.object({ + type: z.literal('FETCH') + }) as any + }, + actors: { + fetchData: createMachine({}) + }, + initial: 'idle', + context, + states: { + idle: { + on: { FETCH: { target: 'loading' } } + }, + loading: { + invoke: { + id: 'fetchData', + // src: 'fetchData', + src: ({ actors }: any) => actors.fetchData, + // onDone: { + // target: 'success', + // actions: assign({ + // data: ({ event }) => { + // return event.output; + // } + // }), + // guard: ({ event }) => !!event.output.length + // } + onDone: ({ event }: any) => { + if ((event.output as any).length > 0) { + return { + context: { + data: event.output + }, + target: 'success' + }; + } + } + } as any + }, + success: { + type: 'final' + } + } + }); + + const actorRef = createActor( + fetchMachine.provide({ + actors: { + fetchData: createMachine({ + initial: 'done', + states: { + done: { + type: 'final' + } + }, + output: 'persisted data' + }) as any + } + }) + ).start(); + actorRef.send({ type: 'FETCH' }); + + const persistedSuccessFetchState = actorRef.getPersistedSnapshot(); + + const Fetcher: React.FC<{ + onFetch: () => Promise; + persistedState?: Snapshot; + }> = ({ + onFetch = () => { + return new Promise((res) => res('some data')); + }, + persistedState + }) => { + const [current, send] = useActor( + fetchMachine.provide({ + actors: { + fetchData: createAsyncLogic({ run: onFetch }) as any + } + }), + { + snapshot: persistedState + } + ); + + switch (current.value) { + case 'idle': + return ; + case 'loading': + return
Loading...
; + case 'success': + return ( +
+ Success! Data:
{current.context.data}
+
+ ); + default: + return null; + } + }; + + it('should work with the useActor hook', async () => { + render( new Promise((res) => res('fake data'))} />); + const button = screen.getByText('Fetch'); + fireEvent.click(button); + screen.getByText('Loading...'); + await screen.findByText(/Success/); + const dataEl = screen.getByTestId('data'); + expect(dataEl.textContent).toBe('fake data'); + }); + + it('should work with the useActor hook (rehydrated state)', async () => { + render( + new Promise((res) => res('fake data'))} + persistedState={persistedSuccessFetchState} + /> + ); + + await screen.findByText(/Success/); + const dataEl = screen.getByTestId('data'); + expect(dataEl.textContent).toBe('persisted data'); + }); + + it('should work with the useMachine hook (rehydrated state config)', async () => { + const persistedFetchStateConfig = JSON.parse( + JSON.stringify(persistedSuccessFetchState) + ); + render( + new Promise((res) => res('fake data'))} + persistedState={persistedFetchStateConfig} + /> + ); + + await screen.findByText(/Success/); + const dataEl = screen.getByTestId('data'); + expect(dataEl.textContent).toBe('persisted data'); + }); + + it('should provide the service', () => { + const Test = () => { + const [, , service] = useActor(fetchMachine); + + if (!(service instanceof Actor)) { + throw new Error('service not instance of Interpreter'); + } + + return null; + }; + + render(); + }); + + it('should accept input and provide it to the context factory', () => { + const testMachine = createMachine({ + context: (({ input }: any) => ({ + foo: 'bar', + test: input.test ?? false + })) as any, + initial: 'idle', + states: { + idle: {} + } + }); + + const Test = () => { + const [state] = useActor(testMachine, { + input: { test: true } + }); + + expect(state.context).toEqual({ + foo: 'bar', + test: true + }); + + return null; + }; + + render(); + }); + + it('should not spawn actors until service is started', async () => { + const spawnMachine = createMachine({ + id: 'spawn', + initial: 'start', + context: { ref: undefined } as any, + states: { + start: { + // entry: assign({ + // ref: ({ spawn }) => + // spawn( + // createAsyncLogic(() => { + // return new Promise((res) => res(42)); + // }), + // { id: 'my-promise' } + // ) + // }), + entry: (_, enq) => ({ + context: { + ref: enq.spawn( + createAsyncLogic({ + run: () => { + return new Promise((res) => res(42)); + } + }), + { id: 'my-promise' } + ) + } + }), + on: { + 'xstate.done.actor.my-promise': { target: 'success' } + } + }, + success: { + type: 'final' + } + } + }); + + const Spawner = () => { + const [current] = useActor(spawnMachine); + + switch (current.value) { + case 'start': + return ; + case 'success': + return ; + default: + return null; + } + }; + + render(); + + await screen.findByTestId('success'); + }); + + it('actions should not use stale data in a builtin transition action', () => { + const { resolve, promise } = Promise.withResolvers(); + + const toggleMachine = createMachine({ + // types: {} as { + // context: { latest: number }; + // events: { type: 'SET_LATEST' }; + // }, + context: { + latest: 0 + } as any, + actions: { + getLatest: () => {} + }, + on: { + SET_LATEST: ({ actions }, enq) => { + enq(actions.getLatest); + } + } + }); + + const Component = () => { + const [count, setCount] = useState(1); + + const [, send] = useActor( + toggleMachine.provide({ + actions: { + getLatest: () => { + expect(count).toBe(2); + resolve(); + } + } + }) + ); + + return ( + <> + + ); + }; + + render(); + + const button = screen.getByTestId('button'); + + fireEvent.click(button); + act(() => { + vi.advanceTimersByTime(110); + }); + + expect(currentState!.matches('idle')).toBe(true); + }); + + it('should not miss initial synchronous updates', () => { + const m = createMachine({ + // types: {} as { context: { count: number } }, + schemas: { + context: z.object({ + count: z.number() + }) + }, + initial: 'idle', + context: { + count: 0 + }, + // entry: [assign({ count: 1 }), raise({ type: 'INC' })], + entry: (_, enq) => { + enq.raise({ type: 'INC' }); + return { + context: { + count: 1 + } + }; + }, + on: { + // INC: { + // actions: [ + // assign({ count: ({ context }) => context.count + 1 }), + // raise({ type: 'UNHANDLED' }) + // ] + // } + INC: ({ context }, enq) => { + enq.raise({ type: 'UNHANDLED' }); + return { + context: { + count: context.count + 1 + } + }; + } + }, + states: { + idle: {} + } + }); + + const App = () => { + const [state] = useActor(m); + return <>{state.context.count}; + }; + + const { container } = render(); + + expect(container.textContent).toBe('2'); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart invoked + // children (observable actors), so the subscription is lost + it('should work with `onSnapshot`', () => { + const subject = new BehaviorSubject(0); + + const spy = vi.fn(); + + const machine = createMachine({ + invoke: { + src: createObservableLogic(() => subject), + // onSnapshot: { + // actions: [({ event }) => spy((event.snapshot as any).context)] + // } + onSnapshot: ({ event }) => { + spy((event.snapshot as any).context); + } + } + }); + + const App = () => { + useActor(machine); + return null; + }; + + render(); + + spy.mockClear(); + + subject.next(42); + subject.next(100); + + expect(spy.mock.calls).toEqual([[42], [100]]); + }); + + it('should execute a delayed transition of the initial state', async () => { + const machine = createMachine({ + initial: 'one', + states: { + one: { + after: { + 10: { target: 'two' } + } + }, + two: {} + } + }); + + const App = () => { + const [state] = useActor(machine); + return <>{state.value}; + }; + + const { container } = render(); + + expect(container.textContent).toBe('one'); + + await act(async () => { + await sleep(10); + }); + + expect(container.textContent).toBe('two'); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart invoked + // children (promise actors), so the error never propagates + it('should throw an error to an error boundary when the actor reaches an error state', async () => { + const errorMessage = 'test_useActor_error'; + + const machine = createMachine({ + initial: 'loading', + states: { + loading: { + invoke: { + src: createAsyncLogic({ + run: () => Promise.reject(new Error(errorMessage)) + }) + } + } + } + }); + + class ErrorBoundary extends React.Component< + { children: React.ReactNode }, + { error: Error | null } + > { + state = { error: null as Error | null }; + static getDerivedStateFromError(error: Error) { + return { error }; + } + render() { + if (this.state.error) { + return
{this.state.error.message}
; + } + return this.props.children; + } + } + + const App = () => { + const [state] = useActor(machine); + return
{String(state.value)}
; + }; + + console.error = vi.fn(); + + render( + + + + ); + + await screen.findByTestId('error'); + expect(screen.getByTestId('error').textContent).toBe(errorMessage); + }); +}); diff --git a/xstate-react/test/useActorRef.test.tsx b/xstate-react/test/useActorRef.test.tsx new file mode 100644 index 00000000..6d0acef3 --- /dev/null +++ b/xstate-react/test/useActorRef.test.tsx @@ -0,0 +1,645 @@ +import { + fireEvent, + screen, + waitFor as testWaitFor +} from '@testing-library/react'; +import * as React from 'react'; +import { + ActorRefFrom, + createAsyncLogic, + createLogic, + createMachine +} from 'xstate'; +import { useActorRef, useMachine, useSelector } from '../src/index.ts'; +import { describeEachReactMode } from './utils.tsx'; +import { z } from 'zod'; + +afterEach(() => { + vi.restoreAllMocks(); +}); + +describeEachReactMode('useActorRef (%s)', ({ suiteKey, render }) => { + it('rebinds a stable observer before a replacement actor starts', () => { + const first = createMachine({ on: { PING: {} } }); + const second = createMachine({ on: { PING: {} } }); + const observer = vi.fn(); + let ref: ActorRefFrom; + const App = ({ machine }: { machine: typeof first }) => { + ref = useActorRef(machine, undefined, observer); + return null; + }; + const { rerender } = render(); + const original = ref!; + observer.mockClear(); + rerender(); + expect(ref!).not.toBe(original); + expect(observer).toHaveBeenCalledExactlyOnceWith(ref!.getSnapshot()); + observer.mockClear(); + ref!.send({ type: 'PING' }); + expect(observer).toHaveBeenCalledExactlyOnceWith(ref!.getSnapshot()); + }); + + it('should accept events from effects when mounted in strict mode', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + let received = 0; + const machine = createMachine({ + actions: { + record: () => { + received++; + } + }, + on: { + INC: ({ actions }, enq) => enq(actions.record) + } + }); + + const App = () => { + const actorRef = useActorRef(machine); + + React.useEffect(() => { + actorRef.send({ type: 'INC' }); + }, [actorRef]); + + return null; + }; + + render(); + + expect(warnSpy).not.toHaveBeenCalledWith( + expect.stringContaining('was not delivered (stopped)') + ); + expect(received).toBe(suiteKey === 'strict' ? 2 : 1); + }); + + it('should still warn when sending to an actor after unmount', async () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const machine = createMachine({}); + let actorRef: ActorRefFrom; + + const App = () => { + actorRef = useActorRef(machine); + return null; + }; + + const { unmount } = render(); + unmount(); + await new Promise((resolve) => queueMicrotask(resolve)); + + actorRef!.send({ type: 'INC' }); + + expect(warnSpy).toHaveBeenCalledWith( + expect.stringContaining('was not delivered (stopped)') + ); + }); + + it('observer should be called with next state', () => { + const { resolve, promise } = Promise.withResolvers(); + const machine = createMachine({ + initial: 'inactive', + states: { + inactive: { + on: { + ACTIVATE: { target: 'active' } + } + }, + active: {} + } + }); + + const App = () => { + const actorRef = useActorRef(machine); + + React.useEffect(() => { + actorRef.subscribe((state) => { + if (state.matches('active')) { + resolve(); + } + }); + }, [actorRef]); + + return ( + + ); + }; + + render(); + const button = screen.getByTestId('button'); + + fireEvent.click(button); + return promise; + }); + + it('actions created by a layout effect should access the latest closure values', () => { + const actual: number[] = []; + + const machine = createMachine({ + initial: 'foo', + actions: { + recordProp: () => {} + }, + states: { + foo: { + on: { + // EXEC_ACTION: { + // actions: 'recordProp' + // } + EXEC_ACTION: ({ actions }, enq) => enq(actions.recordProp) + } + } + } + }); + + const App = ({ value }: { value: number }) => { + const service = useActorRef( + machine.provide({ + actions: { + recordProp: () => actual.push(value) + } + }) + ); + + React.useLayoutEffect(() => { + service.send({ type: 'EXEC_ACTION' }); + }); + + return null; + }; + + const { rerender } = render(); + + expect(actual).toEqual(suiteKey === 'strict' ? [1, 1] : [1]); + + actual.length = 0; + rerender(); + + expect(actual).toEqual([42]); + }); + + it('should rerender OK when only the provided machine sources have changed', () => { + const machine = createMachine({ + initial: 'foo', + schemas: { + context: z.object({ + id: z.number() + }) + }, + guards: { + hasOverflown: () => false + }, + context: { id: 1 }, + states: { + foo: { + on: { + // CHECK: { + // target: 'bar', + // guard: 'hasOverflown' + // } + CHECK: ({ guards }) => { + if (guards.hasOverflown()) { + return { + target: 'bar' + }; + } + } + } + }, + bar: {} + } + }); + + const App = () => { + const [id, setId] = React.useState(1); + useMachine( + machine.provide({ + guards: { + hasOverflown: (() => id > 1) as any + } + }) + ); + + return ( + <> + + {id} + + ); + }; + + render(); + + fireEvent.click(screen.getByRole('button')); + + expect(screen.getByText('2')).toBeTruthy(); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart spawned children + // because StateMachine.start() no longer auto-starts children + it('should change state when started', async () => { + const childMachine = createMachine({ + initial: 'waiting', + states: { + waiting: { + on: { + EVENT: { target: 'received' } + } + }, + received: {} + } + }); + + const parentMachine = createMachine({ + schemas: { + context: z.object({ + childRef: z.custom>() + }) + }, + context: ({ spawn }) => ({ + childRef: spawn(childMachine) + }), + on: { + SEND_TO_CHILD: ({ context }, enq) => { + enq.sendTo(context.childRef, { type: 'EVENT' }); + } + } + }); + + const App = () => { + const parentActor = useActorRef(parentMachine); + const parentState = useSelector(parentActor, (s) => s); + const childState = useSelector(parentState.context.childRef, (s) => s); + + return ( + <> + +
{childState.value as string}
+ + ); + }; + + render(); + + const button = screen.getByTestId('button'); + const childState = screen.getByTestId('child-state'); + + expect(childState.textContent).toBe('waiting'); + + fireEvent.click(button); + + expect(childState.textContent).toBe('received'); + }); + + it('should change state when started (useMachine)', async () => { + const childMachine = createMachine({ + initial: 'waiting', + states: { + waiting: { + on: { + EVENT: { target: 'received' } + } + }, + received: {} + } + }); + + const parentMachine = createMachine({ + // types: {} as { + // context: { + // childRef: ActorRefFrom; + // }; + // }, + schemas: { + context: z.object({ + childRef: z.custom>() + }) + }, + context: ({ spawn }) => ({ + childRef: spawn(childMachine) + }), + on: { + // SEND_TO_CHILD: { + // actions: sendTo(({ context }) => context.childRef, { type: 'EVENT' }) + // } + SEND_TO_CHILD: ({ context }, enq) => { + enq.sendTo(context.childRef, { type: 'EVENT' }); + } + } + }); + + const App = () => { + const [parentState, parentSend] = useMachine(parentMachine); + const childState = useSelector(parentState.context.childRef, (s) => s); + + return ( + <> + +
{childState.value as string}
+ + ); + }; + + render(); + + const button = screen.getByTestId('button'); + const childState = screen.getByTestId('child-state'); + + expect(childState.textContent).toBe('waiting'); + + fireEvent.click(button); + + expect(childState.textContent).toBe('received'); + }); + + it('should work with custom logic', () => { + const someLogic = createLogic({ + context: 0, + run: ({ context, event }) => { + if (event.type === 'inc') { + return { context: context + 1 }; + } + return; + } + }); + + const App = () => { + const actorRef = useActorRef(someLogic); + const count = useSelector(actorRef, (state) => state); + + return ( +
actorRef.send({ type: 'inc' })}> + {count.context} +
+ ); + }; + + render(); + + const count = screen.getByTestId('count'); + + expect(count.textContent).toBe('0'); + + fireEvent.click(count); + + expect(count.textContent).toBe('1'); + }); + + it('should work with a promise actor', async () => { + const promiseLogic = createAsyncLogic({ + run: () => + new Promise((resolve) => setTimeout(() => resolve(42), 10)) + }); + + const App = () => { + const actorRef = useActorRef(promiseLogic); + const count = useSelector(actorRef, (state) => state); + + return
{count.output}
; + }; + + render(); + + const count = screen.getByTestId('count'); + + expect(count.textContent).toBe(''); + + await testWaitFor(() => expect(count.textContent).toBe('42')); + }); + + it('should switch to a new machine when the component key changes', () => { + const machine1 = createMachine({ + initial: 'a', + states: { a: {} } + }); + + const machine2 = createMachine({ + initial: 'a', + states: { + a: { + on: { NEXT: { target: 'b' } } + }, + b: {} + } + }); + + function Test({ machine }: { machine: typeof machine2 }) { + const actorRef = useActorRef(machine); + const value = useSelector(actorRef, (state) => state.value); + + return ( + <> + + {value as string} + + ); + } + + function App() { + const [machine, setMachine] = React.useState(machine1); + return ( + <> + + + + ); + } + + render(); + + fireEvent.click(screen.getByText('Reload machine')); + fireEvent.click(screen.getByText('Send event')); + + expect(screen.getByText('b')).toBeTruthy(); + }); + + it('should keep the first machine when a different machine is passed later', () => { + const machine1 = createMachine({ + initial: 'a', + states: { + a: { + on: { NEXT: { target: 'b' } } + }, + b: {} + } + }); + + const machine2 = createMachine({ + initial: 'b', + states: { + b: { + on: { NEXT: { target: 'c' } } + }, + c: {} + } + }); + + const refs = new Set(); + + function Test() { + const [machine, setMachine] = React.useState(machine1); + const actorRef = useActorRef(machine); + refs.add(actorRef); + const value = useSelector(actorRef, (state) => state.value); + + return ( + <> + + + {value as string} + + ); + } + + render(); + + fireEvent.click(screen.getByText('Send event')); + fireEvent.click(screen.getByText('Reload machine')); + fireEvent.click(screen.getByText('Send event')); + + // machine1 is still in use: 'b' has no transitions there. + expect(screen.getByText('b')).toBeTruthy(); + expect(refs.size).toBe(1); + }); + + it('should not loop or reset state when a machine factory is called on every render', () => { + let renders = 0; + + function Test() { + renders++; + const [snapshot, send] = useMachine( + createMachine({ + context: { count: 0 }, + on: { + INC: ({ context }) => ({ + context: { count: context.count + 1 } + }) + } + }) + ); + + return ( + + ); + } + + render(); + const button = screen.getByRole('button'); + + fireEvent.click(button); + fireEvent.click(button); + fireEvent.click(button); + + expect(button.textContent).toBe('3'); + expect(renders).toBeLessThan(20); + }); + + it("should execute action bound to a specific machine's instance when the action is provided in render", () => { + const spy1 = vi.fn(); + const spy2 = vi.fn(); + + const machine = createMachine({ + actions: { + stuff: spy1 + }, + on: { + // DO: { + // actions: 'stuff' + // } + DO: ({ actions }, enq) => enq(actions.stuff) + } + }); + + const Test = () => { + const actorRef1 = useActorRef( + machine.provide({ + actions: { + stuff: spy1 + } + }) + ); + useActorRef( + machine.provide({ + actions: { + stuff: spy2 + } + }) + ); + + return ( + + ); + }; + + render(); + + screen.getByRole('button').click(); + + expect(spy1).toHaveBeenCalledTimes(1); + expect(spy2).not.toHaveBeenCalled(); + }); +}); diff --git a/xstate-react/test/useSelector.test.tsx b/xstate-react/test/useSelector.test.tsx new file mode 100644 index 00000000..b07d6044 --- /dev/null +++ b/xstate-react/test/useSelector.test.tsx @@ -0,0 +1,1022 @@ +import { act, fireEvent, screen } from '@testing-library/react'; +import * as React from 'react'; +import { + ActorRef, + ActorRefFrom, + ActorFromLogic, + AnyMachineSnapshot, + createLogic, + createAsyncLogic, + createActor, + SnapshotFrom, + LogicSnapshot, + createMachine, + setup, + types +} from 'xstate'; +import { + shallowEqual, + useActorRef, + useMachine, + useSelector +} from '../src/index.ts'; +import { describeEachReactMode } from './utils'; +import z from 'zod'; + +const originalConsoleError = console.error; + +afterEach(() => { + console.error = originalConsoleError; +}); + +describeEachReactMode('useSelector (%s)', ({ suiteKey, render }) => { + it('only rerenders for selected values', () => { + const machine = createMachine({ + // types: {} as { context: { count: number; other: number } }, + schemas: { + context: z.object({ + count: z.number(), + other: z.number() + }) + }, + initial: 'active', + context: { + other: 0, + count: 0 + }, + states: { + active: {} + }, + on: { + OTHER: ({ context }) => ({ + context: { + other: context.other + 1 + } + }), + INCREMENT: ({ context }) => ({ + context: { + count: context.count + 1 + } + }) + } + }); + + let rerenders = 0; + + const App = () => { + const service = useActorRef(machine); + const count = useSelector(service, (state) => state.context.count); + + rerenders++; + + return ( + <> +
{count}
+ + + + ); + }; + + render(); + const countButton = screen.getByTestId('count'); + const otherButton = screen.getByTestId('other'); + const incrementEl = screen.getByTestId('increment'); + + fireEvent.click(incrementEl); + + rerenders = 0; + + fireEvent.click(otherButton); + fireEvent.click(otherButton); + fireEvent.click(otherButton); + fireEvent.click(otherButton); + + expect(rerenders).toEqual(0); + + fireEvent.click(incrementEl); + + expect(countButton.textContent).toBe('2'); + }); + + it('should work with a custom comparison function', () => { + const machine = createMachine({ + // types: {} as { + // context: { name: string }; + // events: { type: 'CHANGE'; value: string }; + // }, + schemas: { + context: z.object({ + name: z.string() + }), + events: z.object({ + type: z.literal('CHANGE'), + value: z.string() + }) as any + }, + initial: 'active', + context: { + name: 'david' + }, + states: { + active: {} + }, + on: { + // CHANGE: { + // actions: assign({ name: ({ event }) => event.value }) + // } + CHANGE: ({ event }: any) => ({ + context: { + name: event.value + } + }) + } + }); + + const App = () => { + const service = useActorRef(machine); + const name = useSelector( + service, + (state) => state.context.name, + (a, b) => a.toUpperCase() === b.toUpperCase() + ); + + return ( + <> +
{name}
+ + + + ); + }; + + render(); + const nameEl = screen.getByTestId('name'); + const sendUpperButton = screen.getByTestId('sendUpper'); + const sendOtherButton = screen.getByTestId('sendOther'); + + expect(nameEl.textContent).toEqual('david'); + + fireEvent.click(sendUpperButton); + + // unchanged due to comparison function + expect(nameEl.textContent).toEqual('david'); + + fireEvent.click(sendOtherButton); + + expect(nameEl.textContent).toEqual('other'); + + fireEvent.click(sendUpperButton); + + expect(nameEl.textContent).toEqual('DAVID'); + }); + + it('should work with the shallowEqual comparison function', () => { + const machine = createMachine({ + // types: {} as { context: { user: { name: string } } }, + schemas: { + context: z.object({ + user: z.object({ + name: z.string() + }) + }) + }, + initial: 'active', + context: { + user: { name: 'david' } + }, + states: { + active: {} + }, + on: { + 'change.same': () => ({ + context: { + user: { name: 'david' } + } + }), + 'change.other': () => ({ + context: { + user: { name: 'other' } + } + }) + } + }); + + const App = () => { + const service = useActorRef(machine); + const [userChanges, setUserChanges] = React.useState(0); + const user = useSelector( + service, + (state) => state.context.user, + shallowEqual + ); + const prevUser = React.useRef(user); + + React.useEffect(() => { + if (user !== prevUser.current) { + setUserChanges((c) => c + 1); + } + prevUser.current = user; + }, [user]); + + return ( + <> +
{user.name}
+
{userChanges}
+ + + + ); + }; + + render(); + const nameEl = screen.getByTestId('name'); + const changesEl = screen.getByTestId('changes'); + const sendSameButton = screen.getByTestId('sendSame'); + const sendOtherButton = screen.getByTestId('sendOther'); + + expect(nameEl.textContent).toEqual('david'); + + // unchanged due to comparison function + fireEvent.click(sendSameButton); + expect(nameEl.textContent).toEqual('david'); + expect(changesEl.textContent).toEqual('0'); + + // changed + fireEvent.click(sendOtherButton); + expect(nameEl.textContent).toEqual('other'); + expect(changesEl.textContent).toEqual('1'); + + // changed + fireEvent.click(sendSameButton); + expect(nameEl.textContent).toEqual('david'); + expect(changesEl.textContent).toEqual('2'); + + // unchanged due to comparison function + fireEvent.click(sendSameButton); + expect(nameEl.textContent).toEqual('david'); + expect(changesEl.textContent).toEqual('2'); + }); + + it('should work with selecting values from initially invoked actors', () => { + const childMachine = createMachine({ + id: 'childMachine', + initial: 'active', + states: { + active: {} + } + }); + const machine = createMachine({ + initial: 'active', + invoke: { + id: 'child', + src: childMachine + }, + states: { + active: {} + } + }); + + const ChildTest: React.FC<{ + actor: ActorRefFrom; + }> = ({ actor }) => { + const state = useSelector(actor, (s) => s); + + expect(state.value).toEqual('active'); + + return null; + }; + + const Test = () => { + const actorRef = useActorRef(machine); + const childActor = useSelector( + actorRef, + (s) => s.children.child as ActorRefFrom + ); + return ; + }; + + render(); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart spawned + // children, so the child actor won't process events + it('should work with selecting values from initially spawned actors', () => { + const childMachine = createMachine({ + schemas: { + context: z.object({ + count: z.number() + }) + }, + context: { + count: 0 + }, + on: { + // UPDATE_COUNT: { + // actions: assign({ + // count: ({ context }) => context.count + 1 + // }) + // } + UPDATE_COUNT: ({ context }) => ({ + context: { + count: context.count + 1 + } + }) + } + }); + + const parentMachine = createMachine({ + // types: { + // context: {} as { + // childActor: ActorRefFrom; + // } + // }, + schemas: { + context: z.object({ + childActor: z.custom>() + }) + }, + context: ({ spawn }) => ({ + childActor: spawn(childMachine) + }) + }); + const selector = (state: SnapshotFrom) => + state.context.count; + + const App = () => { + const [state] = useMachine(parentMachine); + const actor = state.context.childActor; + const count = useSelector(actor, selector); + + return ( + <> +
{count}
+ + + + ); + }; + + const { container, rerender } = render( 'foo'} />); + expect(container.textContent).toEqual('foo'); + + rerender( 'bar'} />); + expect(container.textContent).toEqual('bar'); + + fireEvent.click(await screen.findByRole('button')); + expect(container.textContent).toEqual('bar'); + }); + + it('should only rerender once when the selected value changes', () => { + const selector = (state: any) => state.context.foo; + + const machine = createMachine({ + // types: {} as { context: { foo: number }; events: { type: 'INC' } }, + schemas: { + context: z.object({ + foo: z.number() + }), + events: z.object({ + type: z.literal('INC') + }) as any + }, + context: { + foo: 0 + }, + on: { + // INC: { + // actions: assign({ + // foo: ({ context }) => ++context.foo + // }) + // } + INC: ({ context }) => ({ + context: { + foo: context.foo + 1 + } + }) + } + }); + + const service = createActor(machine).start(); + + let renders = 0; + + const App = () => { + ++renders; + useSelector(service, selector); + + return null; + }; + + render(); + + // reset + renders = 0; + act(() => { + service.send({ type: 'INC' }); + }); + + expect(renders).toBe(suiteKey === 'strict' ? 2 : 1); + }); + + it('should compute a stable snapshot internally when selecting from uninitialized service', () => { + const child = createMachine({}); + const machine = createMachine({ + invoke: { + id: 'child', + src: child + } + }); + + const snapshots: AnyMachineSnapshot[] = []; + + function App() { + const service = useActorRef(machine); + useSelector(service, (state) => { + snapshots.push(state); + return state.children.child; + }); + return null; + } + + console.error = vi.fn(); + render(); + + const [snapshot1] = snapshots; + expect(snapshots.every((s) => s === snapshot1)); + expect(console.error).toHaveBeenCalledTimes(0); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart spawned + // children, so the child actor won't process events + it('should work with initially deferred actors spawned in lazy context', () => { + const childMachine = createMachine({ + initial: 'one', + states: { + one: { + on: { NEXT: { target: 'two' } } + }, + two: {} + } + }); + + const machine = createMachine({ + schemas: { + context: z.object({ + ref: z.custom>() + }) + }, + context: ({ spawn }) => ({ + ref: spawn(childMachine) + }), + initial: 'waiting', + states: { + waiting: { + on: { TEST: { target: 'success' } } + }, + success: { + type: 'final' + } + } + }); + + const App = () => { + const actorRef = useActorRef(machine); + const childRef = useSelector(actorRef, (s) => s.context.ref); + const childState = useSelector(childRef, (s) => s); + + return ( + <> +
{childState.value as string}
+ + + ); + }; + + render(); + + const elState = screen.getByTestId('child-state'); + const elSend = screen.getByTestId('child-send'); + + expect(elState.textContent).toEqual('one'); + fireEvent.click(elSend); + + expect(elState.textContent).toEqual('two'); + }); + + it('should not log any spurious errors when used with a not-started actor', () => { + const spy = vi.fn(); + console.error = spy; + + const machine = createMachine({}); + const App = () => { + useSelector(useActorRef(machine), (s) => s); + + return null; + }; + + render(); + + expect(spy).not.toHaveBeenCalled(); + }); + + it('should work with an optional actor', () => { + const Child = (props: { + actor: + | ActorRef, any> + | undefined; + }) => { + const state = useSelector(props.actor, (s) => s); + + // @ts-expect-error + ((_accept: { count: number }) => {})(state?.context); + ((_accept: { count: number } | undefined) => {})(state?.context); + + return ( +
{state?.context?.count ?? 'undefined'}
+ ); + }; + + const App = () => { + const [actor, setActor] = + React.useState< + ActorRef, any> + >(); + + return ( + <> + + + + ); + }; + + render(); + + const button = screen.getByTestId('button'); + const stateEl = screen.getByTestId('state'); + + expect(stateEl.textContent).toBe('undefined'); + + fireEvent.click(button); + + expect(stateEl.textContent).toBe('42'); + }); + + // v6: In strict mode, the stop/restart cycle doesn't restart invoked + // children (promise actors), so the error never propagates + it('should throw an error to an error boundary when the actor reaches an error state', async () => { + const errorMessage = 'test_useSelector_error'; + + const machine = createMachine({ + initial: 'loading', + states: { + loading: { + invoke: { + src: createAsyncLogic({ + run: () => Promise.reject(new Error(errorMessage)) + }) + } + } + } + }); + + class ErrorBoundary extends React.Component< + { children: React.ReactNode }, + { error: Error | null } + > { + state = { error: null as Error | null }; + static getDerivedStateFromError(error: Error) { + return { error }; + } + render() { + if (this.state.error) { + return
{this.state.error.message}
; + } + return this.props.children; + } + } + + const App = () => { + const actorRef = useActorRef(machine); + const value = useSelector(actorRef, (s) => s.value); + return
{String(value)}
; + }; + + console.error = vi.fn(); + + render( + + + + ); + + await screen.findByTestId('error'); + expect(screen.getByTestId('error').textContent).toBe(errorMessage); + }); +}); diff --git a/xstate-react/test/utils.tsx b/xstate-react/test/utils.tsx new file mode 100644 index 00000000..940ff1c2 --- /dev/null +++ b/xstate-react/test/utils.tsx @@ -0,0 +1,37 @@ +import * as React from 'react'; +import * as RTL from '@testing-library/react'; + +// TS trips over signatures with generic overloads when using bare `typeof RTL.render` +// conditional types just resolve the last overload +// and that is enough for us here +type SimplifiedRTLRender = ( + ...args: Parameters +) => ReturnType; + +const reactModes = [ + ['non-strict', React.Fragment], + ['strict', React.StrictMode] +] as const; + +export function describeEachReactMode( + name: string, + fn: (suiteCase: { + suiteKey: (typeof reactModes)[number][0]; + render: SimplifiedRTLRender; + }) => void +) { + describe.each(reactModes)(name, (suiteKey, Wrapper) => { + const render: SimplifiedRTLRender = (ui, ...rest) => + RTL.render({ui}, ...rest); + + fn({ + suiteKey, + render: (...args) => { + const renderResult = render(...args); + const { rerender } = renderResult; + renderResult.rerender = (ui) => rerender({ui}); + return renderResult; + } + }); + }); +} diff --git a/xstate-store-react/CHANGELOG.md b/xstate-store-react/CHANGELOG.md new file mode 100644 index 00000000..852a0de0 --- /dev/null +++ b/xstate-store-react/CHANGELOG.md @@ -0,0 +1,133 @@ +# @xstate/store-react + +## 2.1.0-alpha.3 + +### Patch Changes + +- Updated dependencies [c27b509] + - @xstate/store@5.0.0-alpha.5 + +## 2.1.0-alpha.2 + +### Patch Changes + +- 69b6663: Keep selected values current when subscriptions start or resume. Vue and Solid now expose terminal error snapshots, and Solid preserves array/object context changes without changing the actor's source data. Vue uses one snapshot subscription per `useActor` call. + + React store selectors now honor custom comparisons when the selector argument is omitted. +- Updated dependencies [69b6663] +- Updated dependencies [69b6663] +- Updated dependencies [69b6663] +- Updated dependencies [69b6663] + - @xstate/store@4.3.0-alpha.3 + +## 2.1.0-alpha.1 + +### Minor Changes + +- c57f80e: The `useStore` hook now accepts an `inspect` option for wiring up inspectors to component-local stores. The inspector is subscribed while the option is provided and stays stable across re-renders. + + ```tsx + import { useStore, useSelector } from '@xstate/store-react'; + import { createBrowserInspector } from '@statelyai/inspect'; + + const inspector = createBrowserInspector(); + + function Counter() { + const store = useStore( + { + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }, + { inspect: inspector.inspect } + ); + const count = useSelector(store, (s) => s.context.count); + + return ; + } + ``` + +## 2.0.1-alpha.0 + +### Patch Changes + +- [#5543](https://github.com/statelyai/xstate/pull/5543) [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `compare` function passed to `useSelector` is now typed as `(a: T, b: T)` instead of `(a: T | undefined, b: T)`, so the previous value is no longer typed as possibly `undefined`. + +- Updated dependencies [[`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925)]: + - @xstate/store@4.3.0-alpha.0 + +## 2.0.0 + +### Major Changes + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Modernize Store v4 package entrypoints. + + Use framework-specific packages such as `@xstate/store-react` and `@xstate/store-solid` instead of `@xstate/store/react` or `@xstate/store/solid`. The Store packages now publish ESM package entrypoints. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `createStoreLogic(...)` for reusable store definitions, and support creating stores from logic in framework hooks. + + ```ts + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }); + + const store = useStore(counterLogic, { initialCount: 0 }); + ``` + + If a store logic requires input, the input argument is also required: + + ```ts + useStore(counterLogic, { initialCount: 0 }); + ``` + + Framework hooks also preserve schema-derived context, event, and emitted event types when creating stores from config objects. + +### Minor Changes + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add reusable atom configs and framework atom-state helpers. + + `createAtomConfig(...)` creates an inert atom definition that can be instantiated with its `createAtom(...)` method or React/Preact/Vue/Solid's `useAtomState(...)`. These helpers return the current framework-native value and live atom instance, and also work with existing atom instances. + + ```ts + const countConfig = createAtomConfig((input: { initialCount: number }) => { + return input.initialCount; + }); + + function Counter() { + const [count, countAtom] = useAtomState(countConfig, { initialCount: 0 }); + + return ( + + ); + } + ``` + +### Patch Changes + +- Updated dependencies [[`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69), [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69)]: + - @xstate/store@4.0.0 + +## 1.0.1 + +### Patch Changes + +- [`d6498eb`](https://github.com/statelyai/xstate/commit/d6498eb8e98100e4977e036904a04714089571e4) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added README.md + +## 1.0.0 + +### Major Changes + +- [#5441](https://github.com/statelyai/xstate/pull/5441) [`6ba9538`](https://github.com/statelyai/xstate/commit/6ba9538e05022c9aad9e4a4f089a87aaed54c06a) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Initial release for `@xstate/store-react`. + +### Patch Changes + +- Updated dependencies [[`6ba9538`](https://github.com/statelyai/xstate/commit/6ba9538e05022c9aad9e4a4f089a87aaed54c06a)]: + - @xstate/store@3.15.0 diff --git a/xstate-store-react/LICENSE b/xstate-store-react/LICENSE new file mode 100644 index 00000000..fc1fe941 --- /dev/null +++ b/xstate-store-react/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Khourshid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/xstate-store-react/README.md b/xstate-store-react/README.md new file mode 100644 index 00000000..d490cffa --- /dev/null +++ b/xstate-store-react/README.md @@ -0,0 +1,187 @@ +# @xstate/store-react + +React adapter for [@xstate/store](https://stately.ai/docs/xstate-store). + +## Installation + +```bash +npm install @xstate/store-react +``` + +## Quickstart + +```tsx +import { createStore, useSelector } from '@xstate/store-react'; +// ... + +const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } +}); + +const App = () => { + const count = useSelector(store, (s) => s.context.count); + + return ( + + ); +}; +``` + +## API + + +### `useSelector(store, selector?, compare?)` + +Subscribes to a store and returns a selected value. + +```tsx +import { createStore, useSelector } from '@xstate/store-react'; +// ... + +const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } +}); + +const App = () => { + const count = useSelector(store, (s) => s.context.count); + // or without selector (returns full snapshot) + const snapshot = useSelector(store); + // ... +}; +``` + +**Arguments:** + +- `store` - Store or other readable value created with `createStore()` +- `selector?` - Function to select a value from snapshot +- `compare?` - Equality function (default: `===`). Also applies to the full snapshot when `selector` is `undefined`. + +**Returns:** Selected value (re-renders on change) + +--- + + + +### `useStore(definition, options?)` + +Creates a store instance scoped to a component. + +```tsx +import { useStore, useSelector } from '@xstate/store-react'; +// ... + +const App = () => { + const store = useStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } + }); + + const count = useSelector(store, (s) => s.context.count); + // ... +}; +``` + +To wire up an inspector, pass a stable `inspect` callback. The inspector is subscribed while the option is provided and unsubscribed when it is removed or the component unmounts. Stores emit `@xstate.transition` events. With `@statelyai/inspect`, forward these through its public `snapshot()` method; its `inspect` observer accepts the XState v5 inspection protocol. + +```tsx +import type { StoreInspectionEvent } from '@xstate/store'; +import { createBrowserInspector } from '@statelyai/inspect'; + +// Outside the component: keep the callback stable between renders. +const inspector = createBrowserInspector(); +const inspectStore = (event: StoreInspectionEvent) => { + inspector.snapshot(event.actorRef, event.snapshot, { event: event.event }); +}; + +// Inside the component: +const store = useStore( + { + context: { count: 0 }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } + }, + { inspect: inspectStore } +); +``` + +**Arguments:** + +- `definition` - Store configuration object, or store logic created with `createStoreLogic()` (followed by its `input`) +- `options?` - Options object: + - `inspect?` - Observer or callback that receives [inspection events](https://stately.ai/docs/inspection) from the store + +**Returns:** Store instance (stable across re-renders) + +--- + +### `useAtom(atom, selector?, compare?)` + +Subscribes to an atom and returns its value. + +```tsx +import { createAtom, useAtom } from '@xstate/store-react'; +// ... + +const countAtom = createAtom(0); + +const App = () => { + const count = useAtom(countAtom); + + return ; +}; +``` + +**Arguments:** + +- `atom` - Atom created with `createAtom()` +- `selector?` - Selector function +- `compare?` - Equality function + +**Returns:** Atom value (re-renders on change) + +--- + +### `createStoreHook(definition)` + +Creates a custom hook that returns `[selectedValue, store]`. + +```tsx +import { createStoreHook } from '@xstate/store-react'; +// ... + +const useCountStore = createStoreHook({ + context: { count: 0 }, + on: { + inc: (ctx, e: { by: number }) => ({ ...ctx, count: ctx.count + e.by }) + } +}); + +const App = () => { + const [count, store] = useCountStore((s) => s.context.count); + + return ; +}; +``` + +**Arguments:** + +- `definition` - Store configuration object + +**Returns:** Custom hook function + +--- + +## Re-exports + +All exports from `@xstate/store` are re-exported, including `createStore`, `createAtom`, and more. + +See the [XState Store docs](https://stately.ai/docs/xstate-store) for the full API, and the [React-specific docs](https://stately.ai/docs/xstate-store#react) for more React examples. diff --git a/xstate-store-react/package.json b/xstate-store-react/package.json new file mode 100644 index 00000000..e6849be0 --- /dev/null +++ b/xstate-store-react/package.json @@ -0,0 +1,50 @@ +{ + "name": "@xstate/store-react", + "version": "2.1.0-alpha.3", + "type": "module", + "description": "XState Store for React", + "keywords": [ + "store", + "state", + "react", + "hook" + ], + "author": "David Khourshid ", + "homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-store-react#readme", + "license": "MIT", + "exports": { + ".": "./dist/xstate-store-react.js", + "./package.json": "./package.json" + }, + "types": "dist/xstate-store-react.cjs.d.ts", + "sideEffects": false, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/statelyai/xstate.git" + }, + "bugs": { + "url": "https://github.com/statelyai/xstate/issues" + }, + "dependencies": { + "@xstate/store": "workspace:^" + }, + "peerDependencies": { + "react": "^18.0.0 || ^19.0.0" + }, + "devDependencies": { + "@testing-library/react": "^16.2.0", + "@types/react": "^19.0.10", + "@types/react-dom": "^19.0.4", + "react": "^19.0.0", + "react-dom": "^19.0.0", + "zod": "^4.4.3" + }, + "preconstruct": { + "entrypoints": [ + "./index.ts" + ] + } +} diff --git a/xstate-store-react/src/index.test.tsx b/xstate-store-react/src/index.test.tsx new file mode 100644 index 00000000..d2eeeaf3 --- /dev/null +++ b/xstate-store-react/src/index.test.tsx @@ -0,0 +1,476 @@ +import { fireEvent, screen, render, act } from '@testing-library/react'; +import { + createStore, + createStoreLogic, + createAtom, + createAtomConfig, + useSelector, + useStore, + useAtom, + useAtomState, + createStoreHook, + type StoreInspectionEvent +} from './index.ts'; + +describe('@xstate/store-react', () => { + describe('useSelector', () => { + it('should work with a selector', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } + }); + + const Counter = () => { + const count = useSelector(store, (s) => s.context.count); + return ( +
store.send({ type: 'inc' })}> + {count} +
+ ); + }; + + render(); + + const countDiv = screen.getByTestId('count'); + expect(countDiv.textContent).toEqual('0'); + + fireEvent.click(countDiv); + expect(countDiv.textContent).toEqual('1'); + }); + + it('should work without a selector (full snapshot)', () => { + const store = createStore({ + context: { count: 0 }, + on: {} + }); + + const Counter = () => { + const snapshot = useSelector(store); + return
{snapshot.context.count}
; + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('0'); + }); + + it('should work with atoms', () => { + const atom = createAtom(0); + + const Counter = () => { + const count = useSelector(atom, (s) => s); + return ( +
atom.set((prev) => prev + 1)}> + {count} +
+ ); + }; + + render(); + + expect(screen.getByTestId('count').textContent).toEqual('0'); + fireEvent.click(screen.getByTestId('count')); + expect(screen.getByTestId('count').textContent).toEqual('1'); + }); + + it('should run compare for falsy selected values', () => { + const store = createStore({ + context: { count: 0, label: 'ready' }, + on: { + rename: (ctx, ev: { label: string }) => ({ ...ctx, label: ev.label }) + } + }); + const compare = vi.fn((a: number | undefined, b: number) => a === b); + + const Counter = () => { + const count = useSelector(store, (s) => s.context.count, compare); + return
{count}
; + }; + + render(); + + act(() => { + store.send({ type: 'rename', label: 'done' }); + }); + + expect(compare).toHaveBeenCalledWith(0, 0); + }); + }); + + describe('useStore', () => { + it('should create a stable store reference', () => { + let storeRefs: object[] = []; + + const Counter = () => { + const store = useStore({ + context: { count: 0 }, + on: { + inc: (ctx: { count: number }) => ({ ...ctx, count: ctx.count + 1 }) + } + }); + + storeRefs.push(store); + const count = useSelector(store, (s) => s.context.count); + + return ( +
store.send({ type: 'inc' })}> + {count} +
+ ); + }; + + render(); + const countDiv = screen.getByTestId('count'); + + expect(countDiv.textContent).toBe('0'); + fireEvent.click(countDiv); + expect(countDiv.textContent).toBe('1'); + expect(storeRefs.every((ref) => ref === storeRefs[0])).toBe(true); + }); + + it('should create a stable store from store logic and input', () => { + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }); + let storeRefs: object[] = []; + + const Counter = () => { + const store = useStore(counterLogic, { initialCount: 10 }); + storeRefs.push(store); + const count = useSelector(store, (s) => s.context.count); + + return ( +
store.trigger.inc()}> + {count} +
+ ); + }; + + render(); + const countDiv = screen.getByTestId('count'); + + expect(countDiv.textContent).toBe('10'); + fireEvent.click(countDiv); + expect(countDiv.textContent).toBe('11'); + expect(storeRefs.every((ref) => ref === storeRefs[0])).toBe(true); + }); + + it('should subscribe an inspector via the inspect option', () => { + const events: string[] = []; + + const Counter = () => { + const store = useStore( + { + context: { count: 0 }, + on: { + inc: (ctx: { count: number }) => ({ count: ctx.count + 1 }) + } + }, + { inspect: (ev) => events.push(ev.event.type) } + ); + const count = useSelector(store, (s) => s.context.count); + + return ( +
store.send({ type: 'inc' })}> + {count} +
+ ); + }; + + const { unmount } = render(); + + // the inspector immediately receives the current snapshot + expect(events).toEqual(['@xstate.init']); + + fireEvent.click(screen.getByTestId('count')); + expect(events).toEqual(['@xstate.init', 'inc']); + + const countBeforeUnmount = events.length; + unmount(); + expect(events.length).toBe(countBeforeUnmount); + }); + + it('should not resubscribe the inspector across re-renders', () => { + const snapshotEvents: string[] = []; + + const Counter = () => { + const store = useStore( + { + context: { count: 0 }, + on: { + inc: (ctx: { count: number }) => ({ count: ctx.count + 1 }) + } + }, + { inspect: (ev) => snapshotEvents.push(ev.event.type) } + ); + const count = useSelector(store, (s) => s.context.count); + + return ( +
store.send({ type: 'inc' })}> + {count} +
+ ); + }; + + render(); + const countDiv = screen.getByTestId('count'); + + fireEvent.click(countDiv); + fireEvent.click(countDiv); + + // 1 init event on subscribe + 1 per transition; no duplicates from + // re-render resubscription + expect(snapshotEvents).toEqual(['@xstate.init', 'inc', 'inc']); + }); + + it('should subscribe an inspector enabled after mount', () => { + const events: string[] = []; + + const Counter = ({ + inspect + }: { + inspect?: (event: StoreInspectionEvent) => void; + }) => { + const store = useStore( + { + context: { count: 0 }, + on: { + inc: (ctx: { count: number }) => ({ count: ctx.count + 1 }) + } + }, + { inspect } + ); + + return ; + }; + + const { rerender } = render(); + rerender( events.push(event.event.type)} />); + + expect(events).toEqual(['@xstate.init']); + + fireEvent.click(screen.getByRole('button')); + expect(events).toEqual(['@xstate.init', 'inc']); + }); + + it('should support the inspect option with store logic and input', () => { + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }); + const events: string[] = []; + + const Counter = () => { + const store = useStore( + counterLogic, + { initialCount: 10 }, + { inspect: (ev) => events.push(ev.event.type) } + ); + const count = useSelector(store, (s) => s.context.count); + + return ( +
store.trigger.inc()}> + {count} +
+ ); + }; + + render(); + + expect(screen.getByTestId('count').textContent).toBe('10'); + expect(events).toEqual(['@xstate.init']); + }); + }); + + describe('useAtom', () => { + it('should return the atom value', () => { + const atom = createAtom(42); + + const TestComponent = () => { + const value = useAtom(atom); + return
{value}
; + }; + + render(); + expect(screen.getByTestId('value').textContent).toBe('42'); + }); + + it('should update when atom changes', () => { + const atom = createAtom(0); + + const TestComponent = () => { + const count = useAtom(atom); + return ( +
+
{count}
+ +
+ ); + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('0'); + + act(() => { + fireEvent.click(screen.getByTestId('increment')); + }); + expect(screen.getByTestId('count').textContent).toBe('1'); + }); + + it('should create a stable atom value from atom config and input', () => { + const config = createAtomConfig((input: { initialCount: number }) => { + return input.initialCount; + }); + + const TestComponent = () => { + const count = useAtom(config, { initialCount: 10 }); + + return
{count}
; + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('10'); + }); + }); + + describe('useAtomState', () => { + it('should return the value and existing atom', () => { + const atom = createAtom(0); + const atomRefs: object[] = []; + + const TestComponent = () => { + const [count, countAtom] = useAtomState(atom); + atomRefs.push(countAtom); + return ( +
+
{count}
+ +
+ ); + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('0'); + + act(() => { + fireEvent.click(screen.getByTestId('increment')); + }); + + expect(screen.getByTestId('count').textContent).toBe('1'); + expect(atomRefs.every((ref) => ref === atom)).toBe(true); + }); + + it('should create a stable atom from atom config and input', () => { + const config = createAtomConfig((input: { initialCount: number }) => { + return input.initialCount; + }); + const atomRefs: object[] = []; + + const TestComponent = () => { + const [count, countAtom] = useAtomState(config, { initialCount: 10 }); + atomRefs.push(countAtom); + return ( +
+
{count}
+ +
+ ); + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('10'); + + act(() => { + fireEvent.click(screen.getByTestId('increment')); + }); + + expect(screen.getByTestId('count').textContent).toBe('11'); + expect(atomRefs.every((ref) => ref === atomRefs[0])).toBe(true); + }); + }); + + describe('createStoreHook', () => { + it('should create a reusable store hook', () => { + const useCountStore = createStoreHook({ + context: { count: 0 }, + on: { + inc: (ctx: { count: number }) => ({ ...ctx, count: ctx.count + 1 }) + } + }); + + const Counter = () => { + const [count, store] = useCountStore((s) => s.context.count); + return ( +
+
{count}
+ +
+ ); + }; + + render(); + expect(screen.getByTestId('count').textContent).toBe('0'); + + fireEvent.click(screen.getByRole('button')); + expect(screen.getByTestId('count').textContent).toBe('1'); + }); + }); + + describe('re-exports', () => { + it('should re-export createStore from @xstate/store', () => { + expect(createStore).toBeDefined(); + const store = createStore({ + context: { value: 'test' }, + on: {} + }); + expect(store.get().context.value).toBe('test'); + }); + + it('should re-export createAtom from @xstate/store', () => { + expect(createAtom).toBeDefined(); + const atom = createAtom(123); + expect(atom.get()).toBe(123); + }); + }); +}); + +it('honors a comparator when the selector is omitted', () => { + const atom = createAtom({ count: 0, ignored: 0 }); + let renders = 0; + function View() { + const value = useSelector(atom, undefined, (a, b) => a?.count === b?.count); + renders++; + return
{value.count}
; + } + render(); + const initialRenders = renders; + act(() => atom.set({ count: 0, ignored: 1 })); + expect(renders).toBe(initialRenders); + act(() => atom.set({ count: 1, ignored: 1 })); + expect(screen.getByText('1')).toBeTruthy(); +}); diff --git a/xstate-store-react/src/index.ts b/xstate-store-react/src/index.ts new file mode 100644 index 00000000..be15baf2 --- /dev/null +++ b/xstate-store-react/src/index.ts @@ -0,0 +1,387 @@ +export * from '@xstate/store'; + +import { useCallback, useEffect, useRef, useSyncExternalStore } from 'react'; +import { + type AnyStoreConfig, + type AnyStoreLogicCreator, + type StoreFromStoreLogicCreator, + type StoreFromStoreConfig, + type InputFromStoreLogicCreator, + type Readable, + type AnyAtom, + type AnyAtomConfig, + type AtomConfig, + type BaseAtom, + type InputFromAtomConfig, + type ValueFromAtomConfig, + type StoreSnapshot, + type ContextFromStoreConfig, + type Observer, + type StoreInspectionEvent, + createStore, + isAtom +} from '@xstate/store'; + +function defaultCompare(a: T, b: T) { + return a === b; +} + +function identity(snapshot: T): T { + return snapshot; +} + +function useSelectorWithCompare( + selector: (snapshot: TSnapshot) => T, + compare: (a: T, b: T) => boolean +): (snapshot: TSnapshot) => T { + const previous = useRef(undefined); + + return (snapshot) => { + const next = selector(snapshot); + return previous.current !== undefined && compare(previous.current, next) + ? previous.current + : (previous.current = next); + }; +} + +function createStoreFromDefinition( + definition: TDefinition +): StoreFromStoreConfig; +function createStoreFromDefinition(definition: AnyStoreConfig) { + return createStore(definition); +} + +type StoreDefinition = AnyStoreConfig | AnyStoreLogicCreator; + +type StoreFromStoreDefinition = + TDefinition extends AnyStoreLogicCreator + ? StoreFromStoreLogicCreator + : TDefinition extends AnyStoreConfig + ? StoreFromStoreConfig + : never; + +interface UseStoreOptions { + /** + * An observer or callback that receives [inspection + * events](https://stately.ai/docs/inspection) from the store. Subscribed + * while provided; stable across re-renders. + */ + inspect?: + | Observer + | ((inspectionEvent: StoreInspectionEvent) => void); +} + +type UseStoreArgs = + TDefinition extends AnyStoreLogicCreator + ? undefined extends InputFromStoreLogicCreator + ? [ + logic: TDefinition, + input?: InputFromStoreLogicCreator, + options?: UseStoreOptions + ] + : [ + logic: TDefinition, + input: InputFromStoreLogicCreator, + options?: UseStoreOptions + ] + : [definition: TDefinition, options?: UseStoreOptions]; + +type AtomDefinition = BaseAtom | AnyAtomConfig; + +type AtomStateFromDefinition = + TDefinition extends AnyAtomConfig + ? readonly [ + value: ValueFromAtomConfig, + atom: ReturnType + ] + : TDefinition extends BaseAtom + ? readonly [value: TValue, atom: TDefinition] + : never; + +type UseAtomStateArgs = + TDefinition extends AnyAtomConfig + ? undefined extends InputFromAtomConfig + ? [config: TDefinition, input?: InputFromAtomConfig] + : [config: TDefinition, input: InputFromAtomConfig] + : [atom: TDefinition]; + +type AtomConfigInput = undefined extends TInput + ? [input?: TInput] + : [input: TInput]; + +/** + * A React hook that subscribes to the `store` and selects a value from the + * store's snapshot via a selector function, with an optional compare function. + * + * @example + * + * ```ts + * function Component() { + * const count = useSelector(store, (s) => s.count); + * + * return
{count}
; + * } + * ``` + * + * @param store The store, created from `createStore(…)` + * @param selector A function which takes in the `snapshot` and returns a + * selected value + * @param compare An optional function which compares the selected value to the + * previous value + * @returns The selected value + */ +export function useSelector( + store: Readable, + selector: (snapshot: TSnapshot) => T, + compare?: (a: T, b: T) => boolean +): T; +/** + * A React hook that subscribes to the `store` and selects a value from the + * store's snapshot via an optional selector function (identity by default), + * with an optional compare function. + * + * @example + * + * ```ts + * function Component() { + * const countSnapshot = useSelector(store); + * + * return
{countSnapshot.context.count}
; + * } + * ``` + * + * @param store The store, created from `createStore(…)` + * @param selector An optional function which takes in the `snapshot` and + * returns a selected value + * @param compare An optional function which compares the selected value to the + * previous value + * @returns The selected value + */ +export function useSelector( + store: Readable, + selector?: undefined, + compare?: (a: TSnapshot | undefined, b: TSnapshot | undefined) => boolean +): TSnapshot; +export function useSelector( + store: Readable, + selector?: (snapshot: TSnapshot) => T, + compare: (a: T, b: T) => boolean = defaultCompare +): T | TSnapshot { + const subscribe = useCallback( + (handleStoreChange: () => void) => + store.subscribe(handleStoreChange).unsubscribe, + [store] + ); + + const selectorWithCompare = useSelectorWithCompare( + (selector ?? identity) as (snapshot: TSnapshot) => T, + compare + ); + + return useSyncExternalStore( + subscribe, + () => selectorWithCompare(store.get()), + () => selectorWithCompare(store.get()) + ); +} + +/** + * Creates a stable store instance for the lifetime of a React component. + * + * Pass `options.inspect` to subscribe an inspector to the store. The + * subscription is removed when the inspector is removed or on unmount. + * + * @example + * + * ```ts + * function Counter() { + * const store = useStore( + * { + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }, + * { inspect: inspector.inspect } + * ); + * // … + * } + * ``` + */ +export function useStore( + ...args: UseStoreArgs +): StoreFromStoreDefinition { + const [definition] = args; + const isLogic = 'createStore' in definition; + const input = isLogic ? args[1] : undefined; + const options = (isLogic ? args[2] : args[1]) as UseStoreOptions | undefined; + + const storeRef = useRef(undefined); + + if (!storeRef.current) { + storeRef.current = isLogic + ? definition.createStore(input) + : createStoreFromDefinition(definition); + } + + const inspectRef = useRef(options?.inspect); + inspectRef.current = options?.inspect; + const shouldInspect = options?.inspect !== undefined; + + useEffect(() => { + if (!inspectRef.current) { + return; + } + return storeRef.current.inspect((inspectionEvent: StoreInspectionEvent) => { + const inspect = inspectRef.current; + if (typeof inspect === 'function') { + inspect(inspectionEvent); + } else { + inspect?.next?.(inspectionEvent); + } + }).unsubscribe; + }, [shouldInspect]); + + return storeRef.current; +} + +/** + * A React hook that subscribes to the `atom` and returns the current value of + * the atom. + * + * @example + * + * ```ts + * const atom = createAtom(0); + * + * const Component = () => { + * const count = useAtom(atom); + * + * return ( + *
+ *
{count}
+ * + *
+ * ); + * }; + * ``` + * + * @param atom The atom, created from `createAtom(…)` + * @param selector An optional function which takes in the `snapshot` and + * returns a selected value + * @param compare An optional function which compares the selected value to the + * previous value + */ +export function useAtom(atom: BaseAtom): T; +export function useAtom( + config: AtomConfig, + ...input: AtomConfigInput +): TValue; +export function useAtom( + atom: BaseAtom, + selector: (snapshot: T) => S, + compare?: (a: S, b: S) => boolean +): S; +export function useAtom( + definition: AnyAtom | AtomConfig, + selectorOrInput?: any, + compare = defaultCompare +) { + const atomRef = useRef(undefined); + + if (isAtom(definition)) { + return useSelector(definition, selectorOrInput ?? identity, compare); + } + + if (!atomRef.current) { + atomRef.current = definition.createAtom(selectorOrInput); + } + + const state = useSelector(atomRef.current, identity, compare); + + return state; +} + +/** + * Creates or subscribes to an atom for the lifetime of a React component. + * + * Pass an existing atom to receive `[value, atom]`, or pass an atom config + * created with `createAtomConfig(...)` to create a stable local atom. + */ +export function useAtomState( + ...[definition, input]: UseAtomStateArgs +): AtomStateFromDefinition { + const atomRef = useRef(undefined); + + if (!atomRef.current) { + atomRef.current = isAtom(definition) + ? definition + : definition.createAtom(input); + } + + const value = useAtom(atomRef.current); + + return [ + value, + atomRef.current + ] as unknown as AtomStateFromDefinition; +} + +/** + * Creates a custom hook that returns the selected value and the store from a + * store configuration object. + * + * @example + * + * ```ts + * const useCountStore = createStoreHook({ + * context: { count: 0 }, + * on: { + * inc: (context, event: { by: number }) => ({ + * ...context, + * count: context.count + event.by + * }) + * } + * }); + * + * function Component() { + * const [count, store] = useCountStore(s => s.context.count); + * + * return ( + *
+ * {count} + * + *
+ * ); + * } + * ``` + * + * @param definition The store configuration object + * @returns A custom hook that returns [selectedValue, store] + */ +export function createStoreHook( + definition: TDefinition +) { + type TStore = StoreFromStoreConfig; + type TSnapshot = StoreSnapshot>; + + const store = createStoreFromDefinition(definition); + + function useStoreHook(): [TSnapshot, TStore]; + function useStoreHook( + selector: (snapshot: TSnapshot) => T, + compare?: (a: T, b: T) => boolean + ): [T, TStore]; + function useStoreHook( + selector?: (snapshot: TSnapshot) => T, + compare: (a: T, b: T) => boolean = defaultCompare + ) { + if (!selector) { + const snapshot = useSelector(store); + return [snapshot, store]; + } + + const selectedValue = useSelector(store, selector, compare); + return [selectedValue, store]; + } + + return useStoreHook; +} diff --git a/xstate-store-react/src/types.test.tsx b/xstate-store-react/src/types.test.tsx new file mode 100644 index 00000000..fdf320a3 --- /dev/null +++ b/xstate-store-react/src/types.test.tsx @@ -0,0 +1,251 @@ +import { + createAtom, + createAtomConfig, + createStoreHook, + createStoreLogic, + useAtom, + useAtomState, + useStore +} from './index.ts'; +import { z } from 'zod'; + +describe('@xstate/store-react types', () => { + it('uses atom config input in useAtomState', () => { + const countAtom = createAtom(0); + const countConfig = createAtomConfig( + (input: { initialCount: number }) => input.initialCount + ); + const optionalInputConfig = createAtomConfig( + (_input?: { initialCount?: number }) => 0 + ); + const noInputConfig = createAtomConfig(0); + + const Component = () => { + const [liveValue, liveAtom] = useAtomState(countAtom); + liveValue satisfies number; + liveAtom.set(1); + + const atomValue = useAtom(countConfig, { initialCount: 1 }); + atomValue satisfies number; + + useAtom(optionalInputConfig); + useAtom(optionalInputConfig, { initialCount: 1 }); + useAtom(noInputConfig); + + useAtomState( + countConfig, + // @ts-expect-error required input + undefined + ); + + const [count, atom] = useAtomState(countConfig, { initialCount: 1 }); + count satisfies number; + atom.set((prev) => prev + 1); + + useAtomState(countConfig, { + // @ts-expect-error wrong input + initialCount: 'one' + }); + + useAtomState(optionalInputConfig); + useAtomState(optionalInputConfig, { initialCount: 1 }); + useAtomState(noInputConfig); + + useAtomState( + noInputConfig, + // @ts-expect-error no input + {} + ); + + return null; + }; + + Component; + }); + + it('uses store logic input in useStore', () => { + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }); + const optionalInputLogic = createStoreLogic({ + context: (_input?: { initialCount?: number }) => ({ count: 0 }), + on: {} + }); + const noInputLogic = createStoreLogic({ + context: { count: 0 }, + on: {} + }); + + const Component = () => { + // @ts-expect-error required input + useStore(counterLogic); + + // @ts-expect-error required input + useStore(counterLogic, undefined); + + const store = useStore(counterLogic, { initialCount: 1 }); + store.getSnapshot().context.count satisfies number; + + // @ts-expect-error wrong input + useStore(counterLogic, { initialCount: 'one' }); + + useStore(optionalInputLogic); + useStore(optionalInputLogic, { initialCount: 1 }); + useStore(noInputLogic); + + // @ts-expect-error no input + useStore(noInputLogic, {}); + + return null; + }; + + Component; + }); + + it('infers schemas in useStore', () => { + const Component = () => { + const store = useStore({ + schemas: { + context: z.object({ count: z.number(), label: z.string() }), + events: { + rename: z.object({ label: z.string() }) + }, + emitted: { + renamed: z.object({ label: z.string() }) + } + }, + context: { + count: 0, + label: 'ready' + }, + on: { + rename: ( + ctx: { count: number; label: string }, + ev: { label: string } + ) => { + return { + ...ctx, + label: ev.label + }; + } + } + }); + + store.getSnapshot().context.label satisfies string; + store.trigger.rename({ label: 'done' }); + + store.on('renamed', (event) => { + event.label satisfies string; + }); + + if (false) { + store.trigger.rename( + // @ts-expect-error + {} + ); + + store.on( + // @ts-expect-error + 'unknown', + () => {} + ); + } + + return null; + }; + }); + + it('preserves inferred events when only emitted schemas are declared in useStore', () => { + const Component = () => { + const store = useStore({ + schemas: { + emitted: { + logged: z.object({ message: z.string() }) + } + }, + context: {}, + on: { + log: (ctx: {}, ev: { message: string }) => { + return ctx; + } + } + }); + + store.trigger.log({ message: 'hello' }); + + if (false) { + store.trigger.log( + // @ts-expect-error + {} + ); + + // @ts-expect-error + store.trigger.unknown(); + } + + return null; + }; + }); + + it('infers schemas in createStoreHook', () => { + const useCounterStore = createStoreHook({ + schemas: { + context: z.object({ count: z.number(), label: z.string() }), + events: { + rename: z.object({ label: z.string() }) + }, + emitted: { + renamed: z.object({ label: z.string() }) + } + }, + context: { + count: 0, + label: 'ready' + }, + on: { + rename: ( + ctx: { count: number; label: string }, + ev: { label: string } + ) => { + return { + ...ctx, + label: ev.label + }; + } + } + }); + + const Component = () => { + const [snapshot, store] = useCounterStore(); + const [label] = useCounterStore((state) => state.context.label); + + snapshot.context.label satisfies string; + label satisfies string; + + store.trigger.rename({ label: 'done' }); + store.on('renamed', (event) => { + event.label satisfies string; + }); + + if (false) { + store.trigger.rename( + // @ts-expect-error + {} + ); + + store.on( + // @ts-expect-error + 'unknown', + () => {} + ); + } + + return null; + }; + }); +}); diff --git a/xstate-store/CHANGELOG.md b/xstate-store/CHANGELOG.md new file mode 100644 index 00000000..9764606a --- /dev/null +++ b/xstate-store/CHANGELOG.md @@ -0,0 +1,1752 @@ +# @xstate/store + +## 5.0.0-alpha.5 + +### Major Changes + +- c27b509: `fromStore()` now returns XState v6 actor logic and requires `xstate@6`. `xstate` is declared as an optional peer dependency; it is only needed if you use `fromStore()`. Use `@xstate/store@4` with XState v5. + + ```ts + import { createActor } from 'xstate'; + import { fromStore } from '@xstate/store'; + + const logic = fromStore({ context: { count: 0 }, on: { inc: (ctx) => ({ count: ctx.count + 1 }) } }); + const actor = createActor(logic).start(); + actor.send({ type: 'inc' }); + ``` + +## 4.3.0-alpha.4 + +### Patch Changes + +- aa49aee: Removed nonexistent `undo`, `persist`, `reset`, and `validate` entries from the package's `files` field. Subpath imports such as `@xstate/store/undo` are unaffected; they resolve through `exports`. + +## 4.3.0-alpha.3 + +### Patch Changes + +- 69b6663: Fix async atoms losing their dependencies after a request succeeds or fails. + Changing a dependency now reloads the value after settlement, including when a + custom comparator suppresses an equivalent result. +- 69b6663: Persist only committed updates when throttling writes. Capability checks, pure transitions, and rejected updates no longer change pending persisted data. + + Async storage writes now complete in event order per store. `flushStorage(store)` also waits for already queued writes; synchronous storage remains synchronous. +- 69b6663: Fix writable atom updaters accidentally tracking other atoms, and deliver queued + subscriber notifications before rethrowing subscriber errors. + + Preserve live extension state through snapshot undo/redo and custom restore + events. Fix throttled persistence applying `pick` twice or losing changes sent + from `onDone`. Report initial async storage read failures through `onError`, and + make `clearStorage` cancel buffered writes and wait for queued writes before + removing data. + + Improve large batches of triggered events while preserving their processing and + effect order. +- 69b6663: Preserve the latest persisted state when effects or subscriptions synchronously trigger another event. Snapshot and event persistence now retain commit order with immediate or throttled writes. + +## 4.3.0-alpha.2 + +### Patch Changes + +- 0f0d6e2: Fixed `fromStore` actor logic so that emitted events and enqueued effects run again. Previously, `enq.emit(...)` and `enq.effect(...)` inside a transition were silently dropped. + + ```ts + const storeLogic = fromStore({ + context: (count: number) => ({ count }), + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, ev: { by: number }, enq) => { + enq.emit.increased({ upBy: ev.by }); // now emitted + return { ...ctx, count: ctx.count + ev.by }; + } + } + }); + + const actor = createActor(storeLogic, { input: 42 }); + actor.on('increased', (e) => console.log(e.upBy)); + actor.start(); + actor.send({ type: 'inc', by: 8 }); // logs: 8 + ``` + +## 4.3.0-alpha.1 + +### Patch Changes + +- c3f7a9d: Actor logic now returns effects from both regular and initial transitions. + + Hand-written actor logic should return `[snapshot, effects]` from `transition(...)` and provide `initialTransition(...)` for creating the initial `[snapshot, effects]` tuple. `getInitialSnapshot(...)` remains available for snapshot-only reads. + + ```ts + const logic = { + transition: (snapshot, event) => [snapshot, []], + initialTransition: (input, _scope) => [ + { + status: 'active', + output: undefined, + error: undefined, + input + }, + [] + ], + getInitialSnapshot: (scope, input) => + logic.initialTransition(input, scope)[0] + }; + ``` + + `transition(...)` and `initialTransition(...)` continue to return `[snapshot, actions]` for machine logic. + + `fromStore(...)` effects now run after the actor snapshot is committed, so effect callbacks read the updated snapshot from `enqueue.getSnapshot()`. + +## 4.3.0-alpha.0 + +### Minor Changes + +- [#5543](https://github.com/statelyai/xstate/pull/5543) [`52970ea`](https://github.com/statelyai/xstate/commit/52970ea75489305fd7bf1223f9b413770cd6d925) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Export a new `isAtom(value)` helper that returns `true` when a value is an atom (i.e. has `get` and `subscribe` methods). + +## 4.2.3 + +### Patch Changes + +- [#5624](https://github.com/statelyai/xstate/pull/5624) [`d146eaa`](https://github.com/statelyai/xstate/commit/d146eaa1cd7112a289b8b9fffaf5cbb2489e859a) Thanks [@Jaybhade](https://github.com/Jaybhade)! - Fixed snapshot-based undo/redo so that undoing after a redo steps back through history instead of staying put. + + ```ts + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) }, + }).with(undoRedo({ strategy: "snapshot" })); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.inc(); // 3 + store.trigger.undo(); // 2 + store.trigger.undo(); // 1 + store.trigger.redo(); // 2 + store.trigger.undo(); // 1 (previously stayed at 2) + ``` + +## 4.2.2 + +### Patch Changes + +- [#5608](https://github.com/statelyai/xstate/pull/5608) [`fbcbd5a`](https://github.com/statelyai/xstate/commit/fbcbd5a389dd76de74f37dbba675b26abe790ff4) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Allow snapshot-based undo and redo to customize restored context while preserving complete history snapshots. Restoration can enqueue emitted events, effects, and store triggers. + + ```ts + const undoableStore = store.with( + undoRedo({ + strategy: "snapshot", + restore: ({ current, next }) => ({ + ...next, + viewport: current.viewport, + }), + }) + ); + ``` + +## 4.2.1 + +### Patch Changes + +- [#5563](https://github.com/statelyai/xstate/pull/5563) [`2911278`](https://github.com/statelyai/xstate/commit/2911278adc330ed3fd3fc4d376e4a0671cf84bac) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fixed inference for selector `context` parameters when using `createStoreLogic(...)` with an input function. + + ```ts + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount, + }), + selectors: { + count: (context) => context.count, + }, + on: { + inc: (context) => ({ count: context.count + 1 }), + }, + }); + ``` + +## 4.2.0 + +### Minor Changes + +- [#5537](https://github.com/statelyai/xstate/pull/5537) [`28c9961`](https://github.com/statelyai/xstate/commit/28c9961bb679de144962139e68198a2fb4351c39) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Effects enqueued via `enq.effect(...)` now receive an enqueue object with `trigger`, `send`, and `getSnapshot`, so you can dispatch events back into the store after async work and read the latest state — without needing a reference to the store. This is especially useful with `createStoreLogic(...)`, where the store is created per-instance and there's no store to close over. + + ```ts + const storeLogic = createStoreLogic({ + context: () => ({ foo: null, loading: false }), + on: { + fetchFoo: (context, event, enq) => { + enq.effect(({ trigger }) => { + myApi.requestFoo().then((response) => trigger.gotFoo({ response })); + }); + return { ...context, loading: true }; + }, + gotFoo: (context, event) => ({ + ...context, + foo: event.response, + loading: false, + }), + }, + }); + ``` + + Use `trigger` for fully-typed dispatch; `send` is a loosely-typed escape hatch for dynamically-constructed events. After an `await`, the `context` argument is stale — use `getSnapshot()` to read the current state: + + ```ts + enq.effect(async ({ getSnapshot, trigger }) => { + await someAsyncWork(); + if (getSnapshot().context.loading) { + trigger.done(); + } + }); + ``` + +## 4.1.0 + +### Minor Changes + +- [#5530](https://github.com/statelyai/xstate/pull/5530) [`0502c04`](https://github.com/statelyai/xstate/commit/0502c041d0e7fd7826323f867e053e8f5422f59b) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Expose `store.schemas` so integrations can read the store's context, event, and emitted event schemas at runtime. + + ```ts + const store = createStore({ + schemas: { + context: z.object({ count: z.number() }), + events: { + inc: z.object({ by: z.number() }), + }, + }, + context: { count: 0 }, + on: { + inc: (context, event) => ({ count: context.count + event.by }), + }, + }); + + store.schemas?.events?.inc; + ``` + +## 4.0.0 + +### Major Changes + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Remove `createStoreWithProducer`. Use `(ctx, ev) => produce(ctx, draft => …)` in `createStore` event handlers instead. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added `enq.trigger` for enqueueing store events from transitions. + + ```ts + const store = createStore({ + schemas: { + events: { + inc: z.object({}), + incTwice: z.object({}), + }, + }, + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }), + incTwice: (context, _event, enq) => { + enq.trigger.inc(); + enq.trigger.inc(); + + return context; + }, + }, + }); + ``` + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Modernize Store v4 package entrypoints. + + Use framework-specific packages such as `@xstate/store-react` and `@xstate/store-solid` instead of `@xstate/store/react` or `@xstate/store/solid`. The Store packages now publish ESM package entrypoints. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `createStoreLogic(...)` for reusable store definitions, and support creating stores from logic in framework hooks. + + ```ts + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount, + }), + on: { + inc: (context) => ({ count: context.count + 1 }), + }, + }); + + const store = useStore(counterLogic, { initialCount: 0 }); + ``` + + If a store logic requires input, the input argument is also required: + + ```ts + useStore(counterLogic, { initialCount: 0 }); + ``` + + Framework hooks also preserve schema-derived context, event, and emitted event types when creating stores from config objects. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update `persist(...)` helpers to support async storage results. + + `clearStorage(...)` and `flushStorage(...)` may return a promise when the configured storage is async. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Remove deprecated Store APIs. + + The deprecated config-wrapping form of `undoRedo(...)` was removed. Use the extension form instead: + + ```ts + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }), + }, + }).with(undoRedo()); + ``` + + Computed atoms now receive only the previous value. Read other atoms directly with `.get()`: + + ```diff + -const doubled = createAtom((read) => read(countAtom) * 2); + +const doubled = createAtom(() => countAtom.get() * 2); + -const accumulated = createAtom((read, prev) => read(countAtom) + (prev ?? 0)); + +const accumulated = createAtom((prev) => countAtom.get() + (prev ?? 0)); + ``` + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add Standard Schema support to store configs and `fromStore(...)`. + + Schemas can type context, accepted events, and emitted events without enabling runtime validation by default. To validate schema-declared values at runtime, use the new `validateSchemas()` extension from `@xstate/store/validate`. + + ```ts + import { createStore } from "@xstate/store"; + import { validateSchemas } from "@xstate/store/validate"; + import { z } from "zod"; + + const store = createStore({ + schemas: { + context: z.object({ count: z.number() }), + events: { + increment: z.object({ by: z.number() }), + }, + }, + context: { count: 0 }, + on: { + increment: (context, event) => ({ + count: context.count + event.by, + }), + }, + }).with(validateSchemas()); + ``` + +### Minor Changes + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Pass an `AbortSignal` to `createAsyncAtom(...)` getters and ignore stale async results after recomputation. + + ```ts + const user = createAsyncAtom(async ({ signal }) => { + const response = await fetch("/user", { signal }); + return response.json(); + }); + ``` + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add reusable atom configs and framework atom-state helpers. + + `createAtomConfig(...)` creates an inert atom definition that can be instantiated with its `createAtom(...)` method or React/Preact/Vue/Solid's `useAtomState(...)`. These helpers return the current framework-native value and live atom instance, and also work with existing atom instances. + + ```ts + const countConfig = createAtomConfig((input: { initialCount: number }) => { + return input.initialCount; + }); + + function Counter() { + const [count, countAtom] = useAtomState(countConfig, { initialCount: 0 }); + + return ( + + ); + } + ``` + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add broadcast-aware storage helpers for persisted stores. + + Use `createBroadcastStorage(...)` with `persist(...)` and `subscribeToBroadcastStorage(...)` to rehydrate a persisted store when another tab or window writes to the same storage key. + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `store.can` for checking whether an event is allowed without updating the store. + + ```ts + const store = createStore({ + context: { count: 0 }, + on: { + increment: (context, event: { by: number }) => { + if (context.count + event.by > 10) { + return; + } + + return { count: context.count + event.by }; + }, + }, + }); + + store.can.increment({ by: 4 }); // true + store.can.increment({ by: 11 }); // false + ``` + +- [#5512](https://github.com/statelyai/xstate/pull/5512) [`063416d`](https://github.com/statelyai/xstate/commit/063416db859581b91fd661ae1a89b75a37fffa69) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `createReducerAtom(...)` for reducer-driven atoms. + + ```ts + const count = createReducerAtom(0, (state, event: { type: "inc" }) => { + if (event.type === "inc") { + return state + 1; + } + return state; + }); + + count.send({ type: "inc" }); + ``` + +## 3.17.5 + +### Patch Changes + +- [#5521](https://github.com/statelyai/xstate/pull/5521) [`c4bb9e3`](https://github.com/statelyai/xstate/commit/c4bb9e3878b7595479554a4ed5ab93b81295d472) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix broken exports caused by missing build step in the publish workflow. + +## 3.17.4 + +### Patch Changes + +- [#5518](https://github.com/statelyai/xstate/pull/5518) [`3a881f5`](https://github.com/statelyai/xstate/commit/3a881f5204cc874c242ec04ce3471110b9d8c506) Thanks [@thecrypticace](https://github.com/thecrypticace)! - Fix synchronous subscribe callbacks still not re-running if a subscription triggers another one through multiple levels of computed atoms. + +## 3.17.3 + +### Patch Changes + +- [#5513](https://github.com/statelyai/xstate/pull/5513) [`d15455b`](https://github.com/statelyai/xstate/commit/d15455b13c42a48ef139e1381cd3ee57e40defba) Thanks [@thecrypticace](https://github.com/thecrypticace)! - Fix computed `atom.subscribe()` callbacks not re-running after one of it's dependencies is synchronously updated inside the callback. Previously, calling `someDependency.set()` inside a subscription callback would prevent that subscription from being notified of future changes. This also affected store selector subscriptions which triggered an update to the store. + +## 3.17.2 + +### Patch Changes + +- [#5510](https://github.com/statelyai/xstate/pull/5510) [`d51fa6d`](https://github.com/statelyai/xstate/commit/d51fa6d640d3aac9e3424417b70f2d6f81466f78) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix `atom.subscribe()` callbacks tracking dependencies from `.get()` calls inside the callback (fixes #5509). Previously, calling `otherAtom.get()` inside a subscription callback would cause the callback to re-run whenever `otherAtom` changed, even if the subscribed atom's value didn't change. + +## 3.17.1 + +### Patch Changes + +- [#5486](https://github.com/statelyai/xstate/pull/5486) [`582e43a`](https://github.com/statelyai/xstate/commit/582e43ac57c935712fbed74d6769e78b721eb0f7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix emitted events not firing on stores with extensions (`.with()`) + +## 3.17.0 + +### Minor Changes + +- [#5479](https://github.com/statelyai/xstate/pull/5479) [`3b8c68e`](https://github.com/statelyai/xstate/commit/3b8c68e20057885f19b8897f4b4cb29380e8f7de) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `strategy: 'event'` option to the `persist` extension. Instead of persisting context snapshots, this persists the event log and replays events on rehydration to reconstruct state. When `maxEvents` is set, a snapshot checkpoint is automatically saved so that replay starts from the checkpoint rather than initial context, preserving correctness. + + Also adds `isHydrated(store)` helper to check hydration status. + + ```ts + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) }, + }).with( + persist({ + name: "my-store", + strategy: "event", + maxEvents: 100, + }) + ); + ``` + +- [#5474](https://github.com/statelyai/xstate/pull/5474) [`e299d40`](https://github.com/statelyai/xstate/commit/e299d404444685857fb8e8cc68eab9c681673d08) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `reset` store extension for resetting store context to its initial state via `.with(reset())`. + + ```ts + import { createStore } from "@xstate/store"; + import { reset } from "@xstate/store/reset"; + + const store = createStore({ + context: { count: 0, user: null }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + login: (ctx, e: { user: string }) => ({ ...ctx, user: e.user }), + }, + }).with(reset()); + + store.trigger.inc(); + store.trigger.reset(); // resets to { count: 0, user: null } + ``` + + Supports custom reset logic via `to` for partial resets: + + ```ts + .with(reset({ + to: (initial, current) => ({ ...initial, user: current.user }) + })) + ``` + +- [#5472](https://github.com/statelyai/xstate/pull/5472) [`f7c2beb`](https://github.com/statelyai/xstate/commit/f7c2beb9a90f21828cab0ce6d85a1afa30f4ae0a) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `persist` store extension for persisting store context to storage (localStorage, sessionStorage, async adapters, etc.) via `.with(persist({ name: 'my-store' }))`. + + ```ts + import { createStore } from "@xstate/store"; + import { + persist, + rehydrateStore, + clearStorage, + flushStorage, + createJSONStorage, + } from "@xstate/store/persist"; + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) }, + }).with(persist({ name: "my-store" })); + // Default storage is localStorage + ``` + + Features: + + - Sync and async storage adapters (localStorage, AsyncStorage, etc.) + - `pick` — persist only selected fields + - `version` + `migrate` — schema versioning and migration + - `merge` — custom merge strategy on rehydration + - `throttle` — batched/throttled writes + - `serialize` / `deserialize` — custom serialization + - `filter` — skip persisting for specific events + - `skipHydration` + `rehydrateStore()` — manual/async rehydration + - `clearStorage()` — remove persisted data + - `flushStorage()` — force immediate write of pending throttled data + - `createJSONStorage()` — SSR-safe storage adapter factory + - `onDone` / `onError` callbacks + +## 3.16.0 + +### Minor Changes + +- [#5467](https://github.com/statelyai/xstate/pull/5467) [`d54cc47`](https://github.com/statelyai/xstate/commit/d54cc4760513ba05e9c0fc7a4a783d0c47a882f2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add wildcard `'*'` support for `store.on('*', …)` to listen to all emitted events. The handler receives the union of all emitted event types. + + ```ts + const store = createStore({ + context: { count: 0 }, + emits: { + increased: (_: { upBy: number }) => {}, + decreased: (_: { downBy: number }) => {}, + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { ...ctx, count: ctx.count + 1 }; + }, + }, + }); + + store.on("*", (ev) => { + // ev: + // | { type: 'increased'; upBy: number } + // | { type: 'decreased'; downBy: number } + }); + ``` + +## 3.15.0 + +### Minor Changes + +- [#5441](https://github.com/statelyai/xstate/pull/5441) [`6ba9538`](https://github.com/statelyai/xstate/commit/6ba9538e05022c9aad9e4a4f089a87aaed54c06a) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added new framework adapter packages for `@xstate/store` and deprecated: + + - `@xstate/store/react` (use `@xstate/store-react` instead) + - `@xstate/store/solid` (use `@xstate/store-solid` instead) + + ```diff + - import { useSelector } from '@xstate/store/react'; + + import { useSelector } from '@xstate/store-react'; + ``` + + ```diff + - import { useSelector } from '@xstate/store/solid'; + + import { useSelector } from '@xstate/store-solid'; + ``` + +## 3.14.1 + +### Patch Changes + +- [#5437](https://github.com/statelyai/xstate/pull/5437) [`ae93af1`](https://github.com/statelyai/xstate/commit/ae93af1a9813c9e7f6ad5eb34fe0f087c147e890) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update the internal atom implementation (alien-signals) + +## 3.14.0 + +### Minor Changes + +- [#5427](https://github.com/statelyai/xstate/pull/5427) [`77ec4ad`](https://github.com/statelyai/xstate/commit/77ec4ad34e3f7e7109a41edd13353bec640cd1a7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `.with()` method for store extensions. + + ```ts + import { createStore } from "@xstate/store"; + import { undoRedo } from "@xstate/store/undo"; + + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }), + }, + }).with(undoRedo()); + + store.trigger.inc(); // count = 1 + + // Added from the undoRedo extension + store.trigger.undo(); // count = 0 + store.trigger.redo(); // count = 1 + ``` + +## 3.13.0 + +### Minor Changes + +- [#5415](https://github.com/statelyai/xstate/pull/5415) [`068f2a7`](https://github.com/statelyai/xstate/commit/068f2a7932343a3a7d418fa87e172a9de9f5e6cb) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add snapshot-based undo/redo strategy to `undoRedo(…)`: + + ```ts + // Snapshot strategy (faster undo/redo, more memory) + undoRedo(config, { + strategy: "snapshot", + historyLimit: 10, + }); + ``` + +## 3.12.0 + +### Minor Changes + +- [#5410](https://github.com/statelyai/xstate/pull/5410) [`45d97de`](https://github.com/statelyai/xstate/commit/45d97de0a174b274aea69d02e27a59b224c2b855) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix go-to-definition for triggers + +- [#5414](https://github.com/statelyai/xstate/pull/5414) [`524a207`](https://github.com/statelyai/xstate/commit/524a207e20ee07560170817052763ad7f3c71d66) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Computed atoms can now access their previous value via an optional second parameter: + + ```ts + const count = createAtom(1); + const double = createAtom((_, prev) => count.get() + (prev ?? 0)); + ``` + +## 3.11.2 + +### Patch Changes + +- [#5401](https://github.com/statelyai/xstate/pull/5401) [`d345e1f`](https://github.com/statelyai/xstate/commit/d345e1fa497c2196e296512937ed52e1c76fd6be) Thanks [@davidkpiano](https://github.com/davidkpiano)! - - Fix type inference for emitted event types when using `undoRedo`. + +## 3.11.1 + +### Patch Changes + +- [#5395](https://github.com/statelyai/xstate/pull/5395) [`8408430`](https://github.com/statelyai/xstate/commit/84084304a1daf19593e8a1c4b13fb73b901a06e8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix redo logic bug where redo would apply too many events when no transaction grouping is used + +## 3.11.0 + +### Minor Changes + +- [#5393](https://github.com/statelyai/xstate/pull/5393) [`6d00d3f`](https://github.com/statelyai/xstate/commit/6d00d3fd3cdb27b3bb19557cc9ee84f85bd38fe8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `snapshot` parameter to `getTransactionId` function. + + ```ts + const store = createStore( + undo( + { + // ... + }, + { + getTransactionId: (event, snapshot) => + snapshot.context.currentTransactionId, + } + ) + ); + ``` + +- [#5392](https://github.com/statelyai/xstate/pull/5392) [`5854b52`](https://github.com/statelyai/xstate/commit/5854b52c3fa1915f7f4620f144482d164af535e8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added an overload to `useSelector` that allows you to select the entire snapshot: + + ```ts + // No selector provided, return the entire snapshot + const snapshot = useSelector(store); + ``` + +- [#5393](https://github.com/statelyai/xstate/pull/5393) [`6d00d3f`](https://github.com/statelyai/xstate/commit/6d00d3fd3cdb27b3bb19557cc9ee84f85bd38fe8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `skipEvent` option to `undoRedo()` to exclude certain events from undo/redo history. + + ```ts + const store = createStore( + undoRedo( + { + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + log: (ctx) => ctx, // No state change + }, + }, + { + skipEvent: (event, snapshot) => event.type === "log", + } + ) + ); + ``` + +## 3.10.0 + +### Minor Changes + +- [#5323](https://github.com/statelyai/xstate/pull/5323) [`cb08332`](https://github.com/statelyai/xstate/commit/cb0833241cb2c0d2a908c413e79fc07b3d7a5fd9) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added support for effect-only transitions that don't trigger state updates. Now, when a transition returns the same state but includes effects, subscribers won't be notified of a state change, but the effects will still be executed. This helps prevent unnecessary re-renders while maintaining side effect functionality. + + ```ts + it("should not trigger update if the snapshot is the same even if there are effects", () => { + const store = createStore({ + context: { count: 0 }, + on: { + doNothing: (ctx, _, enq) => { + enq.effect(() => { + // … + }); + return ctx; // Context is the same, so no update is triggered + // This is the same as not returning anything (void) + }, + }, + }); + + const spy = vi.fn(); + store.subscribe(spy); + + store.trigger.doNothing(); + store.trigger.doNothing(); + + expect(spy).toHaveBeenCalledTimes(0); + }); + ``` + +## 3.9.3 + +### Patch Changes + +- [#5383](https://github.com/statelyai/xstate/pull/5383) [`4b6a513`](https://github.com/statelyai/xstate/commit/4b6a513ebd7ee1ab067856be4b431651b491cba5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix: `trigger` methods now work when passed directly as event handlers, even for events with no payload. Before, the React `event.type` would overwrite the intended event type. + +## 3.9.2 + +### Patch Changes + +- [#5361](https://github.com/statelyai/xstate/pull/5361) [`7f8d90a`](https://github.com/statelyai/xstate/commit/7f8d90a5a6e851ade55e94a9569f746aaebc160a) Thanks [@johnsoncodehk](https://github.com/johnsoncodehk)! - Synchronize the alien-signals algorithm to 2.0.7. + + This is primarily to fix the severe performance degradation discovered in vuejs/core: vuejs/core#13654 + +## 3.9.1 + +### Patch Changes + +- [#5359](https://github.com/statelyai/xstate/pull/5359) [`3f4bffc`](https://github.com/statelyai/xstate/commit/3f4bffc3dc9e4797207617f8166d5b8aac8d64ea) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix `createStoreHook` to create a single shared store instance across all components. Previously, the implementation was creating independent store instances, but now multiple components using the same hook will share state as expected. + +## 3.9.0 + +### Minor Changes + +- [#5354](https://github.com/statelyai/xstate/pull/5354) [`515cc31`](https://github.com/statelyai/xstate/commit/515cc31063f04a7cd238006a485ae9368a8c1278) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add `createStoreHook(…)` function for React. Creates a store hook that returns `[selectedValue, store]` instead of managing store instances manually. + + ```tsx + const useCountStore = createStoreHook({ + context: { count: 0 }, + on: { + inc: (ctx, event: { by: number }) => ({ + ...ctx, + count: ctx.count + event.by, + }), + }, + }); + + // Usage + const [count, store] = useCountStore((s) => s.context.count); + store.trigger.inc({ by: 3 }); + + // Usage (no selector) + const [snapshot, store] = useCountStore(); + ``` + +## 3.8.5 + +### Patch Changes + +- [#5347](https://github.com/statelyai/xstate/pull/5347) [`4dff4e9`](https://github.com/statelyai/xstate/commit/4dff4e94d6aa547f0b1ae37e51e96281a252d236) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix TypeScript error localization in `createStore(…)` overloads + + Previously, TS errors in transitions would appear on the `createStore` call itself rather than on the specific transition. + +## 3.8.4 + +### Patch Changes + +- [#5337](https://github.com/statelyai/xstate/pull/5337) [`b64a6c9`](https://github.com/statelyai/xstate/commit/b64a6c925d87bce6246d35e562bdda6907e2e33f) Thanks [@flbn](https://github.com/flbn)! - chore: add missing EventFromStoreConfig, EmitsFromStoreConfig, ContextFromStoreConfig types from @xstate/store exports + +## 3.8.3 + +### Patch Changes + +- [#5334](https://github.com/statelyai/xstate/pull/5334) [`c4adf25`](https://github.com/statelyai/xstate/commit/c4adf25331faeb15004d449b35799c53bd069b1b) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createStore` function now supports explicit generic type parameters for better type control when needed. This allows you to specify the exact types for context, events, and emitted events instead of relying solely on type inference if desired. + + ```ts + type CoffeeContext = { + beans: number; + cups: number; + }; + + type CoffeeEvents = + | { type: "addBeans"; amount: number } + | { type: "brewCup" }; + + type CoffeeEmitted = + | { type: "beansAdded"; amount: number } + | { type: "cupBrewed" }; + + const coffeeStore = createStore({ + context: { + beans: 0, + cups: 0, + }, + on: { + addBeans: (ctx, event, enq) => { + enq.emit.beansAdded({ amount: event.amount }); + return { ...ctx, beans: ctx.beans + event.amount }; + }, + brewCup: (ctx, _, enq) => { + if (ctx.beans > 0) { + enq.emit.cupBrewed(); + return { ...ctx, beans: ctx.beans - 1, cups: ctx.cups + 1 }; + } + + return ctx; + }, + }, + }); + ``` + +## 3.8.2 + +### Patch Changes + +- [#5329](https://github.com/statelyai/xstate/pull/5329) [`8a27bc4`](https://github.com/statelyai/xstate/commit/8a27bc43f975b03dc82a7e381a3956af49fb0633) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix: `createAsyncAtom` now properly propagates status updates after promise resolves/rejects. + +## 3.8.1 + +### Patch Changes + +- [#5326](https://github.com/statelyai/xstate/pull/5326) [`68ab6fb`](https://github.com/statelyai/xstate/commit/68ab6fb72d20c5bd2eb8d1d6249dc3046da79010) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The XState Store undo/redo package can now be imported as `@xstate/store/undo`. + + ```ts + import { createStore } from "@xstate/store"; + import { undoRedo } from "@xstate/store/undo"; + + const store = createStore( + undoRedo({ + context: { + count: 0, + }, + on: { + // ... + }, + }) + ); + + // ... + ``` + +## 3.8.0 + +### Minor Changes + +- [#5305](https://github.com/statelyai/xstate/pull/5305) [`725530f`](https://github.com/statelyai/xstate/commit/725530fd462c4300319fad82efc545ff44cf3e22) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added undo/redo functionality to XState Store via the `undoRedo` higher-order store logic: + + - Adds `undo` and `redo` events to stores + - Supports grouping related events into transactions using `transactionId` + - Maintains event history for precise state reconstruction + - Automatically clears redo stack when new events occur + + ```ts + import { createStore } from "@xstate/store"; + import { undoRedo } from "@xstate/store/undo"; + + const store = createStore( + undoRedo({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }), + }, + }) + ); + + store.trigger.inc(); + // count: 1 + store.trigger.inc(); + // count: 2 + store.trigger.undo(); + // count: 1 + store.trigger.undo(); + // count: 0 + store.trigger.redo(); + // count: 1 + store.trigger.redo(); + // count: 2 + ``` + +## 3.7.1 + +### Patch Changes + +- [#5307](https://github.com/statelyai/xstate/pull/5307) [`b269485`](https://github.com/statelyai/xstate/commit/b269485e47b95fa57bbc75e34352f107ef2c37c3) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix the types for `useAtom` to accept `ReadonlyAtom` values. + +## 3.7.0 + +### Minor Changes + +- [#5302](https://github.com/statelyai/xstate/pull/5302) [`809d8b5`](https://github.com/statelyai/xstate/commit/809d8b53869ac7d664ec1b1d634eb8286a0d4cd2) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `useAtom` hook is now available for reading the value of an atom or selecting a value from the atom. + + ```tsx + const atom = createAtom(0); + + const Component = () => { + const count = useAtom(atom); + + return ( + <> +
atom.set((c) => c + 1)}>{count}
+ + + ); + }; + ``` + + With selectors: + + ```tsx + const atom = createAtom({ count: 0 }); + + const Component = () => { + const count = useAtom(atom, (s) => s.count); + + return
{count}
; + }; + ``` + +## 3.6.2 + +### Patch Changes + +- [#5280](https://github.com/statelyai/xstate/pull/5280) [`d8a3456bc82af5e4d176990093ba4e649e7ce286`](https://github.com/statelyai/xstate/commit/d8a3456bc82af5e4d176990093ba4e649e7ce286) Thanks [@johnsoncodehk](https://github.com/johnsoncodehk)! - Synchronize the [`alien-signals`](https://github.com/stackblitz/alien-signals/) algorithm to 2.0.4 + +## 3.6.1 + +### Patch Changes + +- [#5282](https://github.com/statelyai/xstate/pull/5282) [`42b1565cfdd6635754a4de63800d63ca74886a70`](https://github.com/statelyai/xstate/commit/42b1565cfdd6635754a4de63800d63ca74886a70) Thanks [@lucioreyli](https://github.com/lucioreyli)! - Add missing `createAsyncAtom` export + +## 3.6.0 + +### Minor Changes + +- [#5266](https://github.com/statelyai/xstate/pull/5266) [`42bfd0a30d74e1c5820728220a00db692023f1f8`](https://github.com/statelyai/xstate/commit/42bfd0a30d74e1c5820728220a00db692023f1f8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added async atoms: + + ```typescript + const atom = createAsyncAtom(async () => { + const response = await fetch(`/api/something`); + return response.json(); + }); + + atom.subscribe((state) => { + // Status can be 'pending', 'done', or 'error' + if (state.status === "done") { + console.log(state.data); + } + }); + ``` + +## 3.5.1 + +### Patch Changes + +- [#5261](https://github.com/statelyai/xstate/pull/5261) [`986c5c86e15efe6d219bd6a0bb2130917c1db50e`](https://github.com/statelyai/xstate/commit/986c5c86e15efe6d219bd6a0bb2130917c1db50e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Reduced the bundle size for the atom implementation + +## 3.5.0 + +### Minor Changes + +- [#5250](https://github.com/statelyai/xstate/pull/5250) [`a1bffb55b2029bde82e542d5936c51d961909a37`](https://github.com/statelyai/xstate/commit/a1bffb55b2029bde82e542d5936c51d961909a37) Thanks [@davidkpiano](https://github.com/davidkpiano)! - - Improved atom architecture with better dependency management (the diamond problem is solved!) + + - Optimized recomputation logic to prevent unnecessary updates + - Added support for custom equality functions through `compare` option in `createAtom`, allowing fine-grained control over when atoms update: + + ```ts + const coordinateAtom = createAtom( + { x: 0, y: 0 }, + { + // only update when x and y change + compare: (prev, next) => prev.x === next.x && prev.y === next.y, + } + ); + ``` + +## 3.4.3 + +### Patch Changes + +- [#5230](https://github.com/statelyai/xstate/pull/5230) [`86e6b58dd18337202df8e319a42f85523d5d0d30`](https://github.com/statelyai/xstate/commit/86e6b58dd18337202df8e319a42f85523d5d0d30) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The types for emitting events with no payload have been fixed so that the following code works: + + ```ts + const store = createStore({ + emits: { + incremented: () => {}, + }, + on: { + inc: (ctx, ev, enq) => { + // No payload is expected + enq.emit.incremented(); + }, + }, + }); + ``` + + Previously, this would have been an error because the `incremented` event was expected to have a payload. + +## 3.4.2 + +### Patch Changes + +- [#5247](https://github.com/statelyai/xstate/pull/5247) [`e8891030162214acc751a9f79a5d57ec916565ee`](https://github.com/statelyai/xstate/commit/e8891030162214acc751a9f79a5d57ec916565ee) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fix type inference for discriminated union event types in the `trigger` and the `emit` object. Previously, using `Omit` with union types would incorrectly combine event types, breaking type inference for discriminated unions. This has been fixed by introducing a `DistributiveOmit` type that correctly preserves the relationship between discriminated properties. + +## 3.4.1 + +### Patch Changes + +- [#5237](https://github.com/statelyai/xstate/pull/5237) [`c68b39025179dd52fdaddb5599a606c5546dc214`](https://github.com/statelyai/xstate/commit/c68b39025179dd52fdaddb5599a606c5546dc214) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fixed a bug where conditional atoms were not properly unsubscribed when no longer needed. + +## 3.4.0 + +### Minor Changes + +- [#5221](https://github.com/statelyai/xstate/pull/5221) [`4635d3d8d3debcfeef5cddd78613e32891c10eac`](https://github.com/statelyai/xstate/commit/4635d3d8d3debcfeef5cddd78613e32891c10eac) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added `createAtom()` for creating reactive atoms that can be combined with other atoms and stores: + + - Create simple atoms with initial values: + + ```ts + import { createAtom } from "@xstate/store"; + + const countAtom = createAtom(0); + countAtom.get(); // 0 + countAtom.set(1); // or use setter function: (prev) => prev + 1 + ``` + + - Subscribe to atom changes: + + ```ts + countAtom.subscribe((value) => console.log(value)); + ``` + + - Combine multiple atoms: + + ```ts + const nameAtom = createAtom("hello"); + const countAtom = createAtom(3); + const combinedAtom = createAtom((read) => + read(nameAtom).repeat(read(countAtom)) + ); + combinedAtom.get(); // "hellohellohello" + ``` + + - Seamlessly combine atoms with stores: + + ```ts + const countAtom = createAtom(0); + const nameStore = createStore({ + context: { name: "David" }, + // ... store config + }); + + const combinedAtom = createAtom( + (read) => read(nameStore).context.name + ` ${read(countAtom)}` + ); + combinedAtom.get(); // "David 0" + ``` + + Atoms automatically update when their dependencies change, making it easy to create derived state from both atoms and stores. + +## 3.3.0 + +### Minor Changes + +- [#5215](https://github.com/statelyai/xstate/pull/5215) [`13279166ed9fa3d3626a2129bd257f6cd663fd0e`](https://github.com/statelyai/xstate/commit/13279166ed9fa3d3626a2129bd257f6cd663fd0e) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added `store.transition(state, event)` method that returns the next state and effects for a given state and event as a tuple, without actually updating the store. This is useful for computing state changes before committing them, or controlling the execution of effects. + + Example: + + ```ts + const [nextState, effects] = store.transition(store.getSnapshot(), { + type: "increment", + by: 1, + }); + ``` + +## 3.2.1 + +### Patch Changes + +- [#5223](https://github.com/statelyai/xstate/pull/5223) [`9e1de554c4ebf49997b717fada540951d01f511c`](https://github.com/statelyai/xstate/commit/9e1de554c4ebf49997b717fada540951d01f511c) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added React 19 as a peer dependency. + +## 3.2.0 + +### Minor Changes + +- [#5200](https://github.com/statelyai/xstate/pull/5200) [`0332a16a42fb372eb614df74ff4cb7f003c31fc8`](https://github.com/statelyai/xstate/commit/0332a16a42fb372eb614df74ff4cb7f003c31fc8) Thanks [@{](https://github.com/{)! - Added selectors to @xstate/store that enable efficient state selection and subscription: + + - `store.select(selector)` function to create a "selector" entity where you can: + - Get current value with `.get()` + - Subscribe to changes with `.subscribe(callback)` + - Only notify subscribers when selected value actually changes + - Support custom equality functions for fine-grained control over updates via `store.select(selector, equalityFn)` + + ```ts + const store = createStore({ + context: { + position: { x: 0, y: 0 }, + name: 'John', age: 30 } + }, + on: { + positionUpdated: ( + context, + event: { position: { x: number; y: number } } + ) => ({ + ...context, + position: event.position + }) + } + }); + + const position = store.select((state) => state.context.position); + + position.get(); // { x: 0, y: 0 } + + position.subscribe((position) => { + console.log(position); + }); + + store.trigger.positionUpdated({ x: 100, y: 200 }); + // Logs: { x: 100, y: 200 } + ``` + +## 3.1.0 + +### Minor Changes + +- [#5205](https://github.com/statelyai/xstate/pull/5205) [`65784aef746b6249a9c3d71d9e4a7c9b454698c8`](https://github.com/statelyai/xstate/commit/65784aef746b6249a9c3d71d9e4a7c9b454698c8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added `createStoreConfig` to create a store config from an object. This is an identity function that returns the config unchanged, but is useful for type inference. + + ```tsx + const storeConfig = createStoreConfig({ + context: { count: 0 }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) }, + }); + + // Reusable store config: + + const store = createStore(storeConfig); + + // ... + function Comp1() { + const store = useStore(storeConfig); + + // ... + } + + function Comp2() { + const store = useStore(storeConfig); + + // ... + } + ``` + +- [#5205](https://github.com/statelyai/xstate/pull/5205) [`65784aef746b6249a9c3d71d9e4a7c9b454698c8`](https://github.com/statelyai/xstate/commit/65784aef746b6249a9c3d71d9e4a7c9b454698c8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - There is now a `useStore()` hook that allows you to create a local component store from a config object. + + ```tsx + import { useStore, useSelector } from "@xstate/store/react"; + + function Counter() { + const store = useStore({ + context: { + name: "David", + count: 0, + }, + on: { + inc: (ctx, { by }: { by: number }) => ({ + ...ctx, + count: ctx.count + by, + }), + }, + }); + const count = useSelector(store, (state) => state.count); + + return ( +
+
Count: {count}
+ + +
+ ); + } + ``` + +### Patch Changes + +- [#5205](https://github.com/statelyai/xstate/pull/5205) [`65784aef746b6249a9c3d71d9e4a7c9b454698c8`](https://github.com/statelyai/xstate/commit/65784aef746b6249a9c3d71d9e4a7c9b454698c8) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createStoreWithProducer(config)` function now accepts an `emits` object. + +## 3.0.1 + +### Patch Changes + +- [#5197](https://github.com/statelyai/xstate/pull/5197) [`5e05d5908093bfd3435dc2243e066e4e91b3ebc5`](https://github.com/statelyai/xstate/commit/5e05d5908093bfd3435dc2243e066e4e91b3ebc5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The emitted event type can no longer be accidentally overridden in the emitted event payload. See #5196 for the issue. + +## 3.0.0 + +### Major Changes + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createStore` function now only accepts a single configuration object argument. This is a breaking change that simplifies the API and aligns with the configuration pattern used throughout XState. + + ```ts + // Before + // createStore( + // { + // count: 0 + // }, + // { + // increment: (context) => ({ count: context.count + 1 }) + // } + // ); + + // After + createStore({ + context: { + count: 0, + }, + on: { + increment: (context) => ({ count: context.count + 1 }), + }, + }); + ``` + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - You can now enqueue effects in state transitions. + + ```ts + const store = createStore({ + context: { + count: 0, + }, + on: { + incrementDelayed: (context, event, enq) => { + enq.effect(async () => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + store.send({ type: "increment" }); + }); + + return context; + }, + increment: (context) => ({ count: context.count + 1 }), + }, + }); + ``` + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `fromStore(config)` function now only supports a single config object argument. + + ```ts + const storeLogic = fromStore({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount, + }), + on: { + inc: (ctx, ev: { by: number }) => ({ + ...ctx, + count: ctx.count + ev.by, + }), + }, + }); + ``` + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createStoreWithProducer(…)` function now only accepts two arguments: a `producer` and a config (`{ context, on }`) object. + + ```ts + // Before + // createStoreWithProducer( + // producer, + // { + // count: 0 + // }, + // { + // increment: (context) => { + // context.count++; + // } + // } + // ); + + // After + createStoreWithProducer(producer, { + context: { + count: 0, + }, + on: { + increment: (context) => { + context.count++; + }, + }, + }); + ``` + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Only complete assigner functions that replace the `context` fully are supported. This is a breaking change that simplifies the API and provides more type safety. + + ```diff + const store = createStore({ + context: { + items: [], + count: 0 + }, + on: { + - increment: { count: (context) => context.count + 1 } + - increment: (context) => ({ count: context.count + 1 }) + + increment: (context) => ({ ...context, count: context.count + 1 }) + } + }) + ``` + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Emitted event types are now specified in functions on the `emits` property of the store definition: + + ```ts + const store = createStore({ + // … + emits: { + increased: (payload: { upBy: number }) => { + // You can execute a side-effect here + // or leave it empty + }, + }, + on: { + inc: (ctx, ev: { by: number }, enq) => { + enq.emit.increased({ upBy: ev.by }); + + // … + }, + }, + }); + ``` + +### Minor Changes + +- [#5175](https://github.com/statelyai/xstate/pull/5175) [`38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5`](https://github.com/statelyai/xstate/commit/38aa9f518ee2f9a5f481306a1dc68c0ad47d28d5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Added `store.trigger` API for sending events with a fluent interface: + + ```ts + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by, + }), + }, + }); + + // Instead of manually constructing event objects: + store.send({ type: "increment", by: 5 }); + + // You can now use the fluent trigger API: + store.trigger.increment({ by: 5 }); + ``` + + The `trigger` API provides full type safety for event names and payloads, making it easier and safer to send events to the store. + +## 2.6.2 + +### Patch Changes + +- [#5136](https://github.com/statelyai/xstate/pull/5136) [`c051ff7ce7d09729ccc0630d684ef5168815f507`](https://github.com/statelyai/xstate/commit/c051ff7ce7d09729ccc0630d684ef5168815f507) Thanks [@Andarist](https://github.com/Andarist)! - Fixed an accidental used reference of `xstate` types + +## 2.6.1 + +### Patch Changes + +- [#5109](https://github.com/statelyai/xstate/pull/5109) [`d67b71dd25d457a2a59f2c943db13f50fab7ec3d`](https://github.com/statelyai/xstate/commit/d67b71dd25d457a2a59f2c943db13f50fab7ec3d) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Add React 19 as a peer dependency + +## 2.6.0 + +### Minor Changes + +- [#5079](https://github.com/statelyai/xstate/pull/5079) [`25963966c394fc904dc9b701a420b6e204ebe7f7`](https://github.com/statelyai/xstate/commit/25963966c394fc904dc9b701a420b6e204ebe7f7) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `createStoreWithProducer(…)` function now uses the new configuration API: + + ```ts + import { createStoreWithProducer } from "@xstate/store"; + // DEPRECATED API + // const store = createStoreWithProducer( + // producer, + // { + // count: 0 + // }, + // { + // inc: (context, event) => { + // context.count++; + // } + // } + // ); + + const store = createStoreWithProducer(producer, { + context: { + count: 0, + }, + on: { + inc: (context, event) => { + context.count++; + }, + }, + }); + ``` + +## 2.5.0 + +### Minor Changes + +- [#5085](https://github.com/statelyai/xstate/pull/5085) [`51437a4d036029ab4ff74cb52721178b3e525c48`](https://github.com/statelyai/xstate/commit/51437a4d036029ab4ff74cb52721178b3e525c48) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `shallowEqual` comparator has been added for selector comparison: + + ```tsx + import { shallowEqual } from "@xstate/store"; + import { useSelector } from "@xstate/store/react"; + + import { store } from "./store"; + + function MyComponent() { + const state = useSelector( + store, + (s) => { + return s.items.filter(/* ... */); + }, + shallowEqual + ); + + // ... + } + ``` + +## 2.4.0 + +### Minor Changes + +- [#5064](https://github.com/statelyai/xstate/pull/5064) [`84aca37d0b02cb9cd5a32c8fd09e487bd8fe2a47`](https://github.com/statelyai/xstate/commit/84aca37d0b02cb9cd5a32c8fd09e487bd8fe2a47) Thanks [@davidkpiano](https://github.com/davidkpiano)! - There is a new single-argument config API for `createStore(config)`: + + ```ts + const store = createStore({ + // Types (optional) + types: { + emitted: {} as { type: "incremented" }, + }, + + // Context + context: { count: 0 }, + + // Transitions + on: { + inc: (context, event: { by: number }, enq) => { + enq.emit({ type: "incremented" }); + + return { count: context.count + event.by }; + }, + dec: (context, event: { by: number }) => ({ + count: context.count - event.by, + }), + }, + }); + ``` + +- [#5064](https://github.com/statelyai/xstate/pull/5064) [`84aca37d0b02cb9cd5a32c8fd09e487bd8fe2a47`](https://github.com/statelyai/xstate/commit/84aca37d0b02cb9cd5a32c8fd09e487bd8fe2a47) Thanks [@davidkpiano](https://github.com/davidkpiano)! - You can now emit events from a store: + + ```ts + import { createStore } from "@xstate/store"; + + const store = createStore({ + context: { + count: 0, + }, + on: { + increment: (context, event, { emit }) => { + emit({ type: "incremented" }); + return { count: context.count + 1 }; + }, + }, + }); + + store.on("incremented", () => { + console.log("incremented!"); + }); + ``` + +## 2.3.0 + +### Minor Changes + +- [#5056](https://github.com/statelyai/xstate/pull/5056) [`8c35da9a72`](https://github.com/statelyai/xstate/commit/8c35da9a72bf067a275335d0391ce9ab85ed8a12) Thanks [@steveadams](https://github.com/steveadams)! - You can now use the xstate/store package with SolidJS. + + Import `useSelector` from `@xstate/store/solid`. Select the data you want via `useSelector(…)` and send events using `store.send(eventObject)`: + + ```tsx + import { donutStore } from "./donutStore.ts"; + import { useSelector } from "@xstate/store/solid"; + + function DonutCounter() { + const donutCount = useSelector(donutStore, (state) => state.context.donuts); + + return ( +
+ +
+ ); + } + ``` + +## 2.2.1 + +### Patch Changes + +- [`b740aafdb1`](https://github.com/statelyai/xstate/commit/b740aafdb12ed6577ba31d0e07653bf99ebaca76) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Fixed some small issues from #5027 regarding XState types being imported + +## 2.2.0 + +### Minor Changes + +- [#5027](https://github.com/statelyai/xstate/pull/5027) [`758a78711d`](https://github.com/statelyai/xstate/commit/758a78711ddb35ce56951b551d48f9b6f54a37b5) Thanks [@davidkpiano](https://github.com/davidkpiano)! - You can now inspect XState stores using the `.inspect(inspector)` method: + + ```ts + import { someStore } from "./someStore"; + + someStore.inspect((inspEv) => { + console.log(inspEv); + // logs "@xstate.event" events and "@xstate.snapshot" events + // whenever an event is sent to the store + }); + // The "@xstate.actor" event is immediately logged + ``` + +## 2.1.0 + +### Minor Changes + +- [#5020](https://github.com/statelyai/xstate/pull/5020) [`e974797b0`](https://github.com/statelyai/xstate/commit/e974797b0b8d4e8f5929cc01b674a5ff92fa2115) Thanks [@with-heart](https://github.com/with-heart)! - Added the `EventFromStore` utility type which extracts the type of events from a store: + + ```ts + import { createStore, type EventFromStore } from "@xstate/store"; + + const store = createStore( + { count: 0 }, + { + add: (context, event: { addend: number }) => ({ + count: context.count + event.addend, + }), + multiply: (context, event: { multiplier: number }) => ({ + count: context.count * event.multiplier, + }), + } + ); + + type StoreEvent = EventFromStore; + // ^? { type: 'add'; addend: number } | { type: 'multiply'; multiplier: number } + ``` + + *** + + `EventFromStore` allows us to create our own utility types which operate on a store's event types. + + For example, we could create a type `EventByType` which extracts the specific type of store event where `Type` matches the event's `type` property: + + ```ts + import { type EventFromStore, type Store } from "@xstate/store"; + + /** + * Extract the event where `Type` matches the event's `type` from the given + * `Store`. + */ + type EventByType< + TStore extends Store, + // creates a type-safe relationship between `Type` and the `type` keys of the + // store's events + Type extends EventFromStore["type"] + > = Extract, { type: Type }>; + ``` + + Here's how the type works with the `store` we defined in the first example: + + ```ts + // we get autocomplete listing the store's event `type` values on the second + // type parameter + type AddEvent = EventByType; + // ^? { type: 'add'; addend: number } + + type MultiplyEvent = EventByType; + // ^? { type: 'multiply'; multiplier: number } + + // the second type parameter is type-safe, meaning we get a type error if the + // value isn't a valid event `type` + type DivideEvent = EventByType; + // Type '"divide"' does not satisfy the constraint '"add" | "multiply"'.ts(2344) + ``` + + Building on that, we could create a type `EventInputByType` to extract a specific event's "input" type (the event type without the `type` property): + + ```ts + import { type EventFromStore, type Store } from "@xstate/store"; + + /** + * Extract a specific store event's "input" type (the event type without the + * `type` property). + */ + type EventInputByType< + TStore extends Store, + Type extends EventFromStore["type"] + > = Omit, "type">; + ``` + + And here's how `EventInputByType` works with our example `store`: + + ```ts + type AddInput = EventInputByType; + // ^? { addend: number } + + type MultiplyInput = EventInputByType; + // ^? { multiplier: number } + + type DivideInput = EventInputByType; + // Type '"divide"' does not satisfy the constraint '"add" | "multiply"'.ts(2344) + ``` + + Putting it all together, we can use `EventInputByType` to create a type-safe transition function for each of our store's defined events: + + ```ts + import { createStore, type EventFromStore, type Store } from "@xstate/store"; + + /** + * Extract the event where `Type` matches the event's `type` from the given + * `Store`. + */ + type EventByType< + TStore extends Store, + Type extends EventFromStore["type"] + > = Extract, { type: Type }>; + + /** + * Extract a specific store event's "input" type (the event type without the + * `type` property). + */ + type EventInputByType< + TStore extends Store, + Type extends EventFromStore["type"] + > = Omit, "type">; + + const store = createStore( + { count: 0 }, + { + add: (context, event: { addend: number }) => ({ + count: context.count + event.addend, + }), + multiply: (context, event: { multiplier: number }) => ({ + count: context.count * event.multiplier, + }), + } + ); + + const add = (input: EventInputByType) => + store.send({ type: "add", addend: input.addend }); + + add({ addend: 1 }); // sends { type: 'add', addend: 1 } + + const multiply = (input: EventInputByType) => + store.send({ type: "multiply", multiplier: input.multiplier }); + + multiply({ multiplier: 2 }); // sends { type: 'multiply', multiplier: 2 } + ``` + + Happy typing! + +## 2.0.0 + +### Major Changes + +- [#5000](https://github.com/statelyai/xstate/pull/5000) [`eeadb7121`](https://github.com/statelyai/xstate/commit/eeadb7121e8523cf34fe3a299731ca085152c65d) Thanks [@TkDodo](https://github.com/TkDodo)! - - Replace `use-sync-external-store/shim` with `useSyncExternalStore` from React. + - Do not memoize `getSnapshot` in `useSyncExternalStore`. + - Implement `getServerSnapshot` in `useSyncExternalStore`. + - Expect `store` to always be defined in `useSelector` + - Update React types to v18 and testing library to v16. + +## 1.0.0 + +### Major Changes + +- [#4921](https://github.com/statelyai/xstate/pull/4921) [`f73366504`](https://github.com/statelyai/xstate/commit/f73366504684266e4a1c7c997896b310ec2e7f29) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Release `@xstate/store` version 1.0 + +## 0.0.5 + +### Patch Changes + +- [#4918](https://github.com/statelyai/xstate/pull/4918) [`3323c85a6`](https://github.com/statelyai/xstate/commit/3323c85a6159d63fc73e83985ef46796f3582d90) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Types are now exported: + + ```ts + import type { SnapshotFromStore } from "@xstate/store"; + + // ... + ``` + +## 0.0.4 + +### Patch Changes + +- [#4890](https://github.com/statelyai/xstate/pull/4890) [`6d92b7770`](https://github.com/statelyai/xstate/commit/6d92b77704750498f669487da185eb005a080034) Thanks [@davidkpiano](https://github.com/davidkpiano)! - The `context` type for `createStoreWithProducer(producer, context, transitions)` will now be properly inferred. + + ```ts + const store = createStoreWithProducer( + produce, + { + count: 0, + }, + { + // ... + } + ); + + store.getSnapshot().context; + // BEFORE: StoreContext + // NOW: { count: number } + ``` + +## 0.0.3 + +### Patch Changes + +- [#4842](https://github.com/statelyai/xstate/pull/4842) [`3a57f4c69`](https://github.com/statelyai/xstate/commit/3a57f4c69b746546dd104989dcf8664c9fbe2f80) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update README.md + +- [#4839](https://github.com/statelyai/xstate/pull/4839) [`4a22edb90`](https://github.com/statelyai/xstate/commit/4a22edb904c1f2517db41e09030d0e9993891796) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Update JS docs + +## 0.0.2 + +### Patch Changes + +- [#4752](https://github.com/statelyai/xstate/pull/4752) [`8a32374e7`](https://github.com/statelyai/xstate/commit/8a32374e79b191dd3bfbab41a15d1b1b4adfd131) Thanks [@davidkpiano](https://github.com/davidkpiano)! - Initial release of `@xstate/store` + + ```ts + import { createStore } from "@xstate/store"; + + const store = createStore( + // initial context + { count: 0, greeting: "hello" }, + // transitions + { + inc: { + count: (context) => context.count + 1, + }, + updateBoth: { + count: () => 42, + greeting: "hi", + }, + } + ); + + store.send({ + type: "inc", + }); + + console.log(store.getSnapshot()); + // Logs: + // { + // status: 'active', + // context: { + // count: 1, + // greeting: 'hello' + // } + // } + ``` diff --git a/xstate-store/LICENSE b/xstate-store/LICENSE new file mode 100644 index 00000000..fc1fe941 --- /dev/null +++ b/xstate-store/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Khourshid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/xstate-store/MIGRATION.md b/xstate-store/MIGRATION.md new file mode 100644 index 00000000..94554632 --- /dev/null +++ b/xstate-store/MIGRATION.md @@ -0,0 +1,439 @@ +# @xstate/store v4 Migration Guide + +This guide covers changes in `packages/xstate-store` only. + +## Added + +### Standard Schema typing + +Store configs now accept `schemas` for type inference and runtime-readable +metadata from any [Standard Schema](https://standardschema.dev/) compatible +library. This can type context, accepted events, and emitted events. + +Store does not validate schemas by default. Use `validateSchemas()` from +`@xstate/store/validate` to opt into runtime validation. + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + context: z.object({ + count: z.number(), + label: z.string() + }), + events: { + rename: z.object({ + label: z.string() + }) + }, + emitted: { + renamed: z.object({ + label: z.string() + }) + } + }, + context: { count: 0, label: 'ready' }, + on: { + rename: (context, event, enq) => { + enq.emit.renamed({ label: event.label }); + + return { + ...context, + label: event.label + }; + } + } +}); +``` + +Event and emitted-event schemas define payload objects. Use an empty object +schema, such as `z.object({})`, for events without payload. + +```ts +import { validateSchemas } from '@xstate/store/validate'; + +const store = createStore({ + schemas: { + events: { + increment: z.object({ by: z.number() }) + } + }, + context: { count: 0 }, + on: { + increment: (context, event) => ({ count: context.count + event.by }) + } +}).with(validateSchemas()); +``` + +`validateSchemas()` validates the event sent to the store, the final context +after the transition completes, and emitted events before effects execute. It +throws `StoreValidationError` for invalid `send(...)`, `trigger.*(...)`, and +`transition(...)` calls. `store.can.*(...)` remains boolean-only and returns +`false` for validation errors. Extension-added event types are treated as known, +even when they do not have payload schemas. + +`fromStore(...)` also accepts `schemas` and can infer context, event, and +emitted-event types from schema definitions. + +```ts +import { fromStore } from '@xstate/store'; +import { z } from 'zod'; + +const logic = fromStore({ + context: (initialCount: number) => ({ count: initialCount }), + schemas: { + emitted: { + increased: z.object({ + by: z.number() + }) + } + }, + on: { + inc: (context, event: { by: number }, enq) => { + enq.emit.increased({ by: event.by }); + return { count: context.count + event.by }; + } + } +}); +``` + +The root package now exports `StandardSchemaV1` and helper types such as +`StoreSchemas`, `InferSchemaOutput`, `InferSchemaPayloadMap`, +`ResolveStoreContext`, `ResolveStoreEventPayloadMap`, and +`ResolveStoreEmittedPayloadMap`. + +### Optional schema-declared handlers + +When events are declared through `schemas.events`, matching handlers in `on` are +optional. Missing handlers are no-ops, but the event still exists for typing and +`store.trigger`. + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + events: { + inc: z.object({ + by: z.number() + }), + reset: z.object({}) + } + }, + context: { count: 0 }, + on: { + inc: (context, event) => ({ count: context.count + event.by }) + } +}); + +store.trigger.reset(); // no-op +``` + +### `enq.trigger` + +Transitions can now enqueue store events with `enq.trigger`. This is useful for +composing event handlers without calling another transition function directly. + +```ts +const store = createStore({ + schemas: { + events: { + addBear: z.object({}), + addFish: z.object({ + amount: z.number() + }), + addBearAndFish: z.object({}) + } + }, + context: { + bears: 0, + fishes: 0 + }, + on: { + addBear: (context) => ({ + ...context, + bears: context.bears + 1 + }), + addFish: (context, event) => ({ + ...context, + fishes: context.fishes + event.amount + }), + addBearAndFish: (context, _event, enq) => { + enq.trigger.addBear(); + enq.trigger.addFish({ amount: 1 }); + + return context; + } + } +}); +``` + +`enq.trigger` is typed from the same event map as `store.trigger`. With +`schemas.events`, unknown events and invalid payloads are type errors. + +### Store selectors and reusable store logic + +Stores can now create reactive selections with `store.select(selector)`. + +```ts +import { createStore } from '@xstate/store'; + +const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } +}); + +const count = store.select((context) => context.count); +const isEven = store.select((context) => context.count % 2 === 0); + +count.subscribe((value) => { + console.log(value); +}); + +store.trigger.inc(); +``` + +`createStoreLogic(...)` creates reusable store definitions. If `selectors` are +provided, each created store exposes them on `store.selectors`, and selectors +are preserved when the store is extended with `store.with(...)`. + +```ts +import { createStoreLogic } from '@xstate/store'; + +const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + selectors: { + count: (context) => context.count, + doubled: (context) => context.count * 2 + }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } +}); + +const store = counterLogic.createStore({ initialCount: 2 }); + +store.selectors.count.get(); // 2 +store.selectors.doubled.get(); // 4 +``` + +## Changed + +### Emitted event declarations moved to `schemas.emitted` + +The `emits` config property has been replaced by `schemas.emitted`. Emitting +events with `enq.emit` is unchanged; only the type declaration moved. + +```diff + const store = createStore({ + context: { count: 0 }, +- emits: { +- increased: (_payload: { by: number }) => {} +- }, ++ schemas: { ++ emitted: { ++ increased: z.object({ ++ by: z.number() ++ }) ++ } ++ }, + on: { + inc: (context, event: { by: number }, enq) => { + enq.emit.increased({ by: event.by }); + return { count: context.count + event.by }; + } + } + }); +``` + +### Store inspection emits one transition event + +`store.inspect(...)` now emits a single `@xstate.transition` event shape instead +of separate `@xstate.actor`, `@xstate.event`, and `@xstate.snapshot` events. + +```diff + store.inspect((inspectionEvent) => { +- // '@xstate.actor' | '@xstate.event' | '@xstate.snapshot' ++ // '@xstate.transition' ++ inspectionEvent.event; ++ inspectionEvent.snapshot; + }); +``` + +Subscribing to inspection immediately emits the current snapshot as an +`@xstate.transition` event with `{ type: '@xstate.init' }`. Previously, +inspection emitted actor/snapshot events and used the initial snapshot on +subscribe. + +### `store.get()` is the readable read + +Stores are now `Readable>` values. Use: + +- `store.getSnapshot()` for explicit snapshot access. +- `store.get()` when reading the store as a reactive/tracked readable value. + +The two methods currently return the same snapshot, but they communicate +different intent. + +### Computed atom getters no longer receive `read` + +Computed atoms now read other atoms directly through `.get()`. The previous +value remains available as the first argument. + +```diff +- const doubled = createAtom((read) => read(countAtom) * 2); ++ const doubled = createAtom(() => countAtom.get() * 2); + +- const withPrev = createAtom((read, prev) => read(countAtom) + (prev ?? 0)); ++ const withPrev = createAtom((prev) => countAtom.get() + (prev ?? 0)); +``` + +### `store.trigger` is concrete when event types are known + +For config-created stores, `store.trigger` is now built from known event types. +Those event types come from `schemas.events` when present, otherwise from +`Object.keys(on)`. Extension events such as `reset`, `undo`, and `redo` are also +added when those extensions are applied. + +Unknown trigger names no longer exist on those concrete trigger objects. If a +store is created from custom logic without event type metadata, `trigger` keeps +the previous proxy behavior. + +### Store extensions reserve their internal event names + +In development, applying `reset()` to a store that already declares a `reset` +event now throws. Applying `undoRedo()` to a store that already declares `undo` +or `redo` now throws. + +The `persist(...)` extension also reserves its internal rehydration event +(`__persist.rehydrate`). + +Rename the conflicting application event before applying the extension. + +### Persistence writes snapshots, not just context + +`persist(...)` still stores context by default, but it now derives the persisted +value from the full store snapshot. If you use `pick`, it still receives the +context value and controls the persisted context portion. + +`clearStorage(store)` and `flushStorage(store)` may now return a `Promise` when +the configured storage adapter is async. + +## Deleted + +### `@xstate/store/react` and `@xstate/store/solid` + +The framework-specific subpath exports were removed from `@xstate/store`. Use +the dedicated framework packages instead. + +```diff +- import { useSelector } from '@xstate/store/react'; ++ import { useSelector } from '@xstate/store-react'; +``` + +```diff +- import { useSelector } from '@xstate/store/solid'; ++ import { useSelector } from '@xstate/store-solid'; +``` + +The `react` and `solid` package folders are no longer published by +`@xstate/store`, and `react` / `solid-js` are no longer peer dependencies of +`@xstate/store`. + +### `createStoreWithProducer` + +`createStoreWithProducer(...)` was removed. Use `createStore(...)` and call your +producer inside transition handlers. + +```diff +- import { createStoreWithProducer } from '@xstate/store'; ++ import { createStore } from '@xstate/store'; + import { produce } from 'immer'; + +- const store = createStoreWithProducer(produce, { ++ const store = createStore({ + context: { count: 0 }, + on: { +- inc: (context) => { +- context.count++; +- } ++ inc: (context) => ++ produce(context, (draft) => { ++ draft.count++; ++ }) + } + }); +``` + +When using Immer, return `undefined` from the transition before calling +`produce(...)` when the event should be unavailable: + +```ts +inc: (context) => { + if (context.count >= 10) { + return; + } + + return produce(context, (draft) => { + draft.count++; + }); +}; +``` + +Immer treats `undefined` returned from a producer as if the producer did not +return anything. If you need `produce(...)` itself to return `undefined`, return +Immer's `nothing` token from the producer. + +### `createStore(context, transitions)` + +The deprecated two-argument `createStore(context, transitions)` API was removed. +Use the config object form. + +```diff +- const store = createStore( +- { count: 0 }, +- { +- inc: (context) => ({ count: context.count + 1 }) +- } +- ); ++ const store = createStore({ ++ context: { count: 0 }, ++ on: { ++ inc: (context) => ({ count: context.count + 1 }) ++ } ++ }); +``` + +### `undoRedo(config, options)` + +The deprecated config-wrapping form of `undoRedo(...)` was removed. Use the +extension form with `.with(...)`. + +```diff +- const store = createStore( +- undoRedo({ +- context: { count: 0 }, +- on: { +- inc: (context) => ({ count: context.count + 1 }) +- } +- }) +- ); ++ const store = createStore({ ++ context: { count: 0 }, ++ on: { ++ inc: (context) => ({ count: context.count + 1 }) ++ } ++ }).with(undoRedo()); +``` + +### Public `_snapshot` access + +Stores no longer expose `_snapshot`. Use `store.getSnapshot()` for explicit +snapshot reads, or `store.get()` when reading the store as a `Readable`. diff --git a/xstate-store/README.md b/xstate-store/README.md new file mode 100644 index 00000000..c11597cc --- /dev/null +++ b/xstate-store/README.md @@ -0,0 +1,523 @@ +# `@xstate/store` + +XState Store is a library for **simple event-based state management**. If you want a state management library that allows you to update a store's state via events, `@xstate/store` is a great option. If you need more complex application logic needs, like state machines/statecharts, effects, communicating actors, and more, consider [using XState instead](https://github.com/statelyai/xstate). + +- **Extremely simple**: transitions update state via events, just like Redux, Zustand, Pinia, etc. +- **Extremely small**: less than 1kb minified/gzipped +- **XState compatible**: use it with (or without) XState, or convert to XState machines when you need to handle more complex logic & effects. `fromStore()` requires XState v6; with XState v5, use `@xstate/store@4`. +- **Extra type-safe**: great typing out of the box, with strong inference and no awkwardness. + +> [!NOTE] +> This readme is written for [TypeScript](#typescript) users. If you are a JavaScript user, just remove the types. + +## Installation + +```bash +# yarn add @xstate/store +# pnpm add @xstate/store +npm install @xstate/store +``` + +## Quick start + +```ts +import { createStore } from '@xstate/store'; + +export const donutStore = createStore({ + context: { + donuts: 0, + favoriteFlavor: 'chocolate' + }, + on: { + addDonut: (context) => ({ + ...context, + donuts: context.donuts + 1 + }), + changeFlavor: (context, event: { flavor: string }) => ({ + ...context, + favoriteFlavor: event.flavor + }), + eatAllDonuts: (context) => ({ + ...context, + donuts: 0 + }) + } +}); + +donutStore.subscribe((snapshot) => { + console.log(snapshot.context); +}); + +// Equivalent to +// donutStore.send({ type: 'addDonut' }); +donutStore.trigger.addDonut(); +// => { donuts: 1, favoriteFlavor: 'chocolate' } + +// donutStore.send({ +// type: 'changeFlavor', +// flavor: 'strawberry' // Strongly-typed! +// }); +donutStore.trigger.changeFlavor({ flavor: 'strawberry' }); +// => { donuts: 1, favoriteFlavor: 'strawberry' } +``` + +## Checking events + + + +Use `store.can` to check whether an event is allowed without updating the store: + +```ts +const store = createStore({ + context: { count: 0 }, + on: { + increment: (context, event: { by: number }) => { + if (context.count + event.by > 10) { + return; + } + + return { + count: context.count + event.by + }; + } + } +}); + +store.can.increment({ by: 4 }); +// => true +``` + +Returning `undefined` marks the event as not allowed. Returning the same context +object is still allowed, and transitions that enqueue effects are allowed. + +## Persistence + + + +Use the `persist` extension to save state after events are committed. Calling +`store.can` or the pure `store.transition` method does not schedule writes. +Writes preserve commit order, including events triggered synchronously by effects +or subscriptions. A newer eligible event can supersede an older pending write; +`onDone` runs for writes actually performed. Asynchronous writes execute in event +order for each store. Call +`await flushStorage(store)` to write buffered changes and wait for queued writes +to finish. Synchronous storage adapters continue to write synchronously. + +With throttling, `pick` runs once per write on the latest buffered context. +`clearStorage(store)` cancels buffered writes and removes saved data after any +already queued writes finish; await its result when using asynchronous storage. +New events sent after clearing can persist new state. For asynchronous storage, +call `await rehydrateStore(store)` to load saved state; initial read failures are +reported through `onError`. + +```ts +import { persist, flushStorage } from '@xstate/store/persist'; + +const savedDonutStore = donutStore.with(persist({ name: 'donuts' })); +savedDonutStore.trigger.addDonut(); +await flushStorage(savedDonutStore); +``` + +### Undo and persistence + + + +Snapshot-based `undoRedo` restores historical state while preserving live +extension metadata, including persistence hydration. A custom `restore` callback +can enqueue events; their updated extension metadata is preserved too. Apply +`persist` after `undoRedo` when undo and redo themselves should write to storage: + +```ts +import { undoRedo } from '@xstate/store/undo'; + +const undoableDonutStore = donutStore + .with(undoRedo({ strategy: 'snapshot' })) + .with(persist({ name: 'undoable-donuts' })); +``` + +## Atom updates and subscriptions + + + +Reads inside a writable atom's `set(previous => next)` updater do not create +reactive dependencies. Use a computed atom getter to track other atoms instead. +If a synchronous subscriber throws, other queued subscribers still receive their +notifications before the first error is rethrown to the caller. The atom's value +has already changed; later updates continue to notify subscribers normally. + +## Async atoms + + + +`createAsyncAtom` loads a value lazily and exposes a `pending`, `done`, or +`error` state. Atoms read synchronously by its getter remain dependencies after +the request succeeds or fails. When a dependency changes, subscribed async atoms +reload; otherwise, they reload on the next read. Read dependencies before the +first `await` to track them. + +```ts +import { createAtom, createAsyncAtom } from '@xstate/store'; + +const userId = createAtom('ada'); +const user = createAsyncAtom(async ({ signal }) => { + const id = userId.get(); + const response = await fetch(`/users/${id}`, { signal }); + return response.json(); +}); + +user.subscribe((state) => { + if (state.status === 'done') { + console.log(state.data); + } +}); + +userId.set('grace'); // Reloads even after the previous request settled. +``` + +Recomputing aborts the previous getter's signal and ignores its stale result. + +## Usage with React + +Import `useSelector` from `@xstate/store-react`. Select the data you want via `useSelector(…)` and send events using `store.send(eventObject)`: + +```tsx +import { donutStore } from './donutStore.ts'; +import { useSelector } from '@xstate/store-react'; + +function DonutCounter() { + const donutCount = useSelector(donutStore, (state) => state.context.donuts); + + return ( +
+ +
+ ); +} +``` + +## Usage with SolidJS + +Import `useSelector` from `@xstate/store-solid`. Select the data you want via `useSelector(…)` and send events using `store.send(eventObject)`: + +```tsx +import { donutStore } from './donutStore.ts'; +import { useSelector } from '@xstate/store-solid'; + +function DonutCounter() { + const donutCount = useSelector(donutStore, (state) => state.context.donuts); + + return ( +
+ +
+ ); +} +``` + +## Usage with Immer + +XState Store works well with immutable update libraries like [Immer](https://github.com/immerjs/immer) or [Mutative](https://github.com/unadlib/mutative). Use `produce(...)` inside your transition functions: + +```ts +import { createStore } from '@xstate/store'; +import { produce } from 'immer'; // or { create } from 'mutative' + +const donutStore = createStore({ + context: { + donuts: 0, + favoriteFlavor: 'chocolate' + }, + on: { + addDonut: (context) => + produce(context, (draft) => { + draft.donuts++; + }), + changeFlavor: (context, event: { flavor: string }) => + produce(context, (draft) => { + draft.favoriteFlavor = event.flavor; + }), + eatAllDonuts: (context) => + produce(context, (draft) => { + draft.donuts = 0; + }) + } +}); +``` + +If a transition should be unavailable, return `undefined` from the transition +before calling `produce(...)`: + +```ts +on: { + eatDonut: (context) => { + if (context.donuts === 0) { + return; + } + + return produce(context, (draft) => { + draft.donuts--; + }); + }; +} +``` + +Immer treats a producer that returns `undefined` the same as a producer that +does not explicitly return anything. If you need `produce(...)` itself to return +`undefined`, return Immer's `nothing` token from the producer: + +```ts +import { nothing, produce } from 'immer'; + +on: { + eatDonut: (context) => + produce(context, (draft) => { + if (draft.donuts === 0) { + return nothing; + } + + draft.donuts--; + }); +} +``` + +## TypeScript + +XState Store is written in TypeScript and provides full type safety, _without_ you having to specify generic type parameters. The `context` type is inferred from the initial context object, and the event types are inferred from the event object payloads you provide in the transition functions. + +```ts +import { createStore } from '@xstate/store'; + +const donutStore = createStore({ + // Context inferred as: + // { + // donuts: number; + // favoriteFlavor: string; + // } + context: { + donuts: 0, + favoriteFlavor: 'chocolate' + }, + on: { + // Event inferred as: + // { + // type: 'changeFlavor'; + // flavor: string; + // } + changeFlavor: (context, event: { flavor: string }) => { + context.favoriteFlavor = event.flavor; + } + } +}); + +donutStore.getSnapshot().context.favoriteFlavor; // string +donutStore.get().context.favoriteFlavor; // same snapshot, readable/tracked read + +donutStore.send({ + type: 'changeFlavor', // Strongly-typed from transition key + flavor: 'strawberry' // Strongly-typed from { flavor: string } +}); +``` + +If you want to provide event or emitted-event types explicitly, you can use `schemas` with any library that implements the [Standard Schema](https://standardschema.dev/) interface. Schemas define the store's runtime-readable contract: the shape of its context, accepted events, and emitted events. Store uses schemas for type inference and metadata by default; it does not validate schema-declared values unless you opt in with `validateSchemas()`. + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + context: z.object({ + donuts: z.number(), + favoriteFlavor: z.string() + }), + events: { + changeFlavor: z.object({ + flavor: z.string() + }) + }, + emitted: { + flavorChanged: z.object({ + flavor: z.string() + }) + } + }, + context: { + donuts: 0, + favoriteFlavor: 'chocolate' + }, + on: { + changeFlavor: (context, event, enqueue) => { + enqueue.emit.flavorChanged({ flavor: event.flavor }); + return { + ...context, + favoriteFlavor: event.flavor + }; + } + } +}); +``` + +Event and emitted-event schemas describe payload objects. Use an empty object +schema for events without payload: + +```ts +schemas: { + events: { + reset: z.object({}) + }, + emitted: { + reset: z.object({}) + } +} +``` + +### Validating schemas + +Use the `validateSchemas()` extension when the store should validate its schema +contract at runtime: + +```ts +import { createStore } from '@xstate/store'; +import { validateSchemas } from '@xstate/store/validate'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + context: z.object({ + count: z.number() + }), + events: { + increment: z.object({ + by: z.number() + }) + }, + emitted: { + increased: z.object({ + by: z.number() + }) + } + }, + context: { count: 0 }, + on: { + increment: (context, event, enqueue) => { + enqueue.emit.increased({ by: event.by }); + return { count: context.count + event.by }; + } + } +}).with(validateSchemas()); +``` + +`validateSchemas()` validates store macrosteps. It validates the event sent to +the store, the final context after the transition completes, and emitted events +before any effects execute. Events queued internally with `enqueue.trigger` are +processed as part of the same macrostep; their payloads are not separately +validated in this version. + +Invalid `send(...)`, `trigger.*(...)`, or `transition(...)` calls throw a +`StoreValidationError`. `store.can.*(...)` always returns a boolean; validation +errors make it return `false`. + +By default, unknown events and emitted events throw when the corresponding +schema map exists. Extension-added event types are treated as known, even when +they do not have payload schemas. You can opt out: + +```ts +const store = createStore({ + // ... +}).with( + validateSchemas({ + unknownEvents: 'ignore', + unknownEmitted: 'ignore' + }) +); +``` + +Use `store.getSnapshot()` when you want an explicit snapshot read from the store itself. Use `store.get()` when consuming the store as a `Readable` value in tracked or reactive code. + +If you want to make the `context` type more specific, you can strongly type the `context` outside of `createStore(…)` and pass it in: + +```ts +import { createStore } from '@xstate/store'; + +interface DonutContext { + donuts: number; + favoriteFlavor: 'chocolate' | 'strawberry' | 'blueberry'; +} + +const donutContext: DonutContext = { + donuts: 0, + favoriteFlavor: 'chocolate' +}; + +const donutStore = createStore({ + context: donutContext, + on: { + // ... (transitions go here) + } +}); +``` + +## Effects and Side Effects + +You can enqueue effects in state transitions using the `enqueue` argument: + +```ts +import { createStore } from '@xstate/store'; + +const store = createStore({ + context: { count: 0 }, + on: { + incrementDelayed: (context, event, enqueue) => { + enqueue.effect(async () => { + await new Promise((resolve) => setTimeout(resolve, 1000)); + store.send({ type: 'increment' }); + }); + + return context; + }, + increment: (context) => ({ + ...context, + count: context.count + 1 + }) + } +}); +``` + +## Emitting Events + +You can emit events from transitions by declaring them in `schemas.emitted` and using `enqueue.emit`: + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + emitted: { + increased: z.object({ + by: z.number() + }) + } + }, + context: { count: 0 }, + on: { + inc: (context, event: { by: number }, enqueue) => { + enqueue.emit.increased({ by: event.by }); + + return { + ...context, + count: context.count + event.by + }; + } + } +}); + +// Listen for emitted events +store.on('increased', (event) => { + console.log(`Count increased by ${event.by}`); +}); +``` diff --git a/xstate-store/docs/effects-and-emitted-events.md b/xstate-store/docs/effects-and-emitted-events.md new file mode 100644 index 00000000..722fc112 --- /dev/null +++ b/xstate-store/docs/effects-and-emitted-events.md @@ -0,0 +1,61 @@ +--- +title: Effects and emitted events +description: Run effects and notify external subscribers. +--- + +Declare emitted event schemas, then use the enqueue argument to schedule effects after the context transition. + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + emitted: { + 'document.saved': z.object({ id: z.string() }) + } + }, + context: { document: null as Document | null }, + on: { + save: (context, event: { document: Document }, enq) => { + enq.effect(() => saveDocument(event.document)); + enq.emit['document.saved']({ id: event.document.id }); + return { document: event.document }; + } + } +}); +``` + +Subscribe to emitted events without observing every context change. + +```ts +store.on('document.saved', (event) => console.log(event.id)); +``` + +Effects run after the next context is calculated. Emitted events notify external consumers without becoming store transitions. + +Use effects to write a draft to storage or send analytics. Use emitted events to notify a toast system or close a dialog after a save. + +Use `store.inspect(...)` to observe every store transition without changing store behavior. + +```ts +const subscription = store.inspect((event) => { + console.log(event.event, store.getSnapshot().context); +}); + +subscription.unsubscribe(); +``` + +## TypeScript + +Emitted event payloads are inferred from the store configuration. + +## Effects cheatsheet + +```ts +enq.effect(() => runEffect()); +enq.emit.notice({ message }); +enq.trigger.refresh(); +store.on('notice', (event) => console.log(event.message)); +store.inspect((event) => console.log(event)); +``` diff --git a/xstate-store/docs/events-and-context.md b/xstate-store/docs/events-and-context.md new file mode 100644 index 00000000..e0aeea29 --- /dev/null +++ b/xstate-store/docs/events-and-context.md @@ -0,0 +1,82 @@ +--- +title: Events and context +description: Update store context in response to events. +--- + +Each transition receives the current context and event. Return the complete next context. + +```ts +import { createStore } from '@xstate/store'; + +const store = createStore({ + context: { items: [] as string[] }, + on: { + add: (context, event: { item: string }) => ({ + items: [...context.items, event.item] + }), + clear: () => ({ items: [] }) + } +}); +``` + +Check whether the store accepts an event with its typed method on `store.can`. + +```ts +if (store.can.add({ item: 'Milk' })) { + store.trigger.add({ item: 'Milk' }); +} +``` + +Transitions are pure calculations. They return context and enqueue effects, but do not mutate the current context. + +Use events that describe what happened. `itemAdded` and `filtersCleared` are easier to trace than `setState`. + +## Runtime schemas + +Use Standard Schema-compatible validators when events cross a network, storage or user-input boundary. + +```ts +import { createStore } from '@xstate/store'; +import { z } from 'zod'; + +const store = createStore({ + schemas: { + context: z.object({ items: z.array(z.string()) }), + events: { + add: z.object({ item: z.string() }) + } + }, + context: { items: [] }, + on: { + add: (context, event) => ({ + items: [...context.items, event.item] + }) + } +}); +``` + +## Pure transitions + +`store.transition(...)` calculates the next snapshot and effects without updating the store or running those effects. + +```ts +const [nextSnapshot, effects] = store.transition(store.getSnapshot(), { + type: 'add', + item: 'Milk' +}); +``` + +Use pure transitions in tests, previews and server-side validation. + +## TypeScript + +Declare event payloads in the transition parameter or use schema-backed store setup when runtime validation is needed. + +## Events cheatsheet + +```ts +store.send({ type: 'add', item: 'Milk' }); +store.trigger.add({ item: 'Milk' }); +store.can.add({ item: 'Milk' }); +store.transition(snapshot, event); +``` diff --git a/xstate-store/docs/frameworks.md b/xstate-store/docs/frameworks.md new file mode 100644 index 00000000..2a9fbffb --- /dev/null +++ b/xstate-store/docs/frameworks.md @@ -0,0 +1,27 @@ +--- +title: Framework bindings +description: Use XState Store with a UI framework. +--- + +XState Store includes bindings for React, Vue and Solid. + +```tsx +import { useSelector } from '@xstate/store-react'; + +const count = useSelector(store, (snapshot) => snapshot.context.count); +``` + +Use the matching package entry point for the framework: + +- `@xstate/store-react` +- `@xstate/store-vue` +- `@xstate/store-svelte` +- `@xstate/store-solid` +- `@xstate/store-preact` +- `@xstate/store-angular` + +Create the store outside a component when components should share it. Create it inside an application provider when each application instance needs separate state. + +Bindings expose `useSelector(...)` for an existing store and `useStore(...)` for a store created with the component lifecycle. Use selectors for values such as a cart total or the visible rows in a table. + +Do not create a shared server-side store at module scope. Create one per request. diff --git a/xstate-store/docs/meta.json b/xstate-store/docs/meta.json new file mode 100644 index 00000000..3f4403a2 --- /dev/null +++ b/xstate-store/docs/meta.json @@ -0,0 +1,14 @@ +{ + "title": "XState Store", + "pages": [ + "quick-start", + "events-and-context", + "effects-and-emitted-events", + "selectors", + "frameworks", + "persistence", + "undo-redo", + "typescript", + "migration" + ] +} diff --git a/xstate-store/docs/migration.md b/xstate-store/docs/migration.md new file mode 100644 index 00000000..ef0b40fa --- /dev/null +++ b/xstate-store/docs/migration.md @@ -0,0 +1,21 @@ +--- +title: Migration +description: Update applications for the current XState Store API. +--- + +Upgrade the package, then update one store at a time. + +```bash +npm install @xstate/store@alpha +``` + +Check these areas: + +- Transition functions return the complete next context. +- Effects use the transition enqueue argument. +- Framework selectors use packages such as `@xstate/store-react`. +- Persistence and undo imports use their extension entry points. +- Tests send public events instead of changing context directly. +- `fromStore()` requires XState v6; with XState v5, use `@xstate/store@4`. + +Run type checking after each store. Type errors often identify renamed events and incomplete context returns. diff --git a/xstate-store/docs/persistence.md b/xstate-store/docs/persistence.md new file mode 100644 index 00000000..2f9edee4 --- /dev/null +++ b/xstate-store/docs/persistence.md @@ -0,0 +1,48 @@ +--- +title: Persistence +description: Persist and restore XState Store context. +--- + +Use the persistence extension from `@xstate/store/persist`. + +```ts +import { persist } from '@xstate/store/persist'; + +const persistedStore = store.with( + persist({ + name: 'cart', + storage: localStorage + }) +); +``` + +Choose a stable key and version stored data when its shape changes. Do not store secrets in browser storage. + +The default snapshot strategy stores context. Use the event strategy when the event history is useful for replay or audit. + +```ts +store.with( + persist({ + name: 'cart', + version: 2, + pick: ({ items, coupon }) => ({ items, coupon }), + migrate: (stored) => migrateCart(stored) + }) +); +``` + +Use `throttle` for frequent edits such as a draft document. Use `filter` to skip transient events such as hover changes. + +Persistence can restore a cart after a refresh or resume an offline draft. Version persisted data before its context shape changes. + +## TypeScript + +`pick`, `merge` and `migrate` use the store's context type. Keep migration return values compatible with the current context. + +## Persistence cheatsheet + +```ts +store.with( + persist({ name, storage, version, migrate, pick, filter, throttle }) +); +``` diff --git a/xstate-store/docs/quick-start.md b/xstate-store/docs/quick-start.md new file mode 100644 index 00000000..0109e0f4 --- /dev/null +++ b/xstate-store/docs/quick-start.md @@ -0,0 +1,62 @@ +--- +title: Quick start +description: Create and use an XState Store. +--- + +Use XState Store when you need event-based state without a state machine. + +```bash +npm install @xstate/store@alpha +``` + +```ts +import { createStore } from '@xstate/store'; + +const store = createStore({ + context: { count: 0 }, + on: { + increment: (context) => ({ count: context.count + 1 }) + } +}); + +store.subscribe((snapshot) => console.log(snapshot.context.count)); +store.send({ type: 'increment' }); +``` + +Use `store.trigger.increment()` when the event has been declared by name. + +Stores work well for a shopping cart, editable table or shared filters. Use XState instead when events depend on a current state, such as a checkout that only accepts `pay` while it is `reviewing`. + +## Reusable store logic + +Use `createStoreLogic(...)` when several store instances share transitions but start with different input. + +```ts +import { createStoreLogic } from '@xstate/store'; + +const counterLogic = createStoreLogic({ + context: (initialCount: number) => ({ count: initialCount }), + on: { + increment: (context) => ({ count: context.count + 1 }) + } +}); + +const firstCounter = counterLogic.createStore(0); +const secondCounter = counterLogic.createStore(10); +``` + +This fits one cart per shop widget or one editable draft per open tab. + +## TypeScript + +Context and event types are inferred from the store configuration. + +## Store cheatsheet + +```ts +store.send({ type: 'event' }); +store.trigger.event(); +store.getSnapshot(); +store.subscribe((snapshot) => console.log(snapshot.context)); +createStoreLogic(config).createStore(input); +``` diff --git a/xstate-store/docs/selectors.md b/xstate-store/docs/selectors.md new file mode 100644 index 00000000..47ba9a3e --- /dev/null +++ b/xstate-store/docs/selectors.md @@ -0,0 +1,57 @@ +--- +title: Selectors +description: Derive values from store snapshots. +--- + +A selector returns the value a consumer needs. Framework selectors receive a store snapshot. + +```ts +const selectTotal = (snapshot: SnapshotFromStore) => + snapshot.context.items.reduce((total, item) => total + item.price, 0); +``` + +Framework bindings subscribe to the selected value and avoid updates when it stays equal. + +Use `store.select(...)` outside a framework. Its selector receives context and returns a readable value. + +```ts +const total = store.select((context) => + context.items.reduce((sum, item) => sum + item.price, 0) +); + +total.get(); +total.subscribe((value) => console.log(value)); +``` + +Select a cart total, visible rows or an unread count instead of subscribing every consumer to the whole store. + +## Atoms + +Use an atom for one independent value or a value derived from other atoms. + +```ts +import { createAtom } from '@xstate/store'; + +const query = createAtom(''); +const normalizedQuery = createAtom(() => query.get().trim().toLowerCase()); + +query.set(' State Machines '); +normalizedQuery.get(); // 'state machines' +``` + +Use a reducer atom when updates are best expressed as events. Use a store when several values change together in named transitions. + +## TypeScript + +Use `SnapshotFromStore` when a standalone selector needs an explicit snapshot type. + +## Selectors cheatsheet + +```ts +const value = selector(store.getSnapshot()); +const selected = store.select((context) => context.value); +selected.get(); +const atom = createAtom(initialValue); +atom.get(); +atom.set(nextValue); +``` diff --git a/xstate-store/docs/typescript.md b/xstate-store/docs/typescript.md new file mode 100644 index 00000000..3171d90b --- /dev/null +++ b/xstate-store/docs/typescript.md @@ -0,0 +1,32 @@ +--- +title: TypeScript +description: Derive types from an XState Store. +--- + +Store context, events, emitted events and triggers are inferred from the configuration. + +```ts +import type { SnapshotFromStore } from '@xstate/store'; + +type StoreSnapshot = SnapshotFromStore; +``` + +Use `EventFromStore` when another function needs to accept every store event. + +```ts +import type { EventFromStore } from '@xstate/store'; + +function sendFromQueue(event: EventFromStore) { + store.send(event); +} +``` + +Prefer derived types over duplicate interfaces. This keeps consumers aligned with the store. + +## TypeScript cheatsheet + +```ts +type Snapshot = SnapshotFromStore; +type Context = Snapshot['context']; +type Event = EventFromStore; +``` diff --git a/xstate-store/docs/undo-redo.md b/xstate-store/docs/undo-redo.md new file mode 100644 index 00000000..cf875ef2 --- /dev/null +++ b/xstate-store/docs/undo-redo.md @@ -0,0 +1,43 @@ +--- +title: Undo and redo +description: Add history controls to an XState Store. +--- + +Use the undo extension from `@xstate/store/undo`. + +```ts +import { undoRedo } from '@xstate/store/undo'; + +const historyStore = store.with(undoRedo()); +``` + +Send undo and redo events through the returned store. Keep transient UI data outside history when users should not undo it. + +The event strategy replays store events. The snapshot strategy restores saved contexts. + +```ts +const historyStore = store.with( + undoRedo({ + strategy: 'snapshot', + historyLimit: 100, + getTransactionId: (event) => + 'transactionId' in event ? String(event.transactionId) : undefined, + skipEvent: (event) => event.type === 'cursorMoved' + }) +); +``` + +Use transactions to group several text edits into one undo step. Skip events such as cursor movement, presence and analytics. + +Undo and redo fit document editors and drawing tools. They usually should not reverse network responses or another user's changes. + +## TypeScript + +The extension adds typed `undo` and `redo` methods to `trigger` and `can`. + +## Undo cheatsheet + +```ts +historyStore.trigger.undo(); +historyStore.trigger.redo(); +``` diff --git a/xstate-store/package.json b/xstate-store/package.json new file mode 100644 index 00000000..96cfc0ea --- /dev/null +++ b/xstate-store/package.json @@ -0,0 +1,64 @@ +{ + "name": "@xstate/store", + "version": "5.0.0-alpha.5", + "type": "module", + "description": "Simple stores", + "keywords": [ + "store", + "state" + ], + "author": "David Khourshid ", + "homepage": "https://github.com/statelyai/xstate/tree/main/packages/xstate-store#readme", + "license": "MIT", + "exports": { + "./undo": "./dist/xstate-store-undo.js", + ".": "./dist/xstate-store.js", + "./reset": "./dist/xstate-store-reset.js", + "./persist": "./dist/xstate-store-persist.js", + "./validate": "./dist/xstate-store-validate.js", + "./package.json": "./package.json" + }, + "sideEffects": false, + "files": [ + "dist" + ], + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/statelyai/xstate.git" + }, + "bugs": { + "url": "https://github.com/statelyai/xstate/issues" + }, + "peerDependencies": { + "xstate": "workspace:^" + }, + "peerDependenciesMeta": { + "xstate": { + "optional": true + } + }, + "devDependencies": { + "@statelyai/inspect": "^0.7.2", + "@testing-library/vue": "^8.1.0", + "@vitejs/plugin-vue": "^6.0.8", + "@xstate/vue": "workspace:^", + "immer": "^10.0.2", + "react": "^19.0.0", + "solid-js": "^1.9.7", + "vite": "^6.4.3", + "vite-plugin-solid": "^2.11.6", + "vue": "3.5.27", + "xstate": "workspace:^", + "zod": "^4.4.3" + }, + "preconstruct": { + "umdName": "XStateStore", + "entrypoints": [ + "./index.ts", + "./undo.ts", + "./persist.ts", + "./reset.ts", + "./validate.ts" + ] + } +} diff --git a/xstate-store/src/alien.ts b/xstate-store/src/alien.ts new file mode 100644 index 00000000..521d42bf --- /dev/null +++ b/xstate-store/src/alien.ts @@ -0,0 +1,654 @@ +/* oxlint-disable */ +// Adapted from Alien Signals +// https://github.com/stackblitz/alien-signals/ + +export interface ReactiveNode { + deps?: Link; + depsTail?: Link; + subs?: Link; + subsTail?: Link; + flags: ReactiveFlags; +} + +export interface Link { + version: number; + dep: ReactiveNode; + sub: ReactiveNode; + prevSub: Link | undefined; + nextSub: Link | undefined; + prevDep: Link | undefined; + nextDep: Link | undefined; +} + +interface Stack { + value: T; + prev: Stack | undefined; +} + +export const enum ReactiveFlags { + None = 0, + Mutable = 1, + Watching = 2, + RecursedCheck = 4, + Recursed = 8, + Dirty = 16, + Pending = 32 +} + +export function createReactiveSystem({ + update, + notify, + unwatched +}: { + update(sub: ReactiveNode): boolean; + notify(sub: ReactiveNode): void; + unwatched(sub: ReactiveNode): void; +}) { + return { + link, + unlink, + propagate, + checkDirty, + shallowPropagate + }; + + function link(dep: ReactiveNode, sub: ReactiveNode, version: number): void { + const prevDep = sub.depsTail; + if (prevDep !== undefined && prevDep.dep === dep) { + return; + } + const nextDep = prevDep !== undefined ? prevDep.nextDep : sub.deps; + if (nextDep !== undefined && nextDep.dep === dep) { + nextDep.version = version; + sub.depsTail = nextDep; + return; + } + const prevSub = dep.subsTail; + if ( + prevSub !== undefined && + prevSub.version === version && + prevSub.sub === sub + ) { + return; + } + const newLink = + (sub.depsTail = + dep.subsTail = + { + version, + dep, + sub, + prevDep, + nextDep, + prevSub, + nextSub: undefined + }); + if (nextDep !== undefined) { + nextDep.prevDep = newLink; + } + if (prevDep !== undefined) { + prevDep.nextDep = newLink; + } else { + sub.deps = newLink; + } + if (prevSub !== undefined) { + prevSub.nextSub = newLink; + } else { + dep.subs = newLink; + } + } + + function unlink(link: Link, sub = link.sub): Link | undefined { + const dep = link.dep; + const prevDep = link.prevDep; + const nextDep = link.nextDep; + const nextSub = link.nextSub; + const prevSub = link.prevSub; + if (nextDep !== undefined) { + nextDep.prevDep = prevDep; + } else { + sub.depsTail = prevDep; + } + if (prevDep !== undefined) { + prevDep.nextDep = nextDep; + } else { + sub.deps = nextDep; + } + if (nextSub !== undefined) { + nextSub.prevSub = prevSub; + } else { + dep.subsTail = prevSub; + } + if (prevSub !== undefined) { + prevSub.nextSub = nextSub; + } else if ((dep.subs = nextSub) === undefined) { + unwatched(dep); + } + return nextDep; + } + + function propagate(link: Link): void { + let next = link.nextSub; + let stack: Stack | undefined; + + top: do { + const sub = link.sub; + let flags = sub.flags; + + if ( + !( + flags & + (ReactiveFlags.RecursedCheck | + ReactiveFlags.Recursed | + ReactiveFlags.Dirty | + ReactiveFlags.Pending) + ) + ) { + sub.flags = flags | ReactiveFlags.Pending; + } else if ( + !(flags & (ReactiveFlags.RecursedCheck | ReactiveFlags.Recursed)) + ) { + flags = ReactiveFlags.None; + } else if (!(flags & ReactiveFlags.RecursedCheck)) { + sub.flags = (flags & ~ReactiveFlags.Recursed) | ReactiveFlags.Pending; + } else if ( + !(flags & (ReactiveFlags.Dirty | ReactiveFlags.Pending)) && + isValidLink(link, sub) + ) { + sub.flags = flags | (ReactiveFlags.Recursed | ReactiveFlags.Pending); + flags &= ReactiveFlags.Mutable; + } else { + flags = ReactiveFlags.None; + } + + if (flags & ReactiveFlags.Watching) { + notify(sub); + } + + if (flags & ReactiveFlags.Mutable) { + const subSubs = sub.subs; + if (subSubs !== undefined) { + const nextSub = (link = subSubs).nextSub; + if (nextSub !== undefined) { + stack = { value: next, prev: stack }; + next = nextSub; + } + continue; + } + } + + if ((link = next!) !== undefined) { + next = link.nextSub; + continue; + } + + while (stack !== undefined) { + link = stack.value!; + stack = stack.prev; + if (link !== undefined) { + next = link.nextSub; + continue top; + } + } + + break; + } while (true); + } + + function checkDirty(link: Link, sub: ReactiveNode): boolean { + let stack: Stack | undefined; + let checkDepth = 0; + let dirty = false; + + top: do { + const dep = link.dep; + const flags = dep.flags; + + if (sub.flags & ReactiveFlags.Dirty) { + dirty = true; + } else if ( + (flags & (ReactiveFlags.Mutable | ReactiveFlags.Dirty)) === + (ReactiveFlags.Mutable | ReactiveFlags.Dirty) + ) { + if (update(dep)) { + const subs = dep.subs!; + if (subs.nextSub !== undefined) { + shallowPropagate(subs); + } + dirty = true; + } + } else if ( + (flags & (ReactiveFlags.Mutable | ReactiveFlags.Pending)) === + (ReactiveFlags.Mutable | ReactiveFlags.Pending) + ) { + if (link.nextSub !== undefined || link.prevSub !== undefined) { + stack = { value: link, prev: stack }; + } + link = dep.deps!; + sub = dep; + ++checkDepth; + continue; + } + + if (!dirty) { + const nextDep = link.nextDep; + if (nextDep !== undefined) { + link = nextDep; + continue; + } + } + + while (checkDepth--) { + const firstSub = sub.subs!; + const hasMultipleSubs = firstSub.nextSub !== undefined; + if (hasMultipleSubs) { + link = stack!.value; + stack = stack!.prev; + } else { + link = firstSub; + } + if (dirty) { + if (update(sub)) { + if (hasMultipleSubs) { + shallowPropagate(firstSub); + } + sub = link.sub; + continue; + } + dirty = false; + } else { + sub.flags &= ~ReactiveFlags.Pending; + } + sub = link.sub; + const nextDep = link.nextDep; + if (nextDep !== undefined) { + link = nextDep; + continue top; + } + } + + return dirty; + } while (true); + } + + function shallowPropagate(link: Link): void { + do { + const sub = link.sub; + const flags = sub.flags; + if ( + (flags & (ReactiveFlags.Pending | ReactiveFlags.Dirty)) === + ReactiveFlags.Pending + ) { + sub.flags = flags | ReactiveFlags.Dirty; + if ( + (flags & (ReactiveFlags.Watching | ReactiveFlags.RecursedCheck)) === + ReactiveFlags.Watching + ) { + notify(sub); + } + } + } while ((link = link.nextSub!) !== undefined); + } + + function isValidLink(checkLink: Link, sub: ReactiveNode): boolean { + let link = sub.depsTail; + while (link !== undefined) { + if (link === checkLink) { + return true; + } + link = link.prevDep; + } + return false; + } +} + +interface EffectNode extends ReactiveNode { + fn(): void; +} + +interface ComputedNode extends ReactiveNode { + value: T | undefined; + getter: (previousValue?: T) => T; +} + +interface SignalNode extends ReactiveNode { + currentValue: T; + pendingValue: T; +} + +let cycle = 0; +let batchDepth = 0; +let notifyIndex = 0; +let queuedLength = 0; +let activeSub: ReactiveNode | undefined; + +const queued: (EffectNode | undefined)[] = []; +const { link, unlink, propagate, checkDirty, shallowPropagate } = + createReactiveSystem({ + update(node: SignalNode | ComputedNode): boolean { + if (node.depsTail !== undefined) { + return updateComputed(node as ComputedNode); + } else { + return updateSignal(node as SignalNode); + } + }, + notify(effect: EffectNode) { + let insertIndex = queuedLength; + let firstInsertedIndex = insertIndex; + + do { + queued[insertIndex++] = effect; + effect.flags &= ~ReactiveFlags.Watching; + effect = effect.subs?.sub as EffectNode; + if (effect === undefined || !(effect.flags & ReactiveFlags.Watching)) { + break; + } + } while (true); + + queuedLength = insertIndex; + + while (firstInsertedIndex < --insertIndex) { + const left = queued[firstInsertedIndex]; + queued[firstInsertedIndex++] = queued[insertIndex]; + queued[insertIndex] = left; + } + }, + unwatched(node) { + if (!(node.flags & ReactiveFlags.Mutable)) { + effectScopeOper.call(node); + } else if (node.depsTail !== undefined) { + node.depsTail = undefined; + node.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty; + purgeDeps(node); + } + } + }); + +export function getActiveSub(): ReactiveNode | undefined { + return activeSub; +} + +export function setActiveSub(sub?: ReactiveNode) { + const prevSub = activeSub; + activeSub = sub; + return prevSub; +} + +export function getBatchDepth(): number { + return batchDepth; +} + +export function startBatch() { + ++batchDepth; +} + +export function endBatch() { + if (!--batchDepth) { + flush(); + } +} + +export function isSignal(fn: () => void): boolean { + return fn.name === 'bound ' + signalOper.name; +} + +export function isComputed(fn: () => void): boolean { + return fn.name === 'bound ' + computedOper.name; +} + +export function isEffect(fn: () => void): boolean { + return fn.name === 'bound ' + effectOper.name; +} + +export function isEffectScope(fn: () => void): boolean { + return fn.name === 'bound ' + effectScopeOper.name; +} + +export function signal(): { + (): T | undefined; + (value: T | undefined): void; +}; +export function signal(initialValue: T): { + (): T; + (value: T): void; +}; +export function signal(initialValue?: T): { + (): T | undefined; + (value: T | undefined): void; +} { + return signalOper.bind({ + currentValue: initialValue, + pendingValue: initialValue, + subs: undefined, + subsTail: undefined, + flags: ReactiveFlags.Mutable + }) as () => T | undefined; +} + +export function computed(getter: (previousValue?: T) => T): () => T { + return computedOper.bind({ + value: undefined, + subs: undefined, + subsTail: undefined, + deps: undefined, + depsTail: undefined, + flags: ReactiveFlags.None, + getter: getter as (previousValue?: unknown) => unknown + }) as () => T; +} + +export function effect(fn: () => void): () => void { + const e: EffectNode = { + fn, + subs: undefined, + subsTail: undefined, + deps: undefined, + depsTail: undefined, + flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck + }; + const prevSub = setActiveSub(e); + if (prevSub !== undefined) { + link(e, prevSub, 0); + } + try { + e.fn(); + } finally { + activeSub = prevSub; + e.flags &= ~ReactiveFlags.RecursedCheck; + } + return effectOper.bind(e); +} + +export function effectScope(fn: () => void): () => void { + const e: ReactiveNode = { + deps: undefined, + depsTail: undefined, + subs: undefined, + subsTail: undefined, + flags: ReactiveFlags.None + }; + const prevSub = setActiveSub(e); + if (prevSub !== undefined) { + link(e, prevSub, 0); + } + try { + fn(); + } finally { + activeSub = prevSub; + } + return effectScopeOper.bind(e); +} + +export function trigger(fn: () => void) { + const sub: ReactiveNode = { + deps: undefined, + depsTail: undefined, + flags: ReactiveFlags.Watching + }; + const prevSub = setActiveSub(sub); + try { + fn(); + } finally { + activeSub = prevSub; + let link = sub.deps; + while (link !== undefined) { + const dep = link.dep; + link = unlink(link, sub); + const subs = dep.subs; + if (subs !== undefined) { + sub.flags = ReactiveFlags.None; + propagate(subs); + shallowPropagate(subs); + } + } + if (!batchDepth) { + flush(); + } + } +} + +function updateComputed(c: ComputedNode): boolean { + ++cycle; + c.depsTail = undefined; + c.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck; + const prevSub = setActiveSub(c); + try { + const oldValue = c.value; + return oldValue !== (c.value = c.getter(oldValue)); + } finally { + activeSub = prevSub; + c.flags &= ~ReactiveFlags.RecursedCheck; + purgeDeps(c); + } +} + +function updateSignal(s: SignalNode): boolean { + s.flags = ReactiveFlags.Mutable; + return s.currentValue !== (s.currentValue = s.pendingValue); +} + +function run(e: EffectNode): void { + const flags = e.flags; + if ( + flags & ReactiveFlags.Dirty || + (flags & ReactiveFlags.Pending && checkDirty(e.deps!, e)) + ) { + ++cycle; + e.depsTail = undefined; + e.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck; + const prevSub = setActiveSub(e); + try { + (e as EffectNode).fn(); + } finally { + activeSub = prevSub; + e.flags &= ~ReactiveFlags.RecursedCheck; + purgeDeps(e); + } + } else { + e.flags = ReactiveFlags.Watching; + } +} + +function flush(): void { + try { + while (notifyIndex < queuedLength) { + const effect = queued[notifyIndex]!; + queued[notifyIndex++] = undefined; + run(effect); + } + } finally { + while (notifyIndex < queuedLength) { + const effect = queued[notifyIndex]!; + queued[notifyIndex++] = undefined; + effect.flags |= ReactiveFlags.Watching | ReactiveFlags.Recursed; + } + notifyIndex = 0; + queuedLength = 0; + } +} + +function computedOper(this: ComputedNode): T { + const flags = this.flags; + if ( + flags & ReactiveFlags.Dirty || + (flags & ReactiveFlags.Pending && + (checkDirty(this.deps!, this) || + ((this.flags = flags & ~ReactiveFlags.Pending), false))) + ) { + if (updateComputed(this)) { + const subs = this.subs; + if (subs !== undefined) { + shallowPropagate(subs); + } + } + } else if (!flags) { + this.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck; + const prevSub = setActiveSub(this); + try { + this.value = this.getter(); + } finally { + activeSub = prevSub; + this.flags &= ~ReactiveFlags.RecursedCheck; + } + } + const sub = activeSub; + if (sub !== undefined) { + link(this, sub, cycle); + } + return this.value!; +} + +function signalOper(this: SignalNode, ...value: [T]): T | void { + if (value.length) { + if (this.pendingValue !== (this.pendingValue = value[0])) { + this.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty; + const subs = this.subs; + if (subs !== undefined) { + propagate(subs); + if (!batchDepth) { + flush(); + } + } + } + } else { + if (this.flags & ReactiveFlags.Dirty) { + if (updateSignal(this)) { + const subs = this.subs; + if (subs !== undefined) { + shallowPropagate(subs); + } + } + } + let sub = activeSub; + while (sub !== undefined) { + if (sub.flags & (ReactiveFlags.Mutable | ReactiveFlags.Watching)) { + link(this, sub, cycle); + break; + } + sub = sub.subs?.sub; + } + return this.currentValue; + } +} + +function effectOper(this: EffectNode): void { + effectScopeOper.call(this); +} + +function effectScopeOper(this: ReactiveNode): void { + this.depsTail = undefined; + this.flags = ReactiveFlags.None; + purgeDeps(this); + const sub = this.subs; + if (sub !== undefined) { + unlink(sub); + } +} + +function purgeDeps(sub: ReactiveNode) { + const depsTail = sub.depsTail; + let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps; + while (dep !== undefined) { + dep = unlink(dep, sub); + } +} diff --git a/xstate-store/src/atom.ts b/xstate-store/src/atom.ts new file mode 100644 index 00000000..8ecacf9d --- /dev/null +++ b/xstate-store/src/atom.ts @@ -0,0 +1,420 @@ +import { + createReactiveSystem, + type ReactiveNode, + ReactiveFlags +} from './alien.ts'; +import { + AnyAtom, + Atom, + AtomConfig, + AtomOptions, + Observer, + ReducerAtom, + ReadonlyAtom, + Subscription +} from './types.ts'; + +/** Returns `true` if `value` is an atom (has `get` and `subscribe` methods). */ +export function isAtom(value: unknown): value is AnyAtom { + return ( + typeof value === 'object' && + value !== null && + typeof (value as any).get === 'function' && + typeof (value as any).subscribe === 'function' + ); +} + +interface InternalAtom extends ReactiveNode { + _snapshot: T; + _update(getValue?: T | ((snapshot: T) => T)): boolean; + get(): T; + subscribe(observerOrFn: Observer | ((value: T) => void)): Subscription; +} + +const queuedEffects: (Effect | undefined)[] = []; +let cycle = 0; +const { link, unlink, propagate, checkDirty, shallowPropagate } = + createReactiveSystem({ + update(atom: InternalAtom): boolean { + return atom._update(); + }, + notify(effect: Effect): void { + queuedEffects[queuedEffectsLength++] = effect; + effect.flags &= ~ReactiveFlags.Watching; + }, + unwatched(atom: InternalAtom): void { + if (atom.depsTail !== undefined) { + atom.depsTail = undefined; + atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty; + purgeDeps(atom); + } + } + }); + +let notifyIndex = 0; +let queuedEffectsLength = 0; +let activeSub: ReactiveNode | undefined; + +function purgeDeps(sub: ReactiveNode) { + const depsTail = sub.depsTail; + let dep = depsTail !== undefined ? depsTail.nextDep : sub.deps; + while (dep !== undefined) { + dep = unlink(dep, sub); + } +} + +function flush(): void { + let didThrow = false; + let firstError: unknown; + try { + while (notifyIndex < queuedEffectsLength) { + const effect = queuedEffects[notifyIndex]!; + queuedEffects[notifyIndex++] = undefined; + try { + effect.notify(); + } catch (error) { + effect.flags |= ReactiveFlags.Watching | ReactiveFlags.Recursed; + if (!didThrow) { + didThrow = true; + firstError = error; + } + } + } + } finally { + notifyIndex = 0; + queuedEffectsLength = 0; + } + if (didThrow) { + throw firstError; + } +} + +/** The current state of an async atom. */ +export type AsyncAtomState = + | { status: 'pending' } + | { status: 'done'; data: Data } + | { status: 'error'; error: Error }; + +/** Options passed to an async atom getter. */ +export interface AsyncAtomOptions { + /** Signal aborted when the async atom recomputes before this run settles. */ + signal: AbortSignal; +} + +function updateAsyncAtom( + atom: InternalAtom>, + nextValue: AsyncAtomState, + compare: ( + previous: AsyncAtomState, + next: AsyncAtomState + ) => boolean = Object.is +): void { + // Settling changes the value without recollecting the getter's dependencies. + if (!compare(atom._snapshot, nextValue)) { + atom._snapshot = nextValue; + const subs = atom.subs; + if (subs !== undefined) { + propagate(subs); + shallowPropagate(subs); + flush(); + } + } +} + +/** + * Creates a read-only atom whose value is loaded from an async getter. + * + * The getter receives an `AbortSignal`; when the async atom recomputes, the + * previous signal is aborted and stale resolutions are ignored. + */ +export function createAsyncAtom( + getValue: (options: AsyncAtomOptions) => Promise, + options?: AtomOptions> +): ReadonlyAtom> { + const ref: { current?: InternalAtom> } = {}; + let currentController: AbortController | undefined; + let currentRunId = 0; + + const atom = createAtom>(() => { + currentController?.abort(); + + const controller = new AbortController(); + const runId = ++currentRunId; + currentController = controller; + + getValue({ signal: controller.signal }).then( + (data) => { + if (runId !== currentRunId || controller.signal.aborted) { + return; + } + updateAsyncAtom( + ref.current!, + { status: 'done', data }, + options?.compare + ); + }, + (error) => { + if (runId !== currentRunId || controller.signal.aborted) { + return; + } + updateAsyncAtom( + ref.current!, + { status: 'error', error }, + options?.compare + ); + } + ); + + return { status: 'pending' } satisfies AsyncAtomState; + }, options); + ref.current = atom as unknown as InternalAtom>; + + return atom; +} + +/** + * Creates an atom. + * + * Pass a value for a writable atom or a getter for a computed read-only atom. + */ +export function createAtom( + getValue: (prev?: T) => T, + options?: AtomOptions +): ReadonlyAtom; +export function createAtom( + initialValue: T, + options?: AtomOptions +): Atom; +export function createAtom( + valueOrFn: T | ((prev?: T) => T), + optionsOrInput?: AtomOptions +): Atom | ReadonlyAtom { + const isComputed = typeof valueOrFn === 'function'; + const getter = valueOrFn as (prev?: T) => T; + + // Create plain object atom + const atom: InternalAtom = { + _snapshot: isComputed ? undefined! : valueOrFn, + + subs: undefined, + subsTail: undefined, + deps: undefined, + depsTail: undefined, + flags: isComputed ? ReactiveFlags.None : ReactiveFlags.Mutable, + + get(): T { + if (activeSub !== undefined) { + link(atom, activeSub, cycle); + } + return atom._snapshot; + }, + + subscribe(observerOrFn: Observer | ((value: T) => void)) { + const observer = + typeof observerOrFn === 'function' + ? { next: observerOrFn } + : observerOrFn; + const observed = { current: false }; + const e = effect(() => { + atom.get(); + if (!observed.current) { + observed.current = true; + } else { + const prevSub = activeSub; + activeSub = undefined; + try { + observer.next?.(atom._snapshot); + } finally { + activeSub = prevSub; + } + + // If the observer synchronously updates any of our deps we'll be + // marked as dirty preventing this effect from re-running. Request + // the value again to reconcile any dirty deps. + atom.get(); + } + }); + + return { + unsubscribe: () => { + e.stop(); + } + }; + }, + _update(getValue?: T | ((snapshot: T) => T)): boolean { + const prevSub = activeSub; + const compare = optionsOrInput?.compare ?? Object.is; + activeSub = isComputed ? atom : undefined; + ++cycle; + atom.depsTail = undefined; + if (isComputed) { + atom.flags = ReactiveFlags.Mutable | ReactiveFlags.RecursedCheck; + } + try { + const oldValue = atom._snapshot; + const newValue = + typeof getValue === 'function' + ? (getValue as (snapshot: T) => T)(oldValue) + : getValue === undefined && isComputed + ? getter(oldValue) + : getValue!; + if (oldValue === undefined || !compare(oldValue, newValue)) { + atom._snapshot = newValue; + return true; + } + return false; + } finally { + activeSub = prevSub; + if (isComputed) { + atom.flags &= ~ReactiveFlags.RecursedCheck; + } + purgeDeps(atom); + } + } + }; + + if (isComputed) { + atom.flags = ReactiveFlags.Mutable | ReactiveFlags.Dirty; + atom.get = function (): T { + const flags = atom.flags; + if ( + flags & ReactiveFlags.Dirty || + (flags & ReactiveFlags.Pending && checkDirty(atom.deps!, atom)) + ) { + if (atom._update()) { + const subs = atom.subs; + if (subs !== undefined) { + shallowPropagate(subs); + } + } + } else if (flags & ReactiveFlags.Pending) { + atom.flags = flags & ~ReactiveFlags.Pending; + } + if (activeSub !== undefined) { + link(atom, activeSub, cycle); + } + return atom._snapshot; + }; + } else { + (atom as unknown as Atom).set = function ( + valueOrFn: T | ((prev: T) => T) + ): void { + if (atom._update(valueOrFn)) { + const subs = atom.subs; + if (subs !== undefined) { + propagate(subs); + shallowPropagate(subs); + flush(); + } + } + }; + } + + return atom as unknown as Atom | ReadonlyAtom; +} + +/** + * Creates an inert atom config that can be instantiated later. + * + * Useful for framework hooks that need to create a stable local atom from + * component input. + */ +export function createAtomConfig( + getInitialValue: (input: TInput) => T, + options?: AtomOptions +): AtomConfig; +export function createAtomConfig( + initialValue: T, + options?: AtomOptions +): AtomConfig; +export function createAtomConfig( + initialValueOrFn: T | ((input: TInput) => T), + options?: AtomOptions +): AtomConfig { + return { + createAtom(input?: TInput) { + const initialValue = + typeof initialValueOrFn === 'function' + ? (initialValueOrFn as (input: TInput) => T)(input as TInput) + : initialValueOrFn; + + return createAtom(initialValue, options); + } + }; +} + +/** Creates an atom whose updates are handled by a reducer function. */ +export function createReducerAtom( + initialValue: TState, + reducer: (state: TState, event: TEvent) => TState, + options?: AtomOptions +): ReducerAtom { + const atom = createAtom(initialValue, options); + + return { + get: atom.get.bind(atom), + subscribe: atom.subscribe.bind(atom), + send(event) { + const prevSub = activeSub; + activeSub = undefined; + let nextState: TState; + try { + nextState = reducer(atom.get(), event); + } finally { + activeSub = prevSub; + } + atom.set(nextState); + } + }; +} + +interface Effect extends ReactiveNode { + notify(): void; + stop(): void; +} + +function effect(fn: () => T): Effect { + const run = (): T => { + const prevSub = activeSub; + activeSub = effectObj; + ++cycle; + effectObj.depsTail = undefined; + effectObj.flags = ReactiveFlags.Watching | ReactiveFlags.RecursedCheck; + try { + return fn(); + } finally { + activeSub = prevSub; + effectObj.flags &= ~ReactiveFlags.RecursedCheck; + purgeDeps(effectObj); + } + }; + const effectObj: Effect = { + deps: undefined, + depsTail: undefined, + subs: undefined, + subsTail: undefined, + flags: ReactiveFlags.Watching | ReactiveFlags.RecursedCheck, + + notify(): void { + const flags = this.flags; + if ( + flags & ReactiveFlags.Dirty || + (flags & ReactiveFlags.Pending && checkDirty(this.deps!, this)) + ) { + run(); + } else { + this.flags = ReactiveFlags.Watching; + } + }, + + stop(): void { + this.flags = ReactiveFlags.None; + this.depsTail = undefined; + purgeDeps(this); + } + }; + + run(); + + return effectObj; +} diff --git a/xstate-store/src/fromStore.ts b/xstate-store/src/fromStore.ts new file mode 100644 index 00000000..3b8a4a84 --- /dev/null +++ b/xstate-store/src/fromStore.ts @@ -0,0 +1,337 @@ +import type { + ActorLogic, + ActorSystemRuntime, + ExecutableActionObject +} from 'xstate'; +import { + createStoreTransition, + TransitionsFromEventPayloadMap +} from './store.ts'; +import { + EnqueueObject, + EventPayloadMap, + StoreContext, + Snapshot, + StoreSnapshot, + EventObject, + ExtractEvents, + InferSchemaPayloadMap, + ResolveStoreContext, + ResolveStoreEmittedPayloadMap, + StoreSchemas, + StandardSchemaMap +} from './types.ts'; +import type { StandardSchemaV1 } from './schema.ts'; + +type StoreLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TInput, + TEmitted extends EventObject +> = ActorLogic, TEvent, TInput, any, TEmitted>; + +type FromStoreEmittedEvents< + TEmittedPayloadMap extends EventPayloadMap, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = ExtractEvents< + ResolveStoreEmittedPayloadMap +>; + +type InferredFromStoreTransitions< + TContext extends StoreContext, + TTransitions extends Record any>, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = Record< + string, + ( + context: NoInfer>, + event: any, + enq: EnqueueObject< + ResolveStoreContext, + FromStoreEmittedEvents, + InferredEventPayloadMap + > + ) => ResolveStoreContext | void +>; + +type InferredEventPayloadMap< + TTransitions extends Record any> +> = { + [K in keyof TTransitions & string]: TTransitions[K] extends ( + context: any, + event: infer TEvent, + ...args: any[] + ) => any + ? Omit + : {}; +}; + +type SchemaFromStoreTransitions< + TContext extends StoreContext, + TEventSchemaMap extends StandardSchemaMap, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = TransitionsFromEventPayloadMap< + InferSchemaPayloadMap, + NoInfer>, + FromStoreEmittedEvents +>; + +type FromStoreValueConfig< + TContext extends StoreContext, + TTransitions extends Record any>, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = { + context: ResolveStoreContext; + schemas?: StoreSchemas; + on: TTransitions & + InferredFromStoreTransitions< + TContext, + TTransitions, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + >; +}; + +type FromStoreInputConfig< + TContext extends StoreContext, + TTransitions extends Record any>, + TInput, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = { + context: (input: TInput) => ResolveStoreContext; + schemas?: StoreSchemas; + on: TTransitions & + InferredFromStoreTransitions< + TContext, + TTransitions, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + >; +}; + +type SchemaFromStoreValueConfig< + TContext extends StoreContext, + TEventSchemaMap extends StandardSchemaMap, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = { + context: ResolveStoreContext; + schemas: StoreSchemas & { + events: TEventSchemaMap; + }; + on: SchemaFromStoreTransitions< + TContext, + TEventSchemaMap, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + >; +}; + +type SchemaFromStoreInputConfig< + TContext extends StoreContext, + TEventSchemaMap extends StandardSchemaMap, + TInput, + TEmittedPayloadMap extends EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = { + context: (input: TInput) => ResolveStoreContext; + schemas: StoreSchemas & { + events: TEventSchemaMap; + }; + on: SchemaFromStoreTransitions< + TContext, + TEventSchemaMap, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + >; +}; + +/** + * An actor logic creator which creates store [actor + * logic](https://stately.ai/docs/actors#actor-logic) for use with XState. + * + * @param config An object containing the store configuration + * @param config.context The initial context for the store, either a function + * that returns context based on input, or the context itself + * @param config.schemas Optional standard-schema definitions used as type + * sources for context, events, and emitted events + * @param config.on An object defining the transitions for different event types + * @returns An actor logic creator function that creates store actor logic + */ +export function fromStore< + TContext extends StoreContext, + const TTransitions extends Record any>, + TInput, + TEmittedPayloadMap extends EventPayloadMap = EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: FromStoreInputConfig< + TContext, + TTransitions, + TInput, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + > +): StoreLogic< + ResolveStoreContext, + ExtractEvents>, + TInput, + FromStoreEmittedEvents +>; +export function fromStore< + TContext extends StoreContext, + const TTransitions extends Record any>, + TEmittedPayloadMap extends EventPayloadMap = EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: FromStoreValueConfig< + TContext, + TTransitions, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + > +): StoreLogic< + ResolveStoreContext, + ExtractEvents>, + unknown, + FromStoreEmittedEvents +>; +export function fromStore< + TContext extends StoreContext, + TEventSchemaMap extends StandardSchemaMap, + TInput, + TEmittedPayloadMap extends EventPayloadMap = EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: SchemaFromStoreInputConfig< + TContext, + TEventSchemaMap, + TInput, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + > +): StoreLogic< + ResolveStoreContext, + ExtractEvents>, + TInput, + FromStoreEmittedEvents +>; +export function fromStore< + TContext extends StoreContext, + TEventSchemaMap extends StandardSchemaMap, + TEmittedPayloadMap extends EventPayloadMap = EventPayloadMap, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: SchemaFromStoreValueConfig< + TContext, + TEventSchemaMap, + TEmittedPayloadMap, + TContextSchema, + TEmittedSchemaMap + > +): StoreLogic< + ResolveStoreContext, + ExtractEvents>, + unknown, + FromStoreEmittedEvents +>; +export function fromStore(config: { + context: ((input: unknown) => StoreContext) | StoreContext; + schemas?: StoreSchemas; + on: TransitionsFromEventPayloadMap; +}): StoreLogic { + const initialContext = config.context; + const transition = createStoreTransition(config.on); + const initialTransition: StoreLogic< + any, + any, + any, + any + >['initialTransition'] = (input: unknown, _: unknown) => [ + { + status: 'active', + context: + typeof initialContext === 'function' + ? initialContext(input) + : initialContext, + output: undefined, + error: undefined + }, + [] + ]; + + return { + transition: (snapshot, event, actorScope) => { + const [nextSnapshot, effects] = transition(snapshot, event); + + return [ + nextSnapshot, + effects.map((effect) => { + if (typeof effect === 'function') { + const action = ( + system: Partial = actorScope.self.system + ) => { + const send = (event: EventObject) => + void system.sendEvent!(actorScope.self, actorScope.self, event); + return effect({ + send, + trigger: new Proxy({} as any, { + get: (_, eventType: string) => { + return (payload: any) => + send({ type: eventType, ...payload }); + } + }), + getSnapshot: () => actorScope.self.getSnapshot() + }); + }; + return { + kind: 'action', + type: 'effect', + action, + params: undefined, + args: [], + exec: action + }; + } + return { + kind: 'emit', + type: effect.type, + source: actorScope.self, + event: effect, + params: undefined, + args: [], + exec: ( + system: Partial = actorScope.self.system + ) => system.emitEvent!(actorScope.self, effect) + }; + }) + ]; + }, + initialTransition, + getInitialSnapshot: (actorScope, input: unknown) => + initialTransition(input, actorScope)[0], + getPersistedSnapshot: (s: Snapshot) => s, + restoreSnapshot: (s: Snapshot) => s as StoreSnapshot + }; +} diff --git a/xstate-store/src/index.ts b/xstate-store/src/index.ts new file mode 100644 index 00000000..4ad42f48 --- /dev/null +++ b/xstate-store/src/index.ts @@ -0,0 +1,72 @@ +export { shallowEqual } from './shallowEqual.ts'; +export { fromStore } from './fromStore.ts'; +export { createStore, createStoreConfig, createStoreLogic } from './store.ts'; +export { + createAtom, + createAtomConfig, + createAsyncAtom, + createReducerAtom, + isAtom +} from './atom.ts'; +export type { AsyncAtomOptions, AsyncAtomState } from './atom.ts'; +export type { StandardSchemaV1 } from './schema.ts'; +export type { + EventPayloadMap, + ExtractEvents, + StandardSchemaMap, + InferSchemaOutput, + InferSchemaPayloadMap, + StoreSchemas, + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ResolveStoreEmittedPayloadMap, + StoreEffect, + StoreEffectEnqueue, + EnqueueObject, + TriggerObject, + CanObject, + StoreAssigner, + StoreSnapshot, + Store, + StoreConfig, + StoreContext, + AnyStore, + SnapshotFromStore, + EventFromStore, + Observer, + Subscription, + Subscribable, + EventObject, + StoreInspectionEvent, + StoreInspectedSnapshotEvent, + StoreInspectedActionEvent, + StoreInspectedEventEvent, + StoreInspectedActorEvent, + ActorRefLike, + Selector, + Selection, + StoreSelectorsConfig, + ResolvedStoreSelectors, + StoreWithSelectors, + StoreLogicCreator, + AnyStoreLogicCreator, + StoreFromStoreLogicCreator, + InputFromStoreLogicCreator, + Readable, + BaseAtom, + Atom, + AtomConfig, + AnyAtomConfig, + ValueFromAtomConfig, + InputFromAtomConfig, + ReducerAtom, + AtomOptions, + AnyAtom, + ReadonlyAtom, + AnyStoreConfig, + EventFromStoreConfig, + EmitsFromStoreConfig, + ContextFromStoreConfig, + StoreFromStoreConfig, + StoreExtension +} from './types.ts'; diff --git a/xstate-store/src/persist.ts b/xstate-store/src/persist.ts new file mode 100644 index 00000000..be5be677 --- /dev/null +++ b/xstate-store/src/persist.ts @@ -0,0 +1,1083 @@ +import { + AnyStoreLogic, + EventObject, + EventPayloadMap, + StoreContext, + StoreExtension, + StoreLogic, + StoreSnapshot +} from './types.ts'; +import { assertNoInternalEventTypeCollisions } from './store.ts'; + +/** + * Storage interface compatible with `localStorage`, `sessionStorage`, and async + * storage adapters (React Native AsyncStorage, IndexedDB, etc.). + */ +export interface StateStorage { + getItem: (name: string) => string | null | Promise; + setItem: (name: string, value: string) => void | Promise; + removeItem: (name: string) => void | Promise; +} + +/** The envelope persisted to storage for snapshot strategy. @public */ +export interface PersistStorageValue { + context: Partial; + version: string | number; +} + +/** The envelope persisted to storage for event strategy. @public */ +export interface PersistEventStorageValue< + TEvent extends EventObject = EventObject +> { + events: TEvent[]; + /** + * Snapshot checkpoint from which to replay events. When events are truncated + * by `maxEvents`, this stores the context at the truncation point so replay + * produces the correct state. + */ + checkpoint?: unknown; + version: string | number; +} + +/** Base options shared by both persist strategies. @public */ +export interface PersistBaseOptions { + /** Storage key (required). */ + name: string; + /** Storage adapter. Defaults to `localStorage`. */ + storage?: StateStorage; + /** Schema version. Defaults to 0. */ + version?: string | number; + /** Minimum milliseconds between storage writes. Defaults to 0 (immediate). */ + throttle?: number; + /** Called after a successful storage write. */ + onDone?: (data: any) => void; + /** Called when a storage read or write fails. */ + onError?: (error: unknown) => void; + /** Skip automatic hydration on store creation. Defaults to `false`. */ + skipHydration?: boolean; +} + +/** Options for the snapshot persist strategy (default). @public */ +export interface PersistSnapshotOptions< + TContext = StoreContext, + TEvent extends EventObject = EventObject +> extends PersistBaseOptions { + /** Persist strategy. Defaults to `'snapshot'`. */ + strategy?: 'snapshot'; + /** + * Controls whether an event should trigger a storage write. Return `false` to + * skip persisting for that event. + */ + filter?: (event: TEvent) => boolean; + /** Select which parts of context to persist. Defaults to full context. */ + pick?: (context: TContext) => Partial; + /** Migration function for version upgrades. */ + migrate?: (persistedContext: any, version: string | number) => TContext; + /** + * Custom merge strategy when rehydrating. Defaults to shallow merge (`{ + * ...currentContext, ...persistedContext }`). + */ + merge?: ( + persistedContext: Partial, + currentContext: TContext + ) => TContext; + /** Custom serializer. Defaults to `JSON.stringify`. */ + serialize?: (value: PersistStorageValue) => string; + /** Custom deserializer. Defaults to `JSON.parse`. */ + deserialize?: (str: string) => PersistStorageValue; +} + +/** Options for the event persist strategy. @public */ +export interface PersistEventOptions< + _TContext = StoreContext, + TEvent extends EventObject = EventObject +> extends PersistBaseOptions { + /** Persist strategy. */ + strategy: 'event'; + /** + * Maximum number of events to keep. When exceeded, a snapshot checkpoint is + * saved and oldest events are dropped. Replay starts from the checkpoint. + * Defaults to Infinity. + */ + maxEvents?: number; + /** Migration function for version upgrades. Receives the stored events array. */ + migrate?: (persistedEvents: any[], version: string | number) => any[]; + /** Custom serializer. Defaults to `JSON.stringify`. */ + serialize?: (value: PersistEventStorageValue) => string; + /** Custom deserializer. Defaults to `JSON.parse`. */ + deserialize?: (str: string) => PersistEventStorageValue; +} + +/** Options for the `persist` store extension. @public */ +export type PersistOptions< + TContext = StoreContext, + TEvent extends EventObject = EventObject +> = + | PersistSnapshotOptions + | PersistEventOptions; + +// Internal helpers +const PERSIST_INTERNALS: unique symbol = Symbol.for('xstate-store-persist'); +const PERSIST_REVISION: unique symbol = Symbol('xstate-store-persist-revision'); + +interface PersistInternals { + options: PersistOptions; + storage: StateStorage; + pendingContext: Partial | null; + pendingEvents: TEvent[] | null; + pendingCheckpoint: unknown; + flushTimeoutId: ReturnType | null; + pendingWrite: Promise | null; + lastScheduledRevision: number; + flush: () => void | Promise; +} + +const PERSIST_REHYDRATE_EVENT_TYPE = '__persist.rehydrate'; +const noopStorage: StateStorage = { + getItem: () => null, + setItem: () => {}, + removeItem: () => {} +}; + +function getStorage(options: PersistOptions): StateStorage { + return options.storage ?? createJSONStorage(() => localStorage); +} + +function isEventStrategy( + options: PersistOptions +): options is PersistEventOptions { + return options.strategy === 'event'; +} + +function serializeSnapshotValue( + options: PersistSnapshotOptions, + value: PersistStorageValue +): string { + return options.serialize ? options.serialize(value) : JSON.stringify(value); +} + +function deserializeSnapshotValue( + options: PersistSnapshotOptions, + str: string +): PersistStorageValue { + return options.deserialize ? options.deserialize(str) : JSON.parse(str); +} + +function serializeEventValue( + options: PersistEventOptions, + value: PersistEventStorageValue +): string { + return options.serialize ? options.serialize(value) : JSON.stringify(value); +} + +function deserializeEventValue( + options: PersistEventOptions, + str: string +): PersistEventStorageValue { + return options.deserialize ? options.deserialize(str) : JSON.parse(str); +} + +function mergeContext( + options: PersistSnapshotOptions, + persistedContext: Partial, + currentContext: TContext +): TContext { + return options.merge + ? options.merge(persistedContext, currentContext) + : { ...currentContext, ...persistedContext }; +} + +function migrateSnapshotIfNeeded( + options: PersistSnapshotOptions, + stored: PersistStorageValue +): Partial { + const currentVersion = options.version ?? 0; + if (stored.version !== currentVersion && options.migrate) { + return options.migrate(stored.context, stored.version) as Partial; + } + return stored.context; +} + +function migrateEventsIfNeeded( + options: PersistEventOptions, + stored: PersistEventStorageValue +): TEvent[] { + const currentVersion = options.version ?? 0; + if (stored.version !== currentVersion && options.migrate) { + return options.migrate(stored.events, stored.version) as TEvent[]; + } + return stored.events; +} + +function enqueueWrite( + internals: PersistInternals, + write: () => void | Promise +): void | Promise { + const result = internals.pendingWrite + ? internals.pendingWrite.then(write, write) + : write(); + if (result instanceof Promise) { + const pending = result.finally(() => { + if (internals.pendingWrite === pending) { + internals.pendingWrite = null; + } + }); + internals.pendingWrite = pending; + return pending; + } +} + +function writeSnapshotToStorage( + internals: PersistInternals, + context: TContext +): void | Promise { + const options = internals.options as PersistSnapshotOptions; + const { storage } = internals; + const contextToPersist = options.pick ? options.pick(context) : context; + + const value: PersistStorageValue = { + context: contextToPersist, + version: options.version ?? 0 + }; + + return enqueueWrite(internals, () => { + try { + const serialized = serializeSnapshotValue(options, value); + const result = storage.setItem(options.name, serialized); + if (result instanceof Promise) { + return result + .then(() => options.onDone?.(contextToPersist)) + .catch((err) => options.onError?.(err)); + } + + options.onDone?.(contextToPersist); + } catch (err) { + options.onError?.(err); + } + }); +} + +function writeEventsToStorage( + internals: PersistInternals, + events: TEvent[], + checkpoint?: unknown +): void | Promise { + const options = internals.options as PersistEventOptions; + const { storage } = internals; + + const value: PersistEventStorageValue = { + events, + version: options.version ?? 0 + }; + if (checkpoint !== undefined) { + value.checkpoint = checkpoint; + } + + return enqueueWrite(internals, () => { + try { + const serialized = serializeEventValue(options, value); + const result = storage.setItem(options.name, serialized); + if (result instanceof Promise) { + return result + .then(() => options.onDone?.(events)) + .catch((err) => options.onError?.(err)); + } + + options.onDone?.(events); + } catch (err) { + options.onError?.(err); + } + }); +} + +function createInternals( + options: PersistOptions +): PersistInternals { + const storage = getStorage(options); + + const internals: PersistInternals = { + options, + storage, + pendingContext: null, + pendingEvents: null, + pendingCheckpoint: null, + flushTimeoutId: null, + pendingWrite: null, + lastScheduledRevision: 0, + flush: () => { + if (internals.flushTimeoutId !== null) { + clearTimeout(internals.flushTimeoutId); + internals.flushTimeoutId = null; + } + if (isEventStrategy(options)) { + if (internals.pendingEvents !== null) { + const events = internals.pendingEvents; + const checkpoint = internals.pendingCheckpoint; + internals.pendingEvents = null; + internals.pendingCheckpoint = null; + return writeEventsToStorage(internals, events, checkpoint); + } + } else { + if (internals.pendingContext !== null) { + const context = internals.pendingContext; + internals.pendingContext = null; + return writeSnapshotToStorage(internals as any, context as TContext); + } + } + return internals.pendingWrite ?? undefined; + } + }; + + return internals; +} + +// Core logic wrapper — snapshot strategy + +function persistSnapshotFromLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject +>( + logic: StoreLogic, TEvent, TEmitted>, + options: PersistSnapshotOptions +): StoreLogic, TEvent, TEmitted> { + assertNoInternalEventTypeCollisions( + logic.eventTypes, + [PERSIST_REHYDRATE_EVENT_TYPE], + 'persist' + ); + + const internals = createInternals(options); + const { storage } = internals; + const throttleMs = options.throttle ?? 0; + + const enhancedLogic: AnyStoreLogic = { + ...logic, + eventTypes: logic.eventTypes, + getInitialSnapshot: () => { + const baseSnapshot = logic.getInitialSnapshot(); + + if (options.skipHydration) { + return { + ...baseSnapshot, + _persist: { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + } + + // Attempt sync read + try { + const storedValue = storage.getItem(options.name); + + // Async storage — can't hydrate synchronously + if (storedValue instanceof Promise) { + void storedValue.catch((error) => options.onError?.(error)); + return { + ...baseSnapshot, + _persist: { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + } + + if (storedValue === null) { + return { + ...baseSnapshot, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } + + const parsed = deserializeSnapshotValue(options, storedValue); + const persistedContext = migrateSnapshotIfNeeded(options, parsed); + const mergedContext = mergeContext( + options, + persistedContext, + baseSnapshot.context + ); + + return { + ...baseSnapshot, + context: mergedContext, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } catch (err) { + options.onError?.(err); + return { + ...baseSnapshot, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } + }, + + transition: (snapshot, event) => { + // Internal rehydrate event (not exposed in trigger types) + if (event.type === PERSIST_REHYDRATE_EVENT_TYPE) { + const rawState = event.state as string | null | undefined; + + if (!rawState) { + return [ + { ...snapshot, _persist: { ...snapshot._persist, hydrated: true } }, + [] + ]; + } + + try { + const parsed = deserializeSnapshotValue(options, rawState); + const persistedContext = migrateSnapshotIfNeeded(options, parsed); + const mergedContext = mergeContext( + options, + persistedContext, + snapshot.context + ); + + return [ + { + ...snapshot, + context: mergedContext, + _persist: { ...snapshot._persist, hydrated: true } + }, + [] + ]; + } catch (err) { + options.onError?.(err); + return [ + { + ...snapshot, + _persist: { ...snapshot._persist, hydrated: true } + }, + [] + ]; + } + } + + // Delegate to wrapped logic + const [nextSnapshot, effects] = logic.transition(snapshot, event); + + const revision = (snapshot[PERSIST_REVISION] ?? 0) + 1; + + // Preserve _persist metadata + const snapshotWithMeta = { + ...nextSnapshot, + [PERSIST_REVISION]: revision, + _persist: snapshot._persist ?? { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + + // Don't write to storage until hydrated + if (!snapshotWithMeta._persist?.hydrated) { + return [snapshotWithMeta, effects]; + } + + // Check filter + if (options.filter && !options.filter(event as TEvent)) { + return [snapshotWithMeta, effects]; + } + + // Commit before wrapped effects can trigger another event. Subscribers can + // already have committed a newer eligible event before effects begin. + const persistEffect = () => { + if (revision <= internals.lastScheduledRevision) return; + internals.lastScheduledRevision = revision; + if (throttleMs > 0) { + internals.pendingContext = nextSnapshot.context; + if (internals.flushTimeoutId === null) { + internals.flushTimeoutId = setTimeout(() => { + void internals.flush(); + }, throttleMs); + } + } else { + void writeSnapshotToStorage(internals as any, nextSnapshot.context); + } + }; + return [snapshotWithMeta, [persistEffect, ...effects]]; + } + }; + + return enhancedLogic; +} + +// Core logic wrapper — event strategy + +function persistEventFromLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject +>( + logic: StoreLogic, TEvent, TEmitted>, + options: PersistEventOptions +): StoreLogic, TEvent, TEmitted> { + assertNoInternalEventTypeCollisions( + logic.eventTypes, + [PERSIST_REHYDRATE_EVENT_TYPE], + 'persist' + ); + + const internals = createInternals(options); + const { storage } = internals; + const throttleMs = options.throttle ?? 0; + const maxEvents = options.maxEvents ?? Infinity; + + function replayEvents(baseSnapshot: any, events: TEvent[]): any { + let current = baseSnapshot; + for (const ev of events) { + const [next] = logic.transition(current, ev); + current = next; + } + return current; + } + + const enhancedLogic: AnyStoreLogic = { + ...logic, + eventTypes: logic.eventTypes, + getInitialSnapshot: () => { + const baseSnapshot = logic.getInitialSnapshot(); + + if (options.skipHydration) { + return { + ...baseSnapshot, + _persistEvents: [], + _persistCheckpoint: null, + _persist: { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + } + + // Attempt sync read + try { + const storedValue = storage.getItem(options.name); + + if (storedValue instanceof Promise) { + void storedValue.catch((error) => options.onError?.(error)); + return { + ...baseSnapshot, + _persistEvents: [], + _persistCheckpoint: null, + _persist: { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + } + + if (storedValue === null) { + return { + ...baseSnapshot, + _persistEvents: [], + _persistCheckpoint: null, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } + + const parsed = deserializeEventValue(options, storedValue); + const events = migrateEventsIfNeeded(options, parsed); + const checkpointSnapshot = parsed.checkpoint + ? { ...baseSnapshot, context: parsed.checkpoint } + : baseSnapshot; + const replayedSnapshot = replayEvents(checkpointSnapshot, events); + + return { + ...replayedSnapshot, + _persistEvents: events, + _persistCheckpoint: parsed.checkpoint ?? null, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } catch (err) { + options.onError?.(err); + return { + ...baseSnapshot, + _persistEvents: [], + _persistCheckpoint: null, + _persist: { hydrated: true }, + [PERSIST_INTERNALS]: internals + }; + } + }, + + transition: (snapshot, event) => { + // Internal rehydrate event + if (event.type === PERSIST_REHYDRATE_EVENT_TYPE) { + const rawState = event.state as string | null | undefined; + + if (!rawState) { + return [ + { + ...snapshot, + _persistEvents: snapshot._persistEvents ?? [], + _persistCheckpoint: snapshot._persistCheckpoint ?? null, + _persist: { ...snapshot._persist, hydrated: true } + }, + [] + ]; + } + + try { + const parsed = deserializeEventValue(options, rawState); + const events = migrateEventsIfNeeded(options, parsed); + const baseSnapshot = logic.getInitialSnapshot(); + const checkpointSnapshot = parsed.checkpoint + ? { ...baseSnapshot, context: parsed.checkpoint } + : baseSnapshot; + const replayedSnapshot = replayEvents(checkpointSnapshot, events); + + return [ + { + ...replayedSnapshot, + [PERSIST_REVISION]: snapshot[PERSIST_REVISION], + _persistEvents: events, + _persistCheckpoint: parsed.checkpoint ?? null, + _persist: { ...snapshot._persist, hydrated: true }, + [PERSIST_INTERNALS]: internals + }, + [] + ]; + } catch (err) { + options.onError?.(err); + return [ + { + ...snapshot, + _persistEvents: snapshot._persistEvents ?? [], + _persistCheckpoint: snapshot._persistCheckpoint ?? null, + _persist: { ...snapshot._persist, hydrated: true } + }, + [] + ]; + } + } + + // Delegate to wrapped logic + const [nextSnapshot, effects] = logic.transition(snapshot, event); + const prevEvents: TEvent[] = snapshot._persistEvents ?? []; + const prevCheckpoint: unknown = snapshot._persistCheckpoint ?? null; + + const revision = (snapshot[PERSIST_REVISION] ?? 0) + 1; + + // Preserve metadata + const snapshotWithMeta = { + ...nextSnapshot, + [PERSIST_REVISION]: revision, + _persistEvents: prevEvents, + _persistCheckpoint: prevCheckpoint, + _persist: snapshot._persist ?? { hydrated: false }, + [PERSIST_INTERNALS]: internals + }; + + // Don't write to storage until hydrated + if (!snapshotWithMeta._persist?.hydrated) { + return [snapshotWithMeta, effects]; + } + + // Append event to persisted list + let nextEvents = [...prevEvents, event as TEvent]; + let nextCheckpoint = prevCheckpoint; + + if (nextEvents.length > maxEvents) { + // Compute checkpoint by replaying dropped events from previous checkpoint + const droppedEvents = nextEvents.slice(0, -maxEvents); + const baseSnapshot = logic.getInitialSnapshot(); + const checkpointBase = prevCheckpoint + ? { ...baseSnapshot, context: prevCheckpoint } + : baseSnapshot; + const checkpointSnapshot = replayEvents(checkpointBase, droppedEvents); + nextCheckpoint = checkpointSnapshot.context; + nextEvents = nextEvents.slice(-maxEvents); + } + + const snapshotWithEvents = { + ...snapshotWithMeta, + _persistEvents: nextEvents, + _persistCheckpoint: nextCheckpoint + }; + + const persistEffect = () => { + if (revision <= internals.lastScheduledRevision) return; + internals.lastScheduledRevision = revision; + if (throttleMs > 0) { + internals.pendingEvents = nextEvents; + internals.pendingCheckpoint = nextCheckpoint; + if (internals.flushTimeoutId === null) { + internals.flushTimeoutId = setTimeout(() => { + void internals.flush(); + }, throttleMs); + } + } else { + void writeEventsToStorage(internals, nextEvents, nextCheckpoint); + } + }; + return [snapshotWithEvents, [persistEffect, ...effects]]; + } + }; + + return enhancedLogic; +} + +// Dispatch to the right strategy +function persistFromLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject +>( + logic: StoreLogic, TEvent, TEmitted>, + options: PersistOptions +): StoreLogic, TEvent, TEmitted> { + if (isEventStrategy(options)) { + return persistEventFromLogic( + logic, + options as PersistEventOptions + ); + } + return persistSnapshotFromLogic( + logic, + options as PersistSnapshotOptions + ); +} + +// Public API + +/** + * Creates a store extension that persists context to storage. + * + * @example + * + * ```ts + * import { persist } from '@xstate/store/persist'; + * + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with(persist({ name: 'my-store' })); + * ``` + * + * @example + * + * ```ts + * // Throttled writes with callbacks + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with( + * persist({ + * name: 'my-store', + * throttle: 1000, + * onDone: (ctx) => console.log('Persisted:', ctx), + * onError: (err) => console.error('Persist failed:', err) + * }) + * ); + * ``` + * + * @example + * + * ```ts + * // Async storage with manual rehydration + * import { + * persist, + * rehydrateStore, + * createJSONStorage + * } from '@xstate/store/persist'; + * + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with( + * persist({ + * name: 'my-store', + * storage: createJSONStorage(() => AsyncStorage), + * skipHydration: true + * }) + * ); + * + * await rehydrateStore(store); + * ``` + */ +export function persist< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + options: PersistOptions> +): StoreExtension { + return (logic: any) => persistFromLogic(logic, options); +} + +/** + * Creates a storage adapter with error handling and SSR safety. + * + * @example + * + * ```ts + * import { createJSONStorage } from '@xstate/store/persist'; + * + * // Safe for SSR — returns noop storage if localStorage is unavailable + * const storage = createJSONStorage(() => localStorage); + * + * // Async storage (React Native) + * const asyncStorage = createJSONStorage(() => AsyncStorage); + * ``` + */ +export function createJSONStorage( + getStorage: () => StateStorage +): StateStorage { + let storage: StateStorage | undefined; + try { + storage = getStorage(); + } catch { + return noopStorage; + } + + return { + getItem: (name) => { + try { + const result = storage?.getItem(name); + + if (result instanceof Promise) { + return result.catch(() => null); + } + + return result ?? null; + } catch { + return null; + } + }, + setItem: (name, value) => { + try { + const result = storage?.setItem(name, value); + + if (result instanceof Promise) { + return result.catch(() => {}); + } + + return result; + } catch { + // Swallow write errors (quota exceeded, etc.) + } + }, + removeItem: (name) => { + try { + const result = storage?.removeItem(name); + + if (result instanceof Promise) { + return result.catch(() => {}); + } + + return result; + } catch { + // Swallow errors + } + } + }; +} + +/** + * Removes persisted data from storage for a store that uses the `persist` + * extension. + * + * @example + * + * ```ts + * import { clearStorage } from '@xstate/store/persist'; + * + * clearStorage(store); + * ``` + */ +export function clearStorage(store: { + getSnapshot: () => any; +}): void | Promise { + const internals = store.getSnapshot()?.[PERSIST_INTERNALS] as + | PersistInternals + | undefined; + if (!internals) { + throw new Error('clearStorage: store does not have a persist extension'); + } + if (internals.flushTimeoutId !== null) { + clearTimeout(internals.flushTimeoutId); + internals.flushTimeoutId = null; + } + internals.pendingContext = null; + internals.pendingEvents = null; + internals.pendingCheckpoint = null; + return enqueueWrite(internals, () => + internals.storage.removeItem(internals.options.name) + ); +} + +/** + * Flushes pending throttled updates and waits for already queued async writes. + * Synchronous storage writes complete before this function returns. + * + * @example + * + * ```ts + * import { flushStorage } from '@xstate/store/persist'; + * + * // Force write before page unload + * window.addEventListener('beforeunload', () => { + * flushStorage(store); + * }); + * ``` + */ +export function flushStorage(store: { + getSnapshot: () => any; +}): void | Promise { + const internals = store.getSnapshot()?.[PERSIST_INTERNALS] as + | PersistInternals + | undefined; + if (!internals) { + throw new Error('flushStorage: store does not have a persist extension'); + } + return internals.flush(); +} + +/** + * Returns whether the store has been hydrated from storage. + * + * @example + * + * ```ts + * import { isHydrated } from '@xstate/store/persist'; + * + * if (isHydrated(store)) { + * // Safe to read persisted state + * } + * ``` + */ +export function isHydrated(store: { getSnapshot: () => any }): boolean { + return store.getSnapshot()?._persist?.hydrated === true; +} + +/** + * Reads persisted state from (potentially async) storage and rehydrates the + * store. Use this for async storage adapters or when `skipHydration` is + * `true`. + * + * @example + * + * ```ts + * import { rehydrateStore } from '@xstate/store/persist'; + * + * const store = createStore({ ... }).with(persist({ + * name: 'my-store', + * storage: createJSONStorage(() => AsyncStorage), + * skipHydration: true + * })); + * + * await rehydrateStore(store); + * ``` + */ +export async function rehydrateStore(store: { + getSnapshot: () => any; + send: (event: any) => void; +}): Promise { + const internals = store.getSnapshot()?.[PERSIST_INTERNALS] as + | PersistInternals + | undefined; + if (!internals) { + throw new Error('rehydrateStore: store does not have a persist extension'); + } + const data = await internals.storage.getItem(internals.options.name); + store.send({ type: PERSIST_REHYDRATE_EVENT_TYPE, state: data }); +} + +/** Options for `createBroadcastStorage(...)`. */ +interface BroadcastStorageOptions { + /** BroadcastChannel name. Defaults to `"xstate-store"`. */ + channel?: string; +} + +/** Storage adapter returned by `createBroadcastStorage(...)`. */ +type BroadcastStorage = StateStorage & { + /** Channel used to announce writes to other same-origin contexts. */ + readonly channel: BroadcastChannel; +}; + +function assertBroadcastChannelAvailable(): void { + if (typeof BroadcastChannel === 'undefined') { + throw new Error( + 'createBroadcastStorage: BroadcastChannel is not available in this environment' + ); + } +} + +/** + * Wraps a storage adapter so writes are announced across same-origin tabs. + * + * Pair with `subscribeToBroadcastStorage(...)` on persisted stores that should + * rehydrate when another tab writes to the same storage key. + */ +export function createBroadcastStorage( + baseStorage: StateStorage, + options?: BroadcastStorageOptions +): BroadcastStorage { + assertBroadcastChannelAvailable(); + + const channel = new BroadcastChannel(options?.channel ?? 'xstate-store'); + + return { + channel, + getItem: (name) => baseStorage.getItem(name), + setItem: (name, value) => { + const result = baseStorage.setItem(name, value); + const broadcast = () => { + channel.postMessage({ type: 'xstate-store-update', name }); + }; + + if (result instanceof Promise) { + return result.then(broadcast); + } + + broadcast(); + return result; + }, + removeItem: (name) => baseStorage.removeItem(name) + }; +} + +/** + * Subscribes a persisted store to broadcast storage updates. + * + * Returns an unsubscribe function that closes the broadcast listener. + */ +export function subscribeToBroadcastStorage(store: { + getSnapshot: () => any; + send: (event: any) => void; +}): () => void { + const internals = store.getSnapshot()?.[PERSIST_INTERNALS] as + | PersistInternals + | undefined; + + if (!internals) { + throw new Error( + 'subscribeToBroadcastStorage: store does not have a persist extension' + ); + } + + const channel = (internals.storage as Partial).channel; + + if ( + typeof BroadcastChannel === 'undefined' || + !(channel instanceof BroadcastChannel) + ) { + throw new Error( + 'subscribeToBroadcastStorage: store storage must be wrapped with createBroadcastStorage()' + ); + } + + const storeName = internals.options.name; + const handler = (event: MessageEvent) => { + const data = event.data; + + if ( + data && + data.type === 'xstate-store-update' && + data.name === storeName + ) { + void rehydrateStore(store); + } + }; + + channel.addEventListener('message', handler); + + return () => { + channel.removeEventListener('message', handler); + }; +} diff --git a/xstate-store/src/reset.ts b/xstate-store/src/reset.ts new file mode 100644 index 00000000..14837147 --- /dev/null +++ b/xstate-store/src/reset.ts @@ -0,0 +1,96 @@ +import { + AnyStoreLogic, + EventObject, + EventPayloadMap, + StoreContext, + StoreExtension, + StoreLogic, + StoreSnapshot +} from './types.ts'; +import { appendInternalEventTypes } from './store.ts'; + +interface ResetOptions { + /** + * Custom reset function. Receives the initial context and the current + * context, returns the context to reset to. + * + * Defaults to returning the initial context (full reset). + */ + to?: (initialContext: TContext, currentContext: TContext) => TContext; +} + +function resetFromLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject +>( + logic: StoreLogic, TEvent, TEmitted>, + options?: ResetOptions +): StoreLogic, TEvent | { type: 'reset' }, TEmitted> { + const enhancedLogic: AnyStoreLogic = { + ...logic, + eventTypes: appendInternalEventTypes(logic.eventTypes, ['reset'], 'reset'), + getInitialSnapshot: () => logic.getInitialSnapshot(), + transition: (snapshot, event) => { + if (event.type === 'reset') { + const initialSnapshot = logic.getInitialSnapshot(); + const resetContext = options?.to + ? options.to(initialSnapshot.context, snapshot.context) + : initialSnapshot.context; + + return [{ ...snapshot, context: resetContext }, []]; + } + + return logic.transition(snapshot, event); + } + }; + + return enhancedLogic; +} + +/** + * Creates a store extension that adds a `reset` trigger to reset the store + * context to its initial state. + * + * @example + * + * ```ts + * import { reset } from '@xstate/store/reset'; + * + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with(reset()); + * + * store.trigger.inc(); + * store.trigger.reset(); // count = 0 + * ``` + * + * @example + * + * ```ts + * // Partial reset: keep some fields + * const store = createStore({ + * context: { count: 0, user: null as string | null }, + * on: { + * inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + * login: (ctx, e: { user: string }) => ({ ...ctx, user: e.user }) + * } + * }).with( + * reset({ + * to: (initial, current) => ({ ...initial, user: current.user }) + * }) + * ); + * + * store.trigger.reset(); // resets count, keeps user + * ``` + */ +export function reset< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + options?: ResetOptions +): StoreExtension { + return (logic: any) => resetFromLogic(logic, options); +} diff --git a/xstate-store/src/schema.ts b/xstate-store/src/schema.ts new file mode 100644 index 00000000..717204c2 --- /dev/null +++ b/xstate-store/src/schema.ts @@ -0,0 +1,77 @@ +/* oxlint-disable */ +/** The Standard Schema interface. */ +export interface StandardSchemaV1 { + /** The Standard Schema properties. */ + readonly '~standard': StandardSchemaV1.Props; +} + +export declare namespace StandardSchemaV1 { + /** The Standard Schema properties interface. */ + export interface Props { + /** The version number of the standard. */ + readonly version: 1; + /** The vendor name of the schema library. */ + readonly vendor: string; + /** Validates unknown input values. */ + readonly validate: ( + value: unknown, + options?: StandardSchemaV1.Options | undefined + ) => Result | Promise>; + /** Inferred types associated with the schema. */ + readonly types?: Types | undefined; + } + + /** The result interface of the validate function. */ + export type Result = SuccessResult | FailureResult; + + /** The result interface if validation succeeds. */ + export interface SuccessResult { + /** The typed output value. */ + readonly value: Output; + /** A falsy value for `issues` indicates success. */ + readonly issues?: undefined; + } + + export interface Options { + /** Explicit support for additional vendor-specific parameters, if needed. */ + readonly libraryOptions?: Record | undefined; + } + + /** The result interface if validation fails. */ + export interface FailureResult { + /** The issues of failed validation. */ + readonly issues: ReadonlyArray; + } + + /** The issue interface of the failure output. */ + export interface Issue { + /** The error message of the issue. */ + readonly message: string; + /** The path of the issue, if any. */ + readonly path?: ReadonlyArray | undefined; + } + + /** The path segment interface of the issue. */ + export interface PathSegment { + /** The key representing a path segment. */ + readonly key: PropertyKey; + } + + /** The Standard Schema types interface. */ + export interface Types { + /** The input type of the schema. */ + readonly input: Input; + /** The output type of the schema. */ + readonly output: Output; + } + + /** Infers the input type of a Standard Schema. */ + export type InferInput = NonNullable< + Schema['~standard']['types'] + >['input']; + + /** Infers the output type of a Standard Schema. */ + export type InferOutput = NonNullable< + Schema['~standard']['types'] + >['output']; +} diff --git a/xstate-store/src/select.test.ts b/xstate-store/src/select.test.ts new file mode 100644 index 00000000..15dec8eb --- /dev/null +++ b/xstate-store/src/select.test.ts @@ -0,0 +1,243 @@ +import { createStore } from './index.ts'; + +interface TestContext { + user: { + name: string; + age: number; + }; + settings: { + theme: 'light' | 'dark'; + notifications: boolean; + }; +} + +describe('select', () => { + it('should get current value', () => { + const store = createStore({ + context: { + user: { name: 'John', age: 30 }, + settings: { theme: 'dark', notifications: true } + } as TestContext, + on: { + UPDATE_NAME: (context, event: { name: string }) => ({ + ...context, + user: { ...context.user, name: event.name } + }), + UPDATE_THEME: (context, event: { theme: 'light' | 'dark' }) => ({ + ...context, + settings: { ...context.settings, theme: event.theme } + }) + } + }); + + const name = store.select((state) => state.user.name).get(); + expect(name).toBe('John'); + }); + + it('should subscribe to changes', () => { + const store = createStore({ + context: { + user: { name: 'John', age: 30 }, + settings: { theme: 'dark', notifications: true } + } as TestContext, + on: { + UPDATE_NAME: (context, event: { name: string }) => ({ + ...context, + user: { ...context.user, name: event.name } + }), + UPDATE_THEME: (context, event: { theme: 'light' | 'dark' }) => ({ + ...context, + settings: { ...context.settings, theme: event.theme } + }) + } + }); + + const callback = vi.fn(); + store.select((state) => state.user.name).subscribe(callback); + store.send({ type: 'UPDATE_NAME', name: 'Jane' }); + + expect(callback).toHaveBeenCalledTimes(1); + expect(callback).toHaveBeenCalledWith('Jane'); + }); + + it('should not notify if selected value has not changed', () => { + const store = createStore({ + context: { + user: { name: 'John', age: 30 }, + settings: { theme: 'dark', notifications: true } + } as TestContext, + on: { + UPDATE_NAME: (context, event: { name: string }) => ({ + ...context, + user: { ...context.user, name: event.name } + }), + UPDATE_THEME: (context, event: { theme: 'light' | 'dark' }) => ({ + ...context, + settings: { ...context.settings, theme: event.theme } + }) + } + }); + + const callback = vi.fn(); + store.select((state) => state.user.name).subscribe(callback); + store.send({ type: 'UPDATE_THEME', theme: 'light' }); + + expect(callback).not.toHaveBeenCalled(); + }); + + it('should support custom equality function', () => { + const store = createStore({ + context: { + user: { name: 'John', age: 30 }, + settings: { theme: 'dark', notifications: true } + } as TestContext, + on: { + UPDATE_NAME: (context, event: { name: string }) => ({ + ...context, + user: { ...context.user, name: event.name } + }), + UPDATE_THEME: (context, event: { theme: 'light' | 'dark' }) => ({ + ...context, + settings: { ...context.settings, theme: event.theme } + }) + } + }); + + const callback = vi.fn(); + const selector = (context: TestContext) => ({ + name: context.user.name, + theme: context.settings.theme + }); + const equalityFn = (a: { name: string }, b: { name: string }) => + a.name === b.name; // Only compare names + + store.select(selector, equalityFn).subscribe(callback); + + store.send({ type: 'UPDATE_THEME', theme: 'light' }); + expect(callback).not.toHaveBeenCalled(); + + store.send({ type: 'UPDATE_NAME', name: 'Jane' }); + expect(callback).toHaveBeenCalledTimes(1); + }); + + it('should unsubscribe correctly', () => { + const store = createStore({ + context: { + user: { name: 'John', age: 30 }, + settings: { theme: 'dark', notifications: true } + } as TestContext, + on: { + UPDATE_NAME: (context, event: { name: string }) => ({ + ...context, + user: { ...context.user, name: event.name } + }), + UPDATE_THEME: (context, event: { theme: 'light' | 'dark' }) => ({ + ...context, + settings: { ...context.settings, theme: event.theme } + }) + } + }); + + const callback = vi.fn(); + const subscription = store + .select((state) => state.user.name) + .subscribe(callback); + subscription.unsubscribe(); + store.send({ type: 'UPDATE_NAME', name: 'Jane' }); + + expect(callback).not.toHaveBeenCalled(); + }); + + it('should handle updates with multiple subscribers', () => { + interface PositionContext { + position: { + x: number; + y: number; + }; + } + + const store = createStore({ + context: { + position: { x: 0, y: 0 }, + user: { name: 'John', age: 30 } + } as PositionContext, + on: { + positionUpdated: ( + context, + event: { position: { x: number; y: number } } + ) => ({ + ...context, + position: event.position + }), + userUpdated: ( + context, + event: { user: { name: string; age: number } } + ) => ({ + ...context, + user: event.user + }) + } + }); + + // Mock DOM manipulation callback + const renderCallback = vi.fn(); + store + .select((state) => state.position) + .subscribe((position) => { + renderCallback(position); + }); + + // Mock logger callback for x position only + const loggerCallback = vi.fn(); + store + .select((state) => state.position.x) + .subscribe((x) => { + loggerCallback(x); + }); + + // Simulate position update + store.trigger.positionUpdated({ + position: { x: 100, y: 200 } + }); + + // Verify render callback received full position update + expect(renderCallback).toHaveBeenCalledTimes(1); + expect(renderCallback).toHaveBeenCalledWith({ x: 100, y: 200 }); + + // Verify logger callback received only x position + expect(loggerCallback).toHaveBeenCalledTimes(1); + expect(loggerCallback).toHaveBeenCalledWith(100); + + // Simulate another update + store.trigger.positionUpdated({ + position: { x: 150, y: 300 } + }); + + expect(renderCallback).toHaveBeenCalledTimes(2); + expect(renderCallback).toHaveBeenLastCalledWith({ x: 150, y: 300 }); + expect(loggerCallback).toHaveBeenCalledTimes(2); + expect(loggerCallback).toHaveBeenLastCalledWith(150); + + // Simulate changing only the y position + store.trigger.positionUpdated({ + position: { x: 150, y: 400 } + }); + + expect(renderCallback).toHaveBeenCalledTimes(3); + expect(renderCallback).toHaveBeenLastCalledWith({ x: 150, y: 400 }); + + // loggerCallback should not have been called + expect(loggerCallback).toHaveBeenCalledTimes(2); + + // Simulate changing only the user + store.trigger.userUpdated({ + user: { name: 'Jane', age: 25 } + }); + + // renderCallback should not have been called + expect(renderCallback).toHaveBeenCalledTimes(3); + + // loggerCallback should not have been called + expect(loggerCallback).toHaveBeenCalledTimes(2); + }); +}); diff --git a/xstate-store/src/shallowEqual.ts b/xstate-store/src/shallowEqual.ts new file mode 100644 index 00000000..1eedb165 --- /dev/null +++ b/xstate-store/src/shallowEqual.ts @@ -0,0 +1,37 @@ +// From https://github.com/reduxjs/react-redux/blob/720f0ba79236cdc3e1115f4ef9a7760a21784b48/src/utils/shallowEqual.ts +function is(x: unknown, y: unknown) { + if (x === y) { + return x !== 0 || y !== 0 || 1 / x === 1 / y; + } else { + return x !== x && y !== y; + } +} + +export function shallowEqual(objA: any, objB: any) { + if (is(objA, objB)) return true; + + if ( + typeof objA !== 'object' || + objA === null || + typeof objB !== 'object' || + objB === null + ) { + return false; + } + + const keysA = Object.keys(objA); + const keysB = Object.keys(objB); + + if (keysA.length !== keysB.length) return false; + + for (let i = 0; i < keysA.length; i++) { + if ( + !Object.prototype.hasOwnProperty.call(objB, keysA[i]) || + !is(objA[keysA[i]], objB[keysA[i]]) + ) { + return false; + } + } + + return true; +} diff --git a/xstate-store/src/store.ts b/xstate-store/src/store.ts new file mode 100644 index 00000000..fa382283 --- /dev/null +++ b/xstate-store/src/store.ts @@ -0,0 +1,869 @@ +import { createAtom } from './atom.ts'; +import { + EnqueueObject, + EventObject, + EventPayloadMap, + ExtractEvents, + InteropSubscribable, + Observer, + Store, + StoreAssigner, + StoreLogicCreator, + StoreSelectorsConfig, + StoreWithSelectors, + ResolvedStoreSelectors, + StoreContext, + StoreConfig, + StoreEffect, + StoreEffectEnqueue, + StoreInspectionEvent, + StoreProducerAssigner, + StoreSnapshot, + Selector, + Selection, + StoreLogic, + StoreTransition, + AnyStoreLogic, + SpecificStoreConfig, + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ResolveStoreEmittedPayloadMap, + StandardSchemaMap, + StoreTransitionResult +} from './types.ts'; +import type { StandardSchemaV1 } from './schema.ts'; +import { isStoreValidationError } from './validationError.ts'; + +const symbolObservable: typeof Symbol.observable = (() => + (typeof Symbol === 'function' && Symbol.observable) || + '@@observable')() as any; +const isDevelopment = + ( + globalThis as { + process?: { + env?: { + NODE_ENV?: string; + }; + }; + } + ).process?.env?.NODE_ENV !== 'production'; + +const UNSUPPORTED_ASYNC_TRANSITION_ERROR = 'Async transition unsupported here'; + +function isPromiseLike(value: T | PromiseLike): value is PromiseLike { + return !!value && typeof (value as any).then === 'function'; +} + +function ignorePromiseRejection(value: PromiseLike) { + Promise.resolve(value).catch(() => {}); +} + +function createTransitionResult< + TSnapshot extends StoreSnapshot, + TEmitted extends EventObject +>( + snapshot: TSnapshot, + effects: StoreEffect[], + allowed?: boolean +): StoreTransitionResult { + const result = [snapshot, effects] as StoreTransitionResult< + TSnapshot, + TEmitted + >; + + if (allowed !== undefined) { + result._allowed = allowed; + } + + return result; +} + +function toEvent(eventType: string, payload: any) { + return payload === undefined + ? { type: eventType } + : { + ...payload, + type: eventType + }; +} + +export function createEnqueueObject( + effects: StoreEffect[], + trigger?: (event: EventObject) => void +): EnqueueObject { + return { + emit: new Proxy({} as any, { + get: (_, eventType: string) => { + return (payload: any) => { + effects.push(toEvent(eventType, payload) as TEmitted); + }; + } + }), + trigger: new Proxy({} as any, { + get: (_, eventType: string) => { + return (payload: any) => { + trigger?.(toEvent(eventType, payload)); + }; + } + }), + effect: (fn) => { + effects.push(fn as StoreEffect); + } + }; +} +function getDistinctEventTypes(eventTypes: readonly string[]): string[] { + return [...new Set(eventTypes)]; +} + +export function assertNoInternalEventTypeCollisions( + existingEventTypes: readonly string[] | undefined, + internalEventTypes: readonly string[], + extensionName: string +): void { + if (!isDevelopment || !existingEventTypes?.length) { + return; + } + + const existingEventTypeSet = new Set(existingEventTypes); + const collisions = getDistinctEventTypes( + internalEventTypes.filter((eventType) => + existingEventTypeSet.has(eventType) + ) + ); + + if (collisions.length === 0) { + return; + } + + throw new Error( + `The "${extensionName}" store extension uses reserved event type(s): ${collisions + .map((eventType) => `"${eventType}"`) + .join( + ', ' + )}. Rename the conflicting store event(s) before applying the extension.` + ); +} + +export function appendInternalEventTypes( + existingEventTypes: readonly string[] | undefined, + internalEventTypes: readonly string[], + extensionName: string +): readonly string[] { + assertNoInternalEventTypeCollisions( + existingEventTypes, + internalEventTypes, + extensionName + ); + + return getDistinctEventTypes([ + ...(existingEventTypes ?? []), + ...internalEventTypes + ]); +} + +function createConcreteTrigger< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + eventTypes: readonly string[], + send: Store['send'] +): Store['trigger'] { + const trigger = {} as Store['trigger']; + + for (const eventType of eventTypes) { + trigger[eventType as keyof typeof trigger] = ((payload?: unknown) => { + send(toEvent(eventType, payload) as ExtractEvents); + }) as (typeof trigger)[keyof typeof trigger]; + } + + return trigger; +} + +function createConcreteCan< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + eventTypes: readonly string[], + can: (event: ExtractEvents) => boolean +): Store['can'] { + const canObject = {} as Store['can']; + + for (const eventType of eventTypes) { + canObject[eventType as keyof typeof canObject] = ((payload?: unknown) => { + return can( + toEvent(eventType, payload) as ExtractEvents + ); + }) as (typeof canObject)[keyof typeof canObject]; + } + + return canObject; +} + +function attachSelectors< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject, + TSelectors extends StoreSelectorsConfig +>( + store: Store, + selectorsConfig: TSelectors +): StoreWithSelectors { + const selectors = {} as ResolvedStoreSelectors; + + for (const key of Object.keys(selectorsConfig) as (keyof TSelectors)[]) { + selectors[key] = store.select( + selectorsConfig[key] + ) as ResolvedStoreSelectors[keyof TSelectors]; + } + + const originalWith = store.with; + const storeWithSelectors = store as StoreWithSelectors< + TContext, + TEventPayloadMap, + TEmitted, + TSelectors + >; + storeWithSelectors.selectors = selectors; + storeWithSelectors.with = ((extension: any) => + attachSelectors(originalWith(extension), selectorsConfig)) as any; + + return storeWithSelectors; +} + +function createStoreCore< + TContext extends StoreContext, + TSnapshot extends StoreSnapshot, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + logic: StoreLogic, TEmitted> +): Store { + type StoreEvent = ExtractEvents; + let listeners: Map> | undefined; + let inspectionObservers: Set> | undefined; + const initialSnapshot = logic.getInitialSnapshot(); + let currentSnapshot: TSnapshot = initialSnapshot; + const atom = createAtom>(currentSnapshot); + const eventTypes = logic.eventTypes; + const schemas = logic.schemas; + + const emit = (ev: TEmitted) => { + listeners?.get(ev.type)?.forEach((listener) => listener(ev)); + listeners + ?.get('*' as TEmitted['type']) + ?.forEach((listener) => listener(ev)); + }; + + const transition = logic.transition; + const notifyInspection = ( + event: EventObject, + snapshot: StoreSnapshot + ) => { + inspectionObservers?.forEach((observer) => { + observer.next?.({ + type: '@xstate.transition', + event, + snapshot, + actorRef: store, + rootId: store.sessionId + }); + }); + }; + + const send: Store['send'] = (event) => { + receive(event as unknown as StoreEvent); + }; + + function receive(event: StoreEvent) { + const [nextSnapshot, effects] = transition(currentSnapshot, event); + currentSnapshot = nextSnapshot; + + atom.set(nextSnapshot); + notifyInspection(event, nextSnapshot); + + let committed = false; + const effectEnqueue = { + trigger, + send, + getSnapshot: () => (committed ? currentSnapshot : nextSnapshot) + } as StoreEffectEnqueue; + + for (const effect of effects) { + if (typeof effect === 'function') { + effect(effectEnqueue); + } else { + emit(effect); + } + } + + committed = true; + } + + const trigger = + eventTypes && eventTypes.length > 0 + ? createConcreteTrigger( + eventTypes, + (event) => store.send(event) + ) + : new Proxy( + {} as Store['trigger'], + { + get: (_, eventType: string) => { + return (payload: any) => { + send( + toEvent(eventType, payload) as ExtractEvents + ); + }; + } + } + ); + + const can = + eventTypes && eventTypes.length > 0 + ? createConcreteCan( + eventTypes, + (event) => canTransition(event) + ) + : new Proxy({} as Store['can'], { + get: (_, eventType: string) => { + return (payload: any) => { + return canTransition( + toEvent(eventType, payload) as ExtractEvents + ); + }; + } + }); + + function canTransition(event: StoreEvent) { + const snapshot = currentSnapshot; + try { + const result = transition(snapshot, event); + const allowed = result._allowed; + return allowed ?? (result[0] !== snapshot || result[1].length > 0); + } catch (error) { + if (isStoreValidationError(error)) { + return false; + } + throw error; + } + } + + const store: Store = { + on(emittedEventType, handler) { + if (!listeners) { + listeners = new Map(); + } + let eventListeners = listeners.get(emittedEventType); + if (!eventListeners) { + eventListeners = new Set(); + listeners.set(emittedEventType, eventListeners); + } + eventListeners.add(handler); + + return { + unsubscribe() { + eventListeners.delete(handler); + } + }; + }, + transition(state, event) { + return transition(state as TSnapshot, event); + }, + schemas, + sessionId: uniqueId(), + send, + getSnapshot() { + return currentSnapshot; + }, + get() { + return atom.get(); + }, + getInitialSnapshot() { + return initialSnapshot; + }, + subscribe: atom.subscribe.bind(atom), + [symbolObservable](): InteropSubscribable> { + return this; + }, + inspect: (observerOrFn) => { + const observer = + typeof observerOrFn === 'function' + ? { next: observerOrFn } + : observerOrFn; + (inspectionObservers ??= new Set()).add(observer); + + observer.next?.({ + type: '@xstate.transition', + event: { type: '@xstate.init' }, + snapshot: currentSnapshot, + actorRef: store, + rootId: store.sessionId + }); + + return { + unsubscribe() { + return inspectionObservers?.delete(observer); + } + }; + }, + trigger, + can, + select( + selector: Selector, + equalityFn: (a: TSelected, b: TSelected) => boolean = Object.is + ): Selection { + return createAtom(() => selector(store.get().context), { + compare: equalityFn + }); + }, + with(extension) { + const extendedLogic = extension(logic as any); + return createStoreCore(extendedLogic) as any; + } + }; + + return store; +} + +export type TransitionsFromEventPayloadMap< + TEventPayloadMap extends EventPayloadMap, + TContext extends StoreContext, + TEmitted extends EventObject +> = { + [K in keyof TEventPayloadMap & string]?: StoreAssigner< + TContext, + { + type: K; + } & TEventPayloadMap[K], + TEmitted, + TEventPayloadMap + >; +}; + +/** + * Creates a **store** that has its own internal state and can be sent events + * that update its internal state based on transitions. + * + * @example + * + * ```ts + * const store = createStore({ + * context: { count: 0, name: 'Ada' }, + * on: { + * inc: (context, event: { by: number }) => ({ + * ...context, + * count: context.count + event.by + * }) + * } + * }); + * + * store.subscribe((snapshot) => { + * console.log(snapshot); + * }); + * + * store.send({ type: 'inc', by: 5 }); + * // Logs { context: { count: 5, name: 'Ada' }, status: 'active', ... } + * ``` + * + * @param config - The store configuration object + * @param config.context - The initial state of the store + * @param config.schemas - Optional standard-schema definitions used as type + * sources for context, events, and emitted events + * @param config.on - An object mapping event types to transition functions + * @returns A store instance with methods to send events and subscribe to state + * changes + */ +export function createStore< + TContext extends StoreContext, + const TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + definition: StoreConfig< + TContext, + TEventPayloadMap, + TEmittedPayloadMap, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > +): Store< + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ExtractEvents< + ResolveStoreEmittedPayloadMap + > +>; +export function createStore< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + definition: + | SpecificStoreConfig< + TContext, + TEvent, + TEmitted, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > + | StoreLogic< + StoreSnapshot>, + TEvent, + TEmitted + > +): Store< + ResolveStoreContext, + { + [E in TEvent as E['type']]: E; + }, + TEmitted +>; +export function createStore(definitionOrLogic: any): any { + if ('transition' in definitionOrLogic) { + return createStoreCore(definitionOrLogic); + } + + const transition = createStoreTransition(definitionOrLogic.on); + const eventTypes = definitionOrLogic.schemas?.events + ? Object.keys(definitionOrLogic.schemas.events) + : Object.keys(definitionOrLogic.on); + const logic: AnyStoreLogic = { + eventTypes, + schemas: definitionOrLogic.schemas, + getInitialSnapshot: () => ({ + status: 'active' as const, + context: definitionOrLogic.context, + output: undefined, + error: undefined + }), + transition + } satisfies AnyStoreLogic; + return createStoreCore(logic); +} + +function _createStoreConfig< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + definition: StoreConfig< + TContext, + TEventPayloadMap, + TEmitted, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > +): StoreConfig< + TContext, + TEventPayloadMap, + TEmitted, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap +> { + return definition; +} + +export const createStoreConfig: { + < + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined + >( + definition: StoreConfig< + TContext, + TEventPayloadMap, + TEmitted, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > + ): StoreConfig< + TContext, + TEventPayloadMap, + TEmitted, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + >; +} = _createStoreConfig; + +export function createStoreLogic< + TContext extends StoreContext, + const TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TInput = undefined, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined, + TSelectors extends StoreSelectorsConfig< + ResolveStoreContext + > = StoreSelectorsConfig> +>( + config: Omit< + StoreConfig< + TContext, + TEventPayloadMap, + TEmittedPayloadMap, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + >, + 'context' + > & { + context: (input: TInput) => ResolveStoreContext; + selectors: TSelectors; + } +): StoreLogicCreator< + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + TInput, + TSelectors +>; +export function createStoreLogic< + TContext extends StoreContext, + const TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TInput = undefined, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: Omit< + StoreConfig< + TContext, + TEventPayloadMap, + TEmittedPayloadMap, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + >, + 'context' + > & { + context: (input: TInput) => ResolveStoreContext; + } +): StoreLogicCreator< + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + TInput, + {} +>; +export function createStoreLogic< + TContext extends StoreContext, + const TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined, + TSelectors extends StoreSelectorsConfig< + ResolveStoreContext + > = {} +>( + config: StoreConfig< + TContext, + TEventPayloadMap, + TEmittedPayloadMap, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > & { + selectors: TSelectors; + } +): StoreLogicCreator< + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + void, + TSelectors +>; +export function createStoreLogic< + TContext extends StoreContext, + const TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +>( + config: StoreConfig< + TContext, + TEventPayloadMap, + TEmittedPayloadMap, + TContextSchema, + TEventSchemaMap, + TEmittedSchemaMap + > +): StoreLogicCreator< + ResolveStoreContext, + ResolveStoreEventPayloadMap, + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + void, + {} +>; +export function createStoreLogic( + config: StoreConfig & { + context: StoreContext | ((input: unknown) => StoreContext); + selectors?: StoreSelectorsConfig; + } +): any { + return { + createStore(input?: unknown) { + const context = + typeof config.context === 'function' + ? config.context(input) + : config.context; + + const store = createStore({ + ...config, + context + }); + + return config.selectors + ? attachSelectors(store, config.selectors) + : store; + } + }; +} + +declare global { + interface SymbolConstructor { + readonly observable: symbol; + } +} + +/** + * Creates a store transition function that handles state updates based on + * events. + * + * @param transitions - An object mapping event types to transition functions + * @param producer - Optional producer function (e.g., Immer's produce) for + * immutable updates + * @returns A transition function that takes a snapshot and event and returns a + * new snapshot with effects + */ +export function createStoreTransition< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + transitions: { + [K in keyof TEventPayloadMap & string]?: StoreAssigner< + TContext, + { type: K } & TEventPayloadMap[K], + TEmitted, + TEventPayloadMap + >; + }, + producer?: ( + context: TContext, + recipe: (context: TContext) => void + ) => TContext +): StoreTransition, TEmitted> { + type StoreEvent = ExtractEvents; + const storeTransition: StoreTransition = ( + snapshot: StoreSnapshot, + event: StoreEvent + ): StoreTransitionResult, TEmitted> => { + let currentSnapshot = snapshot; + const effects: StoreEffect[] = []; + const pendingEvents: StoreEvent[] = [event]; + let allowed = false; + + for (let index = 0; index < pendingEvents.length; index++) { + const currentEvent = pendingEvents[index]; + const currentContext = currentSnapshot.context; + const assigner = transitions?.[currentEvent.type as StoreEvent['type']]; + let producerAssignerResult: unknown; + let assignerResult: TContext | void = undefined; + const effectsLength = effects.length; + + if (!assigner) { + continue; + } + + const enqueue = createEnqueueObject( + effects, + (triggeredEvent) => { + allowed = true; + pendingEvents.push(triggeredEvent as StoreEvent); + } + ); + + const nextContext = producer + ? producer( + currentContext, + (draftContext) => + (producerAssignerResult = ( + assigner as StoreProducerAssigner< + TContext, + StoreEvent, + TEmitted, + TEventPayloadMap + > + )(draftContext, currentEvent, enqueue)) + ) + : (assignerResult = assigner( + currentContext, + currentEvent as any, + enqueue + )) === undefined + ? currentContext + : assignerResult; + + if (isPromiseLike(producer ? producerAssignerResult : nextContext)) { + ignorePromiseRejection( + (producer + ? producerAssignerResult + : nextContext) as PromiseLike + ); + throw new Error(UNSUPPORTED_ASYNC_TRANSITION_ERROR); + } + + allowed ||= producer + ? nextContext !== currentContext || effects.length > effectsLength + : assignerResult !== undefined || effects.length > effectsLength; + + if (nextContext !== currentContext) { + currentSnapshot = { ...currentSnapshot, context: nextContext }; + } + } + + return createTransitionResult(currentSnapshot, effects, allowed); + }; + + return storeTransition; +} + +/** + * Generates a unique 6-character identifier. + * + * @returns A random string identifier + */ +function uniqueId() { + return Math.random().toString(36).slice(6); +} diff --git a/xstate-store/src/types.ts b/xstate-store/src/types.ts new file mode 100644 index 00000000..a65b6e06 --- /dev/null +++ b/xstate-store/src/types.ts @@ -0,0 +1,784 @@ +import type { StandardSchemaV1 } from './schema.ts'; + +export type EventPayloadMap = Record; + +export type ExtractEvents = Values<{ + [K in keyof T & string]: T[K] & { type: K }; +}>; + +export type StandardSchemaMap = Record< + string, + StandardSchemaV1 +>; + +export type InferSchemaOutput< + TSchema extends StandardSchemaV1, + TFallback +> = Compute< + StandardSchemaV1.InferOutput extends TFallback + ? StandardSchemaV1.InferOutput + : never +>; + +export type InferSchemaPayloadMap = { + [K in keyof TSchemaMap & string]: NormalizeSchemaPayload< + InferSchemaOutput + >; +}; + +type NormalizeSchemaPayload = string extends keyof TPayload + ? {} + : TPayload; + +export type StoreSchemas< + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +> = { + context?: TContextSchema; + events?: TEventSchemaMap; + emitted?: TEmittedSchemaMap; +}; + +export type ResolveStoreContext< + TContext extends StoreContext, + TContextSchema extends StandardSchemaV1 | undefined +> = TContextSchema extends StandardSchemaV1 + ? InferSchemaOutput + : TContext; + +export type ResolveStoreEventPayloadMap< + TEventPayloadMap extends EventPayloadMap, + TEventSchemaMap extends StandardSchemaMap | undefined +> = TEventSchemaMap extends StandardSchemaMap + ? InferSchemaPayloadMap + : TEventPayloadMap; + +export type ResolveStoreEmittedPayloadMap< + TEmittedPayloadMap extends EventPayloadMap, + TEmittedSchemaMap extends StandardSchemaMap | undefined +> = TEmittedSchemaMap extends StandardSchemaMap + ? InferSchemaPayloadMap + : TEmittedPayloadMap; + +type EventPayloadFromEvent = TEvent extends { type: string } + ? DistributiveOmit + : TEvent; + +type EventPayloadMapFromTransitions = { + [K in keyof TTransitions & string]: TTransitions[K] extends ( + context: any, + event: infer TEvent, + ...args: any[] + ) => unknown + ? EventPayloadFromEvent + : {}; +}; + +type StoreEventPayloadMapFromConfig = + TConfig extends { schemas: { events: infer TEventSchemaMap } } + ? TEventSchemaMap extends StandardSchemaMap + ? InferSchemaPayloadMap + : {} + : TConfig extends { on: infer TTransitions } + ? EventPayloadMapFromTransitions + : {}; + +type EmitterFunction = ( + ...args: { type: TEmittedEvent['type'] } extends TEmittedEvent + ? [DistributiveOmit?] + : [DistributiveOmit] +) => void; + +type TriggerFunction = ( + ...args: { type: TEvent['type'] } extends TEvent + ? [DistributiveOmit?] + : [DistributiveOmit] +) => void; + +type CanFunction = ( + ...args: { type: TEvent['type'] } extends TEvent + ? [DistributiveOmit?] + : [DistributiveOmit] +) => boolean; + +type EventFromPayload = { + type: TKey; +} & (TPayload extends null | undefined ? {} : TPayload); + +export type TriggerObject = { + [K in keyof TEventPayloadMap & string]: string extends K + ? (...args: any[]) => void + : TriggerFunction>; +}; + +export type CanObject = { + [K in keyof TEventPayloadMap & string]: string extends K + ? (...args: any[]) => boolean + : CanFunction>; +}; + +/** + * The object passed to an effect function enqueued via `enq.effect(...)`. It + * allows effects to send events back into the store (e.g. after an async + * operation resolves) and read the latest store state, which is especially + * useful with `createStoreLogic(...)` where there is no store reference to + * close over. + * + * Use `trigger` for event-specific dispatch; `send` accepts the same event + * objects as `store.send(...)`. `getSnapshot()` returns the current snapshot at + * the time the effect runs, which is the correct way to read fresh context + * after an `await` (the `context` argument to the transition is stale by + * then). + */ +export type StoreEffectEnqueue< + TContext extends StoreContext = StoreContext, + TEventPayloadMap extends EventPayloadMap = {} +> = { + trigger: TriggerObject; + send: (event: EventObject) => void; + getSnapshot: () => StoreSnapshot; +}; + +export type EnqueueObject< + TContext extends StoreContext, + TEmittedEvent extends EventObject, + TEventPayloadMap extends EventPayloadMap = {} +> = { + emit: { + [E in TEmittedEvent as E['type']]: EmitterFunction; + }; + trigger: TriggerObject; + effect: ( + fn: (enq: StoreEffectEnqueue) => void + ) => void; +}; + +export type StoreEffect = + | ((enq?: StoreEffectEnqueue) => void) + | TEmitted; + +export type StoreAssigner< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TEventPayloadMap extends EventPayloadMap = {} +> = ( + context: TContext, + event: TEvent, + enq: EnqueueObject +) => TContext | void; + +export type StoreProducerAssigner< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TEventPayloadMap extends EventPayloadMap = {} +> = ( + context: TContext, + event: TEvent, + enq: EnqueueObject +) => void; + +export type Snapshot = + | { + status: 'active'; + output: undefined; + error: undefined; + } + | { + status: 'done'; + output: TOutput; + error: undefined; + } + | { + status: 'error'; + output: undefined; + error: unknown; + } + | { + status: 'stopped'; + output: undefined; + error: undefined; + }; + +export type StoreSnapshot = Snapshot & { + context: TContext; +}; + +/** + * An actor-like object that: + * + * - Has its own state + * - Can receive events + * - Is observable + */ +export interface Store< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +> + extends + Subscribable>, + InteropObservable>, + Readable> { + /** Standard Schema definitions for this store, if provided. */ + readonly schemas?: StoreSchemas; + send: (event: ExtractEvents) => void; + getSnapshot: () => StoreSnapshot; + /** Read the current snapshot as a `Readable` value. */ + get: () => StoreSnapshot; + getInitialSnapshot: () => StoreSnapshot; + /** + * Subscribes to [inspection events](https://stately.ai/docs/inspection) from + * the store. + * + * Inspectors that call `store.inspect(…)` will immediately receive the + * current snapshot as an "@xstate.transition" inspection event. + */ + inspect: ( + observer: + | Observer + | ((inspectionEvent: StoreInspectionEvent) => void) + ) => Subscription; + sessionId: string; + on: ( + type: TType, + handler: ( + emitted: Compute< + TEmitted & (TType extends '*' ? unknown : { type: TType }) + > + ) => void + ) => Subscription; + /** + * A trigger object that allows you to send events to the store without + * manually constructing event objects. + * + * @example + * + * ```ts + * // Equivalent to: + * // store.send({ type: 'increment', by: 1 }); + * store.trigger.increment({ by: 1 }); + * ``` + */ + trigger: TriggerObject; + can: CanObject; + select( + selector: Selector, + equalityFn?: (a: TSelected, b: TSelected) => boolean + ): Selection; + /** + * Returns the next state and effects for the given state and event, as a + * tuple. + * + * @example + * + * ```ts + * const [nextState, effects] = store.transition(store.getSnapshot(), { + * type: 'increment', + * by: 1 + * }); + * ``` + */ + transition: StoreTransition< + TContext, + ExtractEvents, + TEmitted + >; + /** + * Extends the store with additional functionality via a store extension. + * + * @example + * + * ```ts + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with(undoRedo()); + * + * store.trigger.inc(); + * store.trigger.undo(); // undoes the increment + * ``` + */ + with( + extension: StoreExtension< + TContext, + TEventPayloadMap, + TNewEventPayloadMap, + TEmitted + > + ): Store; +} + +export type StoreTransition< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject +> = ( + state: StoreSnapshot, + event: TEvent +) => StoreTransitionResult, TEmitted>; + +export type StoreTransitionResult< + TSnapshot extends StoreSnapshot, + TEmitted extends EventObject +> = [TSnapshot, StoreEffect[]] & { + _allowed?: boolean; +}; + +export type StoreConfig< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmittedPayloadMap extends EventPayloadMap = {}, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +> = { + context: ResolveStoreContext; + schemas?: StoreSchemas; + on: TEventSchemaMap extends StandardSchemaMap + ? { + [K in keyof ResolveStoreEventPayloadMap< + TEventPayloadMap, + TEventSchemaMap + > & + string]?: StoreAssigner< + ResolveStoreContext, + { + type: K; + } & ResolveStoreEventPayloadMap[K], + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + ResolveStoreEventPayloadMap + >; + } + : { + [K in keyof TEventPayloadMap & string]: StoreAssigner< + ResolveStoreContext, + { type: K } & TEventPayloadMap[K], + ExtractEvents< + ResolveStoreEmittedPayloadMap + >, + ResolveStoreEventPayloadMap + >; + }; +}; + +export type SpecificStoreConfig< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TContextSchema extends StandardSchemaV1 | undefined = undefined, + TEventSchemaMap extends StandardSchemaMap | undefined = undefined, + TEmittedSchemaMap extends StandardSchemaMap | undefined = undefined +> = { + context: ResolveStoreContext; + schemas?: StoreSchemas; + on: { + [E in TEvent as E['type']]?: StoreAssigner< + ResolveStoreContext, + E, + TEmitted, + EventPayloadMapFromEvents + >; + }; +}; + +type EventPayloadMapFromEvents = { + [E in TEvent as E['type']]: DistributiveOmit; +}; + +type Compute
= A extends any ? { [K in keyof A]: A[K] } : never; + +export type AnyStore = Store; + +export type SnapshotFromStore> = + TStore extends Store + ? StoreSnapshot + : never; + +/** + * Extract the type of events from a `Store`. + * + * @example + * + * ```ts + * const store = createStore( + * { count: 0 }, + * { + * inc: (context, event: { by: number }) => ({ + * count: context.count + event.by + * }), + * dec: (context, event: { by: number }) => ({ + * count: context.count - event.by + * }) + * } + * ); + * type StoreEvent = EventFromStore; + * // ^? { type: 'inc', by: number } | { type: 'dec', by: number } + * ``` + * + * @example + * + * Using utility types derived from `EventFromStore` to create individual + * type-safe event transition functions for a store: + * + * ```ts + * import { + * createStore, + * type EventFromStore, + * type Store + * } from '@xstate/store'; + * + * // Extract the event where `Type` matches the event's `type` from the given + * // `Store`. + * type EventByType< + * TStore extends Store, + * Type extends EventFromStore['type'] + * > = Extract, { type: Type }>; + * + * // Extract a specific store event's "input" type (the event type without the + * // `type` property). + * type EventInputByType< + * TStore extends Store, + * Type extends EventFromStore['type'] + * > = Omit, 'type'>; + * + * const store = createStore( + * { count: 0 }, + * { + * add: (context, event: { addend: number }) => ({ + * count: context.count + event.addend + * }), + * multiply: (context, event: { multiplier: number }) => ({ + * count: context.count * event.multiplier + * }) + * } + * ); + * + * const add = (input: EventInputByType) => + * store.send({ type: 'add', addend: input.addend }); + * + * add({ addend: 1 }); // sends { type: 'add', addend: 1 } + * + * const multiply = (input: EventInputByType) => + * store.send({ type: 'multiply', multiplier: input.multiplier }); + * + * multiply({ multiplier: 2 }); // sends { type: 'multiply', multiplier: 2 } + * ``` + */ +export type EventFromStore> = + TStore extends Store + ? ExtractEvents + : never; + +// Copied from XState core +// ----------------------- + +export interface InteropSubscribable { + subscribe(observer: Observer): Subscription; +} + +interface InteropObservable { + [Symbol.observable]: () => InteropSubscribable; +} + +// Based on RxJS types +export type Observer = { + next?: (value: T) => void; + error?: (err: unknown) => void; + complete?: () => void; +}; + +export interface Subscription { + unsubscribe(): void; +} + +export interface Subscribable extends InteropSubscribable { + subscribe(observer: Observer): Subscription; + subscribe( + next: (value: T) => void, + error?: (error: any) => void, + complete?: () => void + ): Subscription; +} + +// Same as MachineContext (for now) +export type StoreContext = Record; + +/** The full definition of an event, with a string `type`. */ +export type EventObject = { + /** The type of event that is sent. */ + type: string; +}; +type Values = T[keyof T]; + +interface StoreBaseInspectionEventProperties { + rootId: string; // the session ID of the root + /** + * The relevant actorRef for the inspection event. + * + * For store transition events, this is the `actorRef` of the store. + */ + actorRef: ActorRefLike; +} + +export interface StoreInspectionEvent extends StoreBaseInspectionEventProperties { + type: '@xstate.transition'; + event: AnyEventObject; // { type: string, ... } + snapshot: Snapshot; +} + +interface AnyEventObject { + type: string; + [key: string]: any; +} + +export type StoreInspectedSnapshotEvent = StoreInspectionEvent; +export type StoreInspectedActionEvent = StoreInspectionEvent; +export type StoreInspectedEventEvent = StoreInspectionEvent; +export type StoreInspectedActorEvent = StoreInspectionEvent; + +// export type ActorRefLike = Pick< +// AnyActorRef, +// 'sessionId' | 'send' | 'getSnapshot' +// >; + +export type ActorRefLike = { + sessionId: string; + // https://github.com/statelyai/xstate/pull/5037/files#r1717036732 + send: (event: any) => void; + getSnapshot: () => any; +}; + +export type Selector = (context: TContext) => TSelected; + +export type Selection = Readable; + +export type StoreSelectorsConfig = Record< + string, + Selector +>; + +export type ResolvedStoreSelectors< + TContext extends StoreContext, + TSelectors extends StoreSelectorsConfig +> = { + [K in keyof TSelectors]: Selection>; +}; + +export type StoreWithSelectors< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject, + TSelectors extends StoreSelectorsConfig +> = Omit, 'with'> & { + selectors: ResolvedStoreSelectors; + with( + extension: StoreExtension< + TContext, + TEventPayloadMap, + TNewEventPayloadMap, + TEmitted + > + ): StoreWithSelectors< + TContext, + TEventPayloadMap & TNewEventPayloadMap, + TEmitted, + TSelectors + >; +}; + +export interface StoreLogicCreator< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject, + TInput, + TSelectors extends StoreSelectorsConfig +> { + createStore: undefined extends TInput + ? ( + input?: TInput + ) => StoreWithSelectors + : ( + input: TInput + ) => StoreWithSelectors; +} + +export type AnyStoreLogicCreator = StoreLogicCreator; + +export type StoreFromStoreLogicCreator = + TLogic extends StoreLogicCreator< + infer TContext, + infer TEventPayloadMap, + infer TEmitted, + any, + infer TSelectors + > + ? StoreWithSelectors + : never; + +export type InputFromStoreLogicCreator = + TLogic extends StoreLogicCreator + ? TInput + : never; + +export interface Readable extends Subscribable { + get: () => T; +} + +export interface BaseAtom extends Subscribable, Readable {} + +export interface Atom extends BaseAtom { + /** Sets the value of the atom using a function. */ + set(fn: (prevVal: T) => T): void; + /** Sets the value of the atom. */ + set(value: T): void; +} + +export interface ReducerAtom extends BaseAtom { + send: (event: TEvent) => void; +} + +export interface AtomOptions { + compare?: (prev: T, next: T) => boolean; +} + +export interface AtomConfig { + createAtom: undefined extends TInput + ? (input?: TInput) => Atom + : (input: TInput) => Atom; +} + +export type AnyAtomConfig = AtomConfig; + +export type ValueFromAtomConfig = + TConfig extends AtomConfig ? TValue : never; + +export type InputFromAtomConfig = + TConfig extends AtomConfig ? TInput : never; + +export type AnyAtom = BaseAtom; + +/** + * An atom that is read-only and cannot be set. + * + * @example + * + * ```ts + * const atom = createAtom(() => 42); + * // @ts-expect-error - Cannot set a readonly atom + * atom.set(43); + * ``` + */ +export interface ReadonlyAtom extends BaseAtom {} + +/** A version of `Omit` that works with distributive types. */ +type DistributiveOmit = T extends any + ? Omit + : never; + +export type StoreLogic< + TSnapshot extends StoreSnapshot, + TEvent extends EventObject, + TEmitted extends EventObject +> = { + eventTypes?: readonly string[]; + schemas?: StoreSchemas; + getInitialSnapshot: () => TSnapshot; + transition: ( + snapshot: TSnapshot, + event: TEvent + ) => StoreTransitionResult; +}; +export type AnyStoreLogic = StoreLogic; + +/** + * A store extension that transforms store logic, optionally adding new events. + * + * @example + * + * ```ts + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with(undoRedo()); + * ``` + */ +export type StoreExtension< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TNewEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +> = ( + logic: StoreLogic< + StoreSnapshot, + ExtractEvents, + TEmitted + > +) => StoreLogic< + StoreSnapshot, + ExtractEvents | ExtractEvents, + TEmitted +>; + +export type AnyStoreConfig = StoreConfig; +export type EventFromStoreConfig = + TStore extends StoreConfig< + any, + infer TEventPayloadMap, + any, + any, + infer TEventSchemaMap, + any + > + ? ExtractEvents< + ResolveStoreEventPayloadMap + > + : never; + +export type EmitsFromStoreConfig = + TStore extends StoreConfig< + any, + any, + infer TEmittedPayloadMap, + any, + any, + infer TEmittedSchemaMap + > + ? ExtractEvents< + ResolveStoreEmittedPayloadMap + > + : never; + +export type ContextFromStoreConfig = + TStore extends StoreConfig< + infer TContext, + any, + any, + infer TContextSchema, + any, + any + > + ? ResolveStoreContext + : never; + +export type StoreFromStoreConfig = + TConfig extends StoreConfig< + infer TContext, + any, + infer TEmittedPayloadMap, + infer TContextSchema, + any, + infer TEmittedSchemaMap + > + ? Store< + ResolveStoreContext, + StoreEventPayloadMapFromConfig, + ExtractEvents< + ResolveStoreEmittedPayloadMap + > + > + : never; diff --git a/xstate-store/src/undo.ts b/xstate-store/src/undo.ts new file mode 100644 index 00000000..5fa037f2 --- /dev/null +++ b/xstate-store/src/undo.ts @@ -0,0 +1,464 @@ +import { + AnyStoreLogic, + EnqueueObject, + EventObject, + EventPayloadMap, + ExtractEvents, + StoreEffect, + StoreContext, + StoreExtension, + StoreLogic, + StoreSnapshot +} from './types.ts'; +import { appendInternalEventTypes, createEnqueueObject } from './store.ts'; + +interface UndoRedoEventOptions< + TContext extends StoreContext, + TEvent extends EventObject +> { + /** A function that returns the transaction ID of an event. */ + getTransactionId?: ( + event: TEvent, + snapshot: StoreSnapshot + ) => string | null | undefined; + /** + * A function that returns whether an event should be skipped during + * undo/redo. Skipped events are not stored in history and are not replayed + * during undo/redo. + */ + skipEvent?: (event: TEvent, snapshot: StoreSnapshot) => boolean; +} + +interface UndoRedoSnapshotOptions< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TEventPayloadMap extends EventPayloadMap +> { + /** A function that returns the transaction ID of an event. */ + getTransactionId?: ( + event: TEvent, + snapshot: StoreSnapshot + ) => string | null | undefined; + /** + * A function that returns whether a snapshot should be skipped during + * undo/redo. Skipped events don't save snapshots to history. + */ + skipEvent?: (event: TEvent, snapshot: StoreSnapshot) => boolean; + /** Maximum number of snapshots to keep in history. Defaults to Infinity. */ + historyLimit?: number; + /** + * A function to compare snapshots for equality. When true, the new snapshot + * will not be added to history. Useful for avoiding duplicate snapshots. + */ + compare?: ( + pastSnapshot: StoreSnapshot, + currentSnapshot: StoreSnapshot + ) => boolean; + /** Customizes the context restored by snapshot-based undo/redo. */ + restore?: ( + args: { + current: TContext; + next: TContext; + direction: 'undo' | 'redo'; + }, + enqueue: EnqueueObject + ) => TContext; +} + +type UndoRedoStrategyOptions< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TEventPayloadMap extends EventPayloadMap +> = + | ({ + strategy?: 'event'; + } & UndoRedoEventOptions) + | ({ + strategy: 'snapshot'; + } & UndoRedoSnapshotOptions); + +// Internal: create undo/redo logic from existing logic (for .with() pattern) +function undoRedoFromLogic< + TContext extends StoreContext, + TEvent extends EventObject, + TEmitted extends EventObject, + TEventPayloadMap extends EventPayloadMap +>( + logic: StoreLogic, TEvent, TEmitted>, + options?: UndoRedoStrategyOptions< + TContext, + TEvent, + TEmitted, + TEventPayloadMap + > +): StoreLogic< + StoreSnapshot, + TEvent | { type: 'undo' } | { type: 'redo' }, + TEmitted +> { + const historyLimit = + options?.strategy === 'snapshot' + ? (options.historyLimit ?? Infinity) + : Infinity; + + if (options?.strategy === 'snapshot') { + const restore = ( + snapshot: any, + historicalSnapshot: StoreSnapshot, + direction: 'undo' | 'redo', + past: any[], + future: any[] + ): [any, StoreEffect[]] => { + if (!options.restore) { + return [{ ...snapshot, ...historicalSnapshot, past, future }, []]; + } + + const effects: StoreEffect[] = []; + const triggeredEvents: EventObject[] = []; + const enqueue = createEnqueueObject(effects, (event) => { + triggeredEvents.push(event); + }) as EnqueueObject; + let triggeredSnapshot = { + ...snapshot, + ...historicalSnapshot, + context: options.restore( + { + current: snapshot.context, + next: historicalSnapshot.context, + direction + }, + enqueue + ) + }; + + for (const triggeredEvent of triggeredEvents) { + const [nextTriggeredSnapshot, triggeredEffects] = logic.transition( + triggeredSnapshot, + triggeredEvent as TEvent + ); + triggeredSnapshot = nextTriggeredSnapshot; + effects.push(...triggeredEffects); + } + + return [ + { + ...triggeredSnapshot, + past, + future + }, + effects + ]; + }; + + // Snapshot strategy + const enhancedLogic: AnyStoreLogic = { + ...logic, + eventTypes: appendInternalEventTypes( + logic.eventTypes, + ['undo', 'redo'], + 'undoRedo' + ), + getInitialSnapshot: () => ({ + ...logic.getInitialSnapshot(), + past: [], + future: [] + }), + transition: (snapshot, event) => { + if (event.type === 'undo') { + const past = snapshot.past.slice(); + const future = snapshot.future.slice(); + + if (!past.length) { + return [snapshot, []]; + } + + const currentSnapshot = { + status: snapshot.status, + context: snapshot.context, + output: snapshot.output, + error: snapshot.error + }; + + const lastItem = past[past.length - 1]; + const lastTransactionId = lastItem.transactionId; + + let newSnapshot; + + if (lastTransactionId === undefined) { + const item = past.pop()!; + newSnapshot = item.snapshot; + future.unshift({ + snapshot: currentSnapshot, + transactionId: lastTransactionId + }); + } else { + const transactionSnapshots: typeof past = []; + while ( + past.length > 0 && + past[past.length - 1].transactionId === lastTransactionId + ) { + transactionSnapshots.unshift(past.pop()); + } + newSnapshot = transactionSnapshots[0].snapshot; + future.unshift({ + snapshot: currentSnapshot, + transactionId: lastTransactionId + }); + } + + return restore(snapshot, newSnapshot, 'undo', past, future); + } + + if (event.type === 'redo') { + const past = snapshot.past.slice(); + const future = snapshot.future.slice(); + + if (!future.length) { + return [snapshot, []]; + } + + const firstItem = future[0]; + const firstTransactionId = firstItem.transactionId; + const currentSnapshot = { + status: snapshot.status, + context: snapshot.context, + output: snapshot.output, + error: snapshot.error + }; + + let newSnapshot; + if (firstTransactionId === undefined) { + newSnapshot = future.shift()!.snapshot; + } else { + while ( + future.length > 0 && + future[0].transactionId === firstTransactionId + ) { + newSnapshot = future.shift()!.snapshot; + } + } + + // Both stacks hold the snapshot that preceded the change, so a redo + // pushes the snapshot it is moving away from, not the one it restores. + past.push({ + snapshot: currentSnapshot, + transactionId: firstTransactionId + }); + + const excessCount = past.length - historyLimit; + if (excessCount > 0) { + past.splice(0, excessCount); + } + + return restore(snapshot, newSnapshot, 'redo', past, future); + } + + const [state, effects] = logic.transition(snapshot, event); + const isEventSkipped = options?.skipEvent?.(event as TEvent, snapshot); + + if (isEventSkipped) { + return [ + { ...state, past: snapshot.past, future: snapshot.future }, + effects + ]; + } + + const currentSnapshot = { + status: snapshot.status, + context: snapshot.context, + output: snapshot.output, + error: snapshot.error + }; + + const lastPastSnapshot = + snapshot.past[snapshot.past.length - 1]?.snapshot; + const isEqual = + lastPastSnapshot && + options?.compare?.(lastPastSnapshot, currentSnapshot); + + if (isEqual) { + return [{ ...state, past: snapshot.past, future: [] }, effects]; + } + + const past = snapshot.past.slice(); + past.push({ + snapshot: currentSnapshot, + transactionId: options?.getTransactionId?.(event as TEvent, snapshot) + }); + + const excessCount = past.length - historyLimit; + if (excessCount > 0) { + past.splice(0, excessCount); + } + + return [{ ...state, past, future: [] }, effects]; + } + }; + return enhancedLogic; + } + + // Event strategy (default) + type UndoEventItem = { event: TEvent; transactionId?: string }; + const enhancedLogic: AnyStoreLogic = { + ...logic, + eventTypes: appendInternalEventTypes( + logic.eventTypes, + ['undo', 'redo'], + 'undoRedo' + ), + getInitialSnapshot: () => ({ + ...logic.getInitialSnapshot(), + events: [] as UndoEventItem[], + undoStack: [] as UndoEventItem[] + }), + transition: (snapshot, event) => { + if (event.type === 'undo') { + const events = snapshot.events.slice(); + const undoStack = snapshot.undoStack.slice(); + if (!events.length) { + return [snapshot, []]; + } + + const lastTransactionId = events[events.length - 1].transactionId; + + if (lastTransactionId === undefined) { + const ev = events.pop()!; + undoStack.push(ev); + } else { + while (true) { + const ev = events.pop()!; + undoStack.push(ev); + if ( + !events.length || + events[events.length - 1].transactionId !== lastTransactionId + ) { + break; + } + } + } + + let state = { ...logic.getInitialSnapshot(), events, undoStack }; + for (const { event: ev } of events) { + const [newState] = logic.transition(state, ev); + state = { ...newState, events, undoStack }; + } + + return [state, []]; + } + + if (event.type === 'redo') { + const events = snapshot.events.slice(); + const undoStack = snapshot.undoStack.slice(); + if (!undoStack.length) { + return [{ ...snapshot, events, undoStack }, []]; + } + + const lastTransactionId = undoStack[undoStack.length - 1].transactionId; + let state = { ...snapshot, events, undoStack }; + const allEffects: any[] = []; + + if (lastTransactionId === undefined) { + const undoEvent = undoStack.pop()!; + events.push(undoEvent); + const [newState, effects] = logic.transition(state, undoEvent.event); + state = { ...newState, events, undoStack }; + allEffects.push(...effects); + } else { + while ( + undoStack.length > 0 && + undoStack[undoStack.length - 1].transactionId === lastTransactionId + ) { + const undoEvent = undoStack.pop()!; + events.push(undoEvent); + const [newState, effects] = logic.transition( + state, + undoEvent.event + ); + state = { ...newState, events, undoStack }; + allEffects.push(...effects); + } + } + + return [state, allEffects]; + } + + const [state, effects] = logic.transition(snapshot, event); + const isEventSkipped = options?.skipEvent?.(event as TEvent, snapshot); + const events = isEventSkipped + ? snapshot.events + : snapshot.events.concat({ + event: event as TEvent, + transactionId: options?.getTransactionId?.( + event as TEvent, + snapshot + ) + }); + + return [{ ...state, events, undoStack: [] }, effects]; + } + }; + + return enhancedLogic; +} + +/** + * Creates store logic with undo/redo functionality. + * + * Supports two strategies: + * + * - 'event' (default): Maintains event history and replays events + * - 'snapshot': Maintains snapshot history for faster undo/redo + * + * @example + * + * ```ts + * const store = createStore({ + * context: { count: 0 }, + * on: { + * inc: (ctx) => ({ count: ctx.count + 1 }) + * } + * }).with(undoRedo()); + * + * store.trigger.inc(); + * store.trigger.undo(); // count = 0 + * ``` + * + * @example + * + * ```ts + * // Snapshot strategy + * const store = createStore({ + * context: { count: 0 }, + * on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + * }).with(undoRedo({ strategy: 'snapshot', historyLimit: 10 })); + * ``` + * + * @returns Store extension with additional `undo` and `redo` event handlers + */ +// Overload: extension pattern (no config, just options) +export function undoRedo< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + options?: UndoRedoStrategyOptions< + TContext, + ExtractEvents, + TEmitted, + TEventPayloadMap + > +): StoreExtension< + TContext, + TEventPayloadMap, + { + undo: null; + redo: null; + }, + TEmitted +>; +// Implementation +export function undoRedo(options?: any): any { + return (logic: AnyStoreLogic) => undoRedoFromLogic(logic, options); +} diff --git a/xstate-store/src/validate.ts b/xstate-store/src/validate.ts new file mode 100644 index 00000000..6bddf32e --- /dev/null +++ b/xstate-store/src/validate.ts @@ -0,0 +1,266 @@ +import { StandardSchemaV1 } from './schema.ts'; +import { + EventObject, + EventPayloadMap, + StoreContext, + StoreEffect, + StoreExtension, + StoreSnapshot +} from './types.ts'; +import { storeValidationErrorSymbol } from './validationError.ts'; + +type ValidationReason = + | 'invalidContext' + | 'invalidEvent' + | 'invalidEmitted' + | 'unknownEvent' + | 'unknownEmitted' + | 'asyncValidationUnsupported'; + +interface StoreValidationErrorOptions { + reason: ValidationReason; + eventType?: string; + context?: unknown; + payload?: unknown; + issues?: unknown; +} + +/** Error thrown by `validateSchemas()` when schema validation fails. */ +export class StoreValidationError extends Error { + public readonly [storeValidationErrorSymbol] = true; + public readonly reason: ValidationReason; + public readonly eventType?: string; + public readonly context?: unknown; + public readonly payload?: unknown; + public readonly issues?: unknown; + + constructor(options: StoreValidationErrorOptions) { + super(getStoreValidationErrorMessage(options)); + this.name = 'StoreValidationError'; + this.reason = options.reason; + this.eventType = options.eventType; + this.context = options.context; + this.payload = options.payload; + this.issues = options.issues; + } +} + +interface ValidateSchemasOptions { + context?: boolean; + events?: boolean; + emitted?: boolean; + unknownEvents?: 'throw' | 'ignore'; + unknownEmitted?: 'throw' | 'ignore'; +} + +const isDevelopment = + ( + globalThis as { + process?: { + env?: { + NODE_ENV?: string; + }; + }; + } + ).process?.env?.NODE_ENV !== 'production'; + +function getStoreValidationErrorMessage(options: StoreValidationErrorOptions) { + switch (options.reason) { + case 'invalidContext': + return 'Invalid context'; + case 'invalidEvent': + return `Invalid event "${options.eventType}"`; + case 'invalidEmitted': + return `Invalid emitted event "${options.eventType}"`; + case 'unknownEvent': + return `Unknown event "${options.eventType}"`; + case 'unknownEmitted': + return `Unknown emitted event "${options.eventType}"`; + case 'asyncValidationUnsupported': + return `Async schema validation is unsupported${ + options.eventType ? ` for event "${options.eventType}"` : '' + }`; + } +} + +function isPromiseLike(value: T | PromiseLike): value is PromiseLike { + return !!value && typeof (value as any).then === 'function'; +} + +function getPayload(event: EventObject): object { + const { type: _, ...payload } = event; + return payload; +} + +function hasAnySchemas(schemas: any): boolean { + return !!(schemas?.context || schemas?.events || schemas?.emitted); +} + +function validateSchema( + schema: StandardSchemaV1, + value: unknown, + errorOptions: Omit +): void { + const result = schema['~standard'].validate(value); + + if (isPromiseLike(result)) { + throw new StoreValidationError({ + ...errorOptions, + reason: 'asyncValidationUnsupported' + }); + } + + if (result.issues) { + throw new StoreValidationError({ + ...errorOptions, + issues: result.issues + }); + } +} + +function validateEvent( + event: EventObject, + schemas: any, + eventTypes: readonly string[] | undefined, + unknownEvents: 'throw' | 'ignore' +): void { + const eventSchemas = schemas.events; + if (!eventSchemas) { + return; + } + + const payload = getPayload(event); + const schema = eventSchemas[event.type]; + + if (!schema) { + if (eventTypes?.includes(event.type)) { + return; + } + + if (unknownEvents === 'throw') { + throw new StoreValidationError({ + reason: 'unknownEvent', + eventType: event.type, + payload + }); + } + return; + } + + validateSchema(schema, payload, { + reason: 'invalidEvent', + eventType: event.type, + payload + }); +} + +function validateContext(context: unknown, schemas: any): void { + const schema = schemas.context; + if (!schema) { + return; + } + + validateSchema(schema, context, { + reason: 'invalidContext', + context + }); +} + +function validateEmitted( + effect: EventObject, + schemas: any, + unknownEmitted: 'throw' | 'ignore' +): void { + const emittedSchemas = schemas.emitted; + if (!emittedSchemas) { + return; + } + + const payload = getPayload(effect); + const schema = emittedSchemas[effect.type]; + + if (!schema) { + if (unknownEmitted === 'throw') { + throw new StoreValidationError({ + reason: 'unknownEmitted', + eventType: effect.type, + payload + }); + } + return; + } + + validateSchema(schema, payload, { + reason: 'invalidEmitted', + eventType: effect.type, + payload + }); +} + +/** + * Validates schema-declared events, emitted events, and context at runtime. + * + * Validation is opt-in; stores with schemas only use those schemas for typing + * and metadata unless this extension is applied. + */ +export function validateSchemas< + TContext extends StoreContext, + TEventPayloadMap extends EventPayloadMap, + TEmitted extends EventObject +>( + options: ValidateSchemasOptions = {} +): StoreExtension { + return (logic) => { + const schemas = logic.schemas; + + if (!hasAnySchemas(schemas)) { + if (isDevelopment) { + console.warn( + 'The "validateSchemas" store extension was used, but the store has no schemas to validate.' + ); + } + return logic; + } + + const validateContextEnabled = options.context ?? true; + const validateEventsEnabled = options.events ?? true; + const validateEmittedEnabled = options.emitted ?? true; + const unknownEvents = options.unknownEvents ?? 'throw'; + const unknownEmitted = options.unknownEmitted ?? 'throw'; + + return { + ...logic, + getInitialSnapshot() { + const snapshot = logic.getInitialSnapshot(); + + if (validateContextEnabled) { + validateContext(snapshot.context, schemas); + } + + return snapshot; + }, + transition(snapshot: StoreSnapshot, event) { + if (validateEventsEnabled) { + validateEvent(event, schemas, logic.eventTypes, unknownEvents); + } + + const result = logic.transition(snapshot, event); + const [nextSnapshot, effects] = result; + + if (validateContextEnabled) { + validateContext(nextSnapshot.context, schemas); + } + + if (validateEmittedEnabled) { + for (const effect of effects as StoreEffect[]) { + if (typeof effect !== 'function') { + validateEmitted(effect, schemas, unknownEmitted); + } + } + } + + return result; + } + }; + }; +} diff --git a/xstate-store/src/validationError.ts b/xstate-store/src/validationError.ts new file mode 100644 index 00000000..c56f934a --- /dev/null +++ b/xstate-store/src/validationError.ts @@ -0,0 +1,9 @@ +export const storeValidationErrorSymbol = Symbol.for( + 'xstate.store.validationError' +); + +export function isStoreValidationError(error: unknown): boolean { + return ( + !!error && typeof error === 'object' && storeValidationErrorSymbol in error + ); +} diff --git a/xstate-store/test/atom.test.ts b/xstate-store/test/atom.test.ts new file mode 100644 index 00000000..222a2dda --- /dev/null +++ b/xstate-store/test/atom.test.ts @@ -0,0 +1,1045 @@ +import { + createStore, + createAtom, + createAtomConfig, + createAsyncAtom, + createReducerAtom +} from '../src/index.ts'; + +it('creates an atom', () => { + const atom = createAtom(42); + + expect(atom.get()).toBe(42); +}); + +it('creates an atom from atom config', () => { + const config = createAtomConfig(42); + const atom = config.createAtom(); + const otherAtom = config.createAtom(); + + atom.set(100); + + expect(atom.get()).toBe(100); + expect(otherAtom.get()).toBe(42); +}); + +it('creates an atom from atom config and input', () => { + const config = createAtomConfig((input: { initialCount: number }) => { + return input.initialCount; + }); + const atom = config.createAtom({ initialCount: 10 }); + + expect(atom.get()).toBe(10); +}); + +it('sets the value of the atom using a function', () => { + const atom = createAtom(0); + + atom.set((prev) => prev + 1); + + expect(atom.get()).toBe(1); + + atom.set((prev) => prev + 1); + + expect(atom.get()).toBe(2); +}); + +it('does not subscribe a writable atom to reads inside its updater', () => { + const source = createAtom(1); + const target = createAtom(10); + const observer = vi.fn(); + const subscription = target.subscribe(observer); + + target.set((previous) => previous + source.get()); + source.set(2); + + expect(target.get()).toBe(11); + expect(observer.mock.calls).toEqual([[11]]); + subscription.unsubscribe(); +}); + +it('drains notifications before rethrowing the first subscriber error', () => { + const source = createAtom(0); + const unrelated = createAtom(0); + const error = new Error('subscriber failed'); + const first = source.subscribe(() => { + throw error; + }); + const observer = vi.fn(); + const second = source.subscribe(observer); + const other = unrelated.subscribe(vi.fn()); + + expect(() => source.set(1)).toThrow(error); + expect(observer.mock.calls).toEqual([[1]]); + unrelated.set(1); + expect(observer.mock.calls).toEqual([[1]]); + expect(() => source.set(2)).toThrow(error); + expect(observer.mock.calls).toEqual([[1], [2]]); + + first.unsubscribe(); + second.unsubscribe(); + other.unsubscribe(); +}); + +it('rethrows undefined and still delivers reentrant notifications', () => { + const source = createAtom(0); + const nested = createAtom(0); + const order: string[] = []; + const subscriptions = [ + nested.subscribe(() => { + order.push('nested'); + throw undefined; + }), + nested.subscribe(() => { + order.push('nested-second'); + throw new Error('later error'); + }), + source.subscribe(() => { + order.push('first'); + nested.set(1); + }), + source.subscribe(() => { + order.push('second'); + }) + ]; + let didThrow = false; + try { + source.set(1); + } catch (error) { + didThrow = true; + expect(error).toBeUndefined(); + } + expect(didThrow).toBe(true); + expect(order).toEqual(['first', 'second', 'nested', 'nested-second']); + subscriptions.forEach((subscription) => subscription.unsubscribe()); +}); + +it('can set the value to undefined', () => { + const atom = createAtom(1); + expect(atom.get()).toBe(1); + + atom.set(undefined); + expect(atom.get()).toBe(undefined); +}); + +it('can subscribe to atom changes', () => { + const log = vi.fn(); + const atom = createAtom(0); + + atom.subscribe(log); + + atom.set(1); + + expect(log).toHaveBeenCalledWith(1); + + atom.set(2); + + expect(log).toHaveBeenCalledWith(2); +}); + +it('can unsubscribe from atom changes', () => { + const log = vi.fn(); + const atom = createAtom(0); + + const sub = atom.subscribe(log); + + atom.set(1); + + expect(log).toHaveBeenCalledWith(1); + + sub.unsubscribe(); + + atom.set(2); + + expect(log).toHaveBeenCalledTimes(1); +}); + +it('can create a combined atom', () => { + const nameAtom = createAtom('a'); + const numAtom = createAtom(3); + const combinedAtom = createAtom(() => nameAtom.get().repeat(numAtom.get())); + + expect(combinedAtom.get()).toBe('aaa'); + + nameAtom.set('b'); + + expect(combinedAtom.get()).toBe('bbb'); + + numAtom.set(5); +}); + +it('allows updates to a computed dependency during a subscription callback', () => { + const atom = createAtom({ a: 0, b: 0, c: 0 }); + + const a0 = createAtom(() => atom.get().a); + const a1 = createAtom(() => a0.get()); + a1.subscribe(() => atom.set((ctx) => ({ ...ctx, b: ctx.a }))); + + const b0 = createAtom(() => atom.get().b); + const b1 = createAtom(() => b0.get()); + b1.subscribe(() => atom.set((ctx) => ({ ...ctx, c: ctx.b }))); + + atom.set((ctx) => ({ ...ctx, a: ctx.a + 1 })); + atom.set((ctx) => ({ ...ctx, a: ctx.a + 1 })); + atom.set((ctx) => ({ ...ctx, a: ctx.a + 1 })); + + expect(a0.get()).toBe(3); + expect(a1.get()).toBe(3); + expect(b0.get()).toBe(3); + expect(b1.get()).toBe(3); + expect(atom.get().a).toBe(3); + expect(atom.get().b).toBe(3); + expect(atom.get().c).toBe(3); +}); + +it('does not loop when updating a computed dependency which affects an atoms own state', () => { + const count = createAtom(0); + const a = createAtom(() => count.get()); + + a.subscribe(() => count.set((val) => val + 1)); + + count.set((val) => val + 1); + + expect(a.get()).toBe(2); + expect(count.get()).toBe(2); +}); + +it('works with a mix of atoms and stores', () => { + const countAtom = createAtom(0); + const store = createStore({ + context: { name: 'David' }, + on: { + nameUpdated: (_, event: { name: string }) => ({ + name: event.name + }) + } + }); + + const log = vi.fn(); + + const combinedAtom = createAtom( + () => store.get().context.name + ` ${countAtom.get()}` + ); + + combinedAtom.subscribe(log); + + expect(combinedAtom.get()).toBe('David 0'); + + store.send({ type: 'nameUpdated', name: 'John' }); + + expect(combinedAtom.get()).toBe('John 0'); + + countAtom.set(1); + + expect(log).toHaveBeenCalledTimes(2); + expect(log).toHaveBeenCalledWith('John 1'); + expect(countAtom.get()).toBe(1); + expect(combinedAtom.get()).toBe('John 1'); +}); + +it('works with stores', () => { + const nameStore = createStore({ + context: { name: 'David' }, + on: { + nameUpdated: (context, event: { name: string }) => ({ + name: event.name + }) + } + }); + + const countStore = createStore({ + context: { count: 0 }, + on: { + increment: (context) => ({ count: context.count + 1 }) + } + }); + + const combinedAtom = createAtom( + () => nameStore.get().context.name + ` ${countStore.get().context.count}` + ); + + expect(combinedAtom.get()).toBe('David 0'); + + nameStore.trigger.nameUpdated({ name: 'John' }); + + expect(combinedAtom.get()).toBe('John 0'); + + countStore.trigger.increment(); + + expect(combinedAtom.get()).toBe('John 1'); +}); + +it('works with selectors', () => { + const store = createStore({ + context: { name: 'David', count: 0 }, + on: { + increment: (context) => ({ ...context, count: context.count + 1 }) + } + }); + + const count = store.select((ctx) => ctx.count); + + const combinedAtom = createAtom(() => 2 * count.get()); + + expect(combinedAtom.get()).toBe(0); + + store.trigger.increment(); + + expect(combinedAtom.get()).toBe(2); +}); + +it('allows sending events to the store during a selector subscription', () => { + const store = createStore({ + context: { a: 0, b: 0 }, + on: { + a: (context) => ({ ...context, a: context.a + 1 }), + b: (context) => ({ ...context, b: context.b + 1 }) + } + }); + + const a = store.select((context) => context.a); + a.subscribe(() => store.trigger.b()); + + store.trigger.a(); + store.trigger.a(); + store.trigger.a(); + + expect(store.get().context.a).toBe(3); + expect(store.get().context.b).toBe(3); +}); + +it('works with selectors (get API)', () => { + const store = createStore({ + context: { name: 'David', count: 0 }, + on: { + increment: (context) => ({ ...context, count: context.count + 1 }) + } + }); + + const count = store.select((ctx) => ctx.count); + + const combinedAtom = createAtom(() => 2 * count.get()); + + expect(combinedAtom.get()).toBe(0); + + store.trigger.increment(); + + expect(combinedAtom.get()).toBe(2); +}); + +it('combined atoms should be read-only', () => { + const atom1 = createAtom(0); + const atom2 = createAtom(1); + const combinedAtom = createAtom(() => atom1.get() + atom2.get()); + + expect(combinedAtom.get()).toBe(1); + + // @ts-expect-error + combinedAtom.set?.(2); + + expect(combinedAtom.get()).toBe(1); +}); + +it('combined atom getters accept only prev as an argument', () => { + const atom = createAtom(1); + + createAtom( + // @ts-expect-error — two-arg (read, prev) signature is no longer supported + (_read, _prev) => atom.get() + ); + + // prev is valid + createAtom((prev) => atom.get() + (prev ?? 0)); +}); + +it('conditionally read atoms are properly read in combined atoms', () => { + const atom1 = createAtom(true); + const atom2 = createAtom(false); + const activatorAtom = createAtom<'inactive' | 'active'>('inactive'); + const combinedAtom = createAtom(() => + activatorAtom.get() === 'active' ? atom1.get() : atom2.get() + ); + + expect(combinedAtom.get()).toBe(false); + + activatorAtom.set('active'); + + expect(combinedAtom.get()).toBe(true); + + activatorAtom.set('inactive'); + + expect(combinedAtom.get()).toBe(false); +}); + +it('conditionally read atoms are properly unsubscribed when no longer needed', () => { + const atom1 = createAtom(true); + const activatorAtom = createAtom<'inactive' | 'active'>('active'); + const combinedAtom = createAtom(() => + activatorAtom.get() === 'active' ? atom1.get() : {} + ); + + const vals: any[] = []; + + combinedAtom.subscribe((val) => { + vals.push(val); + }); + + expect(vals).toEqual([]); + + atom1.set(false); + + expect(vals).toEqual([false]); + + atom1.set(true); + + expect(vals).toEqual([false, true]); + + activatorAtom.set('inactive'); + + // From here, atom1 should no longer be subscribed to + // Without the unsubscribe logic, this would be [false, true, {}, {}, ...] + + expect(vals).toEqual([false, true, {}]); + + atom1.set(false); + + expect(vals).toEqual([false, true, {}]); + + atom1.set(true); + + expect(vals).toEqual([false, true, {}]); + + // Subscribing again should cause atom1 to be subscribed again + + activatorAtom.set('active'); + + expect(vals).toEqual([false, true, {}, true]); + + atom1.set(false); + + expect(vals).toEqual([false, true, {}, true, false]); +}); + +it('handles diamond dependencies with single update', () => { + const log = vi.fn(); + const sourceAtom = createAtom(1); + + const pathA = createAtom(() => sourceAtom.get() * 2); + const pathB = createAtom(() => sourceAtom.get() * 3); + + const bottomAtom = createAtom(() => pathA.get() + pathB.get()); + + bottomAtom.subscribe((x) => { + log(x); + }); + + // Initial value: (1 * 2) + (1 * 3) = 5 + expect(bottomAtom.get()).toBe(5); + expect(log).toHaveBeenCalledTimes(0); + + // Update source: (2 * 2) + (2 * 3) = 10 + sourceAtom.set(2); + + const result = bottomAtom.get(); + + expect(result).toBe(10); + + // Without proper diamond problem handling, log might be called multiple times + // as the update propagates through both paths + expect(log).toHaveBeenCalledTimes(1); + expect(log).toHaveBeenCalledWith(10); +}); + +it('handles complex diamond dependencies correctly', () => { + const log = vi.fn(); + + // Base atom D + const atomD = createAtom(1); + + // Level 1 - C depends on D + const atomC = createAtom(() => atomD.get() * 2); + + // Level 2 - B depends on C and D + const atomB = createAtom(() => atomC.get() + atomD.get()); + + // Level 3 - A depends on B, C, and D + const atomA = createAtom(() => atomB.get() + atomC.get() + atomD.get()); + + atomA.subscribe(log); + + // Initial computation: + // D = 1 + // C = D * 2 = 2 + // B = C + D = 3 + // A = B + C + D = 6 + expect(atomA.get()).toBe(6); + expect(log).toHaveBeenCalledTimes(0); + + // Update base atom D + atomD.set(2); + + // After update: + // D = 2 + // C = D * 2 = 4 + // B = C + D = 6 + // A = B + C + D = 12 + expect(atomA.get()).toBe(12); + + // Should only trigger one update despite multiple dependency paths + expect(log).toHaveBeenCalledTimes(1); + expect(log).toHaveBeenCalledWith(12); + + // Verify intermediate values + expect(atomB.get()).toBe(6); + expect(atomC.get()).toBe(4); + expect(atomD.get()).toBe(2); +}); + +it('supports custom equality functions through compare option', () => { + const log = vi.fn(); + + const coordAtom = createAtom( + { x: 0, y: 0 }, + { + compare: (prev, next) => prev.x === next.x && prev.y === next.y + } + ); + + coordAtom.subscribe(log); + + // Initial value + expect(coordAtom.get()).toEqual({ x: 0, y: 0 }); + expect(log).not.toHaveBeenCalled(); + + // Setting same values shouldn't trigger update + coordAtom.set({ x: 0, y: 0 }); + expect(log).not.toHaveBeenCalled(); + + // Different x value should trigger update + coordAtom.set({ x: 1, y: 0 }); + expect(log).toHaveBeenCalledTimes(1); + expect(log).toHaveBeenCalledWith({ x: 1, y: 0 }); + + // Different y value should trigger update + coordAtom.set({ x: 1, y: 2 }); + expect(log).toHaveBeenCalledTimes(2); + expect(log).toHaveBeenLastCalledWith({ x: 1, y: 2 }); + + // Setting same values should not trigger update + coordAtom.set({ x: 1, y: 2 }); + expect(log).toHaveBeenCalledTimes(2); +}); + +it('uses Object.is as default equality function', () => { + const log = vi.fn(); + const objAtom = createAtom({ value: 0 }); + + objAtom.subscribe(log); + + // Initial value + expect(objAtom.get()).toEqual({ value: 0 }); + expect(log).not.toHaveBeenCalled(); + + // Setting with same shape but new object should trigger update + objAtom.set({ value: 0 }); + expect(log).toHaveBeenCalledTimes(1); + + // Setting with same object reference shouldn't trigger update + const obj = { value: 1 }; + objAtom.set(obj); + expect(log).toHaveBeenCalledTimes(2); + objAtom.set(obj); + expect(log).toHaveBeenCalledTimes(2); +}); + +it('Atom-specific properties should not be exposed', () => { + const atom = createAtom(0); + + // @ts-expect-error + atom._subs; + // @ts-expect-error + atom._subsTail; + // @ts-expect-error + atom._snapshot; + // @ts-expect-error + atom._flags; + // @ts-expect-error + atom._deps; + // @ts-expect-error + atom._depsTail; + + const computed = createAtom(() => atom.get()); + + // @ts-expect-error + computed._subs; + // @ts-expect-error + computed._subsTail; + // @ts-expect-error + computed._snapshot; + // @ts-expect-error + computed._flags; + // @ts-expect-error + computed._deps; + // @ts-expect-error + computed._depsTail; + + const store = createStore({ + context: {}, + on: {} + }); + + // @ts-expect-error + store._subs; + // @ts-expect-error + store._subsTail; + // @ts-expect-error + store._snapshot; + // @ts-expect-error + store._flags; + // @ts-expect-error + store._deps; + // @ts-expect-error + store._depsTail; +}); + +it('computed atoms can use their previous value in the getter', () => { + const count = createAtom(1); + const accumulated = createAtom((prev) => count.get() + (prev ?? 0)); + + expect(accumulated.get()).toBe(1); // 0 + 1 = 1 + + count.set(2); + expect(accumulated.get()).toBe(3); // 1 + 2 = 3 + + count.set(3); + expect(accumulated.get()).toBe(6); // 3 + 3 = 6 +}); + +describe('reducer atoms', () => { + it('updates from current state and sent event', () => { + const counter = createReducerAtom(0, (state, event: number) => + Math.min(10, state + event) + ); + + counter.send(13); + + expect(counter.get()).toBe(10); + }); + + it('can receive arbitrary event values', () => { + const value = createReducerAtom( + '', + (state, event: string | number) => state + event + ); + + value.send('x'); + value.send(1); + + expect(value.get()).toBe('x1'); + }); + + it('notifies subscribers when the reducer changes state', () => { + const counter = createReducerAtom( + 0, + (state, event: number) => state + event + ); + const listener = vi.fn(); + + counter.subscribe(listener); + counter.send(1); + counter.send(0); + counter.send(2); + + expect(listener).toHaveBeenCalledTimes(2); + expect(listener).toHaveBeenNthCalledWith(1, 1); + expect(listener).toHaveBeenNthCalledWith(2, 3); + }); + + it('can be used by derived atoms', () => { + const counter = createReducerAtom( + 0, + (state, event: number) => state + event + ); + const doubled = createAtom(() => counter.get() * 2); + + expect(doubled.get()).toBe(0); + + counter.send(2); + + expect(doubled.get()).toBe(4); + }); + + it('does not track atom reads inside the reducer', () => { + const multiplier = createAtom(2); + const counter = createReducerAtom( + 1, + (state, event: number) => state + event * multiplier.get() + ); + const listener = vi.fn(); + + counter.subscribe(listener); + counter.send(3); + multiplier.set(10); + + expect(counter.get()).toBe(7); + expect(listener).toHaveBeenCalledTimes(1); + }); +}); + +describe('async atoms', () => { + it.each(['done', 'error'] as const)( + 'should recompute after a dependency changes following %s settlement', + async (status) => { + const count = createAtom(1); + const error = new Error('initial failure'); + const atom = createAsyncAtom(async () => { + const value = count.get(); + if (status === 'error' && value === 1) { + throw error; + } + return value * 2; + }); + const selected = createAtom(() => { + const state = atom.get(); + return state.status === 'done' ? state.data : state.status; + }); + const observer = vi.fn(); + const subscription = selected.subscribe(observer); + + await Promise.resolve(); + expect(atom.get()).toEqual( + status === 'done' ? { status, data: 2 } : { status, error } + ); + observer.mockClear(); + + count.set(2); + expect(atom.get()).toEqual({ status: 'pending' }); + await Promise.resolve(); + + expect(atom.get()).toEqual({ status: 'done', data: 4 }); + expect(observer.mock.calls).toEqual([['pending'], [4]]); + subscription.unsubscribe(); + } + ); + + it('should recompute lazily after a settled dependency changes', async () => { + const count = createAtom(1); + const getter = vi.fn(async () => count.get() * 2); + const atom = createAsyncAtom(getter); + + expect(getter).not.toHaveBeenCalled(); + expect(atom.get()).toEqual({ status: 'pending' }); + await Promise.resolve(); + expect(atom.get()).toEqual({ status: 'done', data: 2 }); + + count.set(2); + expect(getter).toHaveBeenCalledTimes(1); + expect(atom.get()).toEqual({ status: 'pending' }); + await Promise.resolve(); + expect(atom.get()).toEqual({ status: 'done', data: 4 }); + expect(getter).toHaveBeenCalledTimes(2); + }); + + it('should retain dependencies when the async comparator suppresses a result', async () => { + const count = createAtom(1); + const atom = createAsyncAtom(async () => count.get() % 2, { + compare: (previous, next) => + next.status === 'pending' || + (previous.status === 'done' && + next.status === 'done' && + previous.data === next.data) + }); + const observer = vi.fn(); + const subscription = atom.subscribe(observer); + + await Promise.resolve(); + expect(atom.get()).toEqual({ status: 'done', data: 1 }); + observer.mockClear(); + + count.set(3); + await Promise.resolve(); + expect(observer).not.toHaveBeenCalled(); + + count.set(4); + await Promise.resolve(); + expect(atom.get()).toEqual({ status: 'done', data: 0 }); + expect(observer).toHaveBeenCalledExactlyOnceWith({ + status: 'done', + data: 0 + }); + subscription.unsubscribe(); + }); + + it('async atoms should work (fulfilled)', async () => { + const atom = createAsyncAtom(async () => 'hello'); + + expect(atom.get()).toEqual({ status: 'pending' }); + + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(atom.get()).toEqual({ status: 'done', data: 'hello' }); + }); + + it('async atoms should work (rejected)', async () => { + const atom = createAsyncAtom(async () => { + throw new Error('test'); + }); + + expect(atom.get()).toEqual({ status: 'pending' }); + + await new Promise((resolve) => setTimeout(resolve, 0)); + + expect(atom.get()).toEqual({ + status: 'error', + error: expect.any(Error) + }); + }); + + it('should only call getValue once for multiple concurrent reads', async () => { + let getValueCallCount = 0; + const RESOLVED_VALUE = 'test-value'; + + const myAsyncAtom = createAsyncAtom(async () => { + getValueCallCount++; + return RESOLVED_VALUE; + }); + + // Initial reads should show pending status + expect(myAsyncAtom.get()).toEqual({ status: 'pending' }); + expect(myAsyncAtom.get()).toEqual({ status: 'pending' }); + + // Let the promise resolve + await new Promise((resolve) => setTimeout(resolve, 0)); + + // Both reads should now show the resolved value + expect(myAsyncAtom.get()).toEqual({ + status: 'done', + data: RESOLVED_VALUE + }); + expect(myAsyncAtom.get()).toEqual({ + status: 'done', + data: RESOLVED_VALUE + }); + + // getValue should have only been called once + expect(getValueCallCount).toBe(1); + + // Additional reads after resolution should still use cached value + expect(myAsyncAtom.get()).toEqual({ + status: 'done', + data: RESOLVED_VALUE + }); + expect(getValueCallCount).toBe(1); + }); + + it('should only call getValue once even when error occurs', async () => { + let getValueCallCount = 0; + const ERROR_MESSAGE = 'test error'; + + const myAsyncAtom = createAsyncAtom(async () => { + getValueCallCount++; + throw new Error(ERROR_MESSAGE); + }); + + // Initial reads should show pending status + expect(myAsyncAtom.get()).toEqual({ status: 'pending' }); + expect(myAsyncAtom.get()).toEqual({ status: 'pending' }); + + // Let the promise reject + await new Promise((resolve) => setTimeout(resolve, 0)); + + // Both reads should now show the error + expect(myAsyncAtom.get()).toEqual({ + status: 'error', + error: expect.any(Error) + }); + expect(myAsyncAtom.get()).toEqual({ + status: 'error', + error: expect.any(Error) + }); + + // getValue should have only been called once + expect(getValueCallCount).toBe(1); + + // Additional reads after rejection should still use cached error + expect(myAsyncAtom.get()).toEqual({ + status: 'error', + error: expect.any(Error) + }); + expect(getValueCallCount).toBe(1); + }); + + it('async atoms should not have a .set() method', () => { + const atom = createAsyncAtom(async () => 'hello'); + + expect('set' in atom).toBe(false); + }); + + it('should pass an abort signal to async atoms', () => { + const atom = createAsyncAtom(async ({ signal }) => { + expect(signal).toBeInstanceOf(AbortSignal); + return 'hello'; + }); + + expect(atom.get()).toEqual({ status: 'pending' }); + }); + + it('should abort and ignore stale async atom results', async () => { + const count = createAtom(1); + const signals: AbortSignal[] = []; + const resolvers: Array<(value: number) => void> = []; + const atom = createAsyncAtom(({ signal }) => { + const currentCount = count.get(); + signals.push(signal); + + return new Promise((resolve) => { + resolvers.push(resolve); + }).then(() => currentCount); + }); + + expect(atom.get()).toEqual({ status: 'pending' }); + + count.set(2); + expect(atom.get()).toEqual({ status: 'pending' }); + expect(signals[0].aborted).toBe(true); + + resolvers[0](1); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(atom.get()).toEqual({ status: 'pending' }); + + resolvers[1](2); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(atom.get()).toEqual({ status: 'done', data: 2 }); + }); + + it('should ignore stale async atom errors', async () => { + const count = createAtom(1); + const rejectors: Array<(error: unknown) => void> = []; + const resolvers: Array<(value: number) => void> = []; + const atom = createAsyncAtom(({ signal }) => { + const currentCount = count.get(); + + return new Promise((resolve, reject) => { + resolvers.push(resolve); + rejectors.push(reject); + }).then(() => { + if (signal.aborted) { + throw new Error('aborted'); + } + return currentCount; + }); + }); + + expect(atom.get()).toEqual({ status: 'pending' }); + + count.set(2); + expect(atom.get()).toEqual({ status: 'pending' }); + + rejectors[0](new Error('stale')); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(atom.get()).toEqual({ status: 'pending' }); + + resolvers[1](2); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(atom.get()).toEqual({ status: 'done', data: 2 }); + }); + + it('should notify subscribers when async operation completes successfully', async () => { + const log = vi.fn(); + const atom = createAsyncAtom(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + return 'test-value'; + }); + + atom.subscribe(log); + + expect(atom.get()).toEqual({ status: 'pending' }); + expect(log).not.toHaveBeenCalled(); + + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(log).toHaveBeenCalledTimes(1); + expect(log).toHaveBeenCalledWith({ status: 'done', data: 'test-value' }); + expect(atom.get()).toEqual({ status: 'done', data: 'test-value' }); + }); + + it('should notify subscribers when async operation fails', async () => { + const log = vi.fn(); + const error = new Error('test error'); + const atom = createAsyncAtom(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + throw error; + }); + + atom.subscribe(log); + + expect(atom.get()).toEqual({ status: 'pending' }); + expect(log).not.toHaveBeenCalled(); + + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(log).toHaveBeenCalledTimes(1); + expect(log).toHaveBeenCalledWith({ status: 'error', error }); + expect(atom.get()).toEqual({ status: 'error', error }); + }); + + it('should notify multiple subscribers when async operation completes', async () => { + const log1 = vi.fn(); + const log2 = vi.fn(); + const atom = createAsyncAtom(async () => { + await new Promise((resolve) => setTimeout(resolve, 10)); + return 'multi-test'; + }); + + atom.subscribe(log1); + atom.subscribe(log2); + + expect(atom.get()).toEqual({ status: 'pending' }); + expect(log1).not.toHaveBeenCalled(); + expect(log2).not.toHaveBeenCalled(); + + await new Promise((resolve) => setTimeout(resolve, 20)); + + expect(log1).toHaveBeenCalledTimes(1); + expect(log1).toHaveBeenCalledWith({ status: 'done', data: 'multi-test' }); + expect(log2).toHaveBeenCalledTimes(1); + expect(log2).toHaveBeenCalledWith({ status: 'done', data: 'multi-test' }); + }); + + it('subscribe callback should not track dependencies from .get() calls', () => { + const items = createAtom([]); + const ids = createAtom(() => Array.from(items.get()).sort().join(',')); + const log = vi.fn(); + + ids.subscribe(() => { + void items.get(); + log(); + }); + + items.set([1]); + items.set([1]); + items.set([1, 2]); + items.set([1, 2]); + + expect(log).toHaveBeenCalledTimes(2); + }); + + it('subscribe callback should not track deps on non-computed atoms', () => { + const ids = createAtom(''); + const items = createAtom([]); + items.subscribe((value) => ids.set(Array.from(value).sort().join(','))); + const log = vi.fn(); + + ids.subscribe(() => { + void items.get(); + log(); + }); + + items.set([1]); + items.set([1]); + items.set([1, 2]); + items.set([1, 2]); + + expect(log).toHaveBeenCalledTimes(2); + }); +}); diff --git a/xstate-store/test/broadcast.test.ts b/xstate-store/test/broadcast.test.ts new file mode 100644 index 00000000..27d6d154 --- /dev/null +++ b/xstate-store/test/broadcast.test.ts @@ -0,0 +1,194 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { createStore } from '../src/index.ts'; +import { + createBroadcastStorage, + persist, + flushStorage, + subscribeToBroadcastStorage, + type StateStorage +} from '../src/persist.ts'; + +type Listener = (event: { data: unknown }) => void; + +const channels = new Map>(); + +class MockBroadcastChannel { + public listeners = new Set(); + + constructor(public name: string) { + let entries = channels.get(name); + if (!entries) { + entries = new Set(); + channels.set(name, entries); + } + entries.add(this); + } + + postMessage(data: unknown) { + const entries = channels.get(this.name); + if (!entries) { + return; + } + + for (const channel of entries) { + if (channel === this) { + continue; + } + + for (const listener of channel.listeners) { + listener({ data }); + } + } + } + + addEventListener(_type: 'message', listener: Listener) { + this.listeners.add(listener); + } + + removeEventListener(_type: 'message', listener: Listener) { + this.listeners.delete(listener); + } + + close() { + channels.get(this.name)?.delete(this); + this.listeners.clear(); + } +} + +function createMemoryStorage(): StateStorage { + const data: Record = {}; + + return { + getItem: (name) => data[name] ?? null, + setItem: (name, value) => { + data[name] = value; + }, + removeItem: (name) => { + delete data[name]; + } + }; +} + +function createCounterStore(storage: StateStorage) { + return createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }).with(persist({ name: 'counter', storage })); +} + +function waitForMicrotask(): Promise { + return new Promise((resolve) => { + setTimeout(resolve, 0); + }); +} + +describe('broadcast storage', () => { + beforeEach(() => { + channels.clear(); + (globalThis as any).BroadcastChannel = MockBroadcastChannel; + }); + + afterEach(() => { + channels.clear(); + delete (globalThis as any).BroadcastChannel; + }); + + it('broadcasts queued persisted writes only after each async write completes', async () => { + const completions: Array<() => void> = []; + let saved: string | null = null; + const baseStorage: StateStorage = { + getItem: () => saved, + removeItem: () => {}, + setItem: (_name, value) => + new Promise((resolve) => { + completions.push(() => { + saved = value; + resolve(); + }); + }) + }; + const storage = createBroadcastStorage(baseStorage); + const receiver = new MockBroadcastChannel('xstate-store'); + const counts: number[] = []; + receiver.addEventListener('message', () => { + counts.push(JSON.parse(saved!).context.count); + }); + const store = createCounterStore(storage); + store.trigger.inc(); + store.trigger.inc(); + expect(completions).toHaveLength(1); + expect(counts).toEqual([]); + const flushed = flushStorage(store); + completions[0](); + await waitForMicrotask(); + expect(counts).toEqual([1]); + expect(completions).toHaveLength(2); + completions[1](); + await flushed; + expect(counts).toEqual([1, 2]); + }); + + it('broadcasts writes to other storage adapters on the same channel', () => { + const baseStorage = createMemoryStorage(); + const storage = createBroadcastStorage(baseStorage); + const receiver = new MockBroadcastChannel('xstate-store'); + const messages: unknown[] = []; + + receiver.addEventListener('message', (event) => { + messages.push(event.data); + }); + + storage.setItem('counter', JSON.stringify({ context: { count: 1 } })); + + expect(messages).toEqual([ + { type: 'xstate-store-update', name: 'counter' } + ]); + }); + + it('rehydrates subscribed stores when another tab writes persisted state', async () => { + const baseStorage = createMemoryStorage(); + const storage1 = createBroadcastStorage(baseStorage); + const storage2 = createBroadcastStorage(baseStorage); + const store1 = createCounterStore(storage1); + const store2 = createCounterStore(storage2); + const unsubscribe = subscribeToBroadcastStorage(store2); + + store1.trigger.inc(); + await waitForMicrotask(); + + expect(store1.getSnapshot().context.count).toBe(1); + expect(store2.getSnapshot().context.count).toBe(1); + + unsubscribe(); + }); + + it('does not rehydrate from unrelated storage names', async () => { + const baseStorage = createMemoryStorage(); + const storage = createBroadcastStorage(baseStorage); + const store = createCounterStore(storage); + const unsubscribe = subscribeToBroadcastStorage(store); + const sender = new MockBroadcastChannel('xstate-store'); + + baseStorage.setItem( + 'other', + JSON.stringify({ context: { count: 100 }, version: 0 }) + ); + sender.postMessage({ type: 'xstate-store-update', name: 'other' }); + await waitForMicrotask(); + + expect(store.getSnapshot().context.count).toBe(0); + + unsubscribe(); + sender.close(); + }); + + it('throws when subscribing a store without broadcast storage', () => { + const store = createCounterStore(createMemoryStorage()); + + expect(() => subscribeToBroadcastStorage(store)).toThrow( + 'subscribeToBroadcastStorage: store storage must be wrapped with createBroadcastStorage()' + ); + }); +}); diff --git a/xstate-store/test/fromStore.test.ts b/xstate-store/test/fromStore.test.ts new file mode 100644 index 00000000..cd42ae97 --- /dev/null +++ b/xstate-store/test/fromStore.test.ts @@ -0,0 +1,180 @@ +import { + createActor, + executeEffects, + initialTransition, + transition +} from 'xstate'; +import { fromStore } from '../src/index.ts'; +import type { StoreEffectEnqueue } from '../src/index.ts'; +import { z } from 'zod'; + +describe('fromStore', () => { + it('creates an actor from store logic with input', () => { + const storeLogic = fromStore({ + context: (count: number) => ({ count }), + on: { + inc: (ctx, ev: { by: number }) => { + return { + ...ctx, + count: ctx.count + ev.by + }; + } + } + }); + + const actor = createActor(storeLogic, { + input: 42 + }); + + actor.start(); + + actor.send({ type: 'inc', by: 8 }); + + expect(actor.getSnapshot().context.count).toEqual(50); + }); + + it('emits events', () => { + const spy = vi.fn(); + + const storeLogic = fromStore({ + context: (count: number) => ({ count }), + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, ev: { by: number }, enq) => { + enq.emit.increased({ upBy: ev.by }); + return { + ...ctx, + count: ctx.count + ev.by + }; + } + } + }); + + const actor = createActor(storeLogic, { + input: 42 + }); + + actor.on('increased', spy); + + actor.start(); + + actor.send({ type: 'inc', by: 8 }); + + expect(actor.getSnapshot().context.count).toEqual(50); + expect(spy).toHaveBeenCalledTimes(1); + expect(spy).toHaveBeenCalledWith({ type: 'increased', upBy: 8 }); + }); + + it('enq.getSnapshot() in a sync effect reflects the post-transition state (matches createStore)', () => { + let seen: number | undefined; + + const storeLogic = fromStore({ + context: (_: void) => ({ count: 0 }), + on: { + inc: (ctx, _, enq) => { + enq.effect( + ({ getSnapshot }: StoreEffectEnqueue<{ count: number }>) => { + seen = getSnapshot().context.count; + } + ); + return { ...ctx, count: ctx.count + 1 }; + } + } + }); + + const actor = createActor(storeLogic).start(); + actor.send({ type: 'inc' }); + + expect(seen).toEqual(1); + }); + + it('enq.getSnapshot() in an async effect reflects the latest committed state', async () => { + let seen: number | undefined; + + const storeLogic = fromStore({ + context: (_: void) => ({ count: 0 }), + on: { + start: (ctx, _, enq) => { + enq.effect( + async ({ getSnapshot }: StoreEffectEnqueue<{ count: number }>) => { + await new Promise((resolve) => setTimeout(resolve, 5)); + seen = getSnapshot().context.count; + } + ); + return { ...ctx, count: ctx.count + 1 }; + }, + bump: (ctx) => ({ count: ctx.count + 10 }) + } + }); + + const actor = createActor(storeLogic).start(); + actor.send({ type: 'start' }); // count -> 1 + actor.send({ type: 'bump' }); // count -> 11 before the async effect resumes + + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(seen).toEqual(11); + }); + + it('routes effect sends through a custom transition runtime', async () => { + let effectCount: number | undefined; + const storeLogic = fromStore({ + context: { count: 0 }, + on: { + inc: (context, _, enq) => { + enq.effect( + ({ getSnapshot, send }: StoreEffectEnqueue<{ count: number }>) => { + effectCount = getSnapshot().context.count; + send({ type: 'dec' }); + } + ); + return { count: context.count + 1 }; + }, + dec: (context) => ({ count: context.count - 1 }) + } + }); + const [initial] = initialTransition(storeLogic); + const [, effects] = transition(storeLogic, initial, { type: 'inc' }); + const sent: string[] = []; + + await executeEffects(effects, { + sendEvent: (_source, _target, event) => { + sent.push(event.type); + } + }); + + expect(sent).toEqual(['dec']); + expect(effectCount).toBe(1); + }); + + it('routes effect triggers through a custom transition runtime', async () => { + const storeLogic = fromStore({ + context: { count: 0 }, + on: { + inc: (context, _, enq) => { + enq.effect( + ({ trigger }: StoreEffectEnqueue<{ count: number }, { dec: {} }>) => + trigger.dec() + ); + return { count: context.count + 1 }; + }, + dec: (context) => ({ count: context.count - 1 }) + } + }); + const [initial] = initialTransition(storeLogic); + const [, effects] = transition(storeLogic, initial, { type: 'inc' }); + const sent: string[] = []; + + await executeEffects(effects, { + sendEvent: (_source, _target, event) => { + sent.push(event.type); + } + }); + + expect(sent).toEqual(['dec']); + }); +}); diff --git a/xstate-store/test/persist.test.ts b/xstate-store/test/persist.test.ts new file mode 100644 index 00000000..4e658e4b --- /dev/null +++ b/xstate-store/test/persist.test.ts @@ -0,0 +1,1565 @@ +import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { createStore } from '../src/index.ts'; +import { z } from 'zod'; +import { StoreValidationError, validateSchemas } from '../src/validate.ts'; +import { + persist, + createJSONStorage, + clearStorage, + flushStorage, + rehydrateStore, + isHydrated, + type StateStorage +} from '../src/persist.ts'; + +// Mock localStorage +describe('persistence lifecycle regressions', () => { + it.each([0, 100])( + 'preserves an eligible snapshot when a nested event is filtered (throttle %i)', + async (throttle) => { + const storage = createMockStorage(); + const store = createStore({ + context: { value: 0 }, + on: { + outer: () => ({ value: 1 }), + inner: () => ({ value: 2 }) + } + }).with( + persist({ + name: 'filtered-nested', + storage, + throttle, + filter: (event) => event.type === 'outer' + }) + ); + store.subscribe((snapshot) => { + if (snapshot.context.value === 1) store.trigger.inner(); + }); + store.trigger.outer(); + expect(store.getSnapshot().context.value).toBe(2); + await flushStorage(store); + expect( + JSON.parse(storage.getItem('filtered-nested') as string).context.value + ).toBe(1); + } + ); + + it('orders new async writes after a queued clear', async () => { + const operations: string[] = []; + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + persist({ + name: 'counter', + storage: { + getItem: () => null, + setItem: async (_key, value) => { + operations.push(`write ${JSON.parse(value).context.count}`); + }, + removeItem: async () => { + operations.push('clear'); + } + } + }) + ); + + store.trigger.inc(); + const cleared = clearStorage(store); + store.trigger.inc(); + await cleared; + await flushStorage(store); + expect(operations).toEqual(['write 1', 'clear', 'write 2']); + }); + + it.each(['snapshot', 'event'] as const)( + 'reports a rejected initial async read (%s)', + async (strategy) => { + const error = new Error('read failed'); + const rejected = Promise.reject(error); + // Keep the unfixed implementation from leaking rejection into other tests. + void rejected.catch(() => {}); + const onError = vi.fn(); + createStore({ context: {}, on: {} }).with( + persist({ + name: 'counter', + strategy, + onError, + storage: { + getItem: () => rejected, + setItem: vi.fn(), + removeItem: vi.fn() + } + }) + ); + await Promise.resolve(); + expect(onError).toHaveBeenCalledExactlyOnceWith(error); + } + ); + + it('applies pick once when flushing a throttled update', () => { + const storage = createMockStorage(); + const pick = vi.fn((context: { count: number }) => ({ + count: context.count + 1 + })); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with(persist({ name: 'counter', storage, throttle: 100, pick })); + + store.trigger.inc(); + flushStorage(store); + expect(pick).toHaveBeenCalledTimes(1); + expect(JSON.parse(storage.getItem('counter') as string).context).toEqual({ + count: 2 + }); + }); + + it.each(['snapshot', 'event'] as const)( + 'preserves updates triggered by onDone during a throttled flush (%s)', + (strategy) => { + const storage = createMockStorage(); + let firstWrite = true; + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + persist({ + name: 'counter', + storage, + strategy, + throttle: 100, + onDone: () => { + if (firstWrite) { + firstWrite = false; + store.trigger.inc(); + } + } + }) + ); + + store.trigger.inc(); + flushStorage(store); + flushStorage(store); + const saved = JSON.parse(storage.getItem('counter') as string); + expect( + strategy === 'event' ? saved.events.length : saved.context.count + ).toBe(2); + } + ); + + it.each(['snapshot', 'event'] as const)( + 'cancels buffered writes when storage is cleared (%s)', + (strategy) => { + vi.useFakeTimers(); + try { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with(persist({ name: 'counter', strategy, storage, throttle: 100 })); + + store.trigger.inc(); + expect(clearStorage(store)).toBeUndefined(); + vi.advanceTimersByTime(100); + flushStorage(store); + expect(storage.getItem('counter')).toBeNull(); + } finally { + vi.useRealTimers(); + } + } + ); + + it('removes storage after an in-flight async write finishes', async () => { + let completeWrite!: () => void; + let saved: string | null = null; + const removeItem = vi.fn(() => { + saved = null; + }); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + persist({ + name: 'counter', + storage: { + getItem: () => null, + setItem: (_key, value) => + new Promise((resolve) => { + completeWrite = () => { + saved = value; + resolve(); + }; + }), + removeItem + } + }) + ); + + store.trigger.inc(); + const cleared = clearStorage(store); + expect(removeItem).not.toHaveBeenCalled(); + completeWrite(); + await cleared; + expect(removeItem).toHaveBeenCalledExactlyOnceWith('counter'); + expect(saved).toBeNull(); + }); +}); + +function createMockStorage(): StateStorage { + const data: Record = {}; + return { + getItem: (name: string) => data[name] ?? null, + setItem: (name: string, value: string) => { + data[name] = value; + }, + removeItem: (name: string) => { + delete data[name]; + } + }; +} + +function createAsyncMockStorage(): StateStorage { + const data: Record = {}; + return { + getItem: async (name: string) => data[name] ?? null, + setItem: async (name: string, value: string) => { + data[name] = value; + }, + removeItem: async (name: string) => { + delete data[name]; + } + }; +} + +describe('persist', () => { + it('should persist context to storage after each event', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + store.trigger.inc(); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.context).toEqual({ count: 1 }); + expect(stored.version).toBe(0); + }); + + it('should restore context from storage on creation', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 42 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + expect(store.getSnapshot().context.count).toBe(42); + }); + + it('should set _persist.hydrated to true on sync hydration', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + expect(isHydrated(store)).toBe(true); + }); + + it('should set _persist.hydrated to true when storage is empty', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + expect(isHydrated(store)).toBe(true); + }); + + it('should preserve _persist metadata across transitions', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + store.trigger.inc(); + expect(isHydrated(store)).toBe(true); + }); +}); + +describe('persist - pick', () => { + it('should only persist selected fields', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0, secret: 'do-not-persist' }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) + } + }).with( + persist({ + name: 'test', + storage, + pick: (ctx) => ({ count: ctx.count }) + }) + ); + + store.trigger.inc(); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.context).toEqual({ count: 1 }); + expect(stored.context.secret).toBeUndefined(); + }); + + it('should merge picked data with full context on restore', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 42 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0, name: 'Ada' }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + pick: (ctx) => ({ count: ctx.count }) + }) + ); + + expect(store.getSnapshot().context).toEqual({ count: 42, name: 'Ada' }); + }); +}); + +describe('persist - version + migrate', () => { + it('should migrate persisted state when version differs', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 10 }, + version: 1 + }) + ); + + const store = createStore({ + context: { count: 0, label: 'default' }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + version: 2, + migrate: (persisted, version) => { + if (version === 1) { + return { ...persisted, label: 'migrated' }; + } + return persisted; + } + }) + ); + + expect(store.getSnapshot().context.count).toBe(10); + expect(store.getSnapshot().context.label).toBe('migrated'); + }); + + it('should migrate with string versions', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 10 }, + version: '1.0.0' + }) + ); + + const store = createStore({ + context: { count: 0, label: 'default' }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + version: '2.0.0', + migrate: (persisted, version) => { + if (version === '1.0.0') { + return { ...persisted, label: 'migrated' }; + } + return persisted; + } + }) + ); + + expect(store.getSnapshot().context.count).toBe(10); + expect(store.getSnapshot().context.label).toBe('migrated'); + }); + + it('should not migrate when version matches', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 5 }, + version: 2 + }) + ); + + const migrateFn = vi.fn((ctx) => ctx); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + version: 2, + migrate: migrateFn + }) + ); + + expect(migrateFn).not.toHaveBeenCalled(); + expect(store.getSnapshot().context.count).toBe(5); + }); +}); + +describe('persist - merge', () => { + it('should use custom merge strategy', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 42, items: ['a'] }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0, items: ['b', 'c'] as string[] }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + merge: (persisted, current) => ({ + ...current, + ...persisted, + items: [...current.items, ...(persisted.items ?? [])] + }) + }) + ); + + expect(store.getSnapshot().context.count).toBe(42); + expect(store.getSnapshot().context.items).toEqual(['b', 'c', 'a']); + }); +}); + +describe('persist - serialize / deserialize', () => { + it('should use custom serializer and deserializer', () => { + const storage = createMockStorage(); + const prefix = 'CUSTOM:'; + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + serialize: (value) => prefix + JSON.stringify(value), + deserialize: (str) => JSON.parse(str.slice(prefix.length)) + }) + ); + + store.trigger.inc(); + + expect((storage.getItem('test') as string).startsWith(prefix)).toBe(true); + + // Verify roundtrip: create new store from same storage + const store2 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + serialize: (value) => prefix + JSON.stringify(value), + deserialize: (str) => JSON.parse(str.slice(prefix.length)) + }) + ); + + expect(store2.getSnapshot().context.count).toBe(1); + }); +}); + +describe('persist - throttle', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('should batch writes with throttle', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, throttle: 100 })); + + store.trigger.inc(); // count = 1 + store.trigger.inc(); // count = 2 + store.trigger.inc(); // count = 3 + + // Not yet written + expect(storage.getItem('test')).toBeNull(); + + vi.advanceTimersByTime(100); + + // Only last value written + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.context.count).toBe(3); + }); + + it('should not write again if no events between throttle intervals', () => { + const storage = createMockStorage(); + const onDone = vi.fn(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, throttle: 100, onDone })); + + store.trigger.inc(); + vi.advanceTimersByTime(100); + + expect(onDone).toHaveBeenCalledTimes(1); + + vi.advanceTimersByTime(100); + // No extra writes + expect(onDone).toHaveBeenCalledTimes(1); + }); +}); + +describe('persist - flushStorage', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + afterEach(() => { + vi.useRealTimers(); + }); + + it('should force immediate write of pending throttled context', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, throttle: 1000 })); + + store.trigger.inc(); + store.trigger.inc(); + + expect(storage.getItem('test')).toBeNull(); + + flushStorage(store); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.context.count).toBe(2); + }); + + it('should throw when store has no persist extension', () => { + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }); + + expect(() => flushStorage(store)).toThrow( + 'flushStorage: store does not have a persist extension' + ); + }); + + it('should return a promise for async storage flushes', async () => { + const storage = createAsyncMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, throttle: 1000 })); + + await rehydrateStore(store); + + store.trigger.inc(); + store.trigger.inc(); + + await flushStorage(store); + + const stored = JSON.parse((await storage.getItem('test')) as string); + expect(stored.context.count).toBe(2); + }); +}); + +describe('persist - onDone / onError', () => { + it('should call onDone after successful write', () => { + const storage = createMockStorage(); + const onDone = vi.fn(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, onDone })); + + store.trigger.inc(); + + expect(onDone).toHaveBeenCalledWith({ count: 1 }); + }); + + it('should call onDone with picked context when pick is used', () => { + const storage = createMockStorage(); + const onDone = vi.fn(); + const store = createStore({ + context: { count: 0, secret: 'hidden' }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + onDone, + pick: (ctx) => ({ count: ctx.count }) + }) + ); + + store.trigger.inc(); + + expect(onDone).toHaveBeenCalledWith({ count: 1 }); + expect(onDone).not.toHaveBeenCalledWith( + expect.objectContaining({ secret: 'hidden' }) + ); + }); + + it('should call onError on write failure', () => { + const error = new Error('quota exceeded'); + const failStorage: StateStorage = { + getItem: () => null, + setItem: () => { + throw error; + }, + removeItem: () => {} + }; + const onError = vi.fn(); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage: failStorage, onError })); + + store.trigger.inc(); + + expect(onError).toHaveBeenCalledWith(error); + }); + + it('should call onError on read failure during hydration', () => { + const failStorage: StateStorage = { + getItem: () => { + throw new Error('read failed'); + }, + setItem: () => {}, + removeItem: () => {} + }; + const onError = vi.fn(); + + createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage: failStorage, onError })); + + expect(onError).toHaveBeenCalled(); + }); +}); + +describe('persist - filter', () => { + it('should skip persisting when filter returns false', () => { + const storage = createMockStorage(); + const onDone = vi.fn(); + const store = createStore({ + context: { count: 0, mouse: { x: 0, y: 0 } }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + mousemove: (ctx, e: { x: number; y: number }) => ({ + ...ctx, + mouse: { x: e.x, y: e.y } + }) + } + }).with( + persist({ + name: 'test', + storage, + onDone, + filter: (event) => event.type !== 'mousemove' + }) + ); + + store.trigger.mousemove({ x: 10, y: 20 }); + expect(onDone).not.toHaveBeenCalled(); + + store.trigger.inc(); + expect(onDone).toHaveBeenCalledTimes(1); + }); +}); + +describe('persist - skipHydration', () => { + it('should not hydrate when skipHydration is true', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 99 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, skipHydration: true })); + + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(false); + }); +}); + +describe('persist - rehydrateStore', () => { + it('should rehydrate from sync storage', async () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 99 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, skipHydration: true })); + + expect(store.getSnapshot().context.count).toBe(0); + + await rehydrateStore(store); + + expect(store.getSnapshot().context.count).toBe(99); + expect(isHydrated(store)).toBe(true); + }); + + it('should rehydrate from async storage', async () => { + const storage = createAsyncMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 77 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, skipHydration: true })); + + expect(store.getSnapshot().context.count).toBe(0); + + await rehydrateStore(store); + + expect(store.getSnapshot().context.count).toBe(77); + expect(isHydrated(store)).toBe(true); + }); + + it('should merge with events sent before rehydration', async () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 10 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, skipHydration: true })); + + // Send events before rehydration + store.trigger.inc(); // count = 1 + + await rehydrateStore(store); + + // Default merge: persisted overwrites current, so count = 10 + expect(store.getSnapshot().context.count).toBe(10); + }); + + it('should handle empty storage gracefully', async () => { + const storage = createMockStorage(); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, skipHydration: true })); + + await rehydrateStore(store); + + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(true); + }); + + it('should apply migration during rehydration', async () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 5 }, + version: 1 + }) + ); + + const store = createStore({ + context: { count: 0, label: '' }, + on: { inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + version: 2, + skipHydration: true, + migrate: (persisted, version) => { + if (version === 1) { + return { ...persisted, label: 'migrated' }; + } + return persisted; + } + }) + ); + + await rehydrateStore(store); + + expect(store.getSnapshot().context.count).toBe(5); + expect(store.getSnapshot().context.label).toBe('migrated'); + }); + + it('should throw when store has no persist extension', async () => { + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }); + + await expect(rehydrateStore(store)).rejects.toThrow( + 'rehydrateStore: store does not have a persist extension' + ); + }); +}); + +describe('persist - clearStorage', () => { + it('should remove persisted data from storage', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + store.trigger.inc(); + expect(storage.getItem('test')).not.toBeNull(); + + clearStorage(store); + expect(storage.getItem('test')).toBeNull(); + }); + + it('should throw when store has no persist extension', () => { + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }); + + expect(() => clearStorage(store)).toThrow( + 'clearStorage: store does not have a persist extension' + ); + }); + + it('should return a promise for async storage removals', async () => { + const storage = createAsyncMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + store.trigger.inc(); + await Promise.resolve(); + + await clearStorage(store); + + expect(await storage.getItem('test')).toBeNull(); + }); +}); + +describe('persist - createJSONStorage', () => { + it('should return noop storage when getStorage throws', () => { + const storage = createJSONStorage(() => { + throw new Error('no localStorage'); + }); + + expect(storage.getItem('test')).toBeNull(); + expect(() => storage.setItem('test', 'value')).not.toThrow(); + expect(() => storage.removeItem('test')).not.toThrow(); + }); + + it('should wrap a working storage adapter', () => { + const mockStorage = createMockStorage(); + const storage = createJSONStorage(() => mockStorage); + + storage.setItem('foo', 'bar'); + expect(storage.getItem('foo')).toBe('bar'); + + storage.removeItem('foo'); + expect(storage.getItem('foo')).toBeNull(); + }); + + it('should preserve async storage semantics', async () => { + const mockStorage = createAsyncMockStorage(); + const storage = createJSONStorage(() => mockStorage); + + await storage.setItem('foo', 'bar'); + expect(await storage.getItem('foo')).toBe('bar'); + + await storage.removeItem('foo'); + expect(await storage.getItem('foo')).toBeNull(); + }); +}); + +describe('persist - SSR-safe defaults', () => { + it('should not require localStorage when using default storage', () => { + const originalDescriptor = Object.getOwnPropertyDescriptor( + globalThis, + 'localStorage' + ); + + Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + get() { + throw new Error('no localStorage'); + } + }); + + try { + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test' })); + + expect(isHydrated(store)).toBe(true); + expect(() => store.trigger.inc()).not.toThrow(); + } finally { + if (originalDescriptor) { + Object.defineProperty(globalThis, 'localStorage', originalDescriptor); + } else { + delete (globalThis as { localStorage?: Storage }).localStorage; + } + } + }); + + it('should detect persist rehydrate event collisions in development', () => { + const storage = createMockStorage(); + + expect(() => + createStore({ + context: { count: 0 }, + on: { + ['__persist.rehydrate']: (ctx) => ctx + } + }).with(persist({ name: 'test', storage })) + ).toThrow( + 'The "persist" store extension uses reserved event type(s): "__persist.rehydrate".' + ); + }); +}); + +describe('persist - async storage auto-detection', () => { + it('should detect async storage and skip sync hydration', () => { + const storage = createAsyncMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + context: { count: 50 }, + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + // Should NOT have hydrated (async storage detected) + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(false); + }); +}); + +describe('persist - composability', () => { + it('should work with undoRedo extension', () => { + // Import would be needed in real code but this tests the pattern + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage })); + + store.trigger.inc(); + store.trigger.inc(); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.context.count).toBe(2); + expect(store.getSnapshot().context.count).toBe(2); + }); + + it('should persist and restore correctly across store instances', () => { + const storage = createMockStorage(); + const config = { + name: 'test' as const, + storage + }; + + // Store 1: write + const store1 = createStore({ + context: { count: 0, name: 'test' }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + setName: (ctx, e: { name: string }) => ({ ...ctx, name: e.name }) + } + }).with(persist(config)); + + store1.trigger.inc(); + store1.trigger.inc(); + store1.trigger.setName({ name: 'updated' }); + + // Store 2: read + const store2 = createStore({ + context: { count: 0, name: 'test' }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + setName: (ctx, e: { name: string }) => ({ ...ctx, name: e.name }) + } + }).with(persist(config)); + + expect(store2.getSnapshot().context.count).toBe(2); + expect(store2.getSnapshot().context.name).toBe('updated'); + }); +}); + +describe('persist - strategy: event', () => { + it('should persist events to storage', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + store.trigger.inc(); + store.trigger.inc(); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.events).toHaveLength(2); + expect(stored.events[0].type).toBe('inc'); + expect(stored.version).toBe(0); + }); + + it('should restore state by replaying events', () => { + const storage = createMockStorage(); + + // Store 1: produce events + const store1 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + store1.trigger.inc(); + store1.trigger.inc(); + store1.trigger.inc(); + + // Store 2: restore from events + const store2 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + expect(store2.getSnapshot().context.count).toBe(3); + }); + + it('should restore state with event payloads', () => { + const storage = createMockStorage(); + + const store1 = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + add: (ctx, e: { amount: number }) => ({ count: ctx.count + e.amount }) + } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + store1.trigger.inc(); + store1.trigger.add({ amount: 10 }); + + const store2 = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + add: (ctx, e: { amount: number }) => ({ count: ctx.count + e.amount }) + } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + expect(store2.getSnapshot().context.count).toBe(11); + }); + + it('should set _persist.hydrated to true on sync hydration', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + expect(isHydrated(store)).toBe(true); + }); + + it('should respect maxEvents option', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', maxEvents: 2 }) + ); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.inc(); // 3 + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.events).toHaveLength(2); + expect(stored.checkpoint).toEqual({ count: 1 }); + + // New store replays last 2 events from checkpoint, getting correct total + const store2 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', maxEvents: 2 }) + ); + + expect(store2.getSnapshot().context.count).toBe(3); + }); + + it('should not hydrate when skipHydration is true', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + events: [{ type: 'inc' }, { type: 'inc' }], + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', skipHydration: true }) + ); + + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(false); + }); + + it('should rehydrate from async storage', async () => { + const storage = createAsyncMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + events: [{ type: 'inc' }, { type: 'inc' }, { type: 'inc' }], + version: 0 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', skipHydration: true }) + ); + + expect(store.getSnapshot().context.count).toBe(0); + + await rehydrateStore(store); + + expect(store.getSnapshot().context.count).toBe(3); + expect(isHydrated(store)).toBe(true); + }); + + it('should continue accumulating events after rehydration', () => { + const storage = createMockStorage(); + + // Store 1 + const store1 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + store1.trigger.inc(); + store1.trigger.inc(); + + // Store 2: restore then continue + const store2 = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + expect(store2.getSnapshot().context.count).toBe(2); + + store2.trigger.inc(); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.events).toHaveLength(3); + expect(store2.getSnapshot().context.count).toBe(3); + }); + + it('should migrate events when version differs', () => { + const storage = createMockStorage(); + storage.setItem( + 'test', + JSON.stringify({ + events: [{ type: 'increment' }, { type: 'increment' }], + version: 1 + }) + ); + + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage, + strategy: 'event', + version: 2, + migrate: (events, _version) => + events.map((e: any) => + e.type === 'increment' ? { ...e, type: 'inc' } : e + ) + }) + ); + + expect(store.getSnapshot().context.count).toBe(2); + }); + + it('should work with clearStorage', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + store.trigger.inc(); + expect(storage.getItem('test')).not.toBeNull(); + + clearStorage(store); + expect(storage.getItem('test')).toBeNull(); + }); + + it('should handle empty storage gracefully', () => { + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with(persist({ name: 'test', storage, strategy: 'event' })); + + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(true); + }); + + it('should call onError on read failure during hydration', () => { + const failStorage: StateStorage = { + getItem: () => { + throw new Error('read failed'); + }, + setItem: () => {}, + removeItem: () => {} + }; + const onError = vi.fn(); + + createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'test', + storage: failStorage, + strategy: 'event', + onError + }) + ); + + expect(onError).toHaveBeenCalled(); + }); + + it('should work with throttle', () => { + vi.useFakeTimers(); + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', throttle: 100 }) + ); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); + + expect(storage.getItem('test')).toBeNull(); + + vi.advanceTimersByTime(100); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.events).toHaveLength(3); + vi.useRealTimers(); + }); + + it('should work with flushStorage', () => { + vi.useFakeTimers(); + const storage = createMockStorage(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'test', storage, strategy: 'event', throttle: 1000 }) + ); + + store.trigger.inc(); + store.trigger.inc(); + + expect(storage.getItem('test')).toBeNull(); + + flushStorage(store); + + const stored = JSON.parse(storage.getItem('test') as string); + expect(stored.events).toHaveLength(2); + vi.useRealTimers(); + }); +}); + +describe.each(['snapshot', 'event'] as const)( + 'persist committed %s writes', + (strategy) => { + it.each([ + [0, 'effect'], + [100, 'effect'], + [0, 'subscriber'], + [100, 'subscriber'] + ] as const)( + 'persists nested events in commit order (throttle %i, %s)', + async (throttle, nestedFrom) => { + const storage = createMockStorage(); + const makeStore = () => + createStore({ + context: { value: 0 }, + on: { + outer: (context, _event, enqueue) => { + if (nestedFrom === 'effect') { + enqueue.effect(({ trigger }) => trigger.inner()); + } + return { value: context.value * 10 + 1 }; + }, + inner: (context) => ({ value: context.value * 10 + 2 }) + } + }).with( + persist({ + name: 'nested', + strategy, + storage, + throttle, + ...(strategy === 'event' ? { maxEvents: 1 } : {}) + }) + ); + const store = makeStore(); + expect(store.can.outer()).toBe(true); + store.transition(store.getSnapshot(), { type: 'outer' }); + await flushStorage(store); + expect(storage.getItem('nested')).toBeNull(); + + const subscription = store.subscribe((snapshot) => { + if (nestedFrom === 'subscriber' && snapshot.context.value === 1) { + store.trigger.inner(); + } + }); + store.trigger.outer(); + subscription.unsubscribe(); + expect(store.getSnapshot().context.value).toBe(12); + await flushStorage(store); + const saved = JSON.parse(storage.getItem('nested') as string); + if (strategy === 'snapshot') { + expect(saved.context.value).toBe(12); + } else { + expect(saved.events).toEqual([{ type: 'inner' }]); + expect(saved.checkpoint).toEqual({ value: 1 }); + } + expect(makeStore().getSnapshot().context.value).toBe(12); + + await rehydrateStore(store); + store.trigger.inner(); + await flushStorage(store); + expect(makeStore().getSnapshot().context.value).toBe(122); + } + ); + + it.each(['can', 'transition', 'validation'] as const)( + 'does not buffer %s evaluations', + async (evaluation) => { + vi.useFakeTimers(); + try { + const storage = createMockStorage(); + const base = createStore({ + schemas: { context: z.object({ count: z.number().max(1) }) }, + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ + name: 'committed', + strategy, + storage, + throttle: 100, + ...(strategy === 'event' ? { maxEvents: 1 } : {}) + }) + ); + const store = + evaluation === 'validation' ? base.with(validateSchemas()) : base; + store.trigger.inc(); + if (evaluation === 'can') { + expect(store.can.inc()).toBe(true); + } else if (evaluation === 'transition') { + store.transition(store.getSnapshot(), { type: 'inc' }); + } else { + expect(() => store.trigger.inc()).toThrow(StoreValidationError); + } + await vi.advanceTimersByTimeAsync(100); + expect(store.getSnapshot().context.count).toBe(1); + const saved = JSON.parse(storage.getItem('committed') as string); + if (strategy === 'snapshot') expect(saved.context.count).toBe(1); + else { + expect(saved.events).toEqual([{ type: 'inc' }]); + expect(saved.checkpoint).toBeNull(); + } + } finally { + vi.useRealTimers(); + } + } + ); + + it('flushes throttled data after an already pending asynchronous write', async () => { + vi.useFakeTimers(); + try { + const writes: Array<{ value: string; resolve: () => void }> = []; + const storage: StateStorage = { + getItem: () => null, + removeItem: () => {}, + setItem: (_name, value) => + new Promise((resolve) => writes.push({ value, resolve })) + }; + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'throttled', storage, strategy, throttle: 100 }) + ); + store.trigger.inc(); + await vi.advanceTimersByTimeAsync(100); + store.trigger.inc(); + const flushed = flushStorage(store); + expect(writes).toHaveLength(1); + writes[0].resolve(); + await vi.advanceTimersByTimeAsync(0); + expect(writes).toHaveLength(2); + const saved = JSON.parse(writes[1].value); + if (strategy === 'snapshot') expect(saved.context.count).toBe(2); + else expect(saved.events).toHaveLength(2); + writes[1].resolve(); + await flushed; + await vi.advanceTimersByTimeAsync(100); + expect(writes).toHaveLength(2); + } finally { + vi.useRealTimers(); + } + }); + + it.each([false, true])( + 'orders asynchronous writes and recovers after failure: %s', + async (failFirst) => { + const writes: Array<{ + value: string; + resolve: () => void; + reject: (error: unknown) => void; + }> = []; + let saved: string | null = null; + const onDone = vi.fn(); + const onError = vi.fn(); + const storage: StateStorage = { + getItem: () => saved, + removeItem: () => {}, + setItem: (_key, value) => + new Promise((resolve, reject) => { + writes.push({ + value, + resolve: () => { + saved = value; + resolve(); + }, + reject + }); + }) + }; + const store = createStore({ + context: { count: 0 }, + on: { inc: (ctx) => ({ count: ctx.count + 1 }) } + }).with( + persist({ name: 'ordered', strategy, storage, onDone, onError }) + ); + store.trigger.inc(); + store.trigger.inc(); + // A fast second write cannot overtake the first: it has not started yet. + expect(writes).toHaveLength(1); + const flushed = flushStorage(store); + expect(flushed).toBeInstanceOf(Promise); + const completed = vi.fn(); + void Promise.resolve(flushed).then(completed); + if (failFirst) writes[0].reject(new Error('write failed')); + else writes[0].resolve(); + await vi.waitFor(() => expect(writes).toHaveLength(2)); + expect(completed).not.toHaveBeenCalled(); + writes[1].resolve(); + await flushed; + const value = JSON.parse(saved!); + if (strategy === 'snapshot') expect(value.context.count).toBe(2); + else expect(value.events).toHaveLength(2); + expect(onError).toHaveBeenCalledTimes(failFirst ? 1 : 0); + expect(onDone).toHaveBeenCalledTimes(failFirst ? 1 : 2); + } + ); + } +); diff --git a/xstate-store/test/reset.test.ts b/xstate-store/test/reset.test.ts new file mode 100644 index 00000000..fae125cb --- /dev/null +++ b/xstate-store/test/reset.test.ts @@ -0,0 +1,175 @@ +import { createStore } from '../src/index.ts'; +import { reset } from '../src/reset.ts'; +import { undoRedo } from '../src/undo.ts'; + +describe('reset extension', () => { + it('should reset to initial context', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(reset()); + + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(2); + + store.trigger.reset(); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should reset multiple fields to initial context', () => { + const store = createStore({ + context: { count: 0, name: 'Ada' }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + setName: (ctx, e: { name: string }) => ({ ...ctx, name: e.name }) + } + }).with(reset()); + + store.trigger.inc(); + store.trigger.setName({ name: 'Bob' }); + expect(store.getSnapshot().context).toEqual({ count: 1, name: 'Bob' }); + + store.trigger.reset(); + expect(store.getSnapshot().context).toEqual({ count: 0, name: 'Ada' }); + }); + + it('should support partial reset via `to` option', () => { + const store = createStore({ + context: { count: 0, user: null as string | null }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + login: (ctx, e: { user: string }) => ({ ...ctx, user: e.user }) + } + }).with( + reset({ + to: (initial, current) => ({ ...initial, user: current.user }) + }) + ); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.login({ user: 'Alice' }); + expect(store.getSnapshot().context).toEqual({ count: 2, user: 'Alice' }); + + store.trigger.reset(); + expect(store.getSnapshot().context).toEqual({ count: 0, user: 'Alice' }); + }); + + it('should be idempotent when no changes have been made', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(reset()); + + const before = store.getSnapshot(); + store.trigger.reset(); + expect(store.getSnapshot().context).toEqual(before.context); + }); + + it('should preserve snapshot status', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(reset()); + + store.trigger.inc(); + store.trigger.reset(); + expect(store.getSnapshot().status).toBe('active'); + }); + + it('should notify subscribers on reset', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(reset()); + + const snapshots: number[] = []; + store.subscribe((snap) => snapshots.push(snap.context.count)); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.reset(); // 0 + + expect(snapshots).toEqual([1, 2, 0]); + }); + + it('should work with undoRedo (reset is undoable)', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }) + .with(reset()) + .with(undoRedo()); + + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(2); + + store.trigger.reset(); + expect(store.getSnapshot().context.count).toBe(0); + + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(2); + }); + + it('should allow resetting after multiple operations', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(reset()); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.dec(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(2); + + store.trigger.reset(); + expect(store.getSnapshot().context.count).toBe(0); + + // Should still work after reset + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(1); + }); + + it('should detect reset event collisions in development', () => { + expect(() => + createStore({ + context: { count: 0 }, + on: { + reset: (ctx) => ctx + } + }).with(reset()) + ).toThrow( + 'The "reset" store extension uses reserved event type(s): "reset".' + ); + }); + + it('should return initial snapshot from getInitialSnapshot', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(reset()); + + store.trigger.inc(); + store.trigger.inc(); + + expect(store.getInitialSnapshot().context.count).toBe(0); + }); +}); diff --git a/xstate-store/test/store.test.ts b/xstate-store/test/store.test.ts new file mode 100644 index 00000000..0649d634 --- /dev/null +++ b/xstate-store/test/store.test.ts @@ -0,0 +1,1555 @@ +import { + createStore, + createStoreLogic, + createStoreConfig +} from '../src/index.ts'; +import { createStoreTransition } from '../src/store.ts'; +import { reset } from '../src/reset.ts'; +import { createBrowserInspector } from '@statelyai/inspect'; +import { produce } from 'immer'; +import { z } from 'zod'; +import { + AnyStoreConfig, + ContextFromStoreConfig, + EventFromStoreConfig +} from '../src/types.ts'; + +it('processes triggered events breadth-first when handlers append more events', () => { + const processed: number[] = []; + const effects: number[] = []; + const store = createStore({ + context: { count: 0 }, + on: { + start: (_context, _event, enqueue) => { + for (let id = 0; id < 100; id++) { + enqueue.trigger.item({ id }); + } + }, + item: (context, event: { id: number }, enqueue) => { + processed.push(event.id); + if (event.id < 100) { + enqueue.trigger.item({ id: event.id + 100 }); + } + enqueue.effect(() => effects.push(event.id)); + return { count: context.count + 1 }; + } + } + }); + + store.trigger.start(); + const expected = Array.from({ length: 200 }, (_, index) => index); + expect(processed).toEqual(expected); + expect(effects).toEqual(expected); + expect(store.getSnapshot().context.count).toBe(200); +}); + +it('updates a store with an event without mutating original context', () => { + const context = { count: 0 }; + const store = createStore({ + context, + on: { + inc: (context, event: { by: number }) => { + return { + count: context.count + event.by + }; + } + } + }); + + const initial = store.getInitialSnapshot(); + + store.trigger.inc({ + by: 1 + }); + + const next = store.getSnapshot(); + + expect(initial.context).toEqual({ count: 0 }); + expect(next.context).toEqual({ count: 1 }); + expect(context.count).toEqual(0); +}); + +it('can update context', () => { + const store = createStore({ + context: { count: 0, greeting: 'hello' }, + on: { + inc: (ctx) => ({ + ...ctx, + count: ctx.count + 1 + }), + updateBoth: () => ({ + count: 42, + greeting: 'hi' + }) + } + }); + + store.trigger.inc(); + expect(store.getSnapshot().context).toEqual({ count: 1, greeting: 'hello' }); + + store.trigger.updateBoth(); + expect(store.getSnapshot().context).toEqual({ count: 42, greeting: 'hi' }); +}); + +it('handles unknown events sent via store.send (does not do anything)', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ + count: ctx.count + 1 + }) + } + }); + + store.send({ type: 'unknown' } as any); + expect(store.getSnapshot().context).toEqual({ count: 0 }); +}); + +it('updates state from sent events', () => { + const store = createStore({ + context: { + count: 0 + }, + on: { + inc: (ctx, ev: { by: number }) => { + return { + count: ctx.count + ev.by + }; + }, + dec: (ctx, ev: { by: number }) => { + return { + count: ctx.count - ev.by + }; + }, + clear: () => { + return { + count: 0 + }; + } + } + }); + + store.trigger.inc({ + by: 9 + }); + store.trigger.dec({ + by: 3 + }); + + expect(store.getSnapshot().context).toEqual({ count: 6 }); + store.trigger.clear(); + + expect(store.getSnapshot().context).toEqual({ count: 0 }); +}); + +it('can be observed', () => { + const store = createStore({ + context: { + count: 0 + }, + on: { + inc: (ctx) => ({ + count: ctx.count + 1 + }) + } + }); + + const counts: number[] = []; + + const sub = store.subscribe((s) => counts.push(s.context.count)); + + expect(counts).toEqual([]); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.inc(); // 3 + + expect(counts).toEqual([1, 2, 3]); + + sub.unsubscribe(); + + store.trigger.inc(); // 4 + store.trigger.inc(); // 5 + store.trigger.inc(); // 6 + + expect(counts).toEqual([1, 2, 3]); +}); + +it('does not expose atom internals at runtime', () => { + const store = createStore({ + context: { count: 0 }, + on: {} + }); + + expect('_snapshot' in store).toBe(false); +}); + +it('exposes schemas at runtime', () => { + const schemas = { + context: z.object({ count: z.number() }), + events: { + inc: z.object({ by: z.number() }) + }, + emitted: { + increased: z.object({ by: z.number() }) + } + }; + const store = createStore({ + schemas, + context: { count: 0 }, + on: { + inc: (context, event, enq) => { + enq.emit.increased({ by: event.by }); + return { count: context.count + event.by }; + } + } + }); + + expect(store.schemas).toBe(schemas); +}); + +it('exposes schemas after extension', () => { + const schemas = { + context: z.object({ count: z.number() }) + }; + const store = createStore({ + schemas, + context: { count: 0 }, + on: {} + }).with(reset()); + + expect(store.schemas).toBe(schemas); +}); + +it('can be inspected', () => { + const store = createStore({ + context: { + count: 0 + }, + on: { + inc: (ctx) => ({ + count: ctx.count + 1 + }) + } + }); + + const evs: any[] = []; + + store.inspect((ev) => evs.push(ev)); + + store.trigger.inc(); + + expect(evs).toEqual([ + expect.objectContaining({ + type: '@xstate.transition', + event: { type: '@xstate.init' }, + snapshot: expect.objectContaining({ context: { count: 0 } }) + }), + expect.objectContaining({ + type: '@xstate.transition', + event: { type: 'inc' }, + snapshot: expect.objectContaining({ context: { count: 1 } }) + }) + ]); +}); + +it('forwards store snapshots to @statelyai/inspect and unsubscribes', async () => { + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }); + const send = vi.fn(); + const inspector = createBrowserInspector({ autoStart: false, send }); + const subscription = store.inspect((event) => { + inspector.snapshot(event.actorRef, event.snapshot, { event: event.event }); + }); + + try { + store.trigger.inc(); + await vi.waitFor(() => { + expect(send).toHaveBeenCalledWith( + expect.objectContaining({ + type: '@xstate.snapshot', + event: { type: 'inc' }, + snapshot: expect.objectContaining({ context: { count: 1 } }) + }) + ); + }); + subscription.unsubscribe(); + const sentCount = send.mock.calls.length; + store.trigger.inc(); + await new Promise((resolve) => requestAnimationFrame(resolve)); + expect(send).toHaveBeenCalledTimes(sentCount); + } finally { + subscription.unsubscribe(); + inspector.stop(); + } +}); + +it('emitted events can be subscribed to', () => { + const store = createStore({ + context: { + count: 0 + }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { + ...ctx, + count: ctx.count + 1 + }; + } + } + }); + + const spy = vi.fn(); + + store.on('increased', spy); + + store.trigger.inc(); + + expect(spy).toHaveBeenCalledWith({ type: 'increased', upBy: 1 }); +}); + +it('emitted events can be unsubscribed to', () => { + const store = createStore({ + context: { + count: 0 + }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + + return { + ...ctx, + count: ctx.count + 1 + }; + } + } + }); + + const spy = vi.fn(); + const sub = store.on('increased', spy); + store.trigger.inc(); + + expect(spy).toHaveBeenCalledWith({ type: 'increased', upBy: 1 }); + + sub.unsubscribe(); + store.trigger.inc(); + + expect(spy).toHaveBeenCalledTimes(1); +}); + +it('emitted events occur after the snapshot is updated', () => { + const store = createStore({ + context: { + count: 0 + }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + + return { + ...ctx, + count: ctx.count + 1 + }; + } + } + }); + + expect.assertions(1); + + store.on('increased', () => { + const s = store.getSnapshot(); + + expect(s.context.count).toEqual(1); + }); + + store.trigger.inc(); +}); + +it('events can be emitted with no payload', () => { + const spy = vi.fn(); + + const store = createStore({ + schemas: { + emitted: { + incremented: z.object({}), + decremented: z.object({}), + expectsPayload: z.object({ payload: z.string() }) + } + }, + context: { + count: 0 + }, + on: { + inc: (_ctx, _ev, enq) => { + enq.emit.incremented(); + }, + dec: (_ctx, _ev, enq) => { + enq.emit.decremented({}); + }, + hasPayload: (_ctx, _ev, enq) => { + enq.emit + // @ts-expect-error Payload expected + .expectsPayload(); + } + } + }); + + store.on('incremented', spy); + + store.trigger.inc(); + + expect(spy).toHaveBeenCalledWith({ type: 'incremented' }); +}); + +it('events can be emitted with optional payloads (type check)', () => { + createStore({ + schemas: { + emitted: { + optionalPayload: z.object({ payload: z.string().optional() }) + } + }, + context: {}, + on: { + inc: (_ctx, _ev, enq) => { + enq.emit.optionalPayload(); + + enq.emit.optionalPayload({ payload: 'hello' }); + + enq.emit.optionalPayload({}); + + enq.emit.optionalPayload( + // @ts-expect-error + 'foo' + ); + } + } + }); +}); + +it('effects can be enqueued', async () => { + const store = createStore({ + context: { + count: 0 + }, + on: { + inc: (ctx, _, enq) => { + enq.effect(() => { + setTimeout(() => { + store.trigger.dec(); + }, 5); + }); + + return { + ...ctx, + count: ctx.count + 1 + }; + }, + dec: (ctx) => ({ + ...ctx, + count: ctx.count - 1 + }) + } + }); + + store.trigger.inc(); + + expect(store.getSnapshot().context.count).toEqual(1); + + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(store.getSnapshot().context.count).toEqual(0); +}); + +it('events can be enqueued from transitions', () => { + const store = createStore({ + context: { + bears: 0, + fishes: 0 + }, + schemas: { + events: { + addBear: z.object({}), + addFish: z.object({ amount: z.number() }), + addBearAndFish: z.object({}) + } + }, + on: { + addBear: (ctx) => ({ + ...ctx, + bears: ctx.bears + 1 + }), + addFish: (ctx, event) => ({ + ...ctx, + fishes: ctx.fishes + event.amount + }), + addBearAndFish: (ctx, _, enq) => { + enq.trigger.addBear(); + enq.trigger.addFish({ amount: 1 }); + + return ctx; + } + } + }); + + store.trigger.addBearAndFish(); + + expect(store.getSnapshot().context).toEqual({ + bears: 1, + fishes: 1 + }); +}); + +it('effect-only transitions should execute effects', () => { + const spy = vi.fn(); + const store = createStore({ + context: { count: 0 }, + on: { + justEffect: (ctx, _, enq) => { + enq.effect(spy); + } + } + }); + + store.trigger.justEffect(); + + expect(spy).toHaveBeenCalledTimes(1); +}); + +it('emits-only transitions should emit events', () => { + const spy = vi.fn(); + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + emitted: z.object({}) + } + }, + on: { + justEmit: (ctx, _, enq) => { + enq.emit.emitted(); + } + } + }); + + store.on('emitted', spy); + + store.trigger.justEmit(); + + expect(spy).toHaveBeenCalledTimes(1); +}); + +it('checks whether events can transition', () => { + const effectSpy = vi.fn(); + const emittedSpy = vi.fn(); + const store = createStore({ + context: { count: 9 }, + schemas: { + events: { + increment: z.object({ by: z.number() }), + noop: z.object({}), + effectOnly: z.object({}), + emitOnly: z.object({}), + triggerOnly: z.object({}), + unavailable: z.object({}) + }, + emitted: { + emitted: z.object({}) + } + }, + on: { + increment: (ctx, ev) => { + if (ctx.count + ev.by > 10) { + return; + } + + return { count: ctx.count + ev.by }; + }, + noop: (ctx) => ctx, + effectOnly: (_, __, enq) => { + enq.effect(effectSpy); + }, + emitOnly: (_, __, enq) => { + enq.emit.emitted(); + }, + triggerOnly: (_, __, enq) => { + enq.trigger.increment({ by: 1 }); + } + } + }); + + store.on('emitted', emittedSpy); + + expect(store.can.increment({ by: 1 })).toBe(true); + expect(store.can.increment({ by: 2 })).toBe(false); + expect(store.can.noop()).toBe(true); + expect(store.can.effectOnly()).toBe(true); + expect(store.can.emitOnly()).toBe(true); + expect(store.can.triggerOnly()).toBe(true); + expect(store.can.unavailable()).toBe(false); + expect(store.getSnapshot().context).toEqual({ count: 9 }); + expect(effectSpy).not.toHaveBeenCalled(); + expect(emittedSpy).not.toHaveBeenCalled(); +}); + +it('checks whether Immer transitions can transition without changing context', () => { + const store = createStore({ + context: { count: 10 }, + on: { + increment: (ctx, ev: { by: number }) => { + if (ctx.count + ev.by > 10) { + return; + } + + return produce(ctx, (draft) => { + draft.count += ev.by; + }); + } + } + }); + + const snapshot = store.getSnapshot(); + + expect(store.can.increment({ by: 0 })).toBe(true); + expect(store.getSnapshot()).toBe(snapshot); + expect(store.can.increment({ by: 1 })).toBe(false); + + store.trigger.increment({ by: 0 }); + expect(store.getSnapshot().context).toEqual({ count: 10 }); + + store.trigger.increment({ by: 1 }); + expect(store.getSnapshot().context).toEqual({ count: 10 }); +}); + +it('wildcard listener receives all emitted events', () => { + const spy = vi.fn(); + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }), + decreased: z.object({ downBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { ...ctx, count: ctx.count + 1 }; + }, + dec: (ctx, _, enq) => { + enq.emit.decreased({ downBy: 1 }); + return { ...ctx, count: ctx.count - 1 }; + } + } + }); + + store.on('*', spy); + + store.trigger.inc(); + expect(spy).toHaveBeenCalledWith({ type: 'increased', upBy: 1 }); + + store.trigger.dec(); + expect(spy).toHaveBeenCalledWith({ type: 'decreased', downBy: 1 }); + + expect(spy).toHaveBeenCalledTimes(2); +}); + +it('wildcard listener can be unsubscribed', () => { + const spy = vi.fn(); + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { ...ctx, count: ctx.count + 1 }; + } + } + }); + + const sub = store.on('*', spy); + store.trigger.inc(); + expect(spy).toHaveBeenCalledTimes(1); + + sub.unsubscribe(); + store.trigger.inc(); + expect(spy).toHaveBeenCalledTimes(1); +}); + +it('wildcard listener is called after specific listener', () => { + const order: string[] = []; + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { ...ctx, count: ctx.count + 1 }; + } + } + }); + + store.on('increased', () => order.push('specific')); + store.on('*', () => order.push('wildcard')); + + store.trigger.inc(); + + expect(order).toEqual(['specific', 'wildcard']); +}); + +it('async effects can be enqueued', async () => { + const store = createStore({ + context: { + count: 0 + }, + on: { + inc: (ctx, _, enq) => { + enq.effect(async () => { + await new Promise((resolve) => setTimeout(resolve, 5)); + store.trigger.dec(); + }); + + return { + ...ctx, + count: ctx.count + 1 + }; + }, + dec: (ctx) => ({ + ...ctx, + count: ctx.count - 1 + }) + } + }); + + store.trigger.inc(); + + expect(store.getSnapshot().context.count).toEqual(1); + + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(store.getSnapshot().context.count).toEqual(0); +}); + +it('effects receive an enqueue object to trigger events (no closure needed)', async () => { + const logic = createStoreLogic({ + context: () => ({ count: 0, status: 'idle' }), + on: { + inc: (ctx, _, enq) => { + enq.effect(async ({ trigger }) => { + await new Promise((resolve) => setTimeout(resolve, 5)); + trigger.done(); + }); + return { ...ctx, status: 'loading' }; + }, + done: (ctx) => ({ count: ctx.count + 1, status: 'done' }) + } + }); + + const store = logic.createStore(); + + store.trigger.inc(); + expect(store.getSnapshot().context).toEqual({ count: 0, status: 'loading' }); + + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(store.getSnapshot().context).toEqual({ count: 1, status: 'done' }); +}); + +it('effects can read fresh state after awaiting via enq.getSnapshot()', async () => { + const seen: number[] = []; + const store = createStore({ + context: { count: 0 }, + on: { + start: (ctx, _, enq) => { + enq.effect(async ({ getSnapshot, trigger }) => { + // `ctx` is stale by now; getSnapshot() reflects the bump below + await new Promise((resolve) => setTimeout(resolve, 5)); + seen.push(getSnapshot().context.count); + trigger.done(); + }); + return { ...ctx, count: ctx.count + 1 }; + }, + bump: (ctx) => ({ count: ctx.count + 10 }), + done: (ctx) => ctx + } + }); + + store.trigger.start(); // count -> 1 + store.trigger.bump(); // count -> 11 (after effect was enqueued, before it runs) + + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(seen).toEqual([11]); +}); + +it('sync effects read the current transition snapshot via enq.getSnapshot()', () => { + const seen: number[] = []; + const store = createStore({ + context: { count: 0 }, + on: { + start: (ctx, _, enq) => { + enq.effect(({ trigger }) => { + trigger.bump(); + }); + enq.effect(({ getSnapshot }) => { + seen.push(getSnapshot().context.count); + }); + return { count: ctx.count + 1 }; + }, + bump: (ctx) => ({ count: ctx.count + 10 }) + } + }); + + store.trigger.start(); + + expect(seen).toEqual([1]); + expect(store.getSnapshot().context.count).toEqual(11); +}); + +it('effects can use enq.send to dispatch events', async () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx, _, enq) => { + enq.effect(({ send }) => { + send({ type: 'dec' }); + }); + return { ...ctx, count: ctx.count + 1 }; + }, + dec: (ctx) => ({ ...ctx, count: ctx.count - 1 }) + } + }); + + store.trigger.inc(); + + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(store.getSnapshot().context.count).toEqual(0); +}); + +it('rejects async handlers in createStoreTransition(...)', () => { + const store = createStore({ + context: { count: 0 }, + on: {} + }); + const transition = store.transition; + + expect(() => + transition(store.getSnapshot(), { + type: 'bad' + } as any) + ).not.toThrow(); + + const unsupportedTransition = createStoreTransition({ + bad: (async (ctx: { count: number }) => ({ + count: ctx.count + 1 + })) as any + }); + + expect(() => + unsupportedTransition( + { + context: { count: 0 }, + status: 'active', + output: undefined, + error: undefined + }, + { type: 'bad' } + ) + ).toThrow('Async transition unsupported here'); +}); + +describe('store.trigger', () => { + it('should allow triggering events with a fluent API', () => { + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by + }) + } + }); + + store.trigger.increment({ by: 5 }); + + expect(store.getSnapshot().context.count).toBe(5); + }); + + it('should provide type safety for event payloads', () => { + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by + }), + reset: () => ({ count: 0 }) + } + }); + + if (false) { + // @ts-expect-error - missing required 'by' property + store.trigger.increment({}); + + // @ts-expect-error - extra property not allowed + store.trigger.increment({ by: 1, extra: true }); + + // @ts-expect-error - unknown event + store.trigger.unknown({}); + } + + // Valid usage with no payload + store.trigger.reset(); + + // Valid usage with payload + store.trigger.increment({ by: 1 }); + }); + + it('should be equivalent to store.send', () => { + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by + }) + } + }); + + const sendSpy = vi.spyOn(store, 'send'); + + store.trigger.increment({ by: 5 }); + + expect(sendSpy).toHaveBeenCalledWith({ + type: 'increment', + by: 5 + }); + }); + + it('should fail fast for unknown trigger names on config-based stores', () => { + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by + }), + reset: () => ({ count: 0 }) + } + }); + + expect(Object.keys(store.trigger)).toEqual(['increment', 'reset']); + expect(() => (store.trigger as any).unknown()).toThrow(TypeError); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should include extension events in the concrete trigger object', () => { + const store = createStore({ + context: { count: 0 }, + on: { + increment: (ctx, event: { by: number }) => ({ + count: ctx.count + event.by + }) + } + }).with(reset()); + + expect(Object.keys(store.trigger)).toEqual(['increment', 'reset']); + + store.trigger.increment({ by: 2 }); + store.trigger.reset(); + + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should include schema-declared events in the concrete trigger object', () => { + const store = createStore({ + schemas: { + events: { + increment: z.object({ by: z.number() }), + reset: z.object({}) + } + }, + context: { count: 0 }, + on: { + increment: (ctx, event) => ({ + count: ctx.count + event.by + }) + } + }); + + expect(Object.keys(store.trigger)).toEqual(['increment', 'reset']); + + store.trigger.increment({ by: 2 }); + store.trigger.reset(); + store.trigger.reset({}); + + expect(store.getSnapshot().context.count).toBe(2); + }); +}); + +it('works with typestates', () => { + type ContextStates = + | { + status: 'loading'; + data: null; + } + | { + status: 'success'; + data: string; + }; + + const store = createStore({ + context: { + status: 'loading', + data: null + } as ContextStates, + on: { + loaded: () => ({ + status: 'success' as const, + data: 'hello' + }), + loading: () => ({ + status: 'loading' as const, + data: null + }) + } + }); + + const context = store.getSnapshot().context; + + if (context.status === 'loading') { + context.data satisfies null; + // @ts-expect-error + context.data satisfies string; + } else { + context.status satisfies 'success'; + // @ts-expect-error + context.status satisfies 'loading'; + + context.data satisfies string; + // @ts-expect-error + context.data satisfies null; + } +}); + +it('the emit type is not overridden by the payload', () => { + const spy = vi.fn(); + type Context = { + drawer?: Drawer | null; + }; + + type Drawer = { + id: string; + }; + + const context: Context = { + drawer: null + }; + + const drawersBridgeStore = createStore({ + schemas: { + emitted: { + drawerOpened: z.object({ drawer: z.object({ id: z.string() }) }) + } + }, + context, + on: { + openDrawer: (_, event: { drawer: Drawer }, enqueue) => { + enqueue.emit.drawerOpened(event); + + return { + drawer: event.drawer + }; + } + } + }); + + drawersBridgeStore.on('drawerOpened', (event) => { + // expect to be called here + spy(event); + }); + + drawersBridgeStore.trigger.openDrawer({ + drawer: { id: 'a' } + }); + + expect(spy).toHaveBeenCalledWith({ + type: 'drawerOpened', + drawer: { id: 'a' } + }); +}); + +describe('store.transition', () => { + it('returns next state and effects for a given state and event', () => { + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + increased: z.object({ by: z.number() }), + nothing: z.object({}) + } + }, + on: { + inc: (ctx, event: { by: number }, enq) => { + enq.emit.increased({ by: event.by }); + return { + count: ctx.count + event.by + }; + } + } + }); + + const [nextState, effects] = store.transition(store.getSnapshot(), { + type: 'inc', + by: 2 + }); + + expect(nextState.context).toEqual({ count: 2 }); + expect(effects).toHaveLength(1); + expect(effects[0]).toEqual({ type: 'increased', by: 2 }); + }); + + it('returns unchanged state and empty effects for unknown events', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ + count: ctx.count + 1 + }) + } + }); + + const currentState = store.getSnapshot(); + const [nextState, effects] = store.transition(currentState, { + // @ts-expect-error + type: 'unknown' + }); + + expect(nextState).toBe(currentState); + expect(effects).toEqual([]); + }); + + it('collects enqueued effects', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx, _, enq) => { + enq.effect(() => { + // This effect function would normally do something + }); + return { + count: ctx.count + 1 + }; + } + } + }); + + const [nextState, effects] = store.transition(store.getSnapshot(), { + type: 'inc' + }); + + expect(nextState.context).toEqual({ count: 1 }); + expect(effects).toHaveLength(1); + expect(typeof effects[0]).toBe('function'); + }); + + it('resolves enqueued trigger events and collects effects in pure transitions', () => { + const spy = vi.fn(); + const store = createStore({ + context: { count: 0 }, + schemas: { + events: { + inc: z.object({}), + incTwice: z.object({}) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.effect(() => spy('inc')); + + return { + count: ctx.count + 1 + }; + }, + incTwice: (ctx, _, enq) => { + enq.effect(() => spy('before')); + enq.trigger.inc(); + enq.trigger.inc(); + enq.effect(() => spy('after')); + + return ctx; + } + } + }); + + const [nextState, effects] = store.transition(store.getSnapshot(), { + type: 'incTwice' + }); + + expect(nextState.context).toEqual({ count: 2 }); + expect(effects).toHaveLength(4); + expect(effects.every((effect) => typeof effect === 'function')).toBe(true); + for (const effect of effects) { + if (typeof effect === 'function') { + effect(); + } + } + expect(spy).toHaveBeenCalledTimes(4); + expect(spy).toHaveBeenNthCalledWith(1, 'before'); + expect(spy).toHaveBeenNthCalledWith(2, 'after'); + expect(spy).toHaveBeenNthCalledWith(3, 'inc'); + expect(spy).toHaveBeenNthCalledWith(4, 'inc'); + spy.mockClear(); + + store.trigger.incTwice(); + + expect(store.getSnapshot().context).toEqual({ count: 2 }); + expect(spy).toHaveBeenCalledTimes(4); + expect(spy).toHaveBeenNthCalledWith(1, 'before'); + expect(spy).toHaveBeenNthCalledWith(2, 'after'); + expect(spy).toHaveBeenNthCalledWith(3, 'inc'); + expect(spy).toHaveBeenNthCalledWith(4, 'inc'); + }); +}); + +it('can be created with a logic object', () => { + const store = createStore({ + getInitialSnapshot: () => ({ + context: { count: 0 }, + status: 'active' as const, + output: undefined, + error: undefined + }), + transition: ( + snapshot, + event: { + type: 'inc'; + } + ) => { + if (event.type === 'inc') { + return [ + { ...snapshot, context: { count: snapshot.context.count + 1 } }, + [] + ]; + } + return [snapshot, []]; + } + }); + + expect(store.getSnapshot().context).toEqual({ count: 0 }); + + store.trigger.inc(); + + expect(store.getSnapshot().context).toEqual({ count: 1 }); + + // @ts-expect-error + store.trigger.unknown(); + + store.getSnapshot().context.count satisfies number; + + // @ts-expect-error + store.getSnapshot().context.count satisfies string; +}); + +it('can select from a store', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ + count: context.count + 1 + }) + } + }); + + const countSpy = vi.fn(); + const evenSpy = vi.fn(); + const count = store.select((context) => context.count); + const isEven = store.select((context) => context.count % 2 === 0); + + count.subscribe(countSpy); + isEven.subscribe(evenSpy); + + expect(count.get()).toBe(0); + expect(isEven.get()).toBe(true); + + store.trigger.inc(); + + expect(count.get()).toBe(1); + expect(isEven.get()).toBe(false); + expect(countSpy).toHaveBeenCalledWith(1); + expect(evenSpy).toHaveBeenCalledWith(false); +}); + +it('can create reusable store logic with selectors', () => { + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + selectors: { + count: (context) => context.count, + doubled: (context) => { + // @ts-expect-error + context.missing; + return context.count * 2; + } + }, + on: { + inc: (context) => { + return { + count: context.count + 1 + }; + } + } + }); + + const store = counterLogic.createStore({ initialCount: 2 }); + + expect(store.selectors.count.get()).toBe(2); + expect(store.selectors.doubled.get()).toBe(4); + + store.trigger.inc(); + + expect(store.selectors.count.get()).toBe(3); + expect(store.selectors.doubled.get()).toBe(6); +}); + +it('preserves selectors through store extensions', () => { + const counterLogic = createStoreLogic({ + context: { count: 0 }, + selectors: { + doubled: (context: { count: number }) => context.count * 2 + }, + on: { + inc: (context) => ({ + count: context.count + 1 + }) + } + }); + + const store = counterLogic.createStore().with(reset()); + + expect(store.selectors.doubled.get()).toBe(0); + + store.trigger.inc(); + expect(store.selectors.doubled.get()).toBe(2); + + store.trigger.reset(); + expect(store.selectors.doubled.get()).toBe(0); +}); + +it('should not trigger update if the snapshot is the same', () => { + const store = createStore({ + context: { count: 0 }, + on: { + doNothing: (ctx) => ctx + } + }); + + const spy = vi.fn(); + store.subscribe(spy); + + store.trigger.doNothing(); + store.trigger.doNothing(); + + expect(spy).toHaveBeenCalledTimes(0); +}); + +it('should not trigger update if the snapshot is the same even if there are effects', () => { + const store = createStore({ + context: { count: 0 }, + on: { + doNothing: (ctx, _, enq) => { + enq.effect(() => { + // … + }); + return ctx; + } + } + }); + + const spy = vi.fn(); + store.subscribe(spy); + + store.trigger.doNothing(); + store.trigger.doNothing(); + + expect(spy).toHaveBeenCalledTimes(0); +}); + +describe('types', () => { + it('AnyStoreConfig', () => { + function transformStoreConfig(_config: AnyStoreConfig): void {} + + transformStoreConfig({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }); + + // @ts-expect-error + transformStoreConfig({}); + }); + + it('EventFromStoreConfig', () => { + const storeConfig = createStoreConfig({ + context: { count: 0 }, + on: { + inc: (ctx, event: { by: number }) => ({ count: ctx.count + event.by }) + } + }); + + let ev: EventFromStoreConfig = { + type: 'inc', + by: 1 + }; + + ev satisfies { + type: 'inc'; + by: number; + }; + + // @ts-expect-error + ev satisfies { type: 'unknown' }; + }); + + it('ContextFromStoreConfig', () => { + const storeConfig = createStoreConfig({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }); + + type Context = ContextFromStoreConfig; + + const context: Context = { count: 0 }; + + context.count satisfies number; + + // @ts-expect-error + context.count satisfies string; + }); + + it('generics can be provided', () => { + type Context = { + coffeeBeans: number; + water: number; + }; + + type Events = + | { + type: 'addWater'; + amount: number; + } + | { + type: 'grindBeans'; + }; + + type Emitted = + | { type: 'brewing' } + | { type: 'beansGround'; amount: number }; + + const store = createStore({ + context: { + coffeeBeans: 0, + water: 0 + }, + on: { + addWater: (ctx, event) => ({ + ...ctx, + water: ctx.water + event.amount + }), + grindBeans: (ctx, _, enq) => { + enq.emit.brewing(); + + enq.emit.beansGround({ amount: 1 }); + + // @ts-expect-error + enq.emit.beansGround(); + + enq.emit.brewing({}); + + return { + ...ctx, + coffeeBeans: ctx.coffeeBeans + 1 + }; + } + } + }); + + store.trigger.addWater({ amount: 1 }); + + store.trigger.grindBeans(); + + if (false) { + // @ts-expect-error + store.trigger.unknown(); + } + }); + + it('localizes TypeScript errors to the specific transition', () => { + // but now it's localized to the `changeSort` transition. + createStore({ + context: { + sort: 'asc' as const + }, + on: { + // @ts-expect-error + changeSort: (_, event: { sort: 'desc' }) => ({ + sort: event.sort + }) + } + }); + }); +}); + +it('emitted events work with store extensions', () => { + const store = createStore({ + context: { + count: 0 + }, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return { + ...ctx, + count: ctx.count + 1 + }; + } + } + }).with(reset()); + + const spy = vi.fn(); + + store.on('increased', spy); + + store.trigger.inc(); + + expect(spy).toHaveBeenCalledWith({ type: 'increased', upBy: 1 }); +}); diff --git a/xstate-store/test/types.test.tsx b/xstate-store/test/types.test.tsx new file mode 100644 index 00000000..a5ae93b3 --- /dev/null +++ b/xstate-store/test/types.test.tsx @@ -0,0 +1,520 @@ +import { createActor } from 'xstate'; +import { + createStore, + createStoreLogic, + fromStore, + type StoreSchemas +} from '../src/index.ts'; +import { z } from 'zod'; + +describe('emitted', () => { + it('can emit a known event', () => { + createStore({ + context: {}, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ upBy: 1 }); + return ctx; + } + } + }); + }); + + it("can't emit an unknown event", () => { + createStore({ + context: {}, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }), + decreased: z.object({ downBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit + // @ts-expect-error + .unknown(); + return ctx; + } + } + }); + }); + + it("can't emit a known event with wrong payload", () => { + createStore({ + context: {}, + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }), + decreased: z.object({ downBy: z.number() }) + } + }, + on: { + inc: (ctx, _, enq) => { + enq.emit.increased({ + // @ts-expect-error + upBy: 'bazinga' + }); + return ctx; + } + } + }); + }); + + it('can subscribe to a known event', () => { + const store = createStore< + {}, + {}, + { + increased: { upBy: number }; + decreased: { downBy: number }; + } + >({ + context: {}, + on: {} + }); + + store.on('increased', (ev) => { + ev satisfies { type: 'increased'; upBy: number }; + }); + }); + + it("can't subscribe to a unknown event", () => { + const store = createStore({ + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + context: {}, + on: {} + }); + + store.on('increased', (ev) => {}); + + store.on( + // @ts-expect-error + 'unknown', + (ev) => {} + ); + }); + + it('wildcard listener receives union of all emitted events', () => { + const store = createStore({ + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }), + decreased: z.object({ downBy: z.number() }) + } + }, + context: {}, + on: {} + }); + + store.on('*', (ev) => { + ev satisfies + | { type: 'increased'; upBy: number } + | { type: 'decreased'; downBy: number }; + + // @ts-expect-error + ev satisfies { type: 'unknown' }; + }); + }); + + it('works with a discriminated union event payload', () => { + createStore({ + context: {}, + schemas: { + emitted: { + log: z.discriminatedUnion('level', [ + z.object({ level: z.literal('warn'), message: z.string() }), + z.object({ level: z.literal('error'), error: z.string() }) + ]) + } + }, + on: { + log: (ctx, _ev, enq) => { + enq.emit.log({ level: 'warn', message: 'hmm' }); + enq.emit.log({ level: 'error', error: 'uh oh' }); + enq.emit.log({ + level: 'error', + // @ts-expect-error + message: 'foo' + }); + return ctx; + } + } + }); + }); +}); + +describe('trigger', () => { + it('works with a distributive event payload', () => { + const store = createStore({ + context: {}, + on: { + log: ( + ctx, + _ev: + | { level: 'warn'; message: string } + | { level: 'error'; error: string } + ) => { + return ctx; + } + } + }); + + store.trigger.log({ level: 'warn', message: 'hmm' }); + store.trigger.log({ level: 'error', error: 'uh oh' }); + + store.trigger.log({ + level: 'error', + // @ts-expect-error + message: 'foo' + }); + }); + + it('uses schema-declared events for trigger typing', () => { + const store = createStore({ + schemas: { + events: { + log: z.discriminatedUnion('level', [ + z.object({ level: z.literal('warn'), message: z.string() }), + z.object({ level: z.literal('error'), error: z.string() }) + ]) + } + }, + context: {}, + on: {} + }); + + store.trigger.log({ level: 'warn', message: 'hmm' }); + store.trigger.log({ level: 'error', error: 'uh oh' }); + + store.trigger.log({ + level: 'error', + // @ts-expect-error + message: 'foo' + }); + }); + + it('preserves inferred trigger typing when only emitted schemas are declared', () => { + const store = createStore({ + schemas: { + emitted: { + logged: z.object({ message: z.string() }) + } + }, + context: {}, + on: { + log: (ctx, ev: { message: string }, enq) => { + enq.emit.logged({ message: ev.message }); + return ctx; + } + } + }); + + store.trigger.log({ message: 'hello' }); + + if (false) { + // @ts-expect-error + store.trigger.log({}); + + // @ts-expect-error + store.trigger.unknown(); + } + }); + + it('uses schema-declared events for enqueued trigger typing', () => { + createStore({ + schemas: { + events: { + log: z.discriminatedUnion('level', [ + z.object({ level: z.literal('warn'), message: z.string() }), + z.object({ level: z.literal('error'), error: z.string() }) + ]), + flush: z.object({}) + } + }, + context: {}, + on: { + flush: (ctx, _event, enq) => { + enq.trigger.flush(); + enq.trigger.flush({}); + enq.trigger.log({ level: 'warn', message: 'hmm' }); + enq.trigger.log({ level: 'error', error: 'uh oh' }); + + enq.trigger.log({ + level: 'error', + // @ts-expect-error + message: 'foo' + }); + + // @ts-expect-error + enq.trigger.unknown(); + + return ctx; + } + } + }); + }); +}); + +describe('can', () => { + it('uses event payload types', () => { + const store = createStore({ + context: { count: 0 }, + schemas: { + events: { + increment: z.object({ by: z.number() }), + reset: z.object({}) + } + }, + on: { + increment: (ctx, ev) => ({ count: ctx.count + ev.by }), + reset: () => ({ count: 0 }) + } + }); + + store.can.increment({ by: 1 }) satisfies boolean; + store.can.reset() satisfies boolean; + store.can.reset({}) satisfies boolean; + + // @ts-expect-error + store.can.increment(); + store.can.increment({ + // @ts-expect-error + by: 'one' + }); + }); +}); + +describe('logic selectors', () => { + it('infers selected values from a store', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }); + const count = store.select((context) => context.count); + const label = store.select((context) => `Count: ${context.count}`); + + count.get() satisfies number; + label.get() satisfies string; + + if (false) { + // @ts-expect-error + count.get() satisfies string; + } + }); + + it('infers input and selector values from reusable store logic', () => { + const counterLogic = createStoreLogic({ + context: (input: { initialCount: number }) => ({ + count: input.initialCount + }), + selectors: { + count: (context: { count: number }) => context.count, + label: (context: { count: number }) => `Count: ${context.count}` + }, + on: { + inc: (context) => ({ count: context.count + 1 }) + } + }); + + const store = counterLogic.createStore({ initialCount: 1 }); + + store.selectors.count.get() satisfies number; + store.selectors.label.get() satisfies string; + + if (false) { + // @ts-expect-error + counterLogic.createStore(); + + // @ts-expect-error + counterLogic.createStore(undefined); + + // @ts-expect-error + counterLogic.createStore({ initialCount: 'one' }); + + // @ts-expect-error + store.selectors.label.get() satisfies number; + } + }); +}); + +describe('schemas', () => { + const stringSchema = z.string(); + + it('requires event and emitted schemas to define object payloads', () => { + // @ts-expect-error event schemas must describe object payloads + createStore({ + schemas: { + events: { + bad: stringSchema + } + }, + context: {}, + on: {} + }); + + // @ts-expect-error emitted schemas must describe object payloads + createStore({ + schemas: { + emitted: { + bad: stringSchema + } + }, + context: {}, + on: {} + }); + }); + + it('uses schema-declared context for snapshot typing', () => { + const schemas = { + context: z.object({ count: z.number(), label: z.string() }) + }; + const store = createStore({ + schemas, + context: { + count: 0, + label: 'ready' + }, + on: {} + }); + + store.getSnapshot().context.label satisfies string; + store.schemas satisfies StoreSchemas | undefined; + + // @ts-expect-error + store.getSnapshot().context.label satisfies number; + }); + + it('merges schema-declared context with inferred event types', () => { + const store = createStore({ + schemas: { + context: z.object({ count: z.number(), label: z.string() }) + }, + context: { + count: 0, + label: 'ready' + }, + on: { + rename: (ctx, ev: { label: string }) => ({ + ...ctx, + label: ev.label + }) + } + }); + + store.trigger.rename({ label: 'done' }); + store.getSnapshot().context.label satisfies string; + + if (false) { + // @ts-expect-error + store.trigger.rename({}); + } + }); +}); + +describe('fromStore schemas', () => { + it('preserves inferred event types when only emitted schemas are declared', () => { + const logic = fromStore({ + context: (count: number) => ({ count }), + schemas: { + emitted: { + increased: z.object({ upBy: z.number() }) + } + }, + on: { + inc: (ctx, ev: { by: number }, enq) => { + enq.emit.increased({ upBy: ev.by }); + return { + count: ctx.count + ev.by + }; + } + } + }); + + const actor = createActor(logic, { + input: 1 + }); + + actor.send({ type: 'inc', by: 2 }); + actor.on('increased', (event) => { + event.upBy satisfies number; + }); + + if (false) { + actor.send({ + type: 'inc', + // @ts-expect-error + message: 'nope' + }); + + actor.on( + // @ts-expect-error + 'unknown', + () => {} + ); + } + }); + + it('uses schema-declared events for send typing', () => { + const logic = fromStore({ + context: { + count: 0 + }, + schemas: { + events: { + inc: z.object({ by: z.number() }), + reset: z.object({}) + } + }, + on: { + inc: (ctx, ev) => ({ + count: ctx.count + ev.by + }) + } + }); + + const actor = createActor(logic); + + actor.send({ type: 'inc', by: 1 }); + actor.send({ type: 'reset' }); + + if (false) { + // @ts-expect-error + actor.send({ type: 'inc' }); + + // @ts-expect-error + actor.send({ type: 'unknown' }); + } + }); + + it('uses schema-declared context for snapshot typing', () => { + const logic = fromStore({ + schemas: { + context: z.object({ count: z.number(), label: z.string() }) + }, + context: { + count: 0, + label: 'ready' + }, + on: {} + }); + + const snapshot = logic.getInitialSnapshot({} as any, undefined as never); + + snapshot.context.label satisfies string; + + // @ts-expect-error + snapshot.context.label satisfies number; + }); +}); diff --git a/xstate-store/test/undo.test.ts b/xstate-store/test/undo.test.ts new file mode 100644 index 00000000..9966b1a4 --- /dev/null +++ b/xstate-store/test/undo.test.ts @@ -0,0 +1,1244 @@ +import { createStore } from '../src/index.ts'; +import { undoRedo } from '../src/undo.ts'; +import { z } from 'zod'; +import { persist, flushStorage, isHydrated } from '../src/persist.ts'; + +it.each(['persist-first', 'undo-first'] as const)( + 'preserves persistence metadata through snapshot undo and redo (%s)', + (order) => { + const storage = { + getItem: () => null, + setItem: vi.fn(), + removeItem: vi.fn() + }; + const base = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }); + const store = + order === 'persist-first' + ? base + .with(persist({ name: 'counter', storage })) + .with(undoRedo({ strategy: 'snapshot' })) + : base + .with(undoRedo({ strategy: 'snapshot' })) + .with(persist({ name: 'counter', storage })); + + store.trigger.inc(); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + expect(isHydrated(store)).toBe(true); + expect(() => flushStorage(store)).not.toThrow(); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(1); + expect(isHydrated(store)).toBe(true); + } +); + +it('preserves live extension metadata through custom restore triggers', () => { + const writes = vi.fn(); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }) + .with( + persist({ + name: 'counter', + storage: { getItem: () => null, setItem: writes, removeItem: vi.fn() } + }) + ) + .with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.trigger.inc(); + return next; + } + }) + ); + + store.trigger.inc(); + writes.mockClear(); + store.trigger.undo(); + expect(isHydrated(store)).toBe(true); + expect(store.getSnapshot().context.count).toBe(1); + expect(writes).toHaveBeenCalledExactlyOnceWith( + 'counter', + JSON.stringify({ context: { count: 1 }, version: 0 }) + ); +}); + +it('keeps metadata updates produced by custom restore triggers', () => { + const revision = Symbol('revision'); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }) + .with<{}>((logic) => ({ + ...logic, + getInitialSnapshot: () => ({ + ...logic.getInitialSnapshot(), + [revision]: 0 + }), + transition: (snapshot, event) => { + const [next, effects] = logic.transition(snapshot, event); + return [ + { + ...next, + [revision]: (Reflect.get(snapshot, revision) as number) + 1 + }, + effects + ]; + } + })) + .with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.trigger.inc(); + return next; + } + }) + ); + + store.trigger.inc(); + expect(Reflect.get(store.getSnapshot(), revision)).toBe(1); + store.trigger.undo(); + expect(Reflect.get(store.getSnapshot(), revision)).toBe(2); + store.trigger.redo(); + expect(Reflect.get(store.getSnapshot(), revision)).toBe(3); +}); + +it('should undo a single event', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(1); + + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); +}); + +it('should redo a previously undone event', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + store.trigger.inc(); + store.trigger.undo(); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(1); +}); + +it('should undo/redo multiple events, non-transactional', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(3); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(3); +}); + +it('should group events by transaction ID', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(undoRedo({ getTransactionId: (event) => event.type })); + + // First transaction + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(2); + + // Second transaction + store.trigger.dec(); + store.trigger.dec(); + expect(store.getSnapshot().context.count).toBe(0); + + // Undo second transaction (both decrements) + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(2); + + // Undo first transaction (both increments) + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); +}); + +it('should maintain correct state when interleaving undo/redo with new events', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(undoRedo()); + + store.trigger.inc(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.inc(); // 2 + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.dec(); // 0 + expect(store.getSnapshot().context.count).toBe(0); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); // 0 + expect(store.getSnapshot().context.count).toBe(0); + + expect(store.getSnapshot().context.count).toBe(0); +}); + +it('should do nothing when undoing with empty history', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + const initialSnapshot = store.getSnapshot(); + store.trigger.undo(); + expect(store.getSnapshot()).toEqual(initialSnapshot); +}); + +it('should do nothing when redoing with empty undo stack', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + const initialSnapshot = store.getSnapshot(); + store.trigger.redo(); + expect(store.getSnapshot()).toEqual(initialSnapshot); +}); + +it('should clear redo stack when new events occur after undo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(undoRedo()); + + store.trigger.inc(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.inc(); // 2 + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.dec(); // 0 + + // Redo should not work as we added a new event after undo + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(0); +}); + +it('should preserve emitted events during undo/redo', () => { + type Events = { type: 'inc' }; + + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + changed: z.object({ value: z.number() }) + } + }, + on: { + inc: (ctx, _: Events, enq) => { + enq.emit.changed({ value: ctx.count + 1 }); + return { count: ctx.count + 1 }; + } + } + }).with(undoRedo()); + + const emittedEvents: any[] = []; + store.on('changed', (event) => { + emittedEvents.push(event); + }); + + store.trigger.inc(); + store.trigger.undo(); + store.trigger.redo(); + + expect(emittedEvents).toEqual([ + { type: 'changed', value: 1 }, + { type: 'changed', value: 1 } + ]); +}); + +it('should preserve context and event types', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo()); + + store.getSnapshot().context satisfies { count: number }; + store.trigger.inc(); + store.trigger.undo(); + store.trigger.redo(); + + // @ts-expect-error + store.getSnapshot().context.foo; + + if (false) { + // @ts-expect-error + store.trigger.dec(); + } +}); + +it('should skip non-undoable events during undo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + log: (ctx) => ctx // No state change, just logging + } + }).with(undoRedo({ skipEvent: (event) => event.type === 'log' })); + + store.trigger.inc(); // count = 1 + store.trigger.log(); // count = 1 (logged but not undoable) + store.trigger.inc(); // count = 2 + expect(store.getSnapshot().context.count).toBe(2); + + store.trigger.undo(); // count = 1 (skips log event) + expect(store.getSnapshot().context.count).toBe(1); +}); + +it('should skip non-redoable events during redo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + log: (ctx) => ctx // No state change, just logging + } + }).with(undoRedo({ skipEvent: (event) => event.type === 'log' })); + + store.trigger.inc(); // count = 1 + store.trigger.log(); // count = 1 (logged but not redoable) + store.trigger.inc(); // count = 2 + store.trigger.undo(); // count = 1 + expect(store.getSnapshot().context.count).toBe(1); + + store.trigger.redo(); // count = 2 (skips log event) + expect(store.getSnapshot().context.count).toBe(2); +}); + +it('should skip events with transaction grouping', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + log: (ctx) => ctx // No state change, just logging + } + }).with( + undoRedo({ + getTransactionId: (event) => event.type, + skipEvent: (event) => event.type === 'log' + }) + ); + + // First transaction: inc events + store.trigger.inc(); // count = 1 + store.trigger.inc(); // count = 2 + expect(store.getSnapshot().context.count).toBe(2); + + // Log events (not a transaction because they're skipped) + store.trigger.log(); // count = 2 (logged but not undoable) + store.trigger.log(); // count = 2 (logged but not undoable) + expect(store.getSnapshot().context.count).toBe(2); + + // Second transaction: inc events + store.trigger.inc(); // count = 3 + store.trigger.inc(); // count = 4 + expect(store.getSnapshot().context.count).toBe(4); + + // Undo second transaction (all inc events) + store.trigger.undo(); // count = 0 + expect(store.getSnapshot().context.count).toBe(0); +}); + +it('should handle mixed undoable and non-undoable events', () => { + const store = createStore({ + context: { count: 0, logs: [] as string[] }, + on: { + inc: (ctx) => ({ count: ctx.count + 1, logs: ctx.logs }), + log: (ctx, event: { type: 'log'; message: string }) => ({ + logs: [...(ctx.logs || []), event.message], + count: ctx.count + }) + } + }).with( + undoRedo({ + skipEvent: (event) => event.type === 'log' + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.log({ message: 'first log' }); // logs = ['first log'] (not stored in history) + store.trigger.inc(); // count = 2 + store.trigger.log({ message: 'second log' }); // logs = ['first log', 'second log'] (not stored in history) + store.trigger.inc(); // count = 3 + + expect(store.getSnapshot().context.count).toBe(3); + expect(store.getSnapshot().context.logs).toEqual(['first log', 'second log']); + + // Undo should skip log events (they're not in history) but still undo inc events + // Since log events are skipped, they're not replayed during undo, so logs are lost + store.trigger.undo(); // count = 2, logs = [] (logs lost because not replayed) + expect(store.getSnapshot().context.count).toBe(2); + expect(store.getSnapshot().context.logs).toEqual([]); + + store.trigger.undo(); // count = 1, logs = [] (logs lost because not replayed) + expect(store.getSnapshot().context.count).toBe(1); + expect(store.getSnapshot().context.logs).toEqual([]); + + store.trigger.undo(); // count = 0, logs = [] (logs lost because not replayed) + expect(store.getSnapshot().context.count).toBe(0); + expect(store.getSnapshot().context.logs).toEqual([]); +}); + +it('should not replay emitted events for skipped events during undo/redo', () => { + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + changed: z.object({ value: z.number() }), + logged: z.object({ message: z.string() }) + } + }, + on: { + inc: (ctx, _event, enq) => { + enq.emit.changed({ value: ctx.count + 1 }); + return { count: ctx.count + 1 }; + }, + log: (ctx, event: { message: string }, enq) => { + enq.emit.logged({ message: (event as any).message }); + return ctx; // No state change + } + } + }).with( + undoRedo({ + skipEvent: (event) => event.type === 'log' + }) + ); + + const emittedEvents: any[] = []; + store.on('changed', (event) => { + emittedEvents.push(event); + }); + store.on('logged', (event) => { + emittedEvents.push(event); + }); + + store.trigger.inc(); // count = 1, emits changed(1) + store.trigger.log({ message: 'test log' }); // emits logged('test log') but not stored in history + store.trigger.inc(); // count = 2, emits changed(2) + + expect(emittedEvents).toEqual([ + { type: 'changed', value: 1 }, + { type: 'logged', message: 'test log' }, + { type: 'changed', value: 2 } + ]); + + emittedEvents.length = 0; + store.trigger.undo(); // count = 1 + store.trigger.undo(); // count = 0 + store.trigger.redo(); // count = 1, emits changed(1) + store.trigger.redo(); // count = 2, emits changed(2) + + // Only inc events should be emitted during undo/redo, log events are skipped from history + expect(emittedEvents).toEqual([ + { type: 'changed', value: 1 }, + { type: 'changed', value: 2 } + ]); +}); + +it('should skip events with transaction grouping', () => { + const store = createStore({ + context: { count: 0, transactionId: null as string | null }, + on: { + inc: (ctx) => ({ ...ctx, count: ctx.count + 1 }), + transactionIdUpdated: (ctx, event: { id: string }) => ({ + ...ctx, + transactionId: event.id + }) + } + }).with( + undoRedo({ + getTransactionId: (_, snapshot) => snapshot.context.transactionId + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.transactionIdUpdated({ id: '1' }); + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); // count = 4 + store.trigger.transactionIdUpdated({ id: '2' }); + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); // count = 7 + + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(4); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(4); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(7); +}); + +it('should use the snapshot in the skipEvent function', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with( + undoRedo({ + skipEvent: (_event, snapshot) => { + return snapshot.context.count >= 3; + } + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.inc(); // count = 2 + store.trigger.inc(); // count = 3 + store.trigger.inc(); // count = 4 (skipped) + expect(store.getSnapshot().context.count).toBe(4); + store.trigger.undo(); // count = 2 + expect(store.getSnapshot().context.count).toBe(2); +}); + +it('emit event types should be correct', () => { + const store = createStore({ + context: { count: 0 }, + schemas: { + emitted: { + changed: z.object({ value: z.number() }) + } + }, + on: { + // TODO: figure out why we need _: {} and not just _ + inc: (ctx, _: {}, enq) => { + enq.emit.changed({ value: ctx.count + 1 }); + // @ts-expect-error + enq.emit.whatever(); + return { count: ctx.count + 1 }; + } + } + }).with(undoRedo()); + + store.on('changed', (event) => { + event.value satisfies number; + // @ts-expect-error + event.value satisfies string; + // @ts-expect-error + event.unknown; + }); + + store.on( + // @ts-expect-error + 'whatever', + () => {} + ); +}); + +it('should detect undo/redo event collisions in development', () => { + expect(() => + createStore({ + context: { count: 0 }, + on: { + undo: (ctx) => ctx + } + }).with(undoRedo()) + ).toThrow( + 'The "undoRedo" store extension uses reserved event type(s): "undo".' + ); +}); + +describe('undoRedo with snapshot strategy', () => { + it('should undo a single event', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(1); + + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should redo a previously undone event', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); + store.trigger.undo(); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(1); + }); + + it('should undo/redo multiple events, non-transactional', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(3); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(3); + }); + + it('should undo back into history after a redo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.inc(); + store.trigger.undo(); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(2); + + // Undoing the redo returns to the snapshot the redo moved away from + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(1); + }); + + it('should group events by transaction ID', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + getTransactionId: (event) => { + return event.type; + } + }) + ); + + // First transaction + store.trigger.inc(); + store.trigger.inc(); + expect(store.getSnapshot().context.count).toBe(2); + + // Second transaction + store.trigger.dec(); + store.trigger.dec(); + expect(store.getSnapshot().context.count).toBe(0); + + // Undo second transaction (both decrements) + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(2); + + // Undo first transaction (both increments) + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should undo back into history after redoing a transaction', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + getTransactionId: (event) => { + return event.type; + } + }) + ); + + // First transaction + store.trigger.inc(); + store.trigger.inc(); + + // Second transaction + store.trigger.dec(); + store.trigger.dec(); + + store.trigger.undo(); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + + // Redo the first transaction, then undo it again + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should maintain correct state when interleaving undo/redo with new events', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.inc(); // 2 + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.dec(); // 0 + expect(store.getSnapshot().context.count).toBe(0); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.redo(); // 0 + expect(store.getSnapshot().context.count).toBe(0); + + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should do nothing when undoing with empty history', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + const initialSnapshot = store.getSnapshot(); + store.trigger.undo(); + expect(store.getSnapshot().context).toEqual(initialSnapshot.context); + }); + + it('should do nothing when redoing with empty future stack', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + const initialSnapshot = store.getSnapshot(); + store.trigger.redo(); + expect(store.getSnapshot().context).toEqual(initialSnapshot.context); + }); + + it('should clear redo stack when new events occur after undo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.inc(); // 2 + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.dec(); // 0 + + // Redo should not work as we added a new event after undo + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should skip non-undoable events', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + log: (ctx) => ctx // No state change, just logging + } + }).with( + undoRedo({ + strategy: 'snapshot', + skipEvent: (event) => event.type === 'log' + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.log(); // count = 1 (logged but not tracked) + store.trigger.inc(); // count = 2 + expect(store.getSnapshot().context.count).toBe(2); + + store.trigger.undo(); // count = 1 (skips log event) + expect(store.getSnapshot().context.count).toBe(1); + }); + + it('should respect historyLimit', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot', historyLimit: 2 })); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.inc(); // 3 + store.trigger.inc(); // 4 + + // Can only undo 2 times because of history limit + store.trigger.undo(); // 3 + expect(store.getSnapshot().context.count).toBe(3); + store.trigger.undo(); // 2 + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); // Should stay at 2 (limit reached) + expect(store.getSnapshot().context.count).toBe(2); + }); + + it('should apply historyLimit during redo', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(undoRedo({ strategy: 'snapshot', historyLimit: 2 })); + + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + store.trigger.undo(); // 1 + store.trigger.undo(); // 0 + store.trigger.redo(); // 1 + store.trigger.redo(); // 2 + store.trigger.inc(); // 3 + store.trigger.inc(); // 4 + + // History should be trimmed to last 2 snapshots + store.trigger.undo(); // 3 + store.trigger.undo(); // 2 + store.trigger.undo(); // Should stay at 2 + expect(store.getSnapshot().context.count).toBe(2); + }); + + it('should preserve context with skipped events', () => { + const store = createStore({ + context: { count: 0, logs: [] as string[] }, + on: { + inc: (ctx) => ({ count: ctx.count + 1, logs: ctx.logs }), + log: (ctx, event: { type: 'log'; message: string }) => ({ + logs: [...(ctx.logs || []), event.message], + count: ctx.count + }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + skipEvent: (event) => event.type === 'log' + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.log({ message: 'first log' }); // logs = ['first log'] (not tracked) + store.trigger.inc(); // count = 2 + + expect(store.getSnapshot().context.count).toBe(2); + expect(store.getSnapshot().context.logs).toEqual(['first log']); + + // Undo should restore snapshot before second inc, which includes the log + store.trigger.undo(); // count = 1, logs = ['first log'] + expect(store.getSnapshot().context.count).toBe(1); + expect(store.getSnapshot().context.logs).toEqual(['first log']); + }); + + it('should handle transaction grouping with historyLimit', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + dec: (ctx) => ({ count: ctx.count - 1 }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + getTransactionId: (event) => event.type, + historyLimit: 3 + }) + ); + + // First transaction + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + + // Second transaction + store.trigger.dec(); // 1 + store.trigger.dec(); // 0 + + // Third transaction + store.trigger.inc(); // 1 + store.trigger.inc(); // 2 + + // Undo third transaction + store.trigger.undo(); // 0 + expect(store.getSnapshot().context.count).toBe(0); + + // Undo second transaction - only partial history available due to limit + // The {2,dec} snapshot was trimmed, so we can only restore to {1,dec} + store.trigger.undo(); // 1 + expect(store.getSnapshot().context.count).toBe(1); + + // Can't undo further due to limit (first transaction's snapshots were trimmed) + store.trigger.undo(); // Should stay at 1 + expect(store.getSnapshot().context.count).toBe(1); + }); + + it('should use compare function to skip duplicate snapshots', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + noop: (ctx) => ctx + } + }).with( + undoRedo({ + strategy: 'snapshot', + compare: (past, current) => past.context.count === current.context.count + }) + ); + + store.trigger.inc(); // count = 1 + store.trigger.noop(); // count = 1 (duplicate, not saved) + store.trigger.noop(); // count = 1 (duplicate, not saved) + store.trigger.inc(); // count = 2 + + // Should only have 2 snapshots in history (0 and 1), not 4 + store.trigger.undo(); // count = 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.undo(); // count = 0 + expect(store.getSnapshot().context.count).toBe(0); + store.trigger.undo(); // Should stay at 0 + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should save all snapshots when no compare function is provided', () => { + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }), + noop: (ctx) => ctx + } + }).with(undoRedo({ strategy: 'snapshot' })); + + store.trigger.inc(); // count = 1 + store.trigger.noop(); // count = 1 (saved even though duplicate) + store.trigger.noop(); // count = 1 (saved even though duplicate) + store.trigger.inc(); // count = 2 + + // Should have 4 snapshots in history (0, 1, 1, 1) + store.trigger.undo(); // count = 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.undo(); // count = 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.undo(); // count = 1 + expect(store.getSnapshot().context.count).toBe(1); + store.trigger.undo(); // count = 0 + expect(store.getSnapshot().context.count).toBe(0); + }); + + it('should preserve orthogonal context during undo and redo', () => { + const store = createStore({ + context: { document: 'a', viewport: 0 }, + on: { + updateDocument: (context, event: { document: string }) => ({ + ...context, + document: event.document + }), + updateViewport: (context, event: { viewport: number }) => ({ + ...context, + viewport: event.viewport + }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + skipEvent: (event) => event.type === 'updateViewport', + restore: ({ current, next }) => ({ + ...next, + viewport: current.viewport + }) + }) + ); + + store.trigger.updateDocument({ document: 'b' }); + store.trigger.updateViewport({ viewport: 10 }); + store.trigger.undo(); + expect(store.getSnapshot().context).toEqual({ + document: 'a', + viewport: 10 + }); + + store.trigger.redo(); + expect(store.getSnapshot().context).toEqual({ + document: 'b', + viewport: 10 + }); + + store.trigger.updateViewport({ viewport: 20 }); + store.trigger.undo(); + expect(store.getSnapshot().context).toEqual({ + document: 'a', + viewport: 20 + }); + }); + + it('should pass current, next, and direction to restore', () => { + const restore = vi.fn(({ next }) => next); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with(undoRedo({ strategy: 'snapshot', restore })); + + store.trigger.inc(); + store.trigger.undo(); + store.trigger.redo(); + + expect(restore.mock.calls.map(([args]) => args)).toEqual([ + { current: { count: 1 }, next: { count: 0 }, direction: 'undo' }, + { current: { count: 0 }, next: { count: 1 }, direction: 'redo' } + ]); + }); + + it('should restore once for a transaction group', () => { + const restore = vi.fn(({ next }) => next); + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + undoRedo({ + strategy: 'snapshot', + getTransactionId: () => 'transaction', + restore + }) + ); + + store.trigger.inc(); + store.trigger.inc(); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + store.trigger.redo(); + expect(store.getSnapshot().context.count).toBe(2); + store.trigger.undo(); + expect(store.getSnapshot().context.count).toBe(0); + expect(restore).toHaveBeenCalledTimes(3); + }); + + it('should run emitted events after restored context commits', () => { + const observed: number[] = []; + const store = createStore({ + schemas: { + emitted: { restored: z.object({ count: z.number() }) } + }, + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.emit.restored({ count: next.count }); + return next; + } + }) + ); + store.on('restored', () => + observed.push(store.getSnapshot().context.count) + ); + + store.trigger.inc(); + store.trigger.undo(); + + expect(observed).toEqual([0]); + }); + + it('should run effects after restored context commits', () => { + const observed: number[] = []; + const store = createStore({ + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.effect((enq) => { + observed.push(enq!.getSnapshot().context.count); + }); + return next; + } + }) + ); + + store.trigger.inc(); + store.trigger.undo(); + + expect(observed).toEqual([0]); + }); + + it('should apply triggered transitions and effects once without history', () => { + const effect = vi.fn(); + const store = createStore({ + context: { count: 0 }, + on: { + inc: (context) => ({ count: context.count + 1 }), + add: (context, event: { by: number }, enqueue) => { + enqueue.effect(effect); + return { count: context.count + event.by }; + } + } + }).with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.trigger.add({ by: 10 }); + return next; + } + }) + ); + + store.trigger.inc(); + expect(store.can.undo()).toBe(true); + expect(effect).not.toHaveBeenCalled(); + store.trigger.undo(); + + expect(store.getSnapshot().context.count).toBe(10); + expect(effect).toHaveBeenCalledTimes(1); + expect(store.can.undo()).toBe(false); + }); + + it('should not execute enqueued effects when checking can', () => { + const effect = vi.fn(); + const emitted = vi.fn(); + const store = createStore({ + schemas: { emitted: { restored: z.object({}) } }, + context: { count: 0 }, + on: { inc: (context) => ({ count: context.count + 1 }) } + }).with( + undoRedo({ + strategy: 'snapshot', + restore: ({ next }, enqueue) => { + enqueue.effect(effect); + enqueue.emit.restored({}); + return next; + } + }) + ); + store.on('restored', emitted); + + store.trigger.inc(); + expect(store.can.undo()).toBe(true); + expect(effect).not.toHaveBeenCalled(); + expect(emitted).not.toHaveBeenCalled(); + store.trigger.undo(); + expect(store.can.redo()).toBe(true); + expect(effect).toHaveBeenCalledTimes(1); + expect(emitted).toHaveBeenCalledTimes(1); + }); + + it('should infer restore context, emitted events, and triggers', () => { + createStore({ + schemas: { + emitted: { restored: z.object({ count: z.number() }) } + }, + context: { count: 0 }, + on: { + add: (context, event: { by: number }) => ({ + count: context.count + event.by + }) + } + }).with( + undoRedo({ + strategy: 'snapshot', + restore: ({ current, next, direction }, enqueue) => { + current.count satisfies number; + next.count satisfies number; + direction satisfies 'undo' | 'redo'; + enqueue.emit.restored({ count: next.count }); + enqueue.trigger.add({ by: 1 }); + + if (false) { + // @ts-expect-error + enqueue.emit.restored({ count: 'wrong' }); + // @ts-expect-error + enqueue.trigger.add({ by: 'wrong' }); + } + + return next; + } + }) + ); + + if (false) { + undoRedo({ + strategy: 'event', + // @ts-expect-error restore is only available for snapshot strategy + restore: () => ({ count: 0 }) + }); + } + }); +}); diff --git a/xstate-store/test/validate.test.ts b/xstate-store/test/validate.test.ts new file mode 100644 index 00000000..d4488f51 --- /dev/null +++ b/xstate-store/test/validate.test.ts @@ -0,0 +1,347 @@ +import { createStore } from '../src/index.ts'; +import { reset } from '../src/reset.ts'; +import { StoreValidationError, validateSchemas } from '../src/validate.ts'; +import { z } from 'zod'; + +function getThrown(fn: () => void): unknown { + try { + fn(); + } catch (error) { + return error; + } +} + +it('validates initial context when the extension is applied', () => { + expect(() => + createStore({ + schemas: { + context: z.object({ count: z.number() }) + }, + context: { count: 'nope' } as any, + on: {} + }).with(validateSchemas()) + ).toThrow(StoreValidationError); +}); + +it('validates event payloads before transitions', () => { + const store = createStore({ + schemas: { + events: { + inc: z.object({ by: z.number() }) + } + }, + context: { count: 0 }, + on: { + inc: (ctx, ev) => ({ count: ctx.count + ev.by }) + } + }).with(validateSchemas()); + + expect(store.can.inc({ by: 'nope' } as any)).toBe(false); + + expect(() => store.trigger.inc({ by: 'nope' } as any)).toThrow( + StoreValidationError + ); + expect(store.getSnapshot().context).toEqual({ count: 0 }); + + store.trigger.inc({ by: 2 }); + expect(store.getSnapshot().context).toEqual({ count: 2 }); +}); + +it('validates final context after a macrostep', () => { + const store = createStore({ + schemas: { + events: { + break: z.object({}) + }, + context: z.object({ count: z.number() }) + }, + context: { count: 0 }, + on: { + break: () => ({ count: 'nope' }) as any + } + }).with(validateSchemas()); + + expect(store.can.break()).toBe(false); + expect(() => store.trigger.break()).toThrow(StoreValidationError); +}); + +it('validates emitted payloads before running effects', () => { + const effectSpy = vi.fn(); + const store = createStore({ + schemas: { + events: { + send: z.object({}) + }, + emitted: { + sent: z.object({ value: z.number() }) + } + }, + context: {}, + on: { + send: (ctx, _, enq) => { + enq.effect(effectSpy); + enq.emit.sent({ value: 'nope' } as any); + return ctx; + } + } + }).with(validateSchemas()); + + expect(() => store.trigger.send()).toThrow(StoreValidationError); + expect(effectSpy).not.toHaveBeenCalled(); +}); + +it('validates no-payload events and emitted events as empty objects', () => { + const emittedSpy = vi.fn(); + const store = createStore({ + schemas: { + events: { + reset: z.object({}) + }, + emitted: { + reset: z.object({}) + } + }, + context: { count: 1 }, + on: { + reset: (_, __, enq) => { + enq.emit.reset(); + return { count: 0 }; + } + } + }).with(validateSchemas()); + + store.on('reset', emittedSpy); + store.trigger.reset(); + + expect(store.getSnapshot().context).toEqual({ count: 0 }); + expect(emittedSpy).toHaveBeenCalledWith({ type: 'reset' }); +}); + +it('throws for unknown events and emitted events by default', () => { + const store = createStore({ + schemas: { + events: { + send: z.object({}) + }, + emitted: { + known: z.object({}) + } + }, + context: {}, + on: { + send: (ctx, _, enq) => { + (enq.emit as any).unknown(); + return ctx; + } + } + }).with(validateSchemas()); + + expect(getThrown(() => store.send({ type: 'unknown' } as any))).toMatchObject( + { + reason: 'unknownEvent', + eventType: 'unknown', + payload: {} + } + ); + expect(getThrown(() => store.trigger.send())).toMatchObject({ + reason: 'unknownEmitted', + eventType: 'unknown', + payload: {} + }); +}); + +it('returns false from can for validation errors', () => { + const store = createStore({ + schemas: { + events: { + inc: z.object({ by: z.number() }) + } + }, + context: { count: 0 }, + on: { + inc: (ctx, ev) => ({ count: ctx.count + ev.by }) + } + }).with(validateSchemas()); + + expect(store.can.inc({ by: 'nope' } as any)).toBe(false); +}); + +it('exposes validation error details', () => { + const store = createStore({ + schemas: { + events: { + inc: z.object({ by: z.number() }) + } + }, + context: { count: 0 }, + on: { + inc: (ctx, ev) => ({ count: ctx.count + ev.by }) + } + }).with(validateSchemas()); + + expect( + getThrown(() => store.trigger.inc({ by: 'nope' } as any)) + ).toMatchObject({ + name: 'StoreValidationError', + reason: 'invalidEvent', + eventType: 'inc', + payload: { by: 'nope' }, + issues: expect.any(Array) + }); +}); + +it('throws for unknown emitted events by default', () => { + const store = createStore({ + schemas: { + events: { + send: z.object({}) + }, + emitted: { + known: z.object({}) + } + }, + context: {}, + on: { + send: (ctx, _, enq) => { + (enq.emit as any).unknown(); + return ctx; + } + } + }).with(validateSchemas()); + + expect(getThrown(() => store.trigger.send())).toMatchObject({ + reason: 'unknownEmitted', + eventType: 'unknown', + payload: {} + }); +}); + +it('throws for unknown events by default', () => { + const store = createStore({ + schemas: { + events: { + send: z.object({}) + } + }, + context: {}, + on: {} + }).with(validateSchemas()); + + expect(getThrown(() => store.send({ type: 'unknown' } as any))).toMatchObject( + { + reason: 'unknownEvent', + eventType: 'unknown', + payload: {} + } + ); +}); + +it('can ignore unknown events and emitted events', () => { + const emittedSpy = vi.fn(); + const store = createStore({ + schemas: { + events: { + send: z.object({}) + }, + emitted: { + known: z.object({}) + } + }, + context: {}, + on: { + send: (ctx, _, enq) => { + (enq.emit as any).unknown(); + return ctx; + } + } + }).with( + validateSchemas({ + unknownEvents: 'ignore', + unknownEmitted: 'ignore' + }) + ); + + store.on('*', emittedSpy); + store.send({ type: 'unknown' } as any); + store.trigger.send(); + + expect(emittedSpy).toHaveBeenCalledWith({ type: 'unknown' }); +}); + +it('allows extension-added event types without schemas', () => { + const store = createStore({ + schemas: { + context: z.object({ count: z.number() }), + events: { + inc: z.object({}) + } + }, + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }) + .with(reset()) + .with(validateSchemas()); + + store.trigger.inc(); + store.trigger.reset(); + + expect(store.getSnapshot().context).toEqual({ count: 0 }); +}); + +it('can opt out of individual validation areas', () => { + const store = createStore({ + schemas: { + events: { + inc: z.object({ by: z.number() }) + }, + context: z.object({ count: z.number() }) + }, + context: { count: 0 }, + on: { + inc: (ctx, ev) => ({ count: ctx.count + ev.by }) + } + }).with(validateSchemas({ context: false, events: false })); + + store.trigger.inc({ by: 1 }); + expect(store.getSnapshot().context).toEqual({ count: 1 }); +}); + +it('warns and no-ops in dev when there are no schemas', () => { + const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const store = createStore({ + context: { count: 0 }, + on: { + inc: (ctx) => ({ count: ctx.count + 1 }) + } + }).with(validateSchemas()); + + expect(warnSpy).toHaveBeenCalledWith( + 'The "validateSchemas" store extension was used, but the store has no schemas to validate.' + ); + + store.trigger.inc(); + expect(store.getSnapshot().context).toEqual({ count: 1 }); + + warnSpy.mockRestore(); +}); + +it('throws a validation error for async schemas', () => { + const store = createStore({ + schemas: { + events: { + ping: z.object({}).refine(async () => true) + } + }, + context: {}, + on: { + ping: (ctx) => ctx + } + }).with(validateSchemas()); + + expect(getThrown(() => store.trigger.ping())).toMatchObject({ + reason: 'asyncValidationUnsupported', + eventType: 'ping' + }); +}); diff --git a/xstate-test/CHANGELOG.md b/xstate-test/CHANGELOG.md new file mode 100644 index 00000000..517599e3 --- /dev/null +++ b/xstate-test/CHANGELOG.md @@ -0,0 +1,167 @@ +# @xstate/test + +## 2.0.0-alpha.1 + +### Major Changes + +- 97e9166: `@xstate/test` 2.0 is model-based and property-based testing for XState v6, + built on fast-check. A state machine is the model: `@xstate/test` generates + event sequences from it, sends each sequence to the machine and to the system + under test (SUT), and fails when the two disagree or a declared property stops + holding. All exports are experimental. `xstate` and `fast-check` are required + peer dependencies. + + `propertyTest()` generates random event sequences and shrinks a failing one to + a minimal counterexample. fast-check options (`seed`, `numRuns`, + `maxCommands`, …) are top-level options: + + ```ts + import * as fc from 'fast-check'; + import { propertyTest } from '@xstate/test'; + + await propertyTest(cartMachine, { + numRuns: 100, + events: { + ADD: fc.record({ sku: fc.constantFrom('apple', 'pear') }), + CHECKOUT: fc.constant({}) + }, + sut: { + create: () => { + const cart = createCart(); + return { + send: (event) => { + if (event.type === 'ADD') cart.add(event.sku); + }, + read: () => cart.items() + }; + }, + projectModel: (snapshot) => snapshot.context.items + }, + invariant: ({ snapshot }) => { + expect(Object.values(snapshot.context.items).every((n) => n > 0)).toBe(true); + } + }); + ``` + + `testPaths()` walks the machine's state graph and runs every path it finds. It + takes the same `events`, `sut`, `states`, `invariant`, and `reference` options: + + ```ts + import { testPaths } from '@xstate/test'; + + await testPaths(cartMachine, { pathGenerator: 'simple', events, sut: cartSut }); + ``` + + `pick()` builds an event case whose payload comes from the current snapshot. + The case is skipped when there is nothing to pick: + + ```ts + import { pick } from '@xstate/test'; + + await propertyTest(cartMachine, { + events: { + REMOVE: pick( + (snapshot) => Object.keys(snapshot.context.items), + (sku) => ({ sku }) + ) + }, + sut: cartSut + }); + ``` + + A failure throws `ModelTestFailure`, with the trace, the fast-check seed, and a + JSON-safe `fixture`. `replayTest()` replays a fixture without generating + anything. `failures: true` saves failing fixtures to `.xstate-test` and replays + them before the next campaign: + + ```ts + import { ModelTestFailure, replayTest } from '@xstate/test'; + + await expect( + replayTest(cartMachine, fixture, { sut: cartSut }) + ).rejects.toBeInstanceOf(ModelTestFailure); + + await propertyTest(cartMachine, { events, sut: cartSut, failures: true }); + ``` + + Both functions resolve with a `coverage` object: state nodes, transitions, + transition pairs, event types, `meta.requirements`, labels, and temporal + properties. `formatTestCoverage()` renders it as text or markdown; + `formatTestCoverageJUnit()`, `formatTestCoverageHTML()`, and + `testCoverageToJSON()` export it; `assertTestCoverage()` enforces thresholds: + + ```ts + import { assertTestCoverage, formatTestCoverage } from '@xstate/test'; + + const { coverage } = await propertyTest(cartMachine, { events, sut: cartSut }); + console.log(formatTestCoverage(coverage)); + assertTestCoverage(coverage, { transitions: 1, stateNodes: 1 }); + ``` + + `generateTestSuite()` keeps a small set of fixtures from a passing campaign + that preserves its coverage. `serializeTestSuite()` and `parseTestSuite()` + store it, and `describeTestSuite()` registers one test per fixture: + + ```ts + import { describeTestSuite, generateTestSuite } from '@xstate/test'; + + const suite = await generateTestSuite(cartMachine, { + seed: 1, + numRuns: 200, + events, + sut: cartSut + }); + describeTestSuite(suite, cartMachine, { invariant: () => {}, sut: cartSut }); + ``` + + `@xstate/test/vitest` registers a model test in one call. `it.model` runs + `propertyTest()` and `it.paths` runs `testPaths()`; failures are saved per + test: + + ```ts + import { it } from '@xstate/test/vitest'; + + it.model('the cart matches the model', cartMachine, { events, sut: cartSut }); + ``` + + `@xstate/test/playwright` provides `createPlaywrightSut()`, a `sut` that drives + a Playwright page: + + ```ts + import { createPlaywrightSut } from '@xstate/test/playwright'; + + await propertyTest(formMachine, { + events, + sut: createPlaywrightSut(page, { + reset: async (page) => { + await page.goto('/'); + }, + events: { NEXT: (page) => page.click('#next') }, + read: async (page) => ({ step: await page.locator('#step').textContent() }), + projectModel: (snapshot) => ({ step: String(snapshot.value) }) + }) + }); + ``` + + Event generators are derived from the machine's `schemas.events` for every + event type `events` does not configure. Zod schemas are supported directly, + and Effect Schemas through `@xstate/test/effect-schema`. Pass + `deriveEvents: false` to turn this off: + + ```ts + import * as z from 'zod'; + + const counterMachine = createMachine({ + schemas: { events: { INC: z.object({ by: z.number().int().min(1).max(5) }) } }, + context: { count: 0 }, + on: { + INC: ({ context, event }) => ({ context: { count: context.count + event.by } }) + } + }); + + await propertyTest(counterMachine, { + invariant: ({ snapshot }) => { + expect(snapshot.context.count).toBeGreaterThanOrEqual(0); + } + }); + ``` diff --git a/xstate-test/LICENSE b/xstate-test/LICENSE new file mode 100644 index 00000000..8038a1cd --- /dev/null +++ b/xstate-test/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 David Khourshid + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/xstate-test/README.md b/xstate-test/README.md new file mode 100644 index 00000000..7e7f960c --- /dev/null +++ b/xstate-test/README.md @@ -0,0 +1,1813 @@ +# `@xstate/test` + +Model-based and property-based testing for XState, built on +[fast-check](https://fast-check.dev). + +Describe the behavior you expect as a state machine. `@xstate/test` generates +event sequences from that machine, sends each sequence to the machine and to +your implementation, and fails when the two disagree or when a property you +declared stops holding. + +Two functions generate the sequences: + +- `testPaths()` walks the machine's state graph and runs every path it finds. +- `propertyTest()` generates random sequences and shrinks a failing one to a + minimal counterexample. + +Both take the same options, return the same coverage object, and throw the +same `ModelTestFailure`. +[`examples/property-testing-cart`](../../examples/property-testing-cart) is the +complete worked example. + +- [Installation](#installation) +- [Quick start](#quick-start) +- [Concepts](#concepts) +- [How-to guides](#how-to-guides) +- [Reference](#reference) +- [Migrating from `@xstate/test` 0.x and 1.0 beta](#migrating-from-xstatetest-0x-and-10-beta) +- [Comparison](#comparison) + +## Installation + +```bash +pnpm add -D @xstate/test fast-check xstate +``` + +`xstate` and `fast-check` are required peer dependencies. The other peer +dependencies are optional: + +| Package | Needed for | +| --- | --- | +| `zod` (v3.25+ or v4) | Deriving event generators from Zod event schemas. | +| `effect` (v4) | Deriving event generators from Effect Schemas, through `@xstate/test/effect-schema`. | +| `@playwright/test` or `playwright` (1.40+) | `@xstate/test/playwright`. | + +## Quick start + +This section tests a hand-written cart against a cart machine, first with +`propertyTest()` and then with `testPaths()`. + +The machine is the model. It says what the cart must do: + +```ts +// cart.machine.ts +import { createMachine, types } from 'xstate'; + +export const cartMachine = createMachine({ + id: 'cart', + schemas: { + context: types<{ items: Record }>(), + events: { + ADD: types<{ sku: string }>(), + REMOVE: types<{ sku: string }>(), + CHECKOUT: types<{}>() + } + }, + context: { items: {} }, + initial: 'shopping', + states: { + shopping: { + on: { + ADD: ({ context, event }) => ({ + context: { + items: { + ...context.items, + [event.sku]: (context.items[event.sku] ?? 0) + 1 + } + } + }), + REMOVE: ({ context, event }) => { + const { [event.sku]: _removed, ...items } = context.items; + return { context: { items } }; + }, + CHECKOUT: ({ context }) => + Object.keys(context.items).length + ? { target: 'checkedOut' } + : undefined + } + }, + checkedOut: { type: 'final' } + } +}); +``` + +The implementation is the code under test: + +```ts +// cart.ts +export function createCart() { + const items: Record = {}; + return { + add: (sku: string) => { + items[sku] = (items[sku] ?? 0) + 1; + }, + remove: (sku: string) => { + delete items[sku]; + }, + items: () => ({ ...items }) + }; +} +``` + +### Describe the events and the SUT + +`events` says how to generate each event's payload. `sut` says how to send an +event to the cart and how to compare the cart with the machine: + +```ts +// cart.test.ts +import * as fc from 'fast-check'; +import type { EventFrom, SnapshotFrom } from 'xstate'; +import { formatTestCoverage, propertyTest, type TestSut } from '@xstate/test'; +import { createCart } from './cart'; +import { cartMachine } from './cart.machine'; + +const sku = fc.constantFrom('apple', 'pear'); +const events = { + ADD: fc.record({ sku }), + REMOVE: fc.record({ sku }), + CHECKOUT: fc.constant({}) +}; + +const cartSut: TestSut< + SnapshotFrom, + EventFrom +> = { + create: () => { + const cart = createCart(); + return { + send: (event) => { + if (event.type === 'ADD') { + cart.add(event.sku); + } + if (event.type === 'REMOVE') { + cart.remove(event.sku); + } + }, + read: () => cart.items() + }; + }, + projectModel: (snapshot) => snapshot.context.items +}; +``` + +### Generate random sequences with `propertyTest()` + +```ts +test('the cart matches the model', async () => { + const { coverage } = await propertyTest(cartMachine, { + seed: 1, + numRuns: 100, + events, + sut: cartSut + }); + console.log(formatTestCoverage(coverage)); +}); +``` + +`propertyTest()` generates 100 sequences of `ADD`, `REMOVE`, and `CHECKOUT`. +For every step, it applies the event to the machine, sends it to the cart +through `send`, and compares `read()` with `projectModel(snapshot)`. The +printed coverage starts with: + +``` +Test coverage + +states: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +stateNodes: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +configurations: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +statuses: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +eventTypes: 4/4 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +transitions: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +... +event cases: + - ADD / default: 154 generated, 115 applicable, 115 executed, 39 ignored + - CHECKOUT / default: 170 generated, 126 applicable, 126 executed, 44 ignored + - REMOVE / default: 147 generated, 112 applicable, 112 executed, 35 ignored +``` + +An event case is `ignored` when it is not applicable to the current step. Here, +that is every event generated after `CHECKOUT` reaches the final `checkedOut` +state and the actor stops. A case is also inapplicable when its `when` returns +`false`, its `resolve` or `pick()` returns nothing, or `swarm` leaves it out of +the run. Whether the machine has a transition for the event does not matter: +`CHECKOUT` on an empty cart is sent to the machine and the cart, the machine +stays in `shopping`, and the case counts as executed. See [Events](#events) to +skip such events. + +### Walk the state graph with `testPaths()` + +`testPaths()` takes the same `events` and the same `sut`: + +```ts +import { testPaths } from '@xstate/test'; + +test('every simple path matches the model', async () => { + const { coverage, results } = await testPaths(cartMachine, { + pathGenerator: 'simple', + events, + sut: cartSut, + // Quantities grow without bound; stop expanding at 2. + stopWhen: (snapshot) => + Object.values(snapshot.context.items).some((qty) => qty >= 2) + }); + console.log(`${results.length} paths`); + console.log(formatTestCoverage(coverage)); +}); +``` + +Each `fc` arbitrary is sampled into three concrete payloads before traversal +(`samples` defaults to `3`), and each path runs once. The output starts with: + +``` +15 paths +Test coverage + +states: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +stateNodes: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +configurations: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +statuses: 2/2 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +eventTypes: 4/4 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +transitions: 3/3 covered (100.0%), 0 uncovered, 0 unreachable, 0 unknown +``` + +`pathGenerator: 'simple'` is needed here. `REMOVE` of the only item returns +the cart to a state that is already reachable, so the default `'shortest'` +generator never takes it. + +When the cart and the machine disagree, both functions throw a +`ModelTestFailure` that shows the failing sequence step by step. See +[What a failure looks like](../../examples/property-testing-cart#what-a-failure-looks-like) +in the cart example. + +## Concepts + +### Model and system under test + +The **model** is an XState machine that describes the expected behavior. The +**system under test** (SUT) is the code being tested: a class, a store, a +service, or a web page. A run starts both, sends them the same events, and +checks them after every **stable step**, which is the point at which an event +or command has been fully processed. + +The model runs in memory. By default it is stepped through XState's pure +`transition()` function, so no actions run and no actors start. + +### Events + +`events` says which events a run may send, and how their payloads are +produced. Each key is an event type, and each value is one of: + +- a generator, such as `fc.record({ sku })`. The generator produces the payload + without `type`; the key supplies `type`. The generator becomes one **event + case** named `default`. +- a descriptor object, `{ case, generate, when, resolve, weight }`. +- an array of generators and descriptors, one event case each. + +```ts +events: { + ADD: [ + { case: 'apple', generate: fc.constant({ sku: 'apple' }) }, + { + case: 'known-sku', + generate: fc.constantFrom('apple', 'pear'), + resolve: ({ generated }) => ({ sku: generated as string }), + when: ({ snapshot }) => Object.keys(snapshot.context.items).length < 3 + } + ] +} +``` + +| Descriptor field | Purpose | +| --- | --- | +| `generate` | Produces the payload, or with `resolve`, a value `resolve` turns into a payload. | +| `case` | Names the event case in coverage and in `sut.send()`. Defaults to `'default'`. | +| `when` | Returns `false` to make the case inapplicable for the current snapshot and event. | +| `resolve` | Turns the generated value into a payload using the current model snapshot. Returning `undefined` makes the case inapplicable. | +| `weight` | Relative generation frequency under `propertyTest()`. Defaults to `1`. | + +The runner sends an applicable event even when the current state has no +transition for it. The machine does not change, the event reaches the SUT, and +the step checks that the SUT ignores it too. To send only events the machine +handles in the current state, use `snapshot.can(event)`: + +```ts +events: { + CHECKOUT: { + generate: fc.constant({}), + when: ({ snapshot, event }) => snapshot.can(event) + } +} +``` + +`CHECKOUT` on an empty cart is then `ignored` rather than executed. + +`resolve` is for payloads that must refer to the current state, such as an item +that is already in the cart. fast-check shrinks the generated value, and the +resolved event is what gets recorded, so replay fixtures do not depend on the +resolver. + +`pick(select, toPayload?)` builds such a descriptor. `select` lists the +candidates in the current snapshot, and `toPayload` turns the picked one into +the payload; without it, the candidate is the payload. The case is +inapplicable when `select` returns an empty array. The index into the +candidates is generated with `fc.nat()`, so a failing run shrinks towards the +first candidate. The snapshot type is inferred from the machine: + +```ts +import { pick } from '@xstate/test'; + +events: { + REMOVE: pick( + (snapshot) => Object.keys(snapshot.context.items), + (sku) => ({ sku }) + ) +} +``` + +`propertyTest()` sends only the event types that `events` configures, plus the +types it derives from schemas (see +[Derive event generators from schemas](#derive-event-generators-from-schemas)). +`testPaths()` also offers every event type the machine handles that `events` +does not configure, as a bare `{ type }` event. + +Generated payloads must be plain objects. A generator that produces a +primitive, an array, or `null` fails the run with an error naming the event +case. + +### The `sut` option + +`sut` describes the system under test. Both entry points accept the same +shape: + +```ts +sut: { + create: () => { + const cart = createCart(); + return { + send: (event) => { /* perform the event */ }, + read: () => cart.items(), + dispose: () => { /* tear down */ } + }; + }, + projectModel: (snapshot) => snapshot.context.items +} +``` + +`create()` runs once per run: once per generated sequence, per shrink attempt, +or per path. The session it returns is disposed at the end of the run, whether +the run passed or failed. After every stable step, the runner compares +`projectSut(read())` with `projectModel(snapshot)` using `equivalent`, which +defaults to structural, key-order-insensitive deep equality. Omit `read` and `projectModel` to check the SUT only +through `states` assertions. + +The [session members](#sut) are listed in the reference. + +### Oracles + +An **oracle** decides whether a step is correct. Every oracle runs on every +stable step: + +| Oracle | Option | Fails when | +| --- | --- | --- | +| Invariant | `invariant` | The function throws. | +| Temporal property | `temporal` | An `always`, `never`, `eventually`, `until`, or `respond` property is violated. | +| SUT comparison | `sut.projectModel` with `session.read` | The SUT's observation differs from the model's projection. | +| State assertions | `states`, `session.states`, `meta.test` | An assertion for a matching state throws. | +| SUT check | `session.check` | The function throws, such as the page oracles of `@xstate/test/playwright`. | +| Reference implementation | `reference` | A second implementation of the same logic disagrees with the model. | + +Two oracles are checked once, when the campaign ends, and fail it with a +`TestCampaignError`: + +| Oracle | Option | Fails when | +| --- | --- | --- | +| `sometimes` property | `temporal` | The predicate held on no step of any run. | +| Reachability | `reachable` | No run entered a listed state. | + +`states` is keyed by state value (`'shopping'`, `'form.email'`), by state node +id (`'#cart.shopping'`), or `'*'`, which runs when no other key matches. A +`states` map on the session replaces the top-level one. Functions in a state +node's `meta.test` run too, and receive the session and the snapshot. + +### Modes + +`mode` decides how the model runs: + +- `'pure'` (the default) steps the machine through `transition()`. No action + runs and no invoked actor starts. Invoke results and `after` delays are + reached only by sending the internal events for them. +- `'executed'` runs the machine as a real actor on a `SimulatedClock`. Invoked + and spawned actors start, `onDone` and `onError` fire, and `after` + transitions fire when the clock is advanced. + +See [Steer invoked services](#steer-invoked-services) and +[Test delayed transitions](#test-delayed-transitions). + +### `testPaths()` or `propertyTest()` + +| | `testPaths()` | `propertyTest()` | +| --- | --- | --- | +| Sequences | Paths through the reachable state graph | Random sequences | +| Payloads | Sampled once before traversal, `samples` per case | Generated per run | +| On failure | Throws on the first failing path | Throws a shrunk counterexample | +| `onDone`, `onError`, `after` | Traversed as internal events | Reached with `mode: 'executed'` | +| Budget | Every path | `numRuns`, or `until` with `maxRuns` | +| Offline suites | No | `generateTestSuite()` | + +Use `testPaths()` when the reachable graph is finite and you want every path +through it. Use `propertyTest()` when payloads, ordering, or timing matter, or +when the graph is too large to enumerate. + +### Coverage + +Both entry points resolve with `{ coverage }`. Coverage counts what the runs +exercised across these dimensions: `states`, `stateNodes`, `configurations`, +`statuses`, `eventTypes`, `transitions`, `transitionPairs`, `requirements`, +and `frontiers`. Each dimension sorts its ids into `covered`, +`uncovered`, `unreachable`, and `unknown`. Transition hits come from the +microsteps XState took, not from the states that were visited. + +Coverage is relative to the events you supplied and the bounds you set. Full +transition coverage means every declared transition was taken at least once, +not that every behavior was tested. See [Coverage](#coverage-1) in the +reference. + +## How-to guides + +### Derive event generators from schemas + +When the machine declares its event payloads as Zod schemas, `propertyTest()` +and `testPaths()` derive the generators from them: + +```ts +import { setup } from 'xstate'; +import * as z from 'zod'; + +const counterMachine = setup({ + schemas: { + events: { + INC: z.object({ by: z.number().int().min(1).max(5) }), + RESET: z.object({}) + } + } +}).createMachine({ + context: { count: 0 }, + on: { + INC: ({ context, event }) => ({ + context: { count: context.count + event.by } + }), + RESET: () => ({ context: { count: 0 } }) + } +}); + +await propertyTest(counterMachine, { + invariant: ({ snapshot }) => { + expect(snapshot.context.count).toBeGreaterThanOrEqual(0); + } +}); +``` + +Declared constraints are honored: this `INC` generator only produces integers +from 1 to 5. Every event type with a runtime schema that `events` does not +configure is derived. Entries in `events` override derived ones. Pass +`deriveEvents: false` to derive nothing. + +To inspect or edit the derived map, call `eventsFromSchemas()` yourself, and +merge overrides with `mergeEventGenerators()`: + +```ts +import { eventsFromSchemas, mergeEventGenerators } from '@xstate/test'; + +await propertyTest(counterMachine, { + deriveEvents: false, + events: mergeEventGenerators(eventsFromSchemas(counterMachine), { + INC: fc.record({ by: fc.constant(1) }) + }) +}); +``` + +For Effect Schemas, import `eventsFromSchemas` from +`@xstate/test/effect-schema`. `fromEffectSchema(schema)` and +`fromEffectSchemas(map)` from the same entrypoint convert schemas directly: + +```ts +import * as Schema from 'effect/Schema'; +import { fromEffectSchemas } from '@xstate/test/effect-schema'; + +await propertyTest(counterMachine, { + deriveEvents: false, + events: fromEffectSchemas({ + INC: Schema.Struct({ + by: Schema.Int.pipe(Schema.check(Schema.isGreaterThan(0))) + }), + RESET: Schema.Struct({}) + }) +}); +``` + +Schemas that expose no structure cannot be derived from. That includes other +Standard Schema libraries and type-only `types<...>()` declarations. Implicit +derivation skips `types<...>()` declarations. For other schemas, configure the +event in `events`, or pass a `fallback` converter to `eventsFromSchemas()`. +The supported Zod kinds are listed under +[`eventsFromSchemas()`](#eventsfromschemas) in the reference. + +### Steer invoked services + +Run the machine with `mode: 'executed'` to reach `onDone` and `onError` +transitions. Replace real services with `actors` or `outcomes`, so a run +never reaches the network. + +`actors` substitutes fixed logic through `machine.provide({ actors })`: + +```ts +await propertyTest(orderMachine, { + mode: 'executed', + actors: { + chargeCard: createAsyncLogic({ run: async () => ({ id: 'ch_1' }) }) + }, + events: { SUBMIT: fc.constant({}) } +}); +``` + +`outcomes` replaces a named invoke source with a stub. The stub stays pending +until the run generates an `outcome` command for it, so fast-check chooses the +result and when it arrives, and shrinks both: + +```ts +await propertyTest(orderMachine, { + mode: 'executed', + outcomes: { + chargeCard: fc.oneof( + fc.record({ ok: fc.constant(true as const), output: fc.record({ id: fc.string() }) }), + fc.record({ ok: fc.constant(false as const), error: fc.constant('declined') }) + ) + }, + events: { SUBMIT: fc.constant({}) } +}); +``` + +An outcome is `{ ok: true, output }` or `{ ok: false, error }`. A stub that +never receives an outcome stays pending, and the run ends with the machine in +the invoking state. `propertyTest()` rejects `actors` and `outcomes` in pure +mode. + +`testPaths()` already traverses `onDone` and `onError`: the state graph +contains `xstate.done.actor` and `xstate.error.actor` transitions. It samples +`outcomes` the same way it samples `events`: + +- In pure mode, it sends the internal event with the sampled `output` or + `error` as its payload. +- In executed mode, it stubs every invoke source a path resolves and resolves + the stub with the sampled outcome for the branch the path took. A branch + with no matching outcome gets a synthesized one: `{ ok: true, output: undefined }` + or `{ ok: false, error: new Error('generated failure') }`. + +A source named in `outcomes` needs no implementation in either mode. + +```ts +const { coverage } = await testPaths(orderMachine, { + mode: 'executed', + outcomes: { + chargeCard: fc.constant({ ok: true as const, output: { id: 'ch_1' } }) + } +}); +``` + +This run reaches `declined` too: no `ok: false` outcome is declared, so the +error branch resolves with a synthesized failure. + +Executed mode is deterministic for everything that goes through the actor +system and the simulated clock. Real network calls, timers created outside the +actor clock, `Date.now()`, and `Math.random()` are not intercepted. A step +settles once the actor system has produced no new events for two consecutive +macrotask turns. An invoked actor whose promise is still pending at that point +is listed in the step's `pendingActors`, and +`coverage.exploration.pendingActorSteps` counts such steps: its result may +land in a later step. + +### Test delayed transitions + +In executed mode, time moves only through `advance` commands. With +`propertyTest()`, configure a generator for them: + +```ts +await propertyTest(orderMachine, { + mode: 'executed', + outcomes: { chargeCard: fc.constant({ ok: true as const, output: { id: 'ch_1' } }) }, + events: { SUBMIT: fc.constant({}) }, + commands: { advance: fc.integer({ min: 1_000, max: 10_000 }) } +}); +``` + +`testPaths()` needs no configuration. Traversal offers only the `after` +transition that is due first, counting the time already spent in enclosing +states. In executed mode, each `xstate.after` step advances the clock to that +timer's due time, read from the actor's scheduler, so a delay computed at +runtime works too. + +In pure mode, the model has no clock. A SUT that owns its clock can implement +`session.advance(ms)` and return the events that fired; the runner applies +them to the model before the next comparison. + +### Test a web page with Playwright + +`createPlaywrightSut(page, config)` from `@xstate/test/playwright` returns a +`sut` that drives a Playwright page: + +```ts +import { test } from '@playwright/test'; +import * as fc from 'fast-check'; +import { propertyTest } from '@xstate/test'; +import { createPlaywrightSut } from '@xstate/test/playwright'; +import { formMachine } from './form.machine'; + +test('the form matches its model', async ({ page }) => { + await propertyTest(formMachine, { + numRuns: 25, + maxCommands: 8, + events: { + FILL: fc.record({ value: fc.constantFrom('', 'Ada', 'ada@example.com') }), + NEXT: fc.constant({}), + BACK: fc.constant({}) + }, + sut: createPlaywrightSut(page, { + reset: async (page) => { + await page.goto('/'); + }, + events: { + FILL: (page, event) => page.fill('#field', event.value), + NEXT: (page) => page.click('#next'), + BACK: (page) => page.click('#back') + }, + read: async (page) => ({ + step: await page.locator('#step').textContent(), + error: await page.locator('#error').textContent() + }), + projectModel: (snapshot) => ({ + step: String(snapshot.value), + error: snapshot.context.error + }) + }) + }); +}); +``` + +Put navigation in `reset`. It runs at the start of every run, and without it a +run starts from the page the previous run left behind. + +These defaults apply to every step: + +- `settle` waits for `page.waitForLoadState('load')`, then for pending + microtasks, before each comparison. Pass `settle` to wait for something + specific, such as `(page) => expect(page.locator('#step')).toBeVisible()`. + Playwright discourages waiting for `'networkidle'`. +- `advance` calls `page.clock.runFor(ms)`. Call `page.clock.install()` before + navigating for it to have an effect. +- The page oracles fail the step when the page threw an uncaught exception, + logged a console error, left a promise rejection unhandled, or received a + response with a status of 400 or above. + +The page oracles are checked after every stable step. Choose them with +`oracles`. In the object form, oracles you leave out are off: + +```ts +sut: createPlaywrightSut(page, { + events, + read, + projectModel, + // Fail on console warnings too, and only on server errors. + oracles: { pageError: true, console: 'warn', http: 500, unhandledRejection: true } +}) +``` + +`oracles: false` turns them all off. Responses to requests that a `mocks` +route handled are not checked, so a mocked `500` does not fail the step. A +failing oracle fails the run with `SUT check failed after N steps`, and its +cause is a `PlaywrightOracleError` whose `messages` list what the page +reported. + +To attach failure artifacts to the Playwright report, pass the `testInfo` +fixture: + +```ts +test('the form matches its model', async ({ page }, testInfo) => { + await propertyTest(formMachine, { + events, + sut: createPlaywrightSut(page, { + events: formActions, + read, + projectModel, + testInfo, + step: (name, body) => test.step(name, body) + }) + }); +}); +``` + +With `testInfo`, every run records a Playwright trace. When the campaign +fails, the failing run's trace, a `fixture.json` with the `TestFixture`, and +a screenshot of the page are attached. The failing run is the shrunk +counterexample. `trace: 'on'` also attaches the last run's trace when the +campaign passes, and `screenshots: 'every-step'` attaches one screenshot per +stable step of the failing run. `step` wraps each event action, so the report +lists one step per event. + +To stub network calls per event case, use `mocks`. The key is +`"."` or `""`: + +```ts +events: { + SUBMIT: [ + { case: 'ok', generate: fc.constant({}) }, + { case: 'error', generate: fc.constant({}) } + ] +}, +sut: createPlaywrightSut(page, { + events: { SUBMIT: (page) => page.click('#submit') }, + mocks: { + 'SUBMIT.ok': (page) => + page.route('**/api/submit', (route) => route.fulfill({ status: 200 })), + 'SUBMIT.error': (page) => + page.route('**/api/submit', (route) => route.fulfill({ status: 500 })) + }, + read, + projectModel +}) +``` + +A mock runs before the event action, only when the resolved case differs from +the last one applied. Routes a mock installs are removed before another case's +mock is applied and when the run ends. +[`examples/property-testing-playwright`](../../examples/property-testing-playwright) +is a runnable version. All options are listed under +[`createPlaywrightSut()`](#createplaywrightsut) in the reference. + +### Run model tests with Vitest + +`@xstate/test/vitest` registers a model test in one call. `it.model` runs +`propertyTest()`, and `it.paths` runs `testPaths()`: + +```ts +import { it } from '@xstate/test/vitest'; + +it.model('the cart matches the model', cartMachine, { + events, + sut: cartSut +}); + +it.paths('every path matches the model', cartMachine, { + pathGenerator: 'simple', + events, + sut: cartSut, + stopWhen: (snapshot) => + Object.values(snapshot.context.items).some((qty) => qty >= 2) +}); +``` + +Each test: + +- saves failures, keyed by the test file and the test's full name, and + replays them first on the next run. See + [Save failures and replay them first](#save-failures-and-replay-them-first). + Pass `failures: false` to turn this off, or `failures: { dir, replay }` to + change the directory or the replay mode. +- sets the test timeout to `until.timeMs` plus 5 seconds when `until` has a + `timeMs`. A fourth argument sets the timeout explicitly. +- prints `formatTestCoverage(coverage)` when the campaign fails. +- stores `testCoverageToJSON(coverage)` as `task.meta.xstateTestCoverage`, + where custom reporters can read it. + +`it.model.fails` passes only when the campaign fails, and, with `message`, +only when the failure message matches: + +```ts +it.model.fails('finds the remove bug', cartMachine, buggyOptions, { + message: /Property observation diverged/ +}); +``` + +`it` and `test` from `@xstate/test/vitest` use Vitest's global `it` and +`test`, so they need `test.globals: true`. Without globals, wrap Vitest's own: + +```ts +import { it as vitestIt } from 'vitest'; +import { withModelTests } from '@xstate/test/vitest'; + +const it = withModelTests(vitestIt); +``` + +`vitest` is an optional peer dependency. `@xstate/test/vitest` imports only +its types. + +### Check liveness and reachability + +`always` and `never` check every step. Three more checks cover behavior that +must happen: + +- `respond` requires every step on which `trigger` holds to be followed, + within `within` steps, by a step on which `response` holds. The response may + hold on the trigger step itself. +- `sometimes` requires the predicate to hold on at least one step of at least + one run. A run in which it never holds does not fail; the campaign fails + when no run satisfied it. +- `reachable` lists states that at least one run must enter, as state values, + state node ids, or tags. + +This cart machine invokes `pay` from a `paying` state, which moves to `done` +on success and back to `shopping` on failure, as in the +[cart example](../../examples/property-testing-cart): + +```ts +const whileShopping = ({ snapshot }) => snapshot.matches('shopping'); + +await propertyTest(cartMachine, { + events: { + ADD: { generate: fc.record({ sku }), when: whileShopping }, + CHECKOUT: { generate: fc.constant({}), when: whileShopping } + }, + mode: 'executed', + outcomes: { + pay: fc.oneof( + fc.constant({ ok: true as const, output: {} }), + fc.constant({ ok: false as const, error: 'declined' }) + ) + }, + temporal: [ + { + type: 'respond', + id: 'payment-settles', + within: 1, + trigger: ({ snapshot }) => snapshot.matches('paying'), + response: ({ snapshot }) => !snapshot.matches('paying') + }, + { + type: 'sometimes', + id: 'declined', + predicate: ({ snapshot }) => snapshot.context.lastError !== null + } + ], + reachable: ['#cart.done'] +}); +``` + +`payment-settles` holds because `when` offers the cart's events only while +shopping: after `CHECKOUT`, the next step is the payment's outcome. Without +`when`, an `ADD` the machine ignores while paying would be a step without a +response. + +When no run satisfies a `sometimes` property or enters a `reachable` state, +the campaign throws a `TestCampaignError`: + +``` +Campaign assertions failed: + - sometimes "declined" did not hold in 100 run(s) + - reachable "#cart.done" was not entered in 100 run(s) +``` + +`coverage.temporal.counts` records, per property, how many runs satisfied it, +failed it, and ended before it was decided. A `reachable` target appears as +`reachable:`. + +A bounded property whose `within` is larger than the longest sequence a +campaign can produce can never fail. The campaign lists it in +`coverage.temporal.warnings`, and `formatTestCoverage()` prints the warning +under `temporal`: + +``` +temporal: 1 satisfied, 0 failed, 0 inconclusive + - checks-out: 2 satisfied, 0 failed, 23 inconclusive + warning: eventually "checks-out" has within 20, but the longest sequence is 10 steps, so it can never fail +``` + +The longest sequence is `maxCommands` for `propertyTest()`, plus the longest +frontier prefix, and the longest path for `testPaths()`. + +### Gate CI on coverage + +`assertTestCoverage()` throws when a dimension's ratio of +`covered / (covered + uncovered)` is below its threshold. The error message +contains the formatted report: + +```ts +const { coverage } = await propertyTest(cartMachine, { events, sut: cartSut }); + +assertTestCoverage(coverage, { transitions: 1, stateNodes: 1 }); +``` + +To stop a campaign as soon as coverage is reached, use `until`. Runs are +executed in batches of `batchRuns` (default `25`), up to `maxRuns` (default +`100`), and the condition is checked between batches: + +```ts +const { coverage } = await propertyTest(cartMachine, { + events, + sut: cartSut, + until: { transitions: 1 }, + maxRuns: 500 +}); + +coverage.exploration.stoppedBecause; // 'until', 'budget', or 'failure' +``` + +Write reports as CI artifacts with the formatters. Each is deterministic for +the same coverage: + +```ts +import { writeFile } from 'node:fs/promises'; +import { + formatTestCoverage, + formatTestCoverageHTML, + formatTestCoverageJUnit, + testCoverageToJSON +} from '@xstate/test'; + +await writeFile('coverage.md', formatTestCoverage(coverage, { format: 'markdown' })); +await writeFile('coverage.json', JSON.stringify(testCoverageToJSON(coverage))); +await writeFile('coverage.xml', formatTestCoverageJUnit(coverage, { suiteName: 'cart' })); +await writeFile('coverage.html', formatTestCoverageHTML(coverage, { title: 'Cart' })); +``` + +The JUnit report has one `` per transition and per state node: +`` for uncovered ids and `` for unreachable or unknown ones. + +To require that generated sequences reach a situation often enough, record it +with `classify()` or `label()` and set `expectLabels`: + +```ts +await propertyTest(cartMachine, { + events, + invariant: ({ snapshot, classify }) => { + classify(Object.keys(snapshot.context.items).length >= 2, 'two-skus'); + }, + expectLabels: { 'two-skus': { min: 0.1 } } +}); +``` + +`min` is the share of attempted runs, from `0` to `1`, that recorded the label +at least once. `minCount` is a minimum total number of occurrences. Shrink +attempts are not counted. + +### Inspect the distribution of generated data + +`statistics: true` prints how executed events split across event cases, and +the share of runs that recorded each label, after a passing campaign: + +```ts +await propertyTest(cartMachine, { + seed: 1, + events, + statistics: true, + invariant: ({ snapshot, classify }) => { + classify(Object.keys(snapshot.context.items).length >= 2, 'two-skus'); + } +}); +``` + +``` +Test statistics (100 runs) + +event cases (share of executed events): + 32.6% ADD / default: 115 executed, 39 ignored + 35.7% CHECKOUT / default: 126 executed, 44 ignored + 31.7% REMOVE / default: 112 executed, 35 ignored + +labels (share of runs): + 14.0% two-skus: 26 recorded +``` + +`formatTestStatistics(coverage)` returns the same text for any coverage +object. Runs started while fast-check shrinks a counterexample are left out +of the labels and the event cases; `coverage.exploration.shrinkRuns` counts +them. + +### Replay a failure + +A `ModelTestFailure` carries a `fixture`: a JSON-safe record of the sequence +that failed. Save it, and replay it with `replayTest()`: + +```ts +import { ModelTestFailure, replayTest, type TestFixture } from '@xstate/test'; +import fixture from './cart-failure.json'; + +test('regression: removing an item', async () => { + await expect( + replayTest(cartMachine, fixture as TestFixture, { sut: cartSut }) + ).rejects.toBeInstanceOf(ModelTestFailure); +}); +``` + +`replayTest()` stops at the recorded failing step and throws the reproduced +failure. When the failure no longer happens, it throws +`ReplayNotReproducedError`. Pass `expect: 'pass'` to require that the whole +fixture replays without failing, which is how a fixed regression is kept: + +```ts +await replayTest(cartMachine, fixture as TestFixture, { + sut: cartSut, + expect: 'pass' +}); +``` + +Fixtures from executed runs record every invoke outcome, and replay stubs +those sources, so no real service is called. The machine's `id` and `version` +are checked against the fixture. + +To rerun the same fast-check sequence instead, pass the recorded `seed`, +`path`, and `replayPath` back to `propertyTest()`: + +```ts +await propertyTest(cartMachine, { + events, + sut: cartSut, + seed: failure.replay!.seed, + path: failure.replay!.path, + replayPath: failure.replay!.replayPath +}); +``` + +This depends on the same generators and the same fast-check version, which +the fixture does not. + +### Save failures and replay them first + +`failures` saves the fixture of a failing campaign to disk, and replays saved +fixtures before the next campaign: + +```ts +await propertyTest(cartMachine, { + events, + sut: cartSut, + failures: { dir: '.xstate-test', key: 'cart-store' } +}); +``` + +A failing campaign writes `//.json`, with the fixture, the +summary, and the fast-check seed, and adds a line to the failure message. +`` is the first 12 hexadecimal digits of the fixture's SHA-256 hash: + +``` +Saved: .xstate-test/cart-store/.json +``` + +The next campaign replays every saved fixture with `replayTest()` before it +generates anything. A fixture that still fails throws that failure at once, +with `(replayed from )` added to its summary. A fixture that no longer +fails is deleted, and the campaign runs. + +| Option | Default | Description | +| --- | --- | --- | +| `dir` | `'.xstate-test'` | The directory failures are saved in. | +| `replay` | `'first'` | `'first'` replays saved fixtures, then runs the campaign. `'only'` replays them and skips the campaign. `false` saves without replaying. | +| `key` | machine id and a hash | The subdirectory of `dir`. Defaults to the machine's `id` plus a hash of the event cases, the oracles configured, and the mode. | + +`failures: true` uses the defaults. `testPaths()` accepts the same option. +Two tests that run the same machine with different oracles, such as a +`sut` that differs only in its implementation, share the default key; set +`key` so each replays only its own failures. + +Add `.xstate-test/` to `.gitignore` to keep failures local, or commit it so +CI replays the failures found on developer machines first. A run that +starts from a `start` snapshot is not saved. + +`createFailureDatabase(options)` returns the store `failures` creates. Any +object with `load(key)`, `onFailure(fixture, key, failure)`, and optionally +`remove(stored, key)` works as a store, such as one backed by a database; +this is the `TestFailureStore` interface. + +### Record an offline regression suite + +`generateTestSuite()` runs a passing campaign and keeps a small set of fixtures +that preserves the covered transitions and state nodes: + +```ts +import { writeFile } from 'node:fs/promises'; +import { generateTestSuite, serializeTestSuite } from '@xstate/test'; + +const suite = await generateTestSuite(cartMachine, { + seed: 1, + numRuns: 200, + events, + sut: cartSut +}); +await writeFile('cart.suite.json', serializeTestSuite(suite)); +``` + +Replaying generates nothing, so the suite runs the same way every time: + +```ts +import { readFile } from 'node:fs/promises'; +import { describeTestSuite, parseTestSuite } from '@xstate/test'; + +const suite = parseTestSuite(await readFile('cart.suite.json', 'utf8')); + +describeTestSuite(suite, cartMachine, { invariant: () => {}, sut: cartSut }); +``` + +`describeTestSuite()` registers one test per fixture with the global `it` and +`describe` of Vitest or Jest; pass `it` and `describe` to use others. +`replayTestSuite()` replays every fixture and resolves with +`{ passed, failed }` instead. Every fixture is expected to pass. + +### Test concurrency + +A sequential run sends one event at a time, so it never observes a race. Three +tools look for concurrency bugs. + +`scheduler: true` gives every run an `fc.scheduler()`. Wrap the SUT with +`withScheduledSut()` and its `send`, `read`, `settle`, and `advance` calls +resolve in an order fast-check chooses. Schedule the SUT's own background work +on `getCurrentScheduler()`. This SUT commits each increment asynchronously, so +some orderings let `read()` return a stale count, and the campaign fails: + +```ts +import { getCurrentScheduler, withScheduledSut } from '@xstate/test'; + +await propertyTest(counterMachine, { + scheduler: true, + deriveEvents: false, + events: { INC: fc.record({ by: fc.constant(1) }) }, + sut: withScheduledSut({ + create: () => { + const scheduler = getCurrentScheduler()!; + let count = 0; + return { + send: () => { + void scheduler.schedule(Promise.resolve(), 'commit').then(() => { + count++; + }); + }, + read: () => count + }; + }, + projectModel: (snapshot) => snapshot.context.count + }) +}); +``` + +The ordering of a failing run is recorded as `failure.replay.data.scheduler`. +Rebuild it with `fc.schedulerFor(ordering)`. Only work that goes through the +scheduler is reordered. + +`checkLinearizable(history, model)` decides whether a history of overlapping +operations could have come from some sequential order: + +```ts +import { checkLinearizable } from '@xstate/test'; + +const result = checkLinearizable( + [ + { id: 'a', invocation: { type: 'write', value: 1 }, response: undefined, start: 0, end: 4 }, + { id: 'b', invocation: { type: 'read' }, response: 1, start: 1, end: 5 } + ], + { + initial: 0, + apply: (state: number, event: { type: string; value?: number }) => + event.type === 'write' + ? { state: event.value!, response: undefined } + : { state, response: state } + } +); + +result.linearizable; // true +result.witness; // the sequential order that explains the history +``` + +`truncated: true` means the search stopped at `maxExplored` (default `100000`) +before deciding. It is not proof of a bug. + +`runParallelPropertyCommands(machine, options)` runs a sequential `prefix`, +then runs `branches` concurrently against the SUT, and checks the recorded +history against the machine's own `transition()`: + +```ts +import { runParallelPropertyCommands } from '@xstate/test'; + +const result = await runParallelPropertyCommands(counterMachine, { + prefix: [{ type: 'INC', by: 1 }], + branches: [[{ type: 'INC', by: 1 }], [{ type: 'INC', by: 2 }]], + sut: { + create: () => { + let count = 0; + return { + send: async (event) => (count += event.type === 'INC' ? event.by : 0) + }; + }, + projectModel: (snapshot) => snapshot.context.count + } +}); + +result.linearizable; // true +``` + +When `send` resolves to `undefined`, the response is read with `read()`. + +### Steer exploration + +These `propertyTest()` options change which sequences a campaign generates. + +`weight` on an event case or command changes how often it is drawn, relative +to the others: + +```ts +events: { + ADD: { generate: fc.record({ sku }), weight: 5 }, + REMOVE: fc.record({ sku }), + CHECKOUT: { generate: fc.constant({}), weight: 0.5 } +} +``` + +`frontiers` starts runs from paths that reach a state of interest. The prefix +is replayed as-is, and shrinking only shortens the generated continuation: + +```ts +import { getShortestPaths } from 'xstate/graph'; + +await propertyTest(cartMachine, { + events, + frontiers: { + paths: getShortestPaths(cartMachine, { + toState: (snapshot) => Object.keys(snapshot.context.items).length > 0, + stopWhen: (snapshot) => + Object.values(snapshot.context.items).some((qty) => qty >= 2) + }), + runsPerFrontier: 50 + } +}); +``` + +`frontiers: 'auto'` does this for coverage. Between batches, it finds the +shortest path to each state node that still owns an uncovered transition and +uses those paths as prefixes. Combine it with `until`: + +```ts +await propertyTest(cartMachine, { + events, + frontiers: 'auto', + until: { transitions: 1 }, + maxRuns: 200 +}); +``` + +`swarm: true` enables a seeded random subset of at least half the event cases +in each run, so frequent events do not crowd out rare combinations. The +enabled cases are recorded on the trace and the fixture, and are frozen while +a failure shrinks. + +`target` hill-climbs toward high values of a number. With +`frontiers: { strategy: 'target' }`, the prefixes that reached the best values +become the next batch's frontiers: + +```ts +const { coverage } = await propertyTest(cartMachine, { + events, + target: ({ snapshot }) => snapshot.context.items.apple ?? 0, + frontiers: { strategy: 'target' }, + until: (coverage) => coverage.exploration.target.best >= 8, + maxRuns: 400 +}); +``` + +### Start from a snapshot or input + +`input` is passed to the machine's initial transition in every run. `start` +starts every run from an existing snapshot instead, and requires +`serializeSnapshot` so fixtures can record the start: + +```ts +const [cartWithApple] = transition( + cartMachine, + initialTransition(cartMachine)[0], + { type: 'ADD', sku: 'apple' } +); + +await propertyTest(cartMachine, { + events, + start: { + snapshot: cartWithApple, + serializeSnapshot: (snapshot) => snapshot.context + } +}); +``` + +Replaying such a fixture requires `restoreSnapshot`, which turns the recorded +value back into a snapshot. + +### Write a custom adapter + +`propertyTest()` uses the built-in fast-check adapter unless you pass +`adapter`: an object with a +`run(request)` method that drives runners and returns a result. See +[`TestAdapter`](#testadapter) in the reference for the request and the runner +lifecycle, and +[`test/randomAdapter.ts`](./test/randomAdapter.ts) for a dependency-free +adapter without shrinking. + +## Reference + +### Exports + +The fast-check-backed entry points and helpers: + +| Export | Description | +| --- | --- | +| `propertyTest(source, options)` | Runs a random-sequence campaign. Resolves with `{ coverage }`. | +| `testPaths(source, options?)` | Runs generated paths. Resolves with `{ coverage, results }`. | +| `generateTestSuite(source, options)` | Records an offline suite from a passing campaign. | +| `pick(select, toPayload?)` | An event case that picks its payload from the current snapshot, with a fast-check index. | +| `createFailureDatabase(options?)` | The file-system store behind the `failures` option. | +| `fastCheckAdapter(options?)` | The fast-check `TestAdapter`. | +| `extractReplayPath(counterexample)` | Reads `replayPath` from a raw `fc.commands()` counterexample. | +| `eventsFromSchemas(machine, options?)` | Derives the `events` map from `schemas.events`. | +| `arbitraryFromSchema(schema, options?)` | Converts one Zod schema to an arbitrary. | +| `mergeEventGenerators(derived, explicit)` | Merges two `events` maps; explicit entries win. | +| `withScheduledSut(sut)`, `withScheduledReference(reference)` | Route async boundaries through the run's scheduler. | +| `getCurrentScheduler()` | The running `fc.Scheduler`, or `undefined`. | + +`propertyTest()`, `testPaths()`, and `generateTestSuite()` take fast-check +options at the top level, derive events from schemas, and accept +`failures: true`, `{ dir, replay, key }`, or a `TestFailureStore`. + +Replay, reporting, suites, and linearizability: + +| Export | Description | +| --- | --- | +| `replayTest(source, fixture, options)` | Replays a `TestFixture`. | +| `ModelTestFailure`, `ReplayNotReproducedError` | Error classes. | +| `serializeTestTrace(trace)` | Renders a trace as JSON-safe data. | +| `formatTestCoverage`, `formatTestCoverageJUnit`, `formatTestCoverageHTML`, `testCoverageToJSON` | Coverage reports. | +| `formatTestStatistics(coverage)` | The event-case and label distribution `statistics: true` prints. | +| `TestCampaignError` | Thrown when a `sometimes` property or a `reachable` target is never satisfied. | +| `assertTestCoverage(coverage, thresholds)` | Throws when coverage is below thresholds. | +| `replayTestSuite`, `replayTestSuiteFixture`, `describeTestSuite`, `serializeTestSuite`, `parseTestSuite` | Offline suites. | +| `checkLinearizable(history, model, options?)` | Linearizability check. | +| `runParallelPropertyCommands(machine, options)` | Concurrent branches checked for linearizability. | + +Subpath entrypoints: + +| Entrypoint | Exports | +| --- | --- | +| `@xstate/test/playwright` | `createPlaywrightSut`, `PlaywrightOracleError`, and the types `PlaywrightPage`, `PlaywrightSutConfig`, `PlaywrightEventAction`, `PlaywrightMock`, `PlaywrightOracles`, `PlaywrightTestInfo`. | +| `@xstate/test/vitest` | `it` and `test` with `.model` and `.paths`, and `withModelTests`. | +| `@xstate/test/effect-schema` | `eventsFromSchemas` with Effect Schema support, `fromEffectSchema`, `fromEffectSchemas`. | +| `@xstate/test/schema` | `eventsFromSchemas`, `arbitraryFromSchema`, `mergeEventGenerators`. | + +### Shared options + +`propertyTest()`, `testPaths()`, and `generateTestSuite()` accept these: + +| Option | Default | Description | +| --- | --- | --- | +| `events` | `{}` | Event types and their generators. See [Events](#events). | +| `deriveEvents` | `true` | Derives generators for event types with a runtime schema that `events` does not configure. `@xstate/test` only. | +| `sut` | none | The system under test. See [`sut`](#sut). | +| `states` | none | Per-state assertions, run after every stable step. | +| `invariant` | none | `(context) => void`. Throws to fail the step. | +| `temporal` | `[]` | Temporal properties. See [Temporal properties](#temporal-properties). | +| `reachable` | none | State values, `'#id'` state node ids, or tags that at least one run must enter. | +| `failures` | none | Saves failing fixtures and replays them first. `true`, `{ dir?, replay?, key? }`, or a `TestFailureStore`. | +| `statistics` | `false` | Prints `formatTestStatistics(coverage)` after a passing campaign. | +| `reference` | none | A second implementation compared with the model. | +| `mode` | `'pure'` | `'pure'` or `'executed'`. See [Modes](#modes). | +| `actors` | none | Logic substituted for named actor sources. Executed mode only. | +| `outcomes` | none | Invoke sources replaced by stubs, with generators of `{ ok, output }` or `{ ok, error }`. | +| `input` | none | Machine input for every run. | +| `start` | none | `{ snapshot, serializeSnapshot }` to start every run from a snapshot. | +| `target` | none | `(context) => number`, recorded on every stable step for targeted search. | +| `collect` | none | `(trace, { passed, runIndex })`, called after every run. | +| `expectLabels` | none | `{ [label]: { min?, minCount? } }`. Fails the campaign when a label is too rare. | + +The `invariant`, `temporal`, and `target` functions receive a +`TestInvariantContext`: `snapshot`, `previousSnapshot`, `initialSnapshot`, +`event`, `effects` (the actions the step produced), `step`, and `label()`, +`classify()`, and `target()`. + +### `testPaths()` options + +In addition to the shared options: + +| Option | Default | Description | +| --- | --- | --- | +| `pathGenerator` | `'shortest'` | `'shortest'`, `'simple'`, or a custom `PathGenerator`. | +| `paths` | none | Runs these paths instead of generating any. | +| `fromEvents` | none | Runs the single path built from this event sequence. | +| `samples` | `3` | Payloads sampled from each event case and outcome generator. An integer of at least `1`. | +| `seed` | `0` | Sampling seed. Each case samples from its own stream, so adding a case leaves the other cases' payloads unchanged. | +| `limit` | `10_000` | Traversal steps before path generation throws. A context that grows without bound reaches it; merge states with `serializeState` or prune with `stopWhen`. | +| `stopWhen` | none | Stops expanding a state when it returns `true`. | +| `toState` | none | Keeps only paths that end in a matching state. | +| `fromState` | initial state | Starts traversal from this snapshot. | +| `allowDuplicatePaths` | `false` | Keeps paths that are prefixes of longer paths. | +| `serializeState`, `serializeEvent` | built in | Identity functions for traversal. | + +`testPaths()` rejects `commands`. It resolves with `results`, one +`{ path, passed, error }` per path, and sets `coverage.exploration.strategy` +to `'paths'` and `stoppedBecause` to `'paths'`. It throws on the first failing +path. + +After every step, the run's snapshot is compared with the snapshot traversal +planned for that step, using `serializeState`. A run that departs from its +path, such as an event the machine no longer accepts or a service that +resolved on its own, fails with +`Path diverged at step N: expected , got `. + +### `propertyTest()` options + +In addition to the shared options: + +| Option | Default | Description | +| --- | --- | --- | +| `commands` | none | Generators for `advance` (milliseconds), `checkpoint` (`{ label? }`), and `stop` (`{}`) commands. Each may be `{ generate, weight }`. | +| `until` | none | Stop condition. See below. Enables batching. | +| `batchRuns` | `25` | Runs per batch when batching. | +| `maxRuns` | `100` | Total runs when batching. In `@xstate/test`, defaults to `numRuns` when that is set. | +| `frontiers` | none | An array of paths, `{ paths, select?, runsPerFrontier? }`, `'auto'`, `{ strategy: 'uncovered', maxFrontiers?, runsPerFrontier?, limit? }`, or `{ strategy: 'target', maxFrontiers?, runsPerFrontier? }`. | +| `swarm` | `false` | `true`, or `{ minCases?, seed? }`. | +| `adapter` | fast-check | Replaces the generator engine. | + +Without `until` and without `frontiers: 'auto'` or `{ strategy: 'target' }`, +the adapter runs once with its own `numRuns`. + +`until` is a function `(coverage) => boolean`, or an object in which every +key must hold: + +| Key | Holds when | +| --- | --- | +| `stateNodes`, `transitions`, `transitionPairs`, `requirements` | `covered / (covered + uncovered)` is at least the value. | +| `eventCases` | The share of event cases executed at least once is at least the value. | +| `runs` | At least this many runs completed. | +| `timeMs` | At least this many milliseconds elapsed. | +| `any` | At least one of the listed conditions holds. | + +`frontiers` defaults: `maxFrontiers` is `5`, `runsPerFrontier` is an even +split of the batch, and `limit` is `1000`. `swarm` defaults: `minCases` is +half the declared cases, rounded up, and `seed` is `0`. + +### fast-check options + +`propertyTest()` and `generateTestSuite()` from `@xstate/test` pass these +options to fast-check: + +| Option | Description | +| --- | --- | +| `seed`, `path`, `replayPath` | Reproduce a run. `replayPath` is the `fc.commands()` replay path. | +| `numRuns` | Runs per adapter call. fast-check defaults to `100`. | +| `maxCommands` | Maximum generated commands per run. | +| `scheduler` | `true` or `{ act }`. See [Test concurrency](#test-concurrency). | +| `endOnFailure`, `interruptAfterTimeLimit`, `markInterruptAsFailure`, `skipAllAfterTimeLimit`, `timeout`, `maxSkipsPerRun` | Run limits. | +| `reporter`, `asyncReporter` | Called with fast-check's run details after every adapter run: once per campaign, or once per batch with `until` or `frontiers`. | +| `verbose`, `includeErrorInReport` | With `verbose` set to `1` (or `true`) or above, the failure message ends with fast-check's report, `fc.defaultReportMessage()`. | +| `randomType`, `unbiased`, `skipEqualValues`, `ignoreEqualValues`, `plugins` | Generation. | + +### `sut` + +`TestSut`: + +| Member | Description | +| --- | --- | +| `create(context)` | Creates a session for one run. `context` has `logic`, `input`, `snapshot` (the start snapshot, if any), `label`, `classify`, and `target`. | +| `projectModel(snapshot)` | Projects the model snapshot to compare with `read()`. | +| `projectSut(observed)` | Normalizes the value from `read()`. Defaults to identity. | +| `equivalent(model, observed)` | Compares the projections. Defaults to structural deep equality. | +| `complete({ passed, failure })` | Called once when the campaign ends, after every session was disposed. `failure` is the error the campaign throws. | + +`TestSutSession`, returned by `create()`: + +| Member | Description | +| --- | --- | +| `send(event, context)` | Performs the event. `context.snapshot` is the model snapshot after the event. `context.case` is `{ type, name }` for generated events. | +| `read()` | Reads the observable state for comparison. | +| `states` | Per-state assertions, `(snapshot, session) => void`. Replaces the top-level `states`. | +| `settle()` | Waits for quiescence before each comparison. | +| `advance(ms)` | Advances the SUT's clock and returns the events that fired. | +| `checkpoint(label?)` | Handles a `checkpoint` command. | +| `stop()` | Handles a `stop` command. | +| `check()` | Runs after every stable step, after the comparison. Throws to fail the step with `SUT check failed after N steps`. | +| `dispose({ passed, failure })` | Tears the session down at the end of the run. `failure` is the run's `ModelTestFailure`, when an oracle failed. | + +`reference` has the same structure: `create()` returns +`{ transition(event), read(), stop?, dispose? }`, and `projectModel` is +required. + +### Temporal properties + +Each property has a `type`, an `id`, and an optional `description`, and is +checked on every stable step: + +| `type` | Fields | Fails when | +| --- | --- | --- | +| `always` | `predicate` | `predicate` is false on some step. | +| `never` | `predicate` | `predicate` is true on some step. | +| `eventually` | `predicate`, `within?` | `predicate` is not true within `within` steps, or before the run ends. | +| `until` | `hold`, `until`, `within?` | `hold` stops holding before `until` holds, or `until` does not hold within `within` steps or before the run ends. | +| `respond` | `trigger`, `response`, `within?` | A step on which `trigger` holds is not followed by a step on which `response` holds within `within` steps, or before the run ends. The response may hold on the trigger step. | +| `sometimes` | `predicate` | `predicate` holds on no step of any run. Checked when the campaign ends. | + +With `within`, a run that ends before `within` steps is **inconclusive**, not +failed. An id that is inconclusive in every run and satisfied in none is +listed in `coverage.temporal.inconclusive`. + +### Coverage + +`TestCoverage`: + +| Field | Description | +| --- | --- | +| `states`, `stateNodes`, `configurations`, `statuses`, `eventTypes`, `transitions`, `frontiers` | `TestCoverageDimension`: `counts`, `covered`, `uncovered`, `unreachable`, `unknown`. | +| `transitionPairs` | A dimension of `" -> "` ids plus `truncated`. Only pairs of transitions with static targets are declared up front, up to 2,000; a pair involving a transition whose target is computed by a function appears once a run takes it. | +| `requirements` | A dimension of `meta.requirements` ids plus `sources`, the state nodes and transitions that declare each id. | +| `eventCases` | `{ [caseId]: { weight, generated, applicable, executed, ignored } }`. | +| `labels` | `{ [name]: { count, values, share } }`. `share` is the fraction of attempted runs that recorded the label. Shrink attempts are not counted. | +| `temporal` | `satisfied`, `failed`, and `inconclusive` property ids; `counts`, `{ [id]: { satisfied, failed, inconclusive } }` in runs; and `warnings` for bounds that can never fail. | +| `exploration` | `TestExplorationBounds`. See below. | +| `runs`, `steps`, `skipped`, `prefixSteps`, `generatedSteps`, `invariantChecks`, `temporalChecks`, `clockAdvances`, `checkpoints`, `stops`, `sutComparisons`, `oracleComparisons` | Counters. | + +`exploration`: + +| Field | Description | +| --- | --- | +| `strategy` | `'property'` or `'paths'`. | +| `pathCount`, `pathGenerator` | Paths only. | +| `mode` | `'pure'` or `'executed'`. | +| `configuredRuns`, `completedRuns`, `attemptedRuns` | `attemptedRuns` includes shrink attempts. | +| `shrinkRuns` | Runs started after the first failing run, while the counterexample was shrunk. | +| `maximumSequenceLength`, `maximumObservedSequenceLength` | Configured and observed sequence lengths. | +| `frontiers`, `seeds` | Per-frontier budgets, and the adapter seeds and paths used. | +| `swarm` | `{ runs, averageEnabled }`, or `null`. | +| `target` | `{ best, label, improvements }`. `best` is `-Infinity` when unused. | +| `stoppedBecause` | `'until'`, `'budget'`, `'failure'`, `'paths'` (`testPaths()` ran every path), or `'replay'` (`failures.replay` was `'only'`). | +| `truncated`, `truncationReasons` | Why exploration was cut short. | +| `pendingActorSteps` | Executed-mode steps that settled while an invoked or spawned actor's asynchronous work was still in flight. Those timeline entries list the actors in `pendingActors`. | + +Add requirement ids with `meta.requirements` (a string or an array) on state +nodes and transitions. A requirement is covered when any state node or +transition that declares it is covered. + +### `ModelTestFailure` + +| Field | Description | +| --- | --- | +| `summary` | The short message, such as `Property observation diverged`. `testPaths()` prefixes it with the failing path: `Path 2 (ADD → REMOVE) failed: …`. | +| `message` | `summary` and the cause's message; a `Reproduce:` line with the fast-check `seed`, `path`, and `replayPath`; a `Fixture:` line when `fixture` is set; `Shrunk N time(s)` when fast-check shrank the counterexample; `Saved: ` when `failures` saved it; then the trace, one line per entry, and fast-check's report when `verbose` is set. | +| `trace` | `TestTrace`: `start`, `initialSnapshot`, `timeline`, `events`, `commands`, `steps`, `finalSnapshot`, `finalObservation`, `swarm`, `mode`, `outcomes`. | +| `cause` | The error thrown by the oracle or the SUT. | +| `fixture` | A `TestFixture` for `replayTest()`. | +| `replay` | fast-check metadata: `engine`, `engineVersion`, `seed`, `path`, `replayPath`, `numShrinks`, `data`. | +| `coverage` | Coverage up to the failure. | + +`trace.timeline` entries have a `kind`: `'event'`, `'command'` (`advance`, +`checkpoint`, `outcome`, `stop`), or, in executed mode, `'actorEvent'` for a +transition the actor system made on its own. + +The trace in `message` has one line per entry: +`N. -> `. The origin is `generator`, `prefix`, or +`clock` for sent events, `timer` for `xstate.after` events and `advance` +commands, `outcome` for invoke results, and `actor()` for a child actor's +own transition. `` is `formatSnapshot(snapshot)`, which defaults to +`{ value, context }`; pass `formatSnapshot` to `propertyTest()`, +`testPaths()`, or `replayTest()` to print something else. A step whose SUT or +reference observation differs from the model adds `model:` and `observed:` +lines. + +### `TestFixture` + +```ts +interface TestFixture { + formatVersion: 2; + machine?: { id?: string; version?: string }; + start: { type: 'input'; input: unknown } | { type: 'snapshot'; snapshot: unknown }; + timeline: { kind: 'event' | 'command'; command: TestCommand }[]; + failedAt?: number; // absent on fixtures from passing runs + temporalFailure?: { type; id; description?; within?; atStep: number }; + swarm?: string[]; + mode?: 'pure' | 'executed'; + outcomes?: { src: string; occurrence: number; outcome: TestActorOutcome }[]; + stubs?: string[]; // invoke sources the run stubbed, resolved or not +} +``` + +Errors in commands and outcomes are recorded as +`{ xstate$$error: true, name, message }`, since `JSON.stringify()` turns an +`Error` into `{}`. `replayTest()` turns them back into `Error` objects. + +A `TestCommand` is `{ type: 'event', event, phase, origin, caseId? }`, +`{ type: 'advance', milliseconds, deliveredEvents }`, +`{ type: 'checkpoint', label? }`, `{ type: 'outcome', src, outcome }`, or +`{ type: 'stop' }`. Events delivered by a SUT clock appear twice: in the +`advance` command's `deliveredEvents`, and as the following `event` entries +with `origin: 'clock'`. `replayTest()` rejects a fixture in which the two +disagree. + +### `replayTest()` + +`replayTest(source, fixture, options)` resolves with the replayed `TestTrace`. + +| Option | Default | Description | +| --- | --- | --- | +| `expect` | `'failure'` | `'failure'` stops at `failedAt` and throws the reproduced failure, or `ReplayNotReproducedError`. `'pass'` replays everything and lets any failure through. | +| `invariant`, `temporal`, `sut`, `reference`, `states` | none | The oracles to replay against. | +| `mode` | the fixture's mode | `'executed'` replays against a real actor with recorded outcomes stubbed. | +| `actors` | none | Logic to provide before replaying. Executed mode only. | +| `restoreSnapshot` | none | Required for fixtures that start from a snapshot. | + +### `TestSuite` + +`{ formatVersion: 1, machineId?, machineVersion?, generatedAt?, fixtures, coverage }`, +where `coverage` is `testCoverageToJSON()` of the whole campaign. +`generateTestSuite()` takes the `propertyTest()` options plus: + +| Option | Default | Description | +| --- | --- | --- | +| `select` | `'minimal'` | `'minimal'` keeps the smallest greedy subset of traces that preserves the covered set. `'all'` keeps every distinct trace. | +| `maxFixtures` | none | Upper bound on fixtures. | +| `generatedAt` | none | Recorded as-is. Omit it to keep the file byte-stable. | + +### `TestAdapter` + +`TestAdapter.run(request)` receives: + +| Field | Description | +| --- | --- | +| `events` | `{ type, caseId, generator, weight }` per event case. | +| `commands` | `{ type, generator, weight, src? }` per configured command. `type` is `'advance'`, `'checkpoint'`, `'stop'`, or `'outcome'`; `src` is set for `'outcome'`. | +| `runBudget` | Runs to use, when a frontier or batch fixes it. | +| `runOffset` | Runs completed by earlier batches. Offset a fixed seed by it. | +| `createEvent(type, payload)` | Builds a typed event. | +| `createRunner()` | Creates a `PropertyScenarioRunner` for one run or shrink attempt. | + +Each run: + +1. `createRunner()`, then `await runner.start()`. +2. For each step: an event (`runner.canRunGenerated(type, generated, caseId)`, + then `await runner.runGenerated(type, generated, caseId)`), a command + (`runner.canRunCommand(true)`, then `advance(ms)`, `checkpoint(label)`, or + `stop()`), or an outcome (`runner.canRunOutcome()`, then + `outcome(src, outcome)`). +3. `runner.finish()`. +4. `await runner.dispose()`, always. + +`run()` resolves with `{ runs, exploration, error?, replay? }`. +`exploration` has `configuredRuns`, `maximumSequenceLength`, and optionally +`engine`, `seed`, `path`, `truncated`, and `truncationReasons`. + +### `eventsFromSchemas()` + +`eventsFromSchemas(machine, options?)`: + +| Option | Default | Description | +| --- | --- | --- | +| `eventsWithoutSchema` | `'empty'` | `'empty'` generates `{}` for handled event types with no schema. `'skip'` leaves them out. | +| `fallback` | none | `(schema, path) => arbitrary \| undefined` for unrecognized schemas. | + +Supported Zod (v3 and v4) kinds: `object`, `interface`, `string`, `number`, +`int`, `bigint`, `boolean`, `date`, `literal`, `enum`, `nativeEnum`, `union`, +`array`, `set`, `tuple`, `record`, `optional`, `nullable`, `default`, +`prefault`, `catch`, `readonly`, `nonoptional`, `lazy`, `null`, `undefined`, +`void`, `any`, and `unknown`. Mapped checks: lengths, numeric ranges, `int`, +`multipleOf`, `email`, `uuid`, `url`, `regex`, `startsWith`, `endsWith`, +`includes`, `trim`, `toLowerCase`, and `toUpperCase`. An unsupported kind or +check, a recursive schema, a string with two formats, or a schema that no value +satisfies throws an error naming the schema path, such as `'SET.when'`. A +`type` field in a generated payload is removed. + +A handled event type without its own schema key uses the schema of the first +wildcard key it matches, such as `'user.*'`, in both `eventsWithoutSchema` +modes. + +### `createPlaywrightSut()` + +`createPlaywrightSut(page, config)` returns a `TestSut`. `page` is any object +with the parts of Playwright's `Page` the configuration uses; a real `Page` is +assignable. + +| Option | Default | Description | +| --- | --- | --- | +| `events` | required | `(page, event) => void` per event type. | +| `read` | none | Projects the page to a value comparable with `projectModel`. | +| `projectModel` | none | Projects the model snapshot. | +| `states` | none | `(page, snapshot) => void` per state key. | +| `projectSut` | identity | Normalizes the value from `read`. | +| `equivalent` | deep equality | Compares the projections. | +| `settle` | `page.waitForLoadState('load')`, then a microtask flush | Runs before each comparison. | +| `advance` | `page.clock.runFor(ms)` | Handles `advance` commands. May return delivered events. | +| `checkpoint` | screenshot | Writes `/