xstate 6.0.0-beta.1 → 6.0.0-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/{createActor-cbe3abac.esm.js → createActor-49ea55ba.esm.js} +259 -47
- package/dist/{createActor-25900f76.cjs.js → createActor-73aa92ba.cjs.js} +261 -46
- package/dist/{createActor-551369be.development.esm.js → createActor-a085b20b.development.esm.js} +260 -48
- package/dist/{createActor-a49ae0ce.development.cjs.js → createActor-dfb6b790.development.cjs.js} +262 -47
- package/dist/declarations/src/createActor.d.ts +3 -1
- package/dist/declarations/src/createMachine.d.ts +6 -3
- package/dist/declarations/src/durable/index.d.ts +43 -8
- package/dist/declarations/src/effectDescriptor.d.ts +2 -2
- package/dist/declarations/src/fsm.d.ts +7 -7
- package/dist/declarations/src/machineVersion.types.d.ts +2 -2
- package/dist/declarations/src/setup.d.ts +2 -2
- package/dist/declarations/src/systemTransition.d.ts +1 -1
- package/dist/declarations/src/types.d.ts +4 -2
- package/dist/declarations/src/types.v6.d.ts +37 -2
- package/dist/{effectDescriptor-2fa27c54.cjs.js → effectDescriptor-3402f63e.cjs.js} +5 -5
- package/dist/{effectDescriptor-d8b0f749.esm.js → effectDescriptor-65821048.development.esm.js} +5 -5
- package/dist/{effectDescriptor-321a8ce9.development.esm.js → effectDescriptor-72c62058.esm.js} +5 -5
- package/dist/{effectDescriptor-f73da4ec.development.cjs.js → effectDescriptor-d0ea44ad.development.cjs.js} +5 -5
- package/dist/{machineSchemas-b5736804.development.esm.js → legacySnapshot-11aba2d2.development.esm.js} +117 -3
- package/dist/{machineSchemas-6d96bef4.development.cjs.js → legacySnapshot-2e2c1d3b.development.cjs.js} +118 -2
- package/dist/{machineSchemas-88d01821.cjs.js → legacySnapshot-a85dfbe2.cjs.js} +117 -1
- package/dist/{machineSchemas-45c21bc2.esm.js → legacySnapshot-fffe81a0.esm.js} +116 -2
- package/dist/xstate-actors.cjs.js +30 -5
- package/dist/xstate-actors.development.cjs.js +30 -5
- package/dist/xstate-actors.development.esm.js +31 -6
- package/dist/xstate-actors.esm.js +31 -6
- package/dist/xstate-actors.umd.min.js +1 -1
- package/dist/xstate-actors.umd.min.js.map +1 -1
- package/dist/xstate-durable.cjs.js +120 -10
- package/dist/xstate-durable.development.cjs.js +120 -10
- package/dist/xstate-durable.development.esm.js +120 -10
- package/dist/xstate-durable.esm.js +120 -10
- package/dist/xstate-durable.umd.min.js +1 -1
- package/dist/xstate-durable.umd.min.js.map +1 -1
- package/dist/xstate-fsm.cjs.js +61 -31
- package/dist/xstate-fsm.development.cjs.js +61 -31
- package/dist/xstate-fsm.development.esm.js +61 -31
- package/dist/xstate-fsm.esm.js +61 -31
- package/dist/xstate-fsm.umd.min.js +1 -1
- package/dist/xstate-fsm.umd.min.js.map +1 -1
- package/dist/xstate-graph.cjs.js +1 -1
- package/dist/xstate-graph.development.cjs.js +1 -1
- package/dist/xstate-graph.development.esm.js +2 -2
- package/dist/xstate-graph.esm.js +2 -2
- package/dist/xstate-graph.umd.min.js +1 -1
- package/dist/xstate-graph.umd.min.js.map +1 -1
- package/dist/xstate-persist.cjs.js +23 -12
- package/dist/xstate-persist.development.cjs.js +23 -12
- package/dist/xstate-persist.development.esm.js +17 -6
- package/dist/xstate-persist.esm.js +17 -6
- package/dist/xstate-persist.umd.min.js +1 -1
- package/dist/xstate-persist.umd.min.js.map +1 -1
- package/dist/xstate-validation.cjs.js +1 -1
- package/dist/xstate-validation.development.cjs.js +1 -1
- package/dist/xstate-validation.development.esm.js +1 -1
- package/dist/xstate-validation.esm.js +1 -1
- package/dist/xstate.cjs.js +86 -56
- package/dist/xstate.development.cjs.js +86 -56
- package/dist/xstate.development.esm.js +76 -46
- package/dist/xstate.esm.js +76 -46
- package/dist/xstate.umd.min.js +1 -1
- package/dist/xstate.umd.min.js.map +1 -1
- package/docs/actor-logic.md +1 -1
- package/docs/api-stability.json +335 -305
- package/docs/backend-workflows.md +3 -3
- package/docs/durable-execution.md +72 -48
- package/docs/errors.md +2 -2
- package/docs/examples.md +34 -34
- package/docs/faq.md +1 -1
- package/docs/fsm.md +54 -10
- package/docs/guards.md +1 -1
- package/docs/index.md +2 -1
- package/docs/inspect-actor-systems.md +20 -3
- package/docs/inspection.md +5 -1
- package/docs/invoke.md +36 -4
- package/docs/migrate-inspector.md +141 -0
- package/docs/persistence.md +16 -10
- package/docs/serialization.md +1 -1
- package/docs/setup-and-provide.md +3 -3
- package/docs/spawn.md +1 -1
- package/docs/system-transitions.md +8 -6
- package/docs/transitions.md +5 -1
- package/docs/tutorial.md +5 -5
- package/docs/typescript.md +9 -0
- package/docs/xstate-v5-to-v6.md +23 -21
- package/package.json +1 -1
package/docs/invoke.md
CHANGED
|
@@ -112,7 +112,7 @@ const machine = s.createMachine({
|
|
|
112
112
|
|
|
113
113
|
Keep the helper call inline: its enclosing state supplies narrowed context, ancestor context, state input and transition targets. In this example, `context.userId` is `string` and `event.output` is `{ name: string }`.
|
|
114
114
|
|
|
115
|
-
For an async `src`, `schemas.input` types the actor input, `schemas.output` checks the function's resolved value and types `onDone.event.output`, and `schemas.error` types `onError.event.error`. Omit the output schema to infer output from the async return value. The function receives `{ input, signal, self, system }` and the async enqueue object, including `emit` and `step`,
|
|
115
|
+
For an async `src`, `schemas.input` types the actor input, `schemas.output` checks the function's resolved value and types `onDone.event.output`, and `schemas.error` types `onError.event.error`. Omit the output schema to infer output from the async return value. The function receives `{ input, signal, self, system }` and the async enqueue object, including `emit` and `step`, as `createAsyncLogic` does. Its input comes from the invoke's static value or input mapper; parent context stays in the mapper and transition handlers.
|
|
116
116
|
|
|
117
117
|
You can also pass an existing actor logic value, including machine and callback logic:
|
|
118
118
|
|
|
@@ -124,6 +124,14 @@ invoke: s.createInvoke({
|
|
|
124
124
|
})
|
|
125
125
|
```
|
|
126
126
|
|
|
127
|
+
A bare inline invoke such as `{ src: loadUserLogic, onDone }` cannot correlate
|
|
128
|
+
that specific logic with its completion output. With no registered actor
|
|
129
|
+
sources, its `onDone.event.output` is `unknown`, so TypeScript requires
|
|
130
|
+
narrowing before it can be used. For a typed output, use
|
|
131
|
+
`s.createInvoke({ src: loadUserLogic, onDone })` as above, or register the logic
|
|
132
|
+
in `setup({ actors: { loadUserLogic } })` and invoke it with
|
|
133
|
+
`src: 'loadUserLogic'`. Prefer one of these typed forms when generating code.
|
|
134
|
+
|
|
127
135
|
For a logic value, its own schemas determine input, output, error and snapshot types. Declare schemas on that logic rather than repeating them on the invoke.
|
|
128
136
|
|
|
129
137
|
The helper requires `input` when the source's input type excludes `undefined`. Pass a static value or a mapper returning that input type. Logic that accepts `undefined` can omit `input`.
|
|
@@ -146,9 +154,9 @@ Invoked actors belong to the state that starts them:
|
|
|
146
154
|
- leaving the state stops it
|
|
147
155
|
- re-entering the state stops the old actor and starts a new one
|
|
148
156
|
|
|
149
|
-
A state is re-entered by an external transition back to itself, or by a transition with `reenter: true`. A transition that stays inside the invoking state does not restart the child.
|
|
157
|
+
A state is re-entered by an external transition back to itself, or by a targeted transition with `reenter: true`. A transition that stays inside the invoking state does not restart the child. Targetless transitions do not restart the child, even with `reenter: true`.
|
|
150
158
|
|
|
151
|
-
Invoke on the machine root runs for the whole lifetime of the actor. Root invocations survive ordinary transitions between top-level states, and restart only on a root [transition](transitions.md) with `reenter: true`.
|
|
159
|
+
Invoke on the machine root runs for the whole lifetime of the actor. Root invocations survive ordinary transitions between top-level states, and restart only on a root [transition](transitions.md) with an explicit target and `reenter: true`.
|
|
152
160
|
|
|
153
161
|
```ts
|
|
154
162
|
const machine = createMachine({
|
|
@@ -306,7 +314,31 @@ Invoke also is not the right tool when the child must outlive the state, or when
|
|
|
306
314
|
|
|
307
315
|
Provide named actor logic through `setup({ actors })` or `createMachine({ actors })`. XState correlates `src` with `input`, so a static or mapped input is checked against that logic's input type, and `onDone` sees the output type of that logic.
|
|
308
316
|
|
|
309
|
-
|
|
317
|
+
For a literal invoke `id` and a named or inline actor source, XState infers the
|
|
318
|
+
child reference in `snapshot.children`. The child may be absent when the invoke
|
|
319
|
+
state is inactive, so check for `undefined` before sending an event:
|
|
320
|
+
|
|
321
|
+
```ts
|
|
322
|
+
import { createActor, setup, types } from 'xstate';
|
|
323
|
+
|
|
324
|
+
const paymentMachine = setup({
|
|
325
|
+
schemas: { events: { retry: types<{}>() } }
|
|
326
|
+
}).createMachine({ initial: 'idle', states: { idle: {} } });
|
|
327
|
+
|
|
328
|
+
const parent = setup({ actors: { paymentMachine } }).createMachine({
|
|
329
|
+
invoke: { id: 'payment', src: 'paymentMachine' }
|
|
330
|
+
});
|
|
331
|
+
|
|
332
|
+
const payment = createActor(parent).getSnapshot().children.payment;
|
|
333
|
+
payment?.send({ type: 'retry' });
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
Declare child ids with `schemas.children` when the child contract must also be
|
|
337
|
+
available inside machine callbacks. This also checks that each declared `id`
|
|
338
|
+
receives compatible logic. For dynamic IDs, keep the returned child reference
|
|
339
|
+
from `enq.spawn(...)` in context instead of indexing `snapshot.children` with
|
|
340
|
+
an arbitrary string. Spawned children have a separately managed lifetime; see
|
|
341
|
+
[Spawn](spawn.md):
|
|
310
342
|
|
|
311
343
|
```ts
|
|
312
344
|
setup({}).createMachine({
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
---
|
|
2
|
+
title: Migrate to SDK inspection
|
|
3
|
+
description: Replace legacy Stately Inspect integrations with the Stately SDK.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
Use `@statelyai/sdk/inspect` for visual inspection with XState v6. The SDK accepts XState v5 and v6 inspection events. The legacy `@statelyai/inspect` package remains available for existing XState v5 integrations.
|
|
7
|
+
|
|
8
|
+
The SDK is not a drop-in replacement. Check the options and transport changes below before removing the legacy package. This guide describes `@statelyai/sdk` 0.48.0.
|
|
9
|
+
|
|
10
|
+
## Install and connect
|
|
11
|
+
|
|
12
|
+
```bash
|
|
13
|
+
npm install @statelyai/sdk
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Replace the browser factory with the SDK factory:
|
|
17
|
+
|
|
18
|
+
```ts
|
|
19
|
+
// Before: XState v5
|
|
20
|
+
import { createBrowserInspector } from '@statelyai/inspect';
|
|
21
|
+
|
|
22
|
+
const inspector = createBrowserInspector();
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
// After: XState v6
|
|
27
|
+
import { createActor } from 'xstate';
|
|
28
|
+
import { createInspector } from '@statelyai/sdk/inspect';
|
|
29
|
+
import { machine } from './machine';
|
|
30
|
+
|
|
31
|
+
const inspector = createInspector();
|
|
32
|
+
const actor = createActor(machine, { inspect: inspector.inspect });
|
|
33
|
+
actor.start();
|
|
34
|
+
|
|
35
|
+
await inspector.ready;
|
|
36
|
+
console.log(inspector.inspectorUrl);
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
The SDK connects to the hosted relay without an API key. `inspector.ready` resolves after relay registration and the initial-state flush. Open `inspector.inspectorUrl` after it resolves. If you supply a custom transport, the URL is `null` and your transport controls the viewer connection.
|
|
40
|
+
|
|
41
|
+
The SDK's `inspect` property is a callback. Pass it directly to `createActor` instead of calling the legacy observer's `inspect.next(...)` method. To inspect an actor that already exists, call `inspector.attach(actor)`.
|
|
42
|
+
|
|
43
|
+
The SDK has no XState peer dependency restriction, but currently depends on XState v5 internally. An application using XState v6 can have both versions installed.
|
|
44
|
+
|
|
45
|
+
## Open the viewer
|
|
46
|
+
|
|
47
|
+
The SDK does not open a popup automatically. In a browser, expose `inspector.inspectorUrl` as a link after `inspector.ready` resolves. Let the user open it from a click or another user gesture.
|
|
48
|
+
|
|
49
|
+
In Node, request automatic browser launch:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { createInspector } from '@statelyai/sdk/inspect';
|
|
53
|
+
|
|
54
|
+
const inspector = createInspector({ launch: 'browser' });
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`launch: 'browser'` is supported from Node, not from a browser runtime.
|
|
58
|
+
|
|
59
|
+
## Include selected context
|
|
60
|
+
|
|
61
|
+
The default snapshot serializer sends `value`, `status`, and available tags. It omits context. Use `serializeSnapshot` to include fields that your viewer needs:
|
|
62
|
+
|
|
63
|
+
```ts
|
|
64
|
+
import { createInspector } from '@statelyai/sdk/inspect';
|
|
65
|
+
|
|
66
|
+
const inspector = createInspector({
|
|
67
|
+
serializeSnapshot: (snapshot) => {
|
|
68
|
+
const context = snapshot.context;
|
|
69
|
+
const orderId =
|
|
70
|
+
context !== null &&
|
|
71
|
+
typeof context === 'object' &&
|
|
72
|
+
'orderId' in context &&
|
|
73
|
+
typeof context.orderId === 'string'
|
|
74
|
+
? context.orderId
|
|
75
|
+
: undefined;
|
|
76
|
+
|
|
77
|
+
return {
|
|
78
|
+
value: snapshot.value,
|
|
79
|
+
status: snapshot.status,
|
|
80
|
+
tags: snapshot.tags ? Array.from(snapshot.tags) : [],
|
|
81
|
+
context: { orderId }
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Return JSON-serializable data. Avoid sending actor references, DOM nodes, credentials, or personal data. This serializer controls snapshots only; it does not redact event payloads or machine definitions.
|
|
88
|
+
|
|
89
|
+
## Disconnect inspection
|
|
90
|
+
|
|
91
|
+
Replace the legacy `inspector.stop()` teardown call with:
|
|
92
|
+
|
|
93
|
+
```ts
|
|
94
|
+
inspector.destroy();
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
This closes inspection and its subscriptions. It does not stop the application actors. The SDK's `stop(actorId)` method marks a manually inspected actor as stopped; it is not a teardown method. The SDK has no equivalent of the legacy `autoStart: false` and `start()` lifecycle.
|
|
98
|
+
|
|
99
|
+
## Migrate manual inspection
|
|
100
|
+
|
|
101
|
+
Both packages support manual actors, events, and snapshots, but actor registration has a different shape:
|
|
102
|
+
|
|
103
|
+
```ts
|
|
104
|
+
// Before
|
|
105
|
+
inspector.actor('request', { status: 'active' }, { parentId: 'server' });
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```ts
|
|
109
|
+
// After
|
|
110
|
+
inspector.actor('request', {
|
|
111
|
+
snapshot: { status: 'active' },
|
|
112
|
+
parent: 'server'
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Pass actor IDs as strings. Replace actor-reference arguments with their corresponding manual IDs. Map a legacy `definition` to the SDK's `machine` option, and provide a machine config or source string rather than assuming the old serialized definition is accepted.
|
|
117
|
+
|
|
118
|
+
`inspector.snapshot(id, snapshot, event)` takes the triggering event directly as its third argument. The legacy API takes `{ event }` there. `inspector.event(id, event, { source })` continues to accept a source, but the SDK expects the source actor's ID as a string.
|
|
119
|
+
|
|
120
|
+
## Check unsupported options and transports
|
|
121
|
+
|
|
122
|
+
| Legacy API | SDK migration |
|
|
123
|
+
| --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
124
|
+
| `createInspector(adapter, options)` | `createInspector(options)` has a different signature. A custom SDK `transport` must implement the SDK transport interface. |
|
|
125
|
+
| `createWebSocketInspector({ url })` | Use `createInspector({ url })` with a compatible SDK relay. The SDK `url` is a relay URL, not a viewer URL. |
|
|
126
|
+
| `createInspectorServer` from `@statelyai/inspect/server` | For local inspection, use `createNodeInspectionRelay` from `@statelyai/sdk/node-relay`. Install its `ws` peer dependency and start the relay before connecting. |
|
|
127
|
+
| `createBrowserReceiver`, `createWebSocketReceiver` | There are no matching SDK exports. Keep the legacy receiver until its integration supports the SDK protocol. |
|
|
128
|
+
| `iframe`, custom `window`, browser `send` override | There is no equivalent option on the SDK inspector factory. Keep the legacy integration until the viewer integration is migrated. |
|
|
129
|
+
| `filter`, `serialize`, `sanitizeEvent`, `sanitizeContext` | There are no matching SDK options. `serializeSnapshot` only controls snapshots. Keep the legacy integration if it requires event filtering or sanitization that has not been replaced. |
|
|
130
|
+
| `maxDeferredEvents`, `serializationDepthLimit` | There are no matching SDK options. Do not pass them and assume they take effect. |
|
|
131
|
+
| `createSkyInspector({ apiKey })` | The SDK has an `apiKey` option for hosted session ownership, but it uses a different session and transport protocol. Migrate the hosted integration explicitly. |
|
|
132
|
+
|
|
133
|
+
The legacy popup, WebSocket receiver, and local bridge exchange legacy inspection messages. SDK relays exchange room and producer messages. Changing the package name or server URL does not make these protocols compatible.
|
|
134
|
+
|
|
135
|
+
After migrating and verifying your integration, remove `@statelyai/inspect` if no other code uses it:
|
|
136
|
+
|
|
137
|
+
```bash
|
|
138
|
+
npm uninstall @statelyai/inspect
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
See [Inspect actor systems](inspect-actor-systems.md) for the v6 inspection workflow and [Inspection](inspection.md) for XState's event types.
|
package/docs/persistence.md
CHANGED
|
@@ -25,6 +25,12 @@ const restored = restoreActor(
|
|
|
25
25
|
).start();
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
+
In Vue, keep a machine passed to `restoreActor` out of deep reactive state.
|
|
29
|
+
Store it in `shallowRef(machine)` or create it with `markRaw(machine)`. XState
|
|
30
|
+
also accepts a reactive Proxy around a machine, but a raw machine avoids
|
|
31
|
+
wrapping its state nodes and is the recommended way to hold actor logic in Vue.
|
|
32
|
+
See [Vue input and restored snapshots](https://stately.ai/docs/xstate/v6/vue/input-and-snapshots).
|
|
33
|
+
|
|
28
34
|
Pass `system` (a `createSystem()` result) to restore the actor into that system.
|
|
29
35
|
|
|
30
36
|
A restored snapshot is opaque: restoring runs no transitions and re-executes no actions. `always` transitions and choice states in the restored configuration are not re-evaluated until the next event, even if their guards would now pass. Development builds warn when the restored state has eventless transitions.
|
|
@@ -47,11 +53,11 @@ By default a persisted snapshot embeds each child's persisted state, producing a
|
|
|
47
53
|
const persisted = actor.getPersistedSnapshot({ embedChildren: false });
|
|
48
54
|
```
|
|
49
55
|
|
|
50
|
-
The option applies to the whole tree, not to a single placement boundary. Persisting by address requires each child to have a registered source key (a string `src`); `spawn(actors.worker)`, `enq.spawn(actors.worker)` and `enq.spawn('worker')` retain that key, while inline actor logic cannot be referenced by address. The string form makes the exact identity explicit when aliases share logic. Restoring an address-only child produces a location-transparent handle: sends to it route through the [system runtime](durable-execution.md), and its snapshot exposes lifecycle only, since a full snapshot is the last value an actor published and only co-located actors observe it. Install the system runtime before sending to a restored handle
|
|
56
|
+
The option applies to the whole tree, not to a single placement boundary. Persisting by address requires each child to have a registered source key (a string `src`); `spawn(actors.worker)`, `enq.spawn(actors.worker)` and `enq.spawn('worker')` retain that key, while inline actor logic cannot be referenced by address. The string form makes the exact identity explicit when aliases share logic. Restoring an address-only child produces a location-transparent handle: sends to it route through the [system runtime](durable-execution.md), and its snapshot exposes lifecycle only, since a full snapshot is the last value an actor published and only co-located actors observe it. Install the system runtime before sending to a restored handle. Without one, there is no route to the actor it references.
|
|
51
57
|
|
|
52
58
|
Persisted children changed shape in v6: each entry carries an `address` field and either an embedded `snapshot` or a `remote: true` marker. A remote entry may also carry an opaque `incarnation` token, round-tripped verbatim: XState never stamps one, but a host that does gets stale-completion protection on the referencing side and the token on journaled `sendTo` descriptors. Snapshots persisted by v5 or by v6 alphas use other shapes and are not read on restore; discard them or convert them before restoring. See the [migration guide](xstate-v5-to-v6.md#29-names-changed-during-the-v6-prereleases).
|
|
53
59
|
|
|
54
|
-
A timer persisted from a running actor carries its wall-clock start (`scheduledAt`), and restoring the snapshot schedules the remaining time toward the original deadline
|
|
60
|
+
A timer persisted from a running actor carries its wall-clock start (`scheduledAt`), and restoring the snapshot schedules the remaining time toward the original deadline. A timer past due fires immediately. Snapshots produced only by pure transitions carry no timestamp, so restoring one restarts each timer with its declared delay. A [durable execution](durable-execution.md) records timer starts when scheduling effects succeed; await `executeEffects()` before persisting its checkpoint to preserve deadlines. A custom adapter clock must use the same time origin when restoring.
|
|
55
61
|
|
|
56
62
|
For a host-driven durable loop, use `execution.restore(persistedSnapshot)` from
|
|
57
63
|
`xstate/durable`, then `execution.executeEffects(effects)` to resume embedded
|
|
@@ -59,13 +65,13 @@ children and pending timers. Persist `execution.nextTransitionIndex` with the
|
|
|
59
65
|
checkpoint and pass it to the next execution's adapter. See
|
|
60
66
|
[durable checkpoint restoration](durable-execution.md).
|
|
61
67
|
|
|
62
|
-
An actor's address is the `/`-joined path of actor ids from the root, such as `order/worker:0`. It is stable across persistence and restore, unlike `sessionId`, which identifies one incarnation. Generated child ids are recorded in each snapshot's `
|
|
68
|
+
An actor's address is the `/`-joined path of actor ids from the root, such as `order/worker:0`. It is stable across persistence and restore, unlike `sessionId`, which identifies one incarnation. Generated child ids are recorded in each snapshot's `nextActorIds`, so restored actors keep numbering where they left off.
|
|
63
69
|
|
|
64
70
|
## Compatibility
|
|
65
71
|
|
|
66
72
|
A persisted snapshot is a plain JSON-shaped object. Restoring one is lenient: XState reads the fields it knows and does not check a format marker.
|
|
67
73
|
|
|
68
|
-
These envelope fields are stable across 6.x releases: `status`, `value`, `context`, `output`, `error`, `historyValue`, `stateInputs`, `children`, `timers` and `machine`. The [persisted snapshot JSON Schema](https://github.com/statelyai/xstate/blob/next/packages/core/src/persistedSnapshot.schema.json) (draft 2020-12) describes them. Nested machine children carry their own envelope in `children[id].snapshot`. A child entry's `src` is the registered source key the child restores from. A child invoked with inline logic has no `src`; it restores through the invoke definition with its id among the restored active states, and restoring fails when no active state, or more than one, invokes that id.
|
|
74
|
+
These envelope fields are stable across 6.x releases: `status`, `value`, `context`, `output`, `error`, `historyValue`, `stateInputs`, `children`, `timers` and `machine`. The [persisted snapshot JSON Schema](https://github.com/statelyai/xstate/blob/next/packages/core/src/persistedSnapshot.schema.json) (draft 2020-12) describes them. Nested machine children carry their own envelope in `children[id].snapshot`. A child entry's `src` is the registered source key the child restores from. A child invoked with inline logic has no `src`; it restores through the invoke definition with its id among the restored active states, and restoring fails when no active state, or more than one, invokes that id. `nextTimerId` and `nextActorIds` are private. They round-trip verbatim; do not read or write them. No field name in the envelope starts with `$` or `_`, so it can be stored in document databases such as Convex and MongoDB that reserve those prefixes.
|
|
69
75
|
|
|
70
76
|
`timers` is a list of pending timers in scheduling order. A delayed `enq.raise(...)` or `enq.sendTo(...)` entry carries its `id`, or a `seq` number when scheduled without one. Built-in `after` and `timeout` timers have neither; their `event` (`xstate.after`, `xstate.timeout.state` or `xstate.timeout.actor`) identifies them.
|
|
71
77
|
|
|
@@ -95,15 +101,15 @@ In development builds, `getPersistedSnapshot()` warns once per call with the pat
|
|
|
95
101
|
|
|
96
102
|
`Date` values are not reported. `JSON.stringify` writes them as ISO strings, and `JSON.parse` does not turn them back into `Date` objects. Convert them on restore if your context needs `Date` instances.
|
|
97
103
|
|
|
98
|
-
Actor refs in `context` persist as `{
|
|
104
|
+
Actor refs in `context` persist as `{ '@actor': address }` and are not reported. A ref that names one of the snapshot's children restores to that child.
|
|
99
105
|
|
|
100
|
-
|
|
106
|
+
`@actor` is a reserved key in persisted context. On restore, any object in `context` whose keys are exactly `@actor` (and optionally `incarnation`) is read as a serialized actor ref: without an `incarnation`, it becomes the live child at that address, if there is one. Objects with other keys alongside `@actor` stay plain data. Do not store application data as an object with only an `@actor` key.
|
|
101
107
|
|
|
102
108
|
### Serialized actor refs
|
|
103
109
|
|
|
104
|
-
An actor ref serializes with `JSON.stringify` as `{
|
|
110
|
+
An actor ref serializes with `JSON.stringify` as `{ '@actor': address }` (the `SerializedActorRef` type, which also allows an optional string `incarnation`). This shape appears when a ref travels in an event payload, such as a `replyTo` field, and the event is persisted or crosses a process boundary. A serialized ref in `context` keeps its address across persistence and restore.
|
|
105
111
|
|
|
106
|
-
A serialized ref is a valid `enq.sendTo(...)` target. The event is delivered to the live actor at the ref's
|
|
112
|
+
A serialized ref is a valid `enq.sendTo(...)` target. The event is delivered to the live actor at the ref's `@actor` address, including an actor restored after the ref was serialized. If no live actor has that address, the event becomes a dead letter with reason `'missingTarget'`.
|
|
107
113
|
|
|
108
114
|
```ts
|
|
109
115
|
const server = createMachine({
|
|
@@ -154,8 +160,8 @@ const checkoutVersions = machineVersions([
|
|
|
154
160
|
children: z.object({}),
|
|
155
161
|
historyValue: z.object({}),
|
|
156
162
|
timers: z.tuple([]),
|
|
157
|
-
|
|
158
|
-
|
|
163
|
+
nextActorIds: z.record(z.string(), z.number()).optional(),
|
|
164
|
+
nextTimerId: z.number(),
|
|
159
165
|
stateInputs: z.undefined().optional(),
|
|
160
166
|
machine: z.object({
|
|
161
167
|
id: z.literal('checkout'),
|
package/docs/serialization.md
CHANGED
|
@@ -85,7 +85,7 @@ const machine = machineFromJSON(definition, {
|
|
|
85
85
|
|
|
86
86
|
The second argument supplies the runtime sources the definition refers to: `actions`, `guards`, `actors`, `delays`, and `evaluators` for code expressions. Invokes keep their string `src` names, so a machine built this way can be cloned with different actors through [`provide()`](setup-and-provide.md), including when restoring its children. Deserialization still requires an implementation for every referenced actor; provide the initial implementations in the second argument, then override them by name.
|
|
87
87
|
|
|
88
|
-
Actions in JSON are objects. The built-in vocabulary is `{ type: '@xstate.raise', event, id?, delay? }`, `{ type: '@xstate.emit', event }`, `{ type: '@xstate.assign', context }`, `{ type: '@xstate.cancel', id }` and `{ type: '@xstate.log', args }`. Any other `{ type, params }` object is a custom action resolved against the `actions` sources. Guards are `{ type, params? }` references resolved against `guards`. Two guard types are built in: `{ type: '@xstate.not', params: { guard } }` negates another guard reference or expression, and `{ type: '@xstate.stateIn', params: { stateId: '#id' } }` is true while the state node with that `id` is active (the same check as `snapshot.matches('#id')`). Source names, and the names of `actions`, `guards` and `delays` defined in the JSON, may not start with `xstate.` or `@xstate.`; those prefixes are reserved for built-in names. Because the runtime invokes these references itself, a JSON-referenced guard receives the transition arguments object first and the declared `params` second
|
|
88
|
+
Actions in JSON are objects. The built-in vocabulary is `{ type: '@xstate.raise', event, id?, delay? }`, `{ type: '@xstate.emit', event }`, `{ type: '@xstate.assign', context }`, `{ type: '@xstate.cancel', id }` and `{ type: '@xstate.log', args }`. Any other `{ type, params }` object is a custom action resolved against the `actions` sources. Guards are `{ type, params? }` references resolved against `guards`. Two guard types are built in: `{ type: '@xstate.not', params: { guard } }` negates another guard reference or expression, and `{ type: '@xstate.stateIn', params: { stateId: '#id' } }` is true while the state node with that `id` is active (the same check as `snapshot.matches('#id')`). Source names, and the names of `actions`, `guards` and `delays` defined in the JSON, may not start with `xstate.` or `@xstate.`; those prefixes are reserved for built-in names. Because the runtime invokes these references itself, a JSON-referenced guard receives the transition arguments object first and the declared `params` second. This differs from code-authored machines, where guards are plain functions called by your own transition code.
|
|
89
89
|
|
|
90
90
|
Machines built from JSON round-trip losslessly. The loader copies the definition, and each serialization returns a fresh copy. Mutating either copy does not change the machine.
|
|
91
91
|
|
|
@@ -140,8 +140,8 @@ Validation can be installed, replaced or disabled by a derived setup. Installing
|
|
|
140
140
|
|
|
141
141
|
Where a validation failure surfaces depends on which side of the delivery boundary produced the invalid value:
|
|
142
142
|
|
|
143
|
-
- **Events arriving from outside the actor**
|
|
144
|
-
- **Values the actor produces itself**
|
|
143
|
+
- **Events arriving from outside the actor** (from `actor.send` or from another actor) are rejected at the boundary when their payload fails its schema, or when the event type is undeclared and `unknownEvents` is `'error'`. The event is never delivered: the actor does not transition, does not error, and no API throws. The rejection is reported to the `onRejectedEvent` dead-letter hook on `createActor` options and as a development-mode console warning. In pure `transition(...)` calls, the snapshot is returned unchanged together with a `@xstate.deadLetter` effect carrying the rejection.
|
|
144
|
+
- **Values the actor produces itself** (input, context, output, emitted events and delayed raised events) error the actor when they fail their schema, and pure `transition(...)`/`initialTransition(...)` throw an `ActorValidationError`. These are machine bugs.
|
|
145
145
|
|
|
146
146
|
## Sources on the machine
|
|
147
147
|
|
|
@@ -175,7 +175,7 @@ idle: {
|
|
|
175
175
|
}
|
|
176
176
|
```
|
|
177
177
|
|
|
178
|
-
Named actions and guards are plain functions called with only their params
|
|
178
|
+
Named actions and guards are plain functions called with only their params. Nothing is injected. Pass values from `context` or the event explicitly. Declare param types on the function itself, or with `schemas.actions` and `schemas.guards` so the params are checked before the implementations exist:
|
|
179
179
|
|
|
180
180
|
```ts
|
|
181
181
|
setup({
|
package/docs/spawn.md
CHANGED
|
@@ -46,7 +46,7 @@ The name is checked against `actors`; its required input and returned actor refe
|
|
|
46
46
|
|
|
47
47
|
Passing the logic value remains convenient: `enq.spawn(actors.upload, options)`. XState recovers its registered name when possible. Inline unregistered logic may run but cannot be durably persisted.
|
|
48
48
|
|
|
49
|
-
Spawning with an `id` that a live child of the same parent already uses throws: an address names at most one live actor. Stop the existing child first
|
|
49
|
+
Spawning with an `id` that a live child of the same parent already uses throws: an address names at most one live actor. Stop the existing child first. An id stopped earlier in the same transition is free to reuse, and a child that completed on its own frees its id for the transition handling its completion. Generate ids from something stable, such as a file or participant id.
|
|
50
50
|
|
|
51
51
|
## Where you can spawn
|
|
52
52
|
|
|
@@ -67,8 +67,8 @@ actor's macrostep. Microsteps are atomic; system snapshots contain no unfinished
|
|
|
67
67
|
microstep or continuation state. A UI presenting individual completed
|
|
68
68
|
microsteps within a macrostep needs a separate tracing interface.
|
|
69
69
|
|
|
70
|
-
Snapshot actor references are data: `{
|
|
71
|
-
as `actorPath`, for example `snapshot.actors[snapshot.root].snapshot.children.worker
|
|
70
|
+
Snapshot actor references are data: `{ '@actor': address, incarnation }`, the same shape as `SerializedActorRef`, with a string `incarnation`. Use `@actor`
|
|
71
|
+
as `actorPath`, for example `snapshot.actors[snapshot.root].snapshot.children.worker["@actor"]`.
|
|
72
72
|
Paths encode IDs; avoid concatenating unescaped IDs. Replacing an actor at the
|
|
73
73
|
same path allocates a fresh incarnation.
|
|
74
74
|
|
|
@@ -79,6 +79,8 @@ such as `actor.send`, `actor.start`, `actor.on` and `actor.subscribe` throw.
|
|
|
79
79
|
For `enq.listen`/`enq.subscribeTo`, register named pure mapper functions in
|
|
80
80
|
`systemLogic.mappers`; mapped communication and attachment lifetimes belong
|
|
81
81
|
to the snapshot too.
|
|
82
|
+
Mapped events transition through their listener or subscription actor before
|
|
83
|
+
reaching the owner.
|
|
82
84
|
Subscription `done`/`error` mappings enter the owner's message queue before
|
|
83
85
|
the native child completion/error notification, matching live actor ordering.
|
|
84
86
|
|
|
@@ -101,7 +103,7 @@ Select a pending timer in a simulator with its current occurrence:
|
|
|
101
103
|
|
|
102
104
|
```ts
|
|
103
105
|
const selected = snapshot.timers.find((timer) => timer.dueAt === 6000)!;
|
|
104
|
-
const [next] = systemTransition(systemLogic, snapshot, selected.source
|
|
106
|
+
const [next] = systemTransition(systemLogic, snapshot, selected.source["@actor"], {
|
|
105
107
|
type: 'xstate.timer',
|
|
106
108
|
occurrence: selected.occurrence
|
|
107
109
|
});
|
|
@@ -128,7 +130,7 @@ using the source actor's definition and saved input; the host owns the
|
|
|
128
130
|
external implementation. Its result reenters as a correlated input:
|
|
129
131
|
|
|
130
132
|
```ts
|
|
131
|
-
const [resolved] = systemTransition(systemLogic, pendingSnapshot, effect.source
|
|
133
|
+
const [resolved] = systemTransition(systemLogic, pendingSnapshot, effect.source["@actor"], {
|
|
132
134
|
type: 'xstate.system.effect.result',
|
|
133
135
|
effectId: effect.id,
|
|
134
136
|
event: { type: 'xstate.async.resolve', data: result }
|
|
@@ -150,8 +152,8 @@ input, outputs, events and effect arguments are JSON-compatible. Actor reference
|
|
|
150
152
|
state-node references, errors and named mappers use data markers. Errors retain
|
|
151
153
|
name/message. Undefined properties follow ordinary JSON rules. Cycles,
|
|
152
154
|
unregistered functions, live actors, class instances, symbols, bigint and
|
|
153
|
-
nonfinite numbers are rejected.
|
|
154
|
-
|
|
155
|
+
nonfinite numbers are rejected. `@actor`, `@stateNode`, `@error` and
|
|
156
|
+
`@systemMapper` marker shapes are reserved. Logic versions must match on replay.
|
|
155
157
|
|
|
156
158
|
Transition functions, guards and mappers must be deterministic and pure.
|
|
157
159
|
Read external values from input/events and virtual time from `system._clock.now()`.
|
package/docs/transitions.md
CHANGED
|
@@ -35,7 +35,7 @@ schemas: {
|
|
|
35
35
|
|
|
36
36
|
There is no `guard` property. Conditions live inside the transition function, which returns `undefined` to reject the event. Check the condition before calling `enq`: a function that calls `enq` is taken even if it returns `undefined`. See [guards](guards.md).
|
|
37
37
|
|
|
38
|
-
A targetless transition can update context and run effects without leaving the current state.
|
|
38
|
+
A targetless transition can update context and run effects without leaving the current state. It does not run exit or entry behavior, even with `reenter: true`. Specify a target and set `reenter: true` when a self-transition should run exit and entry behavior again.
|
|
39
39
|
|
|
40
40
|
```ts
|
|
41
41
|
on: {
|
|
@@ -101,6 +101,10 @@ Transition functions must be synchronous. A transition function that returns a p
|
|
|
101
101
|
|
|
102
102
|
`always` runs without an external event. `after` runs after a delay. `onDone`, `onError` and `onTimeout` handle actor outcomes.
|
|
103
103
|
|
|
104
|
+
When an `after` timer, state timeout, or delayed `enq.raise(...)` becomes due, the delayed event is processed before `always` is reevaluated. Eventless transitions then settle before immediately raised events are processed. Timer bookkeeping does not itself run `always`: a delayed `enq.sendTo(...)` delivers its event without reevaluating eventless transitions in the sender. If the sender is also the recipient, it processes the delivered event and then reevaluates `always`.
|
|
105
|
+
|
|
106
|
+
If an `always` condition depends only on context updated through transitions, it is reevaluated during those updates and cannot become enabled silently while the machine waits. This also applies to observable values whose updates reach the machine as events and update context. The timer ordering issue concerns conditions that read outside mutable values or depend on the current event. `always` does not poll outside values for changes.
|
|
107
|
+
|
|
104
108
|
Use targetless transitions for edits that keep a form on the same step. Use re-entering transitions to restart a timer, subscription or invoked request.
|
|
105
109
|
|
|
106
110
|
Put shared transitions on a parent state. A child can set an event to `undefined` to forbid that parent transition. Wildcards such as `pointer.*` match an event family when no exact transition matches.
|
package/docs/tutorial.md
CHANGED
|
@@ -430,7 +430,7 @@ Nothing about the machine changes. A UI reads snapshots and sends events.
|
|
|
430
430
|
|
|
431
431
|
```html
|
|
432
432
|
<p id="status">stopped</p>
|
|
433
|
-
<p id="title"
|
|
433
|
+
<p id="title"></p>
|
|
434
434
|
<button id="play">Play</button> <button id="pause">Pause</button>
|
|
435
435
|
<button id="stop">Stop</button> <button id="previous">Previous</button>
|
|
436
436
|
<button id="next">Next</button> <button id="mute">Mute</button>
|
|
@@ -475,7 +475,7 @@ Frameworks work the same way, with a hook or store binding instead of manual sub
|
|
|
475
475
|
|
|
476
476
|
You built one machine with context, guards, invoked async logic, hierarchy, parallel regions, delayed events, emitted events and a UI. From here:
|
|
477
477
|
|
|
478
|
-
- [Statecharts](statecharts.md)
|
|
479
|
-
- [Actors](actors.md)
|
|
480
|
-
- [Frameworks](frameworks.md)
|
|
481
|
-
- [Testing](testing.md)
|
|
478
|
+
- [Statecharts](statecharts.md): nested, parallel and history states
|
|
479
|
+
- [Actors](actors.md): spawning, communication and actor systems
|
|
480
|
+
- [Frameworks](frameworks.md): bindings for React, Vue, Svelte and Solid
|
|
481
|
+
- [Testing](testing.md): testing machines and the actors that run them
|
package/docs/typescript.md
CHANGED
|
@@ -49,6 +49,12 @@ adding explicit type annotations.
|
|
|
49
49
|
|
|
50
50
|
For an actor used in one state, `invoke: s.createInvoke({ src, input, onDone })` infers input and completion output from `src`. Keep the helper inline in `s.createMachine(...)` to also infer that state's narrowed context, ancestor context, state input and transition target requirements. The helper works alongside named actor sources. See [typed inline invokes](invoke.md#typed-inline-invokes).
|
|
51
51
|
|
|
52
|
+
A bare inline `invoke: { src: logic, onDone }` cannot correlate its source with
|
|
53
|
+
the output; with no registered actor sources it has `event.output: unknown`.
|
|
54
|
+
Use `s.createInvoke(...)` or a source registered in `setup({ actors })` when
|
|
55
|
+
reading the output. This is especially important for generated machine code:
|
|
56
|
+
the bare form cannot infer the output type from `src`.
|
|
57
|
+
|
|
52
58
|
An async function can be used directly as `src`. Declare `schemas.input`, `schemas.output`, and `schemas.error` on the invoke to type the function and its lifecycle handlers together. Without `schemas.output`, `onDone.event.output` infers from the async return value.
|
|
53
59
|
|
|
54
60
|
Public schema event keys create typed methods on `actor.trigger`; internal
|
|
@@ -84,6 +90,9 @@ When `schemas.events` is declared, each key in an `on` map must match a
|
|
|
84
90
|
declared event type. Matching wildcards (`'*'`, `'user.*'`) and known reserved
|
|
85
91
|
machine descriptors are allowed; misspelled or invented reserved prefixes are rejected. Without `schemas.events`, any key is accepted.
|
|
86
92
|
|
|
93
|
+
An empty `schemas.events: {}` means the machine has no public events. Final
|
|
94
|
+
state output callbacks still receive the declared context and input types.
|
|
95
|
+
|
|
87
96
|
```ts
|
|
88
97
|
on: {
|
|
89
98
|
toggel: { target: 'active' }
|