@typeonce/effect-machine 0.46.0 → 0.47.1

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.
Files changed (148) hide show
  1. package/AGENTS.md +1823 -0
  2. package/CLAUDE.md +1823 -0
  3. package/README.md +100 -77
  4. package/ai-docs/README.md +18 -0
  5. package/ai-docs/src/10_modeling/01_create-a-machine.ts +51 -0
  6. package/ai-docs/src/10_modeling/02_branch-on-an-event.ts +55 -0
  7. package/ai-docs/src/10_modeling/03_update-retained-state.ts +58 -0
  8. package/ai-docs/src/10_modeling/04_verify-after-changing.ts +29 -0
  9. package/{docs/agent-guide.md → ai-docs/src/10_modeling/index.md} +234 -155
  10. package/{docs/root-api.md → ai-docs/src/20_root-api/index.md} +29 -57
  11. package/{docs/effect-atom-react.md → ai-docs/src/30_react/index.md} +42 -49
  12. package/{docs/machine-review.md → ai-docs/src/40_review/index.md} +42 -40
  13. package/ai-docs/src/index.md +7 -0
  14. package/ai-docs/tsconfig.json +22 -0
  15. package/dist/Machine.d.ts +1195 -1474
  16. package/dist/Machine.d.ts.map +1 -1
  17. package/dist/Machine.js +366 -214
  18. package/dist/Machine.js.map +1 -1
  19. package/dist/internal/machine/atom.js.map +1 -1
  20. package/dist/internal/machine/cluster.js.map +1 -1
  21. package/dist/internal/machine/command.d.ts +8 -0
  22. package/dist/internal/machine/command.d.ts.map +1 -1
  23. package/dist/internal/machine/command.js +2 -2
  24. package/dist/internal/machine/command.js.map +1 -1
  25. package/dist/internal/machine/configuration.d.ts +21 -5
  26. package/dist/internal/machine/configuration.d.ts.map +1 -1
  27. package/dist/internal/machine/configuration.js +1 -0
  28. package/dist/internal/machine/configuration.js.map +1 -1
  29. package/dist/internal/machine/construction.js.map +1 -1
  30. package/dist/internal/machine/declaration.d.ts +2 -1
  31. package/dist/internal/machine/declaration.d.ts.map +1 -1
  32. package/dist/internal/machine/declaration.js +28 -46
  33. package/dist/internal/machine/declaration.js.map +1 -1
  34. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  35. package/dist/internal/machine/executionPlan.js +23 -16
  36. package/dist/internal/machine/executionPlan.js.map +1 -1
  37. package/dist/internal/machine/implementation.d.ts +2 -0
  38. package/dist/internal/machine/implementation.d.ts.map +1 -1
  39. package/dist/internal/machine/implementation.js.map +1 -1
  40. package/dist/internal/machine/initialDeclaration.d.ts +2 -0
  41. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  42. package/dist/internal/machine/initialDeclaration.js +15 -0
  43. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  44. package/dist/internal/machine/invocation.d.ts.map +1 -1
  45. package/dist/internal/machine/invocation.js +25 -19
  46. package/dist/internal/machine/invocation.js.map +1 -1
  47. package/dist/internal/machine/invocationEvent.d.ts +34 -17
  48. package/dist/internal/machine/invocationEvent.d.ts.map +1 -1
  49. package/dist/internal/machine/invocationEvent.js +16 -4
  50. package/dist/internal/machine/invocationEvent.js.map +1 -1
  51. package/dist/internal/machine/machine.d.ts +5 -22
  52. package/dist/internal/machine/machine.d.ts.map +1 -1
  53. package/dist/internal/machine/machine.js +157 -119
  54. package/dist/internal/machine/machine.js.map +1 -1
  55. package/dist/internal/machine/planner.d.ts +15 -4
  56. package/dist/internal/machine/planner.d.ts.map +1 -1
  57. package/dist/internal/machine/planner.js +18 -21
  58. package/dist/internal/machine/planner.js.map +1 -1
  59. package/dist/internal/machine/process.d.ts +2 -0
  60. package/dist/internal/machine/process.d.ts.map +1 -1
  61. package/dist/internal/machine/process.js +2 -0
  62. package/dist/internal/machine/process.js.map +1 -1
  63. package/dist/internal/machine/protocol.js.map +1 -1
  64. package/dist/internal/machine/runtime.d.ts.map +1 -1
  65. package/dist/internal/machine/runtime.js.map +1 -1
  66. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  67. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -1
  68. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  69. package/dist/internal/machine/runtimeProtocol.d.ts +26 -0
  70. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  71. package/dist/internal/machine/runtimeProtocol.js +71 -0
  72. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  73. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  74. package/dist/internal/machine/stateDefinition.js +0 -14
  75. package/dist/internal/machine/stateDefinition.js.map +1 -1
  76. package/dist/internal/machine/symbols.d.ts +9 -0
  77. package/dist/internal/machine/symbols.d.ts.map +1 -1
  78. package/dist/internal/machine/symbols.js.map +1 -1
  79. package/dist/internal/machine/topology.d.ts +18 -9
  80. package/dist/internal/machine/topology.d.ts.map +1 -1
  81. package/dist/internal/machine/topology.js +16 -1
  82. package/dist/internal/machine/topology.js.map +1 -1
  83. package/dist/internal/testing/machine/arbitrary.d.ts.map +1 -1
  84. package/dist/internal/testing/machine/arbitrary.js +2 -0
  85. package/dist/internal/testing/machine/arbitrary.js.map +1 -1
  86. package/dist/internal/testing/machine/check.d.ts +17 -0
  87. package/dist/internal/testing/machine/check.d.ts.map +1 -0
  88. package/dist/internal/testing/machine/check.js +371 -0
  89. package/dist/internal/testing/machine/check.js.map +1 -0
  90. package/dist/internal/testing/machine/exploration.d.ts.map +1 -1
  91. package/dist/internal/testing/machine/exploration.js.map +1 -1
  92. package/dist/internal/testing/machine/finiteModel.d.ts +14 -13
  93. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  94. package/dist/internal/testing/machine/finiteModel.js +21 -23
  95. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  96. package/dist/internal/testing/machine/runtime.d.ts +19 -88
  97. package/dist/internal/testing/machine/runtime.d.ts.map +1 -1
  98. package/dist/internal/testing/machine/runtime.js +0 -19
  99. package/dist/internal/testing/machine/runtime.js.map +1 -1
  100. package/dist/internal/testing/machine/runtimeInvariant.js.map +1 -1
  101. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  102. package/dist/internal/testing/machine/verification.js.map +1 -1
  103. package/dist/testing/MachineTest.d.ts +349 -139
  104. package/dist/testing/MachineTest.d.ts.map +1 -1
  105. package/dist/testing/MachineTest.js +201 -136
  106. package/dist/testing/MachineTest.js.map +1 -1
  107. package/dist/unstable/cluster/ClusterMachine.d.ts +9 -14
  108. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  109. package/dist/unstable/cluster/ClusterMachine.js +9 -14
  110. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  111. package/dist/unstable/reactivity/AtomMachine.d.ts +169 -80
  112. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  113. package/dist/unstable/reactivity/AtomMachine.js +165 -76
  114. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  115. package/package.json +11 -9
  116. package/src/Machine.ts +1141 -2130
  117. package/src/internal/machine/atom.ts +3 -3
  118. package/src/internal/machine/cluster.ts +2 -2
  119. package/src/internal/machine/command.ts +10 -4
  120. package/src/internal/machine/configuration.ts +16 -17
  121. package/src/internal/machine/construction.ts +1 -1
  122. package/src/internal/machine/declaration.ts +25 -50
  123. package/src/internal/machine/executionPlan.ts +90 -56
  124. package/src/internal/machine/implementation.ts +3 -1
  125. package/src/internal/machine/initialDeclaration.ts +16 -0
  126. package/src/internal/machine/invocation.ts +38 -44
  127. package/src/internal/machine/invocationEvent.ts +46 -20
  128. package/src/internal/machine/machine.ts +217 -243
  129. package/src/internal/machine/planner.ts +72 -106
  130. package/src/internal/machine/process.ts +12 -0
  131. package/src/internal/machine/protocol.ts +6 -6
  132. package/src/internal/machine/runtime.ts +1 -5
  133. package/src/internal/machine/runtimeCompiled.ts +2 -2
  134. package/src/internal/machine/runtimeGeneric.ts +2 -4
  135. package/src/internal/machine/runtimeProtocol.ts +80 -4
  136. package/src/internal/machine/stateDefinition.ts +0 -39
  137. package/src/internal/machine/symbols.ts +11 -0
  138. package/src/internal/machine/topology.ts +40 -18
  139. package/src/internal/testing/machine/arbitrary.ts +2 -0
  140. package/src/internal/testing/machine/check.ts +460 -0
  141. package/src/internal/testing/machine/exploration.ts +4 -5
  142. package/src/internal/testing/machine/finiteModel.ts +40 -42
  143. package/src/internal/testing/machine/runtime.ts +31 -170
  144. package/src/internal/testing/machine/runtimeInvariant.ts +3 -3
  145. package/src/internal/testing/machine/verification.ts +14 -14
  146. package/src/testing/MachineTest.ts +366 -145
  147. package/src/unstable/cluster/ClusterMachine.ts +9 -14
  148. package/src/unstable/reactivity/AtomMachine.ts +167 -78
package/dist/Machine.js CHANGED
@@ -14,7 +14,6 @@ import { InitialEventTypeId } from "./internal/machine/machine.js";
14
14
  */
15
15
  export const TypeId = "~effect/Machine";
16
16
  const ParentTypeId = "~effect/Machine/Parent";
17
- const ChildMachineLogicTypeId = internal.ChildMachineLogicTypeId;
18
17
  /**
19
18
  * Type identifier used for the synthetic event passed to startup lifecycle
20
19
  * actions.
@@ -96,10 +95,7 @@ StartupError,
96
95
  StoppedError } from "./internal/machine/machine.js";
97
96
  const RuntimeRequirementTypeId = "~effect/Machine/RuntimeRequirement";
98
97
  const ActionRequirementTypeId = "~effect/Machine/ActionRequirement";
99
- const InvokeTypeId = internal.InvokeTypeId;
100
98
  const StateTypeId = "~effect/Machine/State";
101
- const SnapshotBuilderStateTypeId = internal.SnapshotBuilderStateTypeId;
102
- const SnapshotBuilderConstructionTypeId = Symbol("effect/Machine/SnapshotBuilderConstruction");
103
99
  const ChildAddressTypeId = "~effect/Machine/ChildAddress";
104
100
  const ChildAddressCompatibilityErrorTypeId = "~effect/Machine/ChildAddressCompatibilityError";
105
101
  const ChildParentCompatibilityErrorTypeId = "~effect/Machine/ChildParentCompatibilityError";
@@ -125,16 +121,13 @@ export const isFinal = internal.isFinal;
125
121
  * can be declared inline or reused by mounting a descriptor in multiple places.
126
122
  * Initial edges and value constructors belong in the handler tree.
127
123
  *
128
- * **Example** (Repeated compound state)
124
+ * **Example** (Reusing one subtree in two parallel regions)
129
125
  *
130
- * ```ts
126
+ * ```ts import.meta.vitest
131
127
  * import { Machine } from "@typeonce/effect-machine"
132
- * import { Schema } from "effect"
128
+ * import { Effect, Schema } from "effect"
133
129
  *
134
- * const TradingState = Schema.TaggedUnion({
135
- * InSession: {},
136
- * Applying: {}
137
- * })
130
+ * const TradingState = Schema.TaggedUnion({ InSession: {}, Applying: {} })
138
131
  * const TradingSlot = Machine.state({
139
132
  * states: {
140
133
  * Idle: {},
@@ -142,13 +135,21 @@ export const isFinal = internal.isFinal;
142
135
  * Applying: TradingState.cases.Applying
143
136
  * }
144
137
  * })
138
+ * const States = Machine.state({ type: "parallel", states: { slot1: TradingSlot, slot2: TradingSlot } })
145
139
  *
146
- * const States = Machine.state({
140
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
147
141
  * states: {
148
- * slot1: TradingSlot,
149
- * slot2: TradingSlot
142
+ * slot1: { initial: { target: "slot1.Idle" } },
143
+ * slot2: { initial: { target: "slot2.Idle" } }
150
144
  * }
151
145
  * })
146
+ *
147
+ * const paths = Effect.map(Machine.planInitial(machine), ({ state }) => [
148
+ * state.states.slot1.state.path,
149
+ * state.states.slot2.state.path
150
+ * ])
151
+ *
152
+ * await Effect.runPromise(paths) // => ["slot1.Idle", "slot2.Idle"]
152
153
  * ```
153
154
  *
154
155
  * @category constructors
@@ -160,16 +161,16 @@ export const state = internal.state;
160
161
  *
161
162
  * **Details**
162
163
  *
163
- * State and event schemas provide runtime boundary validation while their
164
- * decoded types drive handler, state, event, target, error, and service
165
- * inference. State-tree validation is applied whether `states` comes from
166
- * `states` or is passed inline. Call `handle` on the returned definition
167
- * to implement state behavior with ordinary TypeScript control flow.
164
+ * `root` is the `Machine.state` descriptor of the complete state tree. State
165
+ * and event schemas provide runtime boundary validation while their decoded
166
+ * types drive handler, state, event, target, error, and service inference.
167
+ * Call `handle` on the returned {@link Definition} to declare the initial
168
+ * target and the behavior of each state.
168
169
  *
169
- * `initial` is a target-first callback. Its outer selector runs once while the
170
- * definition is captured; an attached `.resolve(...)` callback remains lazy
171
- * until initial planning. Return a bare selected state when its schema supports
172
- * default construction.
170
+ * Register Effects, Streams, timers, logic, and child machines under
171
+ * `effects`, `streams`, `timers`, `logic`, and `children`. A state invokes a
172
+ * registered source by name with `invoke: { src }`, and only invoked sources
173
+ * add to the machine's requirements.
173
174
  *
174
175
  * `Machine.events` defines the public input protocol. `Machine.internalEvents`
175
176
  * adds raised events and other machine-local deliveries.
@@ -180,42 +181,82 @@ export const state = internal.state;
180
181
  * schemas opaquely for runtime validation. Public and internal tags must be
181
182
  * disjoint.
182
183
  *
183
- * **Example** (Typed counter machine)
184
+ * **Gotchas**
184
185
  *
185
- * ```ts
186
+ * Source names must be unique across all five registries. A top-level state
187
+ * cannot be named `root`, because `root` names the root state.
188
+ *
189
+ * **Example** (Invoking a registered Effect)
190
+ *
191
+ * ```ts import.meta.vitest
186
192
  * import { Machine } from "@typeonce/effect-machine"
187
- * import { Schema } from "effect"
188
- * class Count extends Schema.TaggedClass<Count>("Count")("Count", {
189
- * value: Schema.Number
190
- * }) {
191
- * }
192
- * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", {
193
- * by: Schema.Number
194
- * }) {
195
- * }
193
+ * import { Effect, Option, Schema } from "effect"
194
+ *
195
+ * const Lookup = Schema.TaggedUnion({ Loading: { id: Schema.String }, Ready: { name: Schema.String } })
196
+ * const States = Machine.state({ states: { Idle: {}, Loading: Lookup.cases.Loading, Ready: Lookup.cases.Ready } })
197
+ * const Events = Machine.events({ Load: { id: Schema.String } })
198
+ *
199
+ * const machine = Machine.make({
200
+ * root: States,
201
+ * events: Events,
202
+ * effects: { findName: (id: string) => Effect.succeed(`User ${id}`) }
203
+ * }).handle({
204
+ * initial: { target: "Idle" },
205
+ * states: {
206
+ * Idle: { on: { Load: { target: "Loading", data: ({ event }) => ({ id: event.id }) } } },
207
+ * Loading: {
208
+ * invoke: {
209
+ * src: "findName",
210
+ * input: ({ state }) => state.id,
211
+ * onDone: { target: "Ready", data: ({ output }) => ({ name: output }) }
212
+ * }
213
+ * }
214
+ * }
215
+ * })
216
+ *
217
+ * const name = Effect.scoped(Effect.gen(function*() {
218
+ * const ref = yield* Machine.start(machine)
219
+ * yield* ref.send(Events.Load({ id: "1" }))
220
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
221
+ * return States.get(ready.state, "Ready").pipe(Option.map((state) => state.name))
222
+ * }))
223
+ *
224
+ * await Effect.runPromise(name) // => Option.some("User 1")
225
+ * ```
226
+ *
227
+ * **Example** (Counting with schema classes)
228
+ *
229
+ * ```ts import.meta.vitest
230
+ * import { Machine } from "@typeonce/effect-machine"
231
+ * import { Effect, Option, Schema } from "effect"
232
+ *
233
+ * class Count extends Schema.TaggedClass<Count>("Count")("Count", { value: Schema.Number }) {}
234
+ * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", { by: Schema.Number }) {}
235
+ *
196
236
  * const States = Machine.state({ states: { Count } })
197
- * const Events = Machine.eventsFromSchemas(Increment)
198
237
  * const counter = Machine.make({
199
238
  * root: States,
200
- * events: Events
239
+ * events: Machine.eventsFromSchemas(Increment)
201
240
  * }).handle({
202
- * initial: {
203
- * target: "Count",
204
- * decoded: true,
205
- * data: new Count({ value: 0 })
206
- * },
241
+ * initial: { target: "Count", decoded: true, data: new Count({ value: 0 }) },
207
242
  * states: {
208
243
  * Count: {
209
244
  * on: {
210
245
  * Increment: {
211
- * update: "Count",
212
- * decoded: true,
213
- * data: ({ event, state }) => new Count({ value: state.value + event.by })
246
+ * update: { Count: { decoded: true, data: ({ event, state }) => new Count({ value: state.value + event.by }) } }
214
247
  * }
215
248
  * }
216
249
  * }
217
250
  * }
218
251
  * })
252
+ *
253
+ * const value = Effect.gen(function*() {
254
+ * const initial = yield* Machine.planInitial(counter)
255
+ * const planned = yield* Machine.plan(counter, initial.state, new Increment({ by: 2 }))
256
+ * return States.get(planned.next, "Count").pipe(Option.map((count) => count.value))
257
+ * })
258
+ *
259
+ * await Effect.runPromise(value) // => Option.some(2)
219
260
  * ```
220
261
  *
221
262
  * @see {@link state} for typed state-tree helpers.
@@ -224,20 +265,68 @@ export const state = internal.state;
224
265
  * @since 0.4.0
225
266
  */
226
267
  export const make = internal.make;
227
- /** Defines a public event protocol from tagged field records.
268
+ /**
269
+ * Defines a public event protocol from tagged field records.
270
+ *
271
+ * Constructors defer schema validation until delivery. Use
272
+ * {@link eventsFromSchemas} when importing existing tagged schemas or protocol
273
+ * descriptors.
274
+ *
275
+ * **Example** (Defining events from fields)
276
+ *
277
+ * ```ts import.meta.vitest
278
+ * import { Machine } from "@typeonce/effect-machine"
279
+ * import { Schema } from "effect"
228
280
  *
229
- * ```ts
230
281
  * const Events = Machine.events({ Increment: { by: Schema.Number }, Reset: {} })
231
- * const increment = Events.Increment({ by: 1 })
282
+ *
283
+ * Events.Increment({ by: 1 })._tag // => "Increment"
284
+ * Events.Reset()._tag // => "Reset"
232
285
  * ```
233
286
  *
234
- * Constructors defer schema validation until delivery. Use eventsFromSchemas
235
- * when importing existing tagged schemas or protocol descriptors.
236
287
  * @category constructors
237
288
  * @since 0.32.0
238
289
  */
239
290
  export const events = internal.eventsFromFields;
240
- /** Imports existing schemas and protocols without rebuilding their contracts.
291
+ /**
292
+ * Defines a public event protocol from existing tagged schemas or protocol
293
+ * descriptors, without rebuilding their contracts, and returns deferred
294
+ * constructors for every statically finite configured event tag.
295
+ *
296
+ * Constructor inputs retain their schema-derived required fields, defaults,
297
+ * and transformations. Construction is deferred until delivery so failures
298
+ * enter the machine's `MachineSchemaDecodeError` channel rather than throwing
299
+ * at the call site.
300
+ *
301
+ * **Example** (Reusing a tagged union as the event protocol)
302
+ *
303
+ * ```ts import.meta.vitest
304
+ * import { Machine } from "@typeonce/effect-machine"
305
+ * import { Effect, Schema } from "effect"
306
+ *
307
+ * const Event = Machine.eventsFromSchemas(
308
+ * Schema.TaggedUnion({
309
+ * Increment: { by: Schema.Number },
310
+ * Reset: {}
311
+ * })
312
+ * )
313
+ * const machine = Machine.make({ root: Machine.state({ fields: { count: Schema.Number } }), events: Event }).handle({
314
+ * root: { count: 0 },
315
+ * on: {
316
+ * Increment: { update: { root: ({ root, event }) => ({ count: root.count + event.by }) } },
317
+ * Reset: { update: { root: { count: 0 } } }
318
+ * }
319
+ * })
320
+ *
321
+ * const count = Effect.scoped(Effect.gen(function*() {
322
+ * const ref = yield* Machine.start(machine)
323
+ * yield* ref.send(Event.Increment({ by: 1 }))
324
+ * return (yield* ref.state).value.count
325
+ * }))
326
+ *
327
+ * await Effect.runPromise(count) // => 1
328
+ * ```
329
+ *
241
330
  * @category constructors
242
331
  * @since 0.32.0
243
332
  */
@@ -269,28 +358,48 @@ export const optionalParent = internal.optionalParent;
269
358
  *
270
359
  * Use these constructors for raised events and other machine-local deliveries.
271
360
  * Construction failures are reported through the
272
- * owning machine's `MachineSchemaDecodeError` channel.
361
+ * owning machine's `MachineSchemaDecodeError` channel. Use
362
+ * {@link internalEventsFromSchemas} when importing existing tagged schemas or
363
+ * protocol descriptors.
273
364
  *
274
- * **Example**
365
+ * **Example** (Raising an internal event)
275
366
  *
276
- * ```ts
277
- * const Internal = Machine.internalEventsFromSchemas(
278
- * Schema.TaggedUnion({
279
- * Loaded: { value: Schema.String },
280
- * Failed: { message: Schema.String }
281
- * })
282
- * )
283
- * const machine = Machine.make({ internalEvents: Internal, ... })
367
+ * ```ts import.meta.vitest
368
+ * import { Machine } from "@typeonce/effect-machine"
369
+ * import { Effect, Schema } from "effect"
370
+ *
371
+ * const Events = Machine.events({ Load: { value: Schema.String } })
372
+ * const Internal = Machine.internalEvents({ Loaded: { value: Schema.String }, Failed: { message: Schema.String } })
373
+ * const machine = Machine.make({
374
+ * root: Machine.state({ fields: { value: Schema.String } }),
375
+ * events: Events,
376
+ * internalEvents: Internal
377
+ * }).handle({
378
+ * root: { value: "" },
379
+ * on: {
380
+ * Load: { stay: true, commands: ({ event }, enqueue) => enqueue.raise(Internal.Loaded({ value: event.value })) },
381
+ * Loaded: { update: { root: ({ event }) => ({ value: event.value }) } },
382
+ * Failed: { stay: true }
383
+ * }
384
+ * })
284
385
  *
285
- * // Inside a transition callback:
286
- * enqueue.raise(Internal.Loaded({ value }))
386
+ * const value = Effect.gen(function*() {
387
+ * const initial = yield* Machine.planInitial(machine)
388
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Load({ value: "ready" }))
389
+ * return planned.next.value.value
390
+ * })
391
+ *
392
+ * await Effect.runPromise(value) // => "ready"
287
393
  * ```
288
394
  *
289
395
  * @category constructors
290
396
  * @since 0.10.0
291
397
  */
292
398
  export const internalEvents = internal.internalEventsFromFields;
293
- /** Imports existing schemas and protocols without rebuilding their contracts.
399
+ /**
400
+ * Defines an internal event protocol from existing tagged schemas or protocol
401
+ * descriptors, without rebuilding their contracts.
402
+ *
294
403
  * @category constructors
295
404
  * @since 0.32.0
296
405
  */
@@ -299,24 +408,47 @@ export const internalEventsFromSchemas = internal.internalEvents;
299
408
  * Defines the ephemeral notifications a machine may publish to external
300
409
  * observers. Emitted events are separate from machine input and are never sent
301
410
  * implicitly to a parent machine. Observe them through `MachineRef.emissions` or
302
- * the AtomMachine emission stream adapters.
411
+ * the AtomMachine emission stream adapters. Use {@link emittedEventsFromSchemas}
412
+ * when importing existing tagged schemas or protocol descriptors.
303
413
  *
304
- * **Example**
414
+ * **Example** (Emitting an event to observers)
305
415
  *
306
- * ```ts
307
- * const Emitted = Machine.emittedEventsFromSchemas(
308
- * Schema.TaggedUnion({
309
- * Saved: { id: Schema.String }
310
- * })
311
- * )
312
- * const machine = Machine.make({ emittedEvents: Emitted, ... })
416
+ * ```ts import.meta.vitest
417
+ * import { Machine } from "@typeonce/effect-machine"
418
+ * import { Effect, Schema } from "effect"
419
+ *
420
+ * const Events = Machine.events({ Save: { id: Schema.String } })
421
+ * const Emitted = Machine.emittedEvents({ Saved: { id: Schema.String } })
422
+ * const machine = Machine.make({
423
+ * root: Machine.state({ states: { Idle: {} } }),
424
+ * events: Events,
425
+ * emittedEvents: Emitted
426
+ * }).handle({
427
+ * initial: { target: "Idle" },
428
+ * states: {
429
+ * Idle: {
430
+ * on: { Save: { stay: true, commands: ({ event }, enqueue) => enqueue.emit(Emitted.Saved({ id: event.id })) } }
431
+ * }
432
+ * }
433
+ * })
434
+ *
435
+ * const emitted = Effect.gen(function*() {
436
+ * const initial = yield* Machine.planInitial(machine)
437
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Save({ id: "a" }))
438
+ * return planned.emittedEvents.length
439
+ * })
440
+ *
441
+ * await Effect.runPromise(emitted) // => 1
313
442
  * ```
314
443
  *
315
444
  * @category constructors
316
445
  * @since 0.10.0
317
446
  */
318
447
  export const emittedEvents = internal.emittedEventsFromFields;
319
- /** Imports existing schemas and protocols without rebuilding their contracts.
448
+ /**
449
+ * Defines an emitted event protocol from existing tagged schemas or protocol
450
+ * descriptors, without rebuilding their contracts.
451
+ *
320
452
  * @category constructors
321
453
  * @since 0.32.0
322
454
  */
@@ -347,29 +479,24 @@ export const emittedEventsFromSchemas = internal.emittedEvents;
347
479
  * Define an explicit JSON codec or keep process-local capabilities outside the
348
480
  * logical snapshot.
349
481
  *
350
- * **Example**
482
+ * **Example** (Encoding a snapshot for storage)
351
483
  *
352
- * ```ts
484
+ * ```ts import.meta.vitest
353
485
  * import { Machine } from "@typeonce/effect-machine"
354
- * import { Effect, Schema } from "effect"
355
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
356
- * }
357
- * const States = Machine.state({ states: { Idle } })
358
- * const machine = Machine.make({
359
- * root: States,
360
- * events: Machine.eventsFromSchemas()
361
- * }).handle({
362
- * initial: {
363
- * target: "Idle"
364
- * },
365
- * states: {
366
- * Idle: {}
367
- * }
486
+ * import { Effect } from "effect"
487
+ *
488
+ * const States = Machine.state({ states: { Idle: {} } })
489
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
490
+ * initial: { target: "Idle" }
368
491
  * })
492
+ *
369
493
  * const encoded = Effect.gen(function*() {
370
494
  * const initial = yield* Machine.planInitial(machine)
371
- * return yield* Machine.encodeSnapshot(machine, initial.state)
495
+ * const snapshot = yield* Machine.encodeSnapshot(machine, initial.state)
496
+ * return typeof snapshot
372
497
  * })
498
+ *
499
+ * await Effect.runPromise(encoded) // => "object"
373
500
  * ```
374
501
  *
375
502
  * @see {@link decodeSnapshot} for restoring an encoded snapshot.
@@ -396,30 +523,25 @@ export const encodeSnapshot = internal.encodeSnapshot;
396
523
  * Decoding restores logical statechart data only. It does not restart invoked
397
524
  * processes, recreate spawned children, or restore a previous `MachineRef`.
398
525
  *
399
- * **Example**
526
+ * **Example** (Restoring an encoded snapshot)
400
527
  *
401
- * ```ts
528
+ * ```ts import.meta.vitest
402
529
  * import { Machine } from "@typeonce/effect-machine"
403
- * import { Effect, Schema } from "effect"
404
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
405
- * }
406
- * const States = Machine.state({ states: { Idle } })
407
- * const machine = Machine.make({
408
- * root: States,
409
- * events: Machine.eventsFromSchemas()
410
- * }).handle({
411
- * initial: {
412
- * target: "Idle"
413
- * },
414
- * states: {
415
- * Idle: {}
416
- * }
530
+ * import { Effect } from "effect"
531
+ *
532
+ * const States = Machine.state({ states: { Idle: {} } })
533
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
534
+ * initial: { target: "Idle" }
417
535
  * })
418
- * const roundTrip = Effect.gen(function*() {
536
+ *
537
+ * const path = Effect.gen(function*() {
419
538
  * const initial = yield* Machine.planInitial(machine)
420
539
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
421
- * return yield* Machine.decodeSnapshot(machine, encoded)
540
+ * const decoded = yield* Machine.decodeSnapshot(machine, encoded)
541
+ * return decoded.state.path
422
542
  * })
543
+ *
544
+ * await Effect.runPromise(path) // => "Idle"
423
545
  * ```
424
546
  *
425
547
  * @see {@link encodeSnapshot} for creating the normalized representation.
@@ -445,26 +567,20 @@ export const decodeSnapshot = internal.decodeSnapshot;
445
567
  * protocol. Manual planners may inspect commands but need running machine targets
446
568
  * to execute child-addressed operations.
447
569
  *
448
- * **Example**
570
+ * **Example** (Planning startup without running the machine)
449
571
  *
450
- * ```ts
572
+ * ```ts import.meta.vitest
451
573
  * import { Machine } from "@typeonce/effect-machine"
452
- * import { Effect, Schema } from "effect"
453
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
454
- * }
455
- * const States = Machine.state({ states: { Idle } })
456
- * const machine = Machine.make({
457
- * root: States,
458
- * events: Machine.eventsFromSchemas()
459
- * }).handle({
460
- * initial: {
461
- * target: "Idle"
462
- * },
463
- * states: {
464
- * Idle: {}
465
- * }
574
+ * import { Effect } from "effect"
575
+ *
576
+ * const States = Machine.state({ states: { Idle: {} } })
577
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
578
+ * initial: { target: "Idle" }
466
579
  * })
467
- * const initialState = Effect.map(Machine.planInitial(machine), (plan) => plan.state)
580
+ *
581
+ * const path = Effect.map(Machine.planInitial(machine), (plan) => plan.state.state.path)
582
+ *
583
+ * await Effect.runPromise(path) // => "Idle"
468
584
  * ```
469
585
  *
470
586
  * @see {@link plan} for planning a received event.
@@ -491,9 +607,9 @@ export const stateNodes = internal.stateNodes;
491
607
  /**
492
608
  * Returns the statically selected root entry used during machine startup.
493
609
  *
494
- * This function does not execute the initial resolver or require machine
495
- * input. `kind: "initial"` means that the selected root enters its declared
496
- * initial configuration.
610
+ * This function does not construct initial state values or require machine
611
+ * input. `kind: "initial"` means that the root enters its declared initial
612
+ * configuration.
497
613
  *
498
614
  * @category getters
499
615
  * @since 0.14.0
@@ -504,7 +620,8 @@ export const initialDefinition = internal.initialDefinition;
504
620
  *
505
621
  * **Details**
506
622
  *
507
- * The returned tuple retains the schemas supplied to {@link events}, including
623
+ * The returned tuple retains the schemas supplied to {@link events} or
624
+ * {@link eventsFromSchemas}, including
508
625
  * grouped tagged unions. Internal and emitted event schemas are excluded. This
509
626
  * getter is intended for tooling that needs to describe or construct valid
510
627
  * external inputs without reaching into the opaque event protocol.
@@ -514,16 +631,16 @@ export const initialDefinition = internal.initialDefinition;
514
631
  */
515
632
  export const inputEventSchemas = internal.inputEventSchemas;
516
633
  /**
517
- * Returns every registered transition handler in state definition order.
634
+ * Returns every declared transition in state definition order.
518
635
  *
519
636
  * **Details**
520
637
  *
521
- * Event handlers retain their handler-key order within each source state and
522
- * are followed by eventless and completion handlers. This function does not
638
+ * Event transitions retain their key order within each source state and are
639
+ * followed by eventless and completion transitions. This function does not
523
640
  * execute resolvers. Every branch exposes its static selection. State updates
524
641
  * retain the updated owner in `selection.path` while leaving `target`
525
642
  * undefined because they do not change topology. `acceptance` reports whether
526
- * the resolver may decline the transition.
643
+ * the transition may decline the event.
527
644
  *
528
645
  * @category getters
529
646
  * @since 0.4.0
@@ -534,7 +651,7 @@ export const transitionDefinitions = internal.transitionDefinitions;
534
651
  *
535
652
  * **Details**
536
653
  *
537
- * Static inline invocation definitions expose stable ownership and lifecycle
654
+ * Static invocation definitions expose stable ownership and lifecycle
538
655
  * metadata without serializing runtime values. Function-valued sources are
539
656
  * represented as dynamic and are never evaluated during inspection.
540
657
  *
@@ -559,7 +676,7 @@ export const configuration = internal.configuration;
559
676
  * Returns event tags with at least one structurally eligible handler in the
560
677
  * current state snapshot.
561
678
  *
562
- * A `declinable` handler may still reject a concrete event at planning time,
679
+ * A handler with `guard` or `{ decline: true }` may still reject a concrete event at planning time,
563
680
  * so this is a static candidate query rather than a guarantee that every value
564
681
  * with the returned tag will be handled.
565
682
  *
@@ -573,9 +690,10 @@ export const enabled = internal.enabled;
573
690
  *
574
691
  * **Details**
575
692
  *
576
- * Required handlers are accepted from their structural eligibility.
577
- * Declinable handlers run their resolver only far enough to decide whether
578
- * they accept the event. Any commands, emissions, or raised events collected
693
+ * Required transitions are accepted from their structural eligibility.
694
+ * Declinable transitions, which have a `guard` or a `{ decline: true }` entry,
695
+ * run their guard or resolver only far enough to decide whether they accept
696
+ * the event. Any commands, emissions, or raised events collected
579
697
  * during that check are discarded.
580
698
  *
581
699
  * Event input is decoded through the machine's public and internal event protocols.
@@ -593,9 +711,9 @@ export const enabled = internal.enabled;
593
711
  * Synchronous transition resolvers cannot execute it. Querying an internal event
594
712
  * does not make that event available to `MachineRef.send`.
595
713
  *
596
- * **Example**
714
+ * **Example** (Checking an event against the current state)
597
715
  *
598
- * ```ts
716
+ * ```ts import.meta.vitest
599
717
  * import { Machine } from "@typeonce/effect-machine"
600
718
  * import { Effect, Schema } from "effect"
601
719
  *
@@ -607,13 +725,15 @@ export const enabled = internal.enabled;
607
725
  * internalEvents
608
726
  * }).handle({
609
727
  * initial: { target: "Idle" },
610
- * states: { Idle: { on: { Loaded: { none: true } } } }
728
+ * states: { Idle: { on: { Loaded: { stay: true } } } }
611
729
  * })
612
730
  *
613
- * export const canLoad = Effect.gen(function*() {
731
+ * const canLoad = Effect.gen(function*() {
614
732
  * const initial = yield* Machine.planInitial(machine)
615
733
  * return yield* Machine.can(machine, initial.state, internalEvents.Loaded())
616
734
  * })
735
+ *
736
+ * await Effect.runPromise(canLoad) // => true
617
737
  * ```
618
738
  *
619
739
  * @category getters
@@ -637,38 +757,30 @@ export const can = internal.can;
637
757
  * `emittedEvents`. Events with no enabled transition are ignored and produce
638
758
  * an unchanged plan.
639
759
  *
640
- * **Example**
760
+ * **Example** (Planning one event without running the machine)
641
761
  *
642
- * ```ts
762
+ * ```ts import.meta.vitest
643
763
  * import { Machine } from "@typeonce/effect-machine"
644
- * import { Effect, Schema } from "effect"
645
- * class Off extends Schema.TaggedClass<Off>("Off")("Off", {}) {
646
- * }
647
- * class On extends Schema.TaggedClass<On>("On")("On", {}) {
648
- * }
649
- * class Toggle extends Schema.TaggedClass<Toggle>("Toggle")("Toggle", {}) {
650
- * }
651
- * const States = Machine.state({ states: { Off, On } })
764
+ * import { Effect } from "effect"
765
+ *
766
+ * const Events = Machine.events({ Toggle: {} })
652
767
  * const machine = Machine.make({
653
- * root: States,
654
- * events: Machine.eventsFromSchemas(Toggle)
768
+ * root: Machine.state({ states: { Off: {}, On: {} } }),
769
+ * events: Events
655
770
  * }).handle({
656
- * initial: {
657
- * target: "Off"
658
- * },
771
+ * initial: { target: "Off" },
659
772
  * states: {
660
- * Off: {
661
- * on: {
662
- * Toggle: { target: "On" }
663
- * }
664
- * },
665
- * On: {}
773
+ * Off: { on: { Toggle: { target: "On" } } }
666
774
  * }
667
775
  * })
668
- * const nextState = Effect.gen(function*() {
776
+ *
777
+ * const path = Effect.gen(function*() {
669
778
  * const initial = yield* Machine.planInitial(machine)
670
- * return (yield* Machine.plan(machine, initial.state, new Toggle({}))).next
779
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Toggle())
780
+ * return planned.next.state.path
671
781
  * })
782
+ *
783
+ * await Effect.runPromise(path) // => "On"
672
784
  * ```
673
785
  *
674
786
  * @see {@link planInitial} for planning machine startup.
@@ -700,8 +812,11 @@ export const plan = internal.plan;
700
812
  * which machine will eventually own it. Prefer typed output, typed child
701
813
  * addresses, or invocation lifecycle transitions when possible.
702
814
  *
703
- * Use an inline `invoke` with an `effect` source for one-shot work.
704
- * @see {@link transition} for event-driven state.
815
+ * For one-shot work, register an Effect in `make({ effects })` and invoke it
816
+ * with `invoke: { src }` instead. Register logic in `make({ logic })` to run it
817
+ * for the lifetime of one state.
818
+ *
819
+ * @see {@link make} for registering sources that states invoke by name.
705
820
  * @category constructors
706
821
  * @since 0.4.0
707
822
  */
@@ -795,9 +910,31 @@ export const watch = internal.watch;
795
910
  * Type predicates narrow the returned snapshot. Intermediate microsteps and
796
911
  * historical snapshots are not observed.
797
912
  *
798
- * @example
799
- * ```ts
800
- * const snapshot = yield* Machine.waitFor(ref, isReady).pipe(Effect.timeout("5 seconds"))
913
+ * **Example** (Waiting for a state with a timeout)
914
+ *
915
+ * ```ts import.meta.vitest
916
+ * import { Machine } from "@typeonce/effect-machine"
917
+ * import { Effect } from "effect"
918
+ *
919
+ * const Events = Machine.events({ Finish: {} })
920
+ * const machine = Machine.make({
921
+ * root: Machine.state({ states: { Working: {}, Ready: {} } }),
922
+ * events: Events
923
+ * }).handle({
924
+ * initial: { target: "Working" },
925
+ * states: {
926
+ * Working: { on: { Finish: { target: "Ready" } } }
927
+ * }
928
+ * })
929
+ *
930
+ * const path = Effect.scoped(Effect.gen(function*() {
931
+ * const ref = yield* Machine.start(machine)
932
+ * yield* ref.send(Events.Finish())
933
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
934
+ * return ready.state.state.path
935
+ * }))
936
+ *
937
+ * await Effect.runPromise(path) // => "Ready"
801
938
  * ```
802
939
  * @category combinators
803
940
  * @since 0.37.0
@@ -814,15 +951,41 @@ export const waitFor = internal.waitFor;
814
951
  * `prepared.start` is one-shot and scoped: the `Scope` that first evaluates it
815
952
  * owns the machine, and closing that `Scope` is equivalent to `ref.stop`.
816
953
  *
817
- * ```ts
818
- * const prepared = yield* Machine.prepare(machine)
954
+ * **Example** (Observing emissions before startup)
819
955
  *
820
- * yield* prepared.emissions.pipe(
821
- * Stream.runForEach(handleEmission),
822
- * Effect.forkScoped({ startImmediately: true })
823
- * )
956
+ * ```ts import.meta.vitest
957
+ * import { Machine } from "@typeonce/effect-machine"
958
+ * import { Effect, Stream } from "effect"
959
+ *
960
+ * const Emitted = Machine.emittedEvents({ Started: {} })
961
+ * const machine = Machine.make({
962
+ * root: Machine.state({ states: { Idle: {} } }),
963
+ * events: Machine.events({}),
964
+ * emittedEvents: Emitted
965
+ * }).handle({
966
+ * initial: { target: "Idle" },
967
+ * states: {
968
+ * Idle: {
969
+ * entry: (_, enqueue) => {
970
+ * enqueue.emit(Emitted.Started())
971
+ * }
972
+ * }
973
+ * }
974
+ * })
975
+ *
976
+ * const emitted = Effect.scoped(Effect.gen(function*() {
977
+ * const prepared = yield* Machine.prepare(machine)
978
+ * const seen: Array<string> = []
979
+ * yield* prepared.emissions.pipe(
980
+ * Stream.runForEach((event) => Effect.sync(() => seen.push(event._tag))),
981
+ * Effect.forkScoped({ startImmediately: true })
982
+ * )
983
+ * yield* prepared.start
984
+ * yield* Effect.yieldNow
985
+ * return seen
986
+ * }))
824
987
  *
825
- * const ref = yield* prepared.start
988
+ * await Effect.runPromise(emitted) // => ["Started"]
826
989
  * ```
827
990
  *
828
991
  * @category constructors
@@ -858,29 +1021,23 @@ export const prepare = internal.prepare;
858
1021
  * rather than being returned by `send`. Sending after the machine reaches any
859
1022
  * terminal state fails immediately with `StoppedError`.
860
1023
  *
861
- * **Example**
1024
+ * **Example** (Starting a machine in a scope)
862
1025
  *
863
- * ```ts
1026
+ * ```ts import.meta.vitest
864
1027
  * import { Machine } from "@typeonce/effect-machine"
865
- * import { Effect, Schema } from "effect"
866
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
867
- * }
868
- * const States = Machine.state({ states: { Idle } })
869
- * const machine = Machine.make({
870
- * root: States,
871
- * events: Machine.eventsFromSchemas()
872
- * }).handle({
873
- * initial: {
874
- * target: "Idle"
875
- * },
876
- * states: {
877
- * Idle: {}
878
- * }
1028
+ * import { Effect } from "effect"
1029
+ *
1030
+ * const States = Machine.state({ states: { Idle: {} } })
1031
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
1032
+ * initial: { target: "Idle" }
879
1033
  * })
880
- * const state = Effect.scoped(Effect.gen(function*() {
1034
+ *
1035
+ * const path = Effect.scoped(Effect.gen(function*() {
881
1036
  * const ref = yield* Machine.start(machine)
882
- * return yield* ref.state
1037
+ * return (yield* ref.state).state.path
883
1038
  * }))
1039
+ *
1040
+ * await Effect.runPromise(path) // => "Idle"
884
1041
  * ```
885
1042
  *
886
1043
  * @see {@link plan} for inspecting the same transition plan without executing it.
@@ -899,7 +1056,7 @@ export const start = internal.start;
899
1056
  * the `Scope` is equivalent to `ref.stop`.
900
1057
  *
901
1058
  * `resume` validates and normalizes the supplied snapshot before publishing it
902
- * as the first state. It does not call the machine's initial function, replay
1059
+ * as the first state. It does not construct the declared initial state, replay
903
1060
  * entry or transition actions, re-deliver raised or emitted events, or
904
1061
  * re-evaluate historical completion and eventless transitions. Active-state
905
1062
  * invokes start once in ancestor and document order with {@link InitialEvent};
@@ -917,31 +1074,26 @@ export const start = internal.start;
917
1074
  * evaluated merely because the runtime was resumed; only ordinary subsequent
918
1075
  * transition planning can enter and stabilize states.
919
1076
  *
920
- * **Example**
1077
+ * **Example** (Resuming from a decoded snapshot)
921
1078
  *
922
- * ```ts
1079
+ * ```ts import.meta.vitest
923
1080
  * import { Machine } from "@typeonce/effect-machine"
924
- * import { Effect, Schema } from "effect"
925
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
926
- * }
927
- * const States = Machine.state({ states: { Idle } })
928
- * const machine = Machine.make({
929
- * root: States,
930
- * events: Machine.eventsFromSchemas()
931
- * }).handle({
932
- * initial: {
933
- * target: "Idle"
934
- * },
935
- * states: {
936
- * Idle: {}
937
- * }
1081
+ * import { Effect } from "effect"
1082
+ *
1083
+ * const States = Machine.state({ states: { Idle: {} } })
1084
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
1085
+ * initial: { target: "Idle" }
938
1086
  * })
939
- * const resumed = Effect.scoped(Effect.gen(function*() {
1087
+ *
1088
+ * const path = Effect.scoped(Effect.gen(function*() {
940
1089
  * const initial = yield* Machine.planInitial(machine)
941
1090
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
942
1091
  * const snapshot = yield* Machine.decodeSnapshot(machine, encoded)
943
- * return yield* Machine.resume(machine, snapshot)
1092
+ * const ref = yield* Machine.resume(machine, snapshot)
1093
+ * return (yield* ref.state).state.path
944
1094
  * }))
1095
+ *
1096
+ * await Effect.runPromise(path) // => "Idle"
945
1097
  * ```
946
1098
  *
947
1099
  * @see {@link decodeSnapshot} for the schema and transport boundary.