@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/src/Machine.ts CHANGED
@@ -28,7 +28,7 @@ import * as internal from "./internal/machine/machine.js"
28
28
  import { InitialEventTypeId } from "./internal/machine/machine.js"
29
29
  import type { EnsureExecutable } from "./internal/machine/readiness.js"
30
30
  import type { ExcludeCompatibleRuntime } from "./internal/machine/requirements.js"
31
- import type * as internalRuntime from "./internal/machine/runtimeProtocol.js"
31
+ import type { MachineRuntime } from "./internal/machine/runtimeProtocol.js"
32
32
  import type * as StateDefinition from "./internal/machine/stateDefinition.js"
33
33
  import type * as Topology from "./internal/machine/topology.js"
34
34
 
@@ -49,17 +49,32 @@ export type TypeId = "~effect/Machine"
49
49
  */
50
50
  export const TypeId: TypeId = "~effect/Machine"
51
51
 
52
- declare const MachineOutputStatesTypeId: unique symbol
53
- declare const MachineTypeId: unique symbol
54
- declare const EventConstructionTypeId: unique symbol
55
- declare const EmittedEventConstructionTypeId: unique symbol
56
- declare const EventProtocolTypeId: unique symbol
57
- declare const ParentModeTypeId: unique symbol
52
+ // Type-level keys of public interfaces. Each is a string literal, as in
53
+ // Effect's own modules, so a consumer's emitted declaration prints the key
54
+ // itself instead of naming a private constant. None of them exists at runtime:
55
+ // a value that needs a runtime marker keeps a private symbol, and the public
56
+ // interface carries the string key as a brand only.
57
+ declare const MachineOutputStatesTypeId: "~effect/Machine/OutputStates"
58
+ declare const MachineTypeId: "~effect/Machine/TypeCarrier"
59
+ declare const EventConstructionTypeId: "~effect/Machine/EventConstruction"
60
+ declare const EmittedEventConstructionTypeId: "~effect/Machine/EmittedEventConstruction"
61
+ declare const EventProtocolTypeId: "~effect/Machine/EventProtocol"
62
+ declare const ParentModeTypeId: "~effect/Machine/ParentMode"
63
+ declare const ChildMachineLogicTypeId: "~effect/Machine/ChildMachineLogic"
64
+ declare const InvokeTypeId: "~effect/Machine/Invoke"
65
+ declare const StateConstructionTypeId: "~effect/Machine/StateConstruction"
66
+ declare const TargetSnapshotTypeId: "~effect/Machine/TargetSnapshot"
67
+ declare const HistoryTargetTypeId: "~effect/Machine/HistoryTarget"
68
+ declare const InitialTargetTypeId: "~effect/Machine/InitialTarget"
69
+ declare const ChoiceTargetTypeId: "~effect/Machine/ChoiceTarget"
70
+ declare const NoTargetTypeId: "~effect/Machine/NoTarget"
71
+ declare const DeclinedTypeId: "~effect/Machine/Declined"
72
+ declare const StateUpdateTypeId: "~effect/Machine/StateUpdate"
73
+ declare const CombinedTargetTypeId: "~effect/Machine/CombinedTarget"
74
+ declare const SelectedBranchTypeId: "~effect/Machine/SelectedBranch"
58
75
 
59
76
  const ParentTypeId = "~effect/Machine/Parent"
60
77
 
61
- const ChildMachineLogicTypeId: typeof internal.ChildMachineLogicTypeId = internal.ChildMachineLogicTypeId
62
-
63
78
  /**
64
79
  * Type identifier used for the synthetic event passed to startup lifecycle
65
80
  * actions.
@@ -112,29 +127,38 @@ type IsAny<A> = 0 extends (1 & A) ? true : false
112
127
  * **Gotchas**
113
128
  *
114
129
  * Use `guard` to decline a transition before constructing its next state.
115
- * Use `declinable: true` when a named branch resolver may return `decline()`.
130
+ * List `{ decline: true }` in `branches` when `resolve` may return `select.decline()`.
116
131
  * Register cancellable state-scoped delays in `make({ timers })`.
117
132
  *
118
- * **Example**
133
+ * **Example** (Declining an event with a guard)
119
134
  *
120
- * ```ts
135
+ * ```ts import.meta.vitest
121
136
  * import { Machine } from "@typeonce/effect-machine"
122
- * import { Schema } from "effect"
137
+ * import { Effect, Schema } from "effect"
138
+ *
123
139
  * const events = Machine.events({ Add: { by: Schema.Number } })
124
140
  * const Root = Machine.state({ fields: { count: Schema.Number } })
125
- * export const counter = Machine.make({
141
+ * const counter = Machine.make({
126
142
  * root: Root,
127
143
  * events
128
144
  * }).handle({
129
145
  * root: () => ({ count: 0 }),
130
146
  * on: {
131
147
  * Add: {
132
- * update: "root",
133
- * guard: ({ event }) => event.by > 0,
134
- * data: ({ root, event }) => ({ count: root.count + event.by })
148
+ * update: { root: ({ root, event }) => ({ count: root.count + event.by }) },
149
+ * guard: ({ event }) => event.by > 0
135
150
  * }
136
151
  * }
137
152
  * })
153
+ *
154
+ * const accepts = (by: number) =>
155
+ * Effect.gen(function*() {
156
+ * const initial = yield* Machine.planInitial(counter)
157
+ * return yield* Machine.can(counter, initial.state, events.Add({ by }))
158
+ * })
159
+ *
160
+ * await Effect.runPromise(accepts(1)) // => true
161
+ * await Effect.runPromise(accepts(0)) // => false
138
162
  * ```
139
163
  *
140
164
  * @category models
@@ -303,19 +327,27 @@ export interface Definition<
303
327
  * captured by value, so later mutation of the supplied objects cannot alter
304
328
  * the resulting machine.
305
329
  *
306
- * **Example**
307
- *
308
- * ```ts
309
- * const counter = definition.handle({ states: {
310
- * Count: {
311
- * on: {
312
- * Increment: {
313
- * update: "Count",
314
- * decoded: ({ event, state }) => new Count({ value: state.value + event.by })
315
- * }
316
- * }
317
- * }
318
- * } })
330
+ * **Example** (Adding handlers to a definition)
331
+ *
332
+ * ```ts import.meta.vitest
333
+ * import { Machine } from "@typeonce/effect-machine"
334
+ * import { Effect, Schema } from "effect"
335
+ *
336
+ * const Events = Machine.events({ Increment: { by: Schema.Number } })
337
+ * const definition = Machine.make({ root: Machine.state({ fields: { count: Schema.Number } }), events: Events })
338
+ *
339
+ * const counter = definition.handle({
340
+ * root: { count: 0 },
341
+ * on: { Increment: { update: { root: ({ root, event }) => ({ count: root.count + event.by }) } } }
342
+ * })
343
+ *
344
+ * const count = Effect.gen(function*() {
345
+ * const initial = yield* Machine.planInitial(counter)
346
+ * const planned = yield* Machine.plan(counter, initial.state, Events.Increment({ by: 2 }))
347
+ * return planned.next.value.count
348
+ * })
349
+ *
350
+ * await Effect.runPromise(count) // => 2
319
351
  * ```
320
352
  *
321
353
  * @since 0.4.0
@@ -412,9 +444,31 @@ export {
412
444
  StoppedError
413
445
  } from "./internal/machine/machine.js"
414
446
 
447
+ export type {
448
+ /**
449
+ * Service required by operations that act on the machine executing them,
450
+ * such as `sendTo`, `stopChild`, and `spawn`.
451
+ *
452
+ * **When to use**
453
+ *
454
+ * Name this requirement when annotating a reusable helper built from those
455
+ * operations, or when exporting a value whose inferred type includes it.
456
+ *
457
+ * **Details**
458
+ *
459
+ * A running machine provides this service to the effects it executes, so it
460
+ * never appears in the requirements of the machine itself. Only the type is
461
+ * public: the service cannot be constructed or provided outside a running
462
+ * machine.
463
+ *
464
+ * @category services
465
+ * @since 0.47.0
466
+ */
467
+ MachineRuntime
468
+ } from "./internal/machine/runtimeProtocol.js"
469
+
415
470
  const RuntimeRequirementTypeId = "~effect/Machine/RuntimeRequirement"
416
471
  const ActionRequirementTypeId = "~effect/Machine/ActionRequirement"
417
- type MachineRuntimeRequirement = internalRuntime.MachineRuntime
418
472
 
419
473
  /**
420
474
  * Opaque marker used to keep staged action errors and services separate from
@@ -462,8 +516,8 @@ export type PlanningServices<Requirements> = Exclude<Requirements, ActionRequire
462
516
  * @since 0.4.0
463
517
  */
464
518
  export type ExecutionServices<Requirements> =
465
- | Exclude<PlanningServices<Requirements>, MachineRuntimeRequirement>
466
- | Exclude<ActionServices<Requirements>, MachineRuntimeRequirement>
519
+ | Exclude<PlanningServices<Requirements>, MachineRuntime>
520
+ | Exclude<ActionServices<Requirements>, MachineRuntime>
467
521
 
468
522
  /**
469
523
  * Managed runtime capability used to deliver raised events and publish
@@ -617,33 +671,6 @@ export type Command =
617
671
  * @since 0.4.0
618
672
  */
619
673
  export declare namespace Runtime {
620
- /**
621
- * Protocol annotation for managed event delivery.
622
- *
623
- * @category models
624
- * @since 0.4.0
625
- */
626
- export interface Protocol {
627
- readonly events?: unknown
628
- readonly emits?: unknown
629
- }
630
-
631
- /**
632
- * Extracts the events required by a runtime protocol annotation.
633
- *
634
- * @category utility types
635
- * @since 0.4.0
636
- */
637
- export type Events<Protocol> = Protocol extends { readonly events: infer Events } ? Events : never
638
-
639
- /**
640
- * Extracts the emitted events required by a runtime protocol annotation.
641
- *
642
- * @category utility types
643
- * @since 0.4.0
644
- */
645
- export type Emits<Protocol> = Protocol extends { readonly emits: infer Emits } ? Emits : never
646
-
647
674
  /**
648
675
  * Opaque service requirement for a machine runtime capability.
649
676
  *
@@ -666,8 +693,6 @@ type IncompatibleRuntime<Requirements, Events, Emits> = Requirements extends Run
666
693
  : Requirements
667
694
  : never
668
695
 
669
- const InvokeTypeId: typeof internal.InvokeTypeId = internal.InvokeTypeId
670
-
671
696
  type StateDefinitionError<
672
697
  Message extends string,
673
698
  Path extends PropertyKey = never,
@@ -706,8 +731,6 @@ type ActiveStateKey<States extends Machine.StateSchemas> = Machine.ActiveStateKe
706
731
 
707
732
  type HistoryStateKey<States extends Machine.StateSchemas> = Machine.HistoryStateKey<States>
708
733
 
709
- type ChoiceStateKey<States extends Machine.StateSchemas> = Machine.ChoiceStateKey<States>
710
-
711
734
  type StateDefinitionPath<Prefix extends string, Key extends PropertyKey> = Key extends string ?
712
735
  Key extends "" ? Prefix extends "" ? "<empty>" : `${Prefix}.<empty>`
713
736
  : Prefix extends "" ? Key
@@ -816,29 +839,6 @@ type ValidateOutputSchema<Node> = "output" extends keyof Node ? Node extends { r
816
839
  : StateDefinitionError<"State output must be a schema">
817
840
  : unknown
818
841
 
819
- type SelectorChildKey<Children extends Machine.StateSchemas> = ActiveStateKey<Children> | ChoiceStateKey<Children>
820
-
821
- type ValidateInitialSelectorChild<Children extends Machine.StateSchemas, Path extends PropertyKey> = "initial" extends
822
- SelectorChildKey<Children> ? StateDefinitionError<
823
- "Active and choice child states cannot use the reserved target selector key \"initial\"",
824
- StateDefinitionPath<Extract<Path, string>, "initial">,
825
- "initial"
826
- >
827
- : unknown
828
-
829
- type ValidateWithSelectorChild<
830
- Node extends Machine.StateNodeConfig,
831
- Children extends Machine.StateSchemas,
832
- Path extends PropertyKey
833
- > = Node extends { readonly schema: Machine.TaggedSchema } ?
834
- "with" extends SelectorChildKey<Children> ? StateDefinitionError<
835
- "Schema-backed compound child states cannot use the reserved local target selector key \"with\"",
836
- StateDefinitionPath<Extract<Path, string>, "with">,
837
- "with"
838
- >
839
- : unknown
840
- : unknown
841
-
842
842
  type ValidateStateNodeWithChildren<
843
843
  Node extends Machine.StateNodeConfig,
844
844
  Children,
@@ -846,9 +846,8 @@ type ValidateStateNodeWithChildren<
846
846
  > = Children extends Machine.StateSchemas ?
847
847
  Node extends { readonly type: "final" } ? StateDefinitionError<"Final states cannot declare child states">
848
848
  : Node extends { readonly type: "parallel" } ?
849
- & ValidateInitialSelectorChild<Children, Path>
850
- & ("initial" extends keyof Node ? StateDefinitionError<"Parallel states cannot declare an initial child">
851
- : { readonly states: ValidateStateTree<Children, true, Extract<Path, string>> } & ValidateOutputSchema<Node>)
849
+ "initial" extends keyof Node ? StateDefinitionError<"Parallel states cannot declare an initial child">
850
+ : { readonly states: ValidateStateTree<Children, true, Extract<Path, string>> } & ValidateOutputSchema<Node>
852
851
  : "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output">
853
852
  : ValidateCompoundStateNode<Node, Children, Path>
854
853
  : StateDefinitionError<"Child states must be a state tree">
@@ -858,9 +857,7 @@ type ValidateCompoundStateNode<
858
857
  Children extends Machine.StateSchemas,
859
858
  Path extends PropertyKey
860
859
  > = "initial" extends keyof Node ? StateDefinitionError<"Declare initial edges in handle", Path>
861
- : ValidateInitialSelectorChild<Children, Path> & ValidateWithSelectorChild<Node, Children, Path> & {
862
- readonly states: ValidateStateTree<Children, true, Extract<Path, string>>
863
- }
860
+ : { readonly states: ValidateStateTree<Children, true, Extract<Path, string>> }
864
861
 
865
862
  type ValidateStateNodeWithoutChildren<Node extends Machine.StateNodeConfig> = "initial" extends keyof Node ?
866
863
  StateDefinitionError<"Atomic states cannot declare an initial child">
@@ -926,7 +923,27 @@ type StateFieldsValidation<Node> = Node extends { readonly [StateTypeId]: typeof
926
923
  } :
927
924
  unknown)
928
925
 
929
- interface StateInput {
926
+ /**
927
+ * Declaration of one state node accepted by {@link state}: its schema or
928
+ * fields, its kind, and its nested child states.
929
+ *
930
+ * **When to use**
931
+ *
932
+ * Name this type when a declaration you emit includes the signature of
933
+ * `Machine.state`. Build state trees with `Machine.state` itself, which checks
934
+ * the declaration further.
935
+ *
936
+ * **Details**
937
+ *
938
+ * Each entry of `states` is a tagged schema, a nested declaration, or a
939
+ * descriptor returned by `Machine.state`. `Machine.state` validates the whole
940
+ * tree further, so satisfying this type alone does not make a declaration
941
+ * valid.
942
+ *
943
+ * @category models
944
+ * @since 0.47.0
945
+ */
946
+ export interface StateDeclaration {
930
947
  readonly schema?: Machine.TaggedSchema
931
948
  readonly fields?: Schema.Struct.Fields
932
949
  readonly type?: "active" | "parallel" | "final" | "history" | "choice"
@@ -934,7 +951,7 @@ interface StateInput {
934
951
  readonly states?: Readonly<
935
952
  Record<
936
953
  string,
937
- Machine.TaggedSchema | StateInput | {
954
+ Machine.TaggedSchema | StateDeclaration | {
938
955
  readonly [StateTypeId]: typeof StateTypeId
939
956
  readonly node: Machine.StateNodeConfig
940
957
  }
@@ -945,8 +962,8 @@ interface StateInput {
945
962
  readonly annotations?: Machine.SchemaLessStateAnnotations
946
963
  }
947
964
 
948
- interface StateConstructor {
949
- <const Node extends StateInput>(
965
+ type StateConstructor = {
966
+ <const Node extends StateDeclaration>(
950
967
  node: Node & StateFieldsValidation<NoInfer<Node>>,
951
968
  ..._validation: ValidateDefinedState<NormalizeState<NoInfer<Node>>>
952
969
  ): State<NormalizedState<Node>>
@@ -996,217 +1013,12 @@ type ValidateEventProtocolBuilder<
996
1013
  > = [Duplicate] extends [never] ? unknown
997
1014
  : EventProtocolError<"Event protocol tags must be unique", Duplicate>
998
1015
 
999
- const SnapshotBuilderStateTypeId: typeof internal.SnapshotBuilderStateTypeId = internal.SnapshotBuilderStateTypeId
1000
- const SnapshotBuilderConstructionTypeId: unique symbol = Symbol("effect/Machine/SnapshotBuilderConstruction")
1001
-
1002
- type SnapshotBuilderComplete<Regions, Constructed extends boolean = false> = {
1003
- readonly [SnapshotBuilderStateTypeId]: Regions
1004
- readonly [SnapshotBuilderConstructionTypeId]: Constructed
1005
- }
1006
-
1007
- type FromCallable<Arguments extends ReadonlyArray<unknown>, Result> = Arguments extends
1008
- readonly [infer Input, ...infer Rest extends ReadonlyArray<unknown>] ? {} extends Input ? {
1009
- (...args: Rest): Result
1010
- (...args: Arguments): Result
1011
- }
1012
- : (...args: Arguments) => Result
1013
- : (...args: Arguments) => Result
1014
-
1015
- type FromMethod<in out Arguments extends ReadonlyArray<unknown>, out Result> = {
1016
- /**
1017
- * Constructs the selected state from its schema make input while the
1018
- * machine plans the resulting configuration. The input may be omitted when
1019
- * the schema accepts an empty constructor object.
1020
- *
1021
- * @since 0.4.0
1022
- */
1023
- readonly from: FromCallable<Arguments, Machine.StateConstruction<Result>>
1024
- }
1025
-
1026
- type DecodedMethod<Arguments extends ReadonlyArray<unknown>, Result> = {
1027
- /**
1028
- * Constructs the selected state from an already-decoded schema value. The
1029
- * machine validates the value against the schema's type side while planning.
1030
- *
1031
- * @since 0.22.0
1032
- */
1033
- readonly decoded: (...args: Arguments) => Result
1034
- }
1035
-
1036
- type ConstructionResult<Result> = Result | Machine.StateConstruction<Result>
1037
-
1038
- type UnwrapConstruction<Result> = Result extends Machine.StateConstruction<infer Value> ? Value : Result
1039
-
1040
1016
  type NodeValue<Node> = [Machine.NodeSchema<Node>] extends [never] ? undefined
1041
1017
  : Machine.NodeSchema<Node>["Type"]
1042
1018
 
1043
1019
  type NodeMakeInput<Node> = [Machine.NodeSchema<Node>] extends [never] ? never
1044
1020
  : Machine.NodeSchema<Node>["~type.make.in"]
1045
1021
 
1046
- type WithNodeValue<Node, Rest extends ReadonlyArray<unknown>> = Machine.NodeSchema<Node> extends never ? Rest
1047
- : readonly [value: NodeValue<Node>, ...Rest]
1048
-
1049
- type WithNodeInput<Node, Rest extends ReadonlyArray<unknown>> = Machine.NodeSchema<Node> extends never ? Rest
1050
- : readonly [input: NodeMakeInput<Node>, ...Rest]
1051
-
1052
- type NodeBuilderMethod<
1053
- Node,
1054
- Arguments extends ReadonlyArray<unknown>,
1055
- Result,
1056
- FromArguments extends ReadonlyArray<unknown>,
1057
- FromResult
1058
- > = Machine.NodeSchema<Node> extends never ? {
1059
- readonly from: FromCallable<FromArguments, FromResult>
1060
- }
1061
- : DecodedMethod<Arguments, Result> & { readonly from: FromCallable<FromArguments, FromResult> }
1062
-
1063
- type NodeMethod<
1064
- Node,
1065
- Arguments extends ReadonlyArray<unknown>,
1066
- Result,
1067
- FromArguments extends ReadonlyArray<unknown>
1068
- > = Machine.NodeSchema<Node> extends never ? FromMethod<FromArguments, Result>
1069
- : DecodedMethod<Arguments, Result> & FromMethod<FromArguments, Result>
1070
-
1071
- type NodeMethodWithInitial<
1072
- Node,
1073
- Arguments extends ReadonlyArray<unknown>,
1074
- Result,
1075
- FromArguments extends ReadonlyArray<unknown>,
1076
- Path extends string
1077
- > = Machine.NodeSchema<Node> extends never ? {
1078
- readonly from: FromCallable<FromArguments, Machine.StateConstruction<Result>>
1079
- readonly initial: InitialTargetFactory<Node, Path>
1080
- }
1081
- :
1082
- & DecodedMethod<Arguments, Result>
1083
- & {
1084
- readonly from: FromCallable<FromArguments, Machine.StateConstruction<Result>>
1085
- readonly initial: InitialTargetFactory<Node, Path>
1086
- }
1087
-
1088
- interface InitialTargetMethod<
1089
- Node,
1090
- Path extends string
1091
- > {
1092
- /** Enters this state through its declared initial configuration. */
1093
- readonly initial: InitialTargetFactory<Node, Path>
1094
- }
1095
-
1096
- interface InitialTargetFactory<
1097
- Node,
1098
- Path extends string
1099
- > {
1100
- readonly from: FromCallable<
1101
- WithNodeInput<Node, readonly []>,
1102
- Machine.StateConstruction<Machine.InitialTarget<Path>>
1103
- >
1104
- readonly decoded: (...args: WithNodeValue<Node, readonly []>) => Machine.InitialTarget<Path>
1105
- }
1106
-
1107
- type NodeConstructionSelectorFromCallable<Node, Builder, Result> = Machine.NodeSchema<Node> extends never ? {
1108
- <Selected extends ConstructionResult<Result>>(
1109
- state: (builder: Builder) => Selected
1110
- ): Machine.StateConstruction<UnwrapConstruction<Selected>>
1111
- }
1112
- : ConstructionSelectorFromCallable<NodeMakeInput<Node>, Builder, Result>
1113
-
1114
- type NestedTargetMethod<Node, Builder, Result, Path extends string> = Machine.NodeSchema<Node> extends never ? {
1115
- readonly from: NodeConstructionSelectorFromCallable<Node, Builder, Result>
1116
- readonly initial: InitialTargetFactory<Node, Path>
1117
- }
1118
- : {
1119
- readonly decoded: <Selected extends ConstructionResult<Result>>(
1120
- value: NodeValue<Node>,
1121
- state: (builder: Builder) => Selected
1122
- ) => Selected
1123
- readonly from: NodeConstructionSelectorFromCallable<Node, Builder, Result>
1124
- readonly initial: InitialTargetFactory<Node, Path>
1125
- }
1126
-
1127
- type ConstructionSelectorFromCallable<Input, Builder, Result> = {} extends Input ? {
1128
- <Selected extends ConstructionResult<Result>>(
1129
- state: (builder: Builder) => Selected
1130
- ): Machine.StateConstruction<UnwrapConstruction<Selected>>
1131
- <Selected extends ConstructionResult<Result>>(
1132
- input: Input,
1133
- state: (builder: Builder) => Selected
1134
- ): Machine.StateConstruction<UnwrapConstruction<Selected>>
1135
- }
1136
- : <Selected extends ConstructionResult<Result>>(
1137
- input: Input,
1138
- state: (builder: Builder) => Selected
1139
- ) => Machine.StateConstruction<UnwrapConstruction<Selected>>
1140
-
1141
- type FullSnapshotBuilderWithPrefix<
1142
- in out States extends Machine.StateSchemas,
1143
- in out Prefix extends string = ""
1144
- > = {
1145
- readonly [Key in ActiveStateKey<States> | ChoiceStateKey<States>]: Key extends ActiveStateKey<States>
1146
- ? FullSnapshotMethod<States, Key, Prefix>
1147
- : () => Machine.ChoiceTargetInstruction<Machine.JoinPath<Prefix, Key>>
1148
- }
1149
-
1150
- type FullSnapshotMethod<
1151
- in out States extends Machine.StateSchemas,
1152
- in out StateId extends ActiveStateKey<States>,
1153
- in out Prefix extends string
1154
- > = {
1155
- readonly [
1156
- /** Constructs this node using schema make input or an already decoded value. */
1157
- Method in Machine.NodeSchema<States[StateId]> extends never ? "from" : "from" | "decoded"
1158
- ]: Method extends "from" ? FromCallable<
1159
- FullSnapshotFromArguments<States, StateId, Prefix>,
1160
- Machine.StateConstruction<FullSnapshotResult<States, StateId, Prefix>>
1161
- >
1162
- : (...args: FullSnapshotArguments<States, StateId, Prefix>) => FullSnapshotResult<States, StateId, Prefix>
1163
- }
1164
-
1165
- type FullSnapshotArguments<
1166
- States extends Machine.StateSchemas,
1167
- StateId extends ActiveStateKey<States>,
1168
- Prefix extends string,
1169
- Path extends string = Machine.JoinPath<Prefix, StateId>
1170
- > = States[StateId] extends infer Node ?
1171
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1172
- WithNodeValue<Node, [
1173
- states: (
1174
- builder: FullParallelBuilder<Children, Path>
1175
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
1176
- ]>
1177
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ? WithNodeValue<Node, [
1178
- state: (
1179
- builder: FullSnapshotBuilderWithPrefix<Children, Path>
1180
- ) =>
1181
- | Machine.SnapshotWithPrefix<Children, Path>
1182
- | Machine.ChoiceTargetInstruction<Machine.ChoiceIdentifierWithPrefix<Children, Path>>
1183
- ]>
1184
- : WithNodeValue<Node, []>
1185
- : never
1186
-
1187
- type FullSnapshotFromArguments<
1188
- States extends Machine.StateSchemas,
1189
- StateId extends ActiveStateKey<States>,
1190
- Prefix extends string,
1191
- Path extends string = Machine.JoinPath<Prefix, StateId>
1192
- > = States[StateId] extends infer Node ?
1193
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1194
- WithNodeInput<Node, [
1195
- states: (
1196
- builder: FullParallelBuilder<Children, Path>
1197
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
1198
- ]>
1199
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ? WithNodeInput<Node, [
1200
- state: (
1201
- builder: FullSnapshotBuilderWithPrefix<Children, Path>
1202
- ) => ConstructionResult<
1203
- | Machine.SnapshotWithPrefix<Children, Path>
1204
- | Machine.ChoiceTargetInstruction<Machine.ChoiceIdentifierWithPrefix<Children, Path>>
1205
- >
1206
- ]>
1207
- : WithNodeInput<Node, []>
1208
- : never
1209
-
1210
1022
  type FullSnapshotResult<
1211
1023
  States extends Machine.StateSchemas,
1212
1024
  StateId extends ActiveStateKey<States>,
@@ -1214,88 +1026,6 @@ type FullSnapshotResult<
1214
1026
  Path extends string = Machine.JoinPath<Prefix, StateId>
1215
1027
  > = Machine.SnapshotByIdentifierWithPath<States, StateId, Path>
1216
1028
 
1217
- type InitialEntryStateKey<States extends Machine.StateSchemas> = {
1218
- readonly [Key in ActiveStateKey<States>]: States[Key] extends { readonly states: Machine.StateSchemas } ? Key : never
1219
- }[ActiveStateKey<States>]
1220
-
1221
- type FullInitialTargetBuilder<States extends Machine.StateSchemas> = {
1222
- readonly [Key in InitialEntryStateKey<States>]: InitialTargetMethod<States[Key], Key>
1223
- }
1224
-
1225
- type FullParallelBuilder<
1226
- States extends Machine.StateSchemas,
1227
- Prefix extends string,
1228
- Remaining extends ActiveStateKey<States> = ActiveStateKey<States>,
1229
- Regions = {},
1230
- Constructed extends boolean = false
1231
- > =
1232
- & SnapshotBuilderComplete<Regions, Constructed>
1233
- & {
1234
- readonly [Key in Remaining]: NodeBuilderMethod<
1235
- States[Key],
1236
- FullSnapshotArguments<States, Key, Prefix>,
1237
- FullParallelBuilder<
1238
- States,
1239
- Prefix,
1240
- Exclude<Remaining, Key>,
1241
- Regions & { readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix> },
1242
- Constructed
1243
- >,
1244
- FullSnapshotFromArguments<States, Key, Prefix>,
1245
- FullParallelBuilder<
1246
- States,
1247
- Prefix,
1248
- Exclude<Remaining, Key>,
1249
- Regions & { readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix> },
1250
- true
1251
- >
1252
- >
1253
- }
1254
-
1255
- type HistorySnapshotArguments<
1256
- States extends Machine.StateSchemas,
1257
- StateId extends ActiveStateKey<States>,
1258
- Prefix extends string,
1259
- Owner extends string,
1260
- Path extends string = Machine.JoinPath<Prefix, StateId>
1261
- > = Path extends Owner ? FullSnapshotArguments<States, StateId, Prefix>
1262
- : States[StateId] extends infer Node ?
1263
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1264
- WithNodeValue<Node, [
1265
- states: (
1266
- builder: HistoryParallelBuilder<Children, Path, Owner>
1267
- ) => SnapshotBuilderComplete<HistorySnapshotRegions<Children, Path, Owner>>
1268
- ]>
1269
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ? WithNodeValue<Node, [
1270
- state: (
1271
- builder: HistorySnapshotBuilderWithPrefix<Children, Owner, Path>
1272
- ) => ConstructionResult<HistorySnapshotWithPrefix<Children, Owner, Path>>
1273
- ]>
1274
- : never
1275
- : never
1276
-
1277
- type HistorySnapshotFromArguments<
1278
- States extends Machine.StateSchemas,
1279
- StateId extends ActiveStateKey<States>,
1280
- Prefix extends string,
1281
- Owner extends string,
1282
- Path extends string = Machine.JoinPath<Prefix, StateId>
1283
- > = Path extends Owner ? FullSnapshotFromArguments<States, StateId, Prefix>
1284
- : States[StateId] extends infer Node ?
1285
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1286
- WithNodeInput<Node, [
1287
- states: (
1288
- builder: HistoryParallelBuilder<Children, Path, Owner>
1289
- ) => SnapshotBuilderComplete<HistorySnapshotRegions<Children, Path, Owner>, boolean>
1290
- ]>
1291
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ? WithNodeInput<Node, [
1292
- state: (
1293
- builder: HistorySnapshotBuilderWithPrefix<Children, Owner, Path>
1294
- ) => ConstructionResult<HistorySnapshotWithPrefix<Children, Owner, Path>>
1295
- ]>
1296
- : never
1297
- : never
1298
-
1299
1029
  type HistorySnapshotResult<
1300
1030
  States extends Machine.StateSchemas,
1301
1031
  StateId extends ActiveStateKey<States>,
@@ -1318,22 +1048,6 @@ type HistorySnapshotResult<
1318
1048
  : never
1319
1049
  : never
1320
1050
 
1321
- type HistorySnapshotMethod<
1322
- in out States extends Machine.StateSchemas,
1323
- in out StateId extends ActiveStateKey<States>,
1324
- in out Prefix extends string,
1325
- in out Owner extends string
1326
- > = {
1327
- readonly [Key in Machine.NodeSchema<States[StateId]> extends never ? "from" : "from" | "decoded"]: Key extends
1328
- "from" ? FromCallable<
1329
- HistorySnapshotFromArguments<States, StateId, Prefix, Owner>,
1330
- Machine.StateConstruction<HistorySnapshotResult<States, StateId, Prefix, Owner>>
1331
- > :
1332
- (
1333
- ...args: HistorySnapshotArguments<States, StateId, Prefix, Owner>
1334
- ) => HistorySnapshotResult<States, StateId, Prefix, Owner>
1335
- }
1336
-
1337
1051
  type HistorySnapshotWithPrefix<
1338
1052
  States extends Machine.StateSchemas,
1339
1053
  Owner extends string,
@@ -1346,352 +1060,20 @@ type HistorySnapshotWithPrefix<
1346
1060
  : never
1347
1061
  }[ActiveStateKey<States>]
1348
1062
 
1349
- type HistorySnapshotBuilderWithPrefix<
1350
- States extends Machine.StateSchemas,
1351
- Owner extends string,
1352
- Prefix extends string = ""
1353
- > = {
1354
- readonly [
1355
- Key in ActiveStateKey<States> as Owner extends
1356
- | Machine.JoinPath<Prefix, Key>
1357
- | (Machine.JoinPath<Prefix, Key> extends "" ? string : `${Machine.JoinPath<Prefix, Key>}.${string}`) ? Key
1358
- : never
1359
- ]: HistorySnapshotMethod<States, Key, Prefix, Owner>
1360
- }
1361
-
1362
- type HistorySnapshotRegions<
1363
- States extends Machine.StateSchemas,
1364
- Prefix extends string,
1365
- Owner extends string
1366
- > = {
1367
- readonly [Key in ActiveStateKey<States>]: Owner extends
1368
- | Machine.JoinPath<Prefix, Key>
1369
- | (Machine.JoinPath<Prefix, Key> extends "" ? string : `${Machine.JoinPath<Prefix, Key>}.${string}`) ?
1370
- HistorySnapshotResult<States, Key, Prefix, Owner>
1371
- : FullSnapshotResult<States, Key, Prefix>
1372
- }
1373
-
1374
- type HistoryParallelBuilder<
1375
- States extends Machine.StateSchemas,
1376
- Prefix extends string,
1377
- Owner extends string,
1378
- Remaining extends ActiveStateKey<States> = ActiveStateKey<States>,
1379
- Regions = {},
1380
- Constructed extends boolean = false
1381
- > =
1382
- & SnapshotBuilderComplete<Regions, Constructed>
1383
- & {
1384
- readonly [Key in Remaining]: Owner extends
1385
- | Machine.JoinPath<Prefix, Key>
1386
- | (Machine.JoinPath<Prefix, Key> extends "" ? string : `${Machine.JoinPath<Prefix, Key>}.${string}`) ?
1387
- NodeBuilderMethod<
1388
- States[Key],
1389
- HistorySnapshotArguments<States, Key, Prefix, Owner>,
1390
- HistoryParallelBuilder<
1391
- States,
1392
- Prefix,
1393
- Owner,
1394
- Exclude<Remaining, Key>,
1395
- Regions & { readonly [Region in Key]: HistorySnapshotResult<States, Key, Prefix, Owner> },
1396
- Constructed
1397
- >,
1398
- HistorySnapshotFromArguments<States, Key, Prefix, Owner>,
1399
- HistoryParallelBuilder<
1400
- States,
1401
- Prefix,
1402
- Owner,
1403
- Exclude<Remaining, Key>,
1404
- Regions & { readonly [Region in Key]: HistorySnapshotResult<States, Key, Prefix, Owner> },
1405
- true
1406
- >
1407
- >
1408
- : NodeBuilderMethod<
1409
- States[Key],
1410
- FullSnapshotArguments<States, Key, Prefix>,
1411
- HistoryParallelBuilder<
1412
- States,
1413
- Prefix,
1414
- Owner,
1415
- Exclude<Remaining, Key>,
1416
- Regions & { readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix> },
1417
- Constructed
1418
- >,
1419
- FullSnapshotFromArguments<States, Key, Prefix>,
1420
- HistoryParallelBuilder<
1421
- States,
1422
- Prefix,
1423
- Owner,
1424
- Exclude<Remaining, Key>,
1425
- Regions & { readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix> },
1426
- true
1427
- >
1428
- >
1429
- }
1430
-
1431
- type ParentPath<Path extends string> = Machine.ImmediateParentStateIdentifier<Path>
1432
-
1433
- type IsCompoundNode<Node> = Node extends { readonly type: "parallel" } ? false
1434
- : Node extends { readonly states: Machine.StateSchemas } ? true
1435
- : false
1436
-
1437
- type NearestCompoundScope<
1438
- States extends Machine.StateSchemas,
1439
- Source extends Machine.StateNodeIdentifier<States>
1440
- > = Source extends Machine.StateIdentifier<States> ?
1441
- IsCompoundNode<Machine.NodeByIdentifier<States, Source>> extends true ? Source
1442
- : ParentPath<Source> extends infer Parent extends Machine.StateIdentifier<States> ?
1443
- NearestCompoundScope<States, Parent>
1444
- : never
1445
- : ParentPath<Source> extends infer Parent extends Machine.StateIdentifier<States> ?
1446
- NearestCompoundScope<States, Parent>
1447
- : never
1448
-
1449
- type ChildrenOf<
1450
- States extends Machine.StateSchemas,
1451
- Path extends Machine.StateIdentifier<States>
1452
- > = Machine.NodeByIdentifier<States, Path> extends { readonly states: infer Children extends Machine.StateSchemas } ?
1453
- Children
1454
- : never
1455
-
1456
- type StateIdentifierFromPath<
1457
- States extends Machine.StateSchemas,
1458
- Path extends string
1459
- > = Extract<Path, Machine.StateIdentifier<States>>
1460
-
1461
- type LocalTargetResult<
1462
- AllStates extends Machine.StateSchemas,
1463
- States extends Machine.StateSchemas,
1464
- StateId extends ActiveStateKey<States>,
1465
- Prefix extends string,
1466
- Path extends string = Machine.JoinPath<Prefix, StateId>
1467
- > = States[StateId] extends { readonly states: infer Children extends Machine.StateSchemas } ?
1468
- States[StateId] extends { readonly type: "parallel" } ?
1469
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>
1470
- : LocalTargetResultWithPrefix<AllStates, Children, Path>
1471
- : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>
1472
-
1473
- type LocalTargetResultWithPrefix<
1474
- AllStates extends Machine.StateSchemas,
1475
- States extends Machine.StateSchemas,
1476
- Prefix extends string
1477
- > =
1478
- | {
1479
- readonly [Key in ActiveStateKey<States>]: LocalTargetResult<AllStates, States, Key, Prefix>
1480
- }[ActiveStateKey<States>]
1481
- | Machine.ChoiceTarget<
1482
- AllStates,
1483
- Extract<Machine.JoinPath<Prefix, ChoiceStateKey<States>>, Machine.ChoiceIdentifier<AllStates>>
1484
- >
1485
-
1486
- type LocalTargetBuilderWithPrefix<
1487
- AllStates extends Machine.StateSchemas,
1488
- States extends Machine.StateSchemas,
1489
- Prefix extends string,
1490
- Source extends Machine.StateNodeIdentifier<AllStates>
1491
- > =
1492
- & {
1493
- readonly [Key in ActiveStateKey<States>]: LocalTargetMethod<AllStates, States, Key, Prefix, Source>
1494
- }
1495
- & {
1496
- readonly [Key in ChoiceStateKey<States>]: () => Machine.ChoiceTarget<
1497
- AllStates,
1498
- Extract<Machine.JoinPath<Prefix, Key>, Machine.ChoiceIdentifier<AllStates>>
1499
- >
1500
- }
1501
-
1502
- type LocalTargetMethod<
1503
- AllStates extends Machine.StateSchemas,
1504
- States extends Machine.StateSchemas,
1505
- StateId extends ActiveStateKey<States>,
1506
- Prefix extends string,
1507
- Source extends Machine.StateNodeIdentifier<AllStates>,
1508
- Path extends string = Machine.JoinPath<Prefix, StateId>
1509
- > = States[StateId] extends infer Node ?
1510
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1511
- Source extends Path | (Path extends "" ? string : `${Path}.${string}`) ? NestedTargetMethod<
1512
- Node,
1513
- LocalTargetBuilderWithPrefix<AllStates, Children, Path, Source>,
1514
- LocalTargetResultWithPrefix<AllStates, Children, Path>,
1515
- Path
1516
- >
1517
- : NodeMethodWithInitial<
1518
- Node,
1519
- WithNodeValue<Node, [
1520
- states: (
1521
- builder: FullParallelBuilder<Children, Path>
1522
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
1523
- ]>,
1524
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>,
1525
- WithNodeInput<Node, [
1526
- states: (
1527
- builder: FullParallelBuilder<Children, Path>
1528
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
1529
- ]>,
1530
- Path
1531
- >
1532
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ? NestedTargetMethod<
1533
- Node,
1534
- LocalTargetBuilderWithPrefix<AllStates, Children, Path, Source>,
1535
- LocalTargetResultWithPrefix<AllStates, Children, Path>,
1536
- Path
1537
- >
1538
- : NodeMethod<
1539
- Node,
1540
- WithNodeValue<Node, []>,
1541
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>,
1542
- WithNodeInput<Node, []>
1543
- >
1544
- : never
1545
-
1546
- type LocalTargetBuilderForScope<
1547
- States extends Machine.StateSchemas,
1548
- Scope extends Machine.StateIdentifier<States>,
1549
- Source extends Machine.StateNodeIdentifier<States>
1550
- > = ChildrenOf<States, Scope> extends infer Children extends Machine.StateSchemas ?
1551
- & LocalTargetBuilderWithPrefix<States, Children, Scope, Source>
1552
- & (Scope extends Machine.ValuedStateIdentifier<States> ? {
1553
- /**
1554
- * Updates the value of the state containing the local group and moves to
1555
- * one of the states inside it. Values in other active branches are kept.
1556
- *
1557
- * @since 0.4.0
1558
- */
1559
- readonly with: {
1560
- readonly decoded: <Result extends ConstructionResult<LocalTargetResultWithPrefix<States, Children, Scope>>>(
1561
- value: Machine.StateByIdentifier<States, Scope>,
1562
- state: (
1563
- builder: LocalTargetBuilderWithPrefix<States, Children, Scope, Source>
1564
- ) => Result
1565
- ) => Result
1566
- readonly from: ConstructionSelectorFromCallable<
1567
- Machine.SchemaByIdentifier<States, Scope>["~type.make.in"],
1568
- LocalTargetBuilderWithPrefix<States, Children, Scope, Source>,
1569
- LocalTargetResultWithPrefix<States, Children, Scope>
1570
- >
1571
- }
1572
- } :
1573
- {})
1574
- : {}
1575
-
1576
- type BranchTargetResult<
1577
- AllStates extends Machine.StateSchemas,
1578
- States extends Machine.StateSchemas,
1579
- StateId extends ActiveStateKey<States>,
1580
- Prefix extends string,
1581
- Path extends string = Machine.JoinPath<Prefix, StateId>
1582
- > = States[StateId] extends { readonly states: infer Children extends Machine.StateSchemas } ?
1583
- States[StateId] extends { readonly type: "parallel" } ?
1584
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>
1585
- : BranchTargetResultWithPrefix<AllStates, Children, Path>
1586
- : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>
1587
-
1588
- type BranchTargetResultWithPrefix<
1589
- AllStates extends Machine.StateSchemas,
1590
- States extends Machine.StateSchemas,
1591
- Prefix extends string
1592
- > =
1593
- | {
1594
- readonly [Key in ActiveStateKey<States>]: BranchTargetResult<AllStates, States, Key, Prefix>
1595
- }[ActiveStateKey<States>]
1596
- | Machine.ChoiceTarget<
1597
- AllStates,
1598
- Extract<Machine.JoinPath<Prefix, ChoiceStateKey<States>>, Machine.ChoiceIdentifier<AllStates>>
1599
- >
1600
-
1601
- type BranchTargetBuilderWithPrefix<
1602
- AllStates extends Machine.StateSchemas,
1603
- States extends Machine.StateSchemas,
1604
- Prefix extends string,
1605
- Source extends Machine.StateNodeIdentifier<AllStates>
1606
- > =
1607
- & {
1608
- readonly [Key in ActiveStateKey<States>]: BranchTargetMethod<AllStates, States, Key, Prefix, Source>
1609
- }
1610
- & {
1611
- readonly [Key in ChoiceStateKey<States>]: () => Machine.ChoiceTarget<
1612
- AllStates,
1613
- Extract<Machine.JoinPath<Prefix, Key>, Machine.ChoiceIdentifier<AllStates>>
1614
- >
1615
- }
1616
-
1617
- type BranchTargetMethod<
1618
- AllStates extends Machine.StateSchemas,
1619
- States extends Machine.StateSchemas,
1620
- StateId extends ActiveStateKey<States>,
1621
- Prefix extends string,
1622
- Source extends Machine.StateNodeIdentifier<AllStates>,
1623
- Path extends string = Machine.JoinPath<Prefix, StateId>
1624
- > = States[StateId] extends infer Node ?
1625
- Node extends { readonly type: "parallel"; readonly states: infer Children extends Machine.StateSchemas } ?
1626
- Source extends Path | (Path extends "" ? string : `${Path}.${string}`) ?
1627
- & NestedTargetMethod<
1628
- Node,
1629
- BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>,
1630
- BranchTargetResultWithPrefix<AllStates, Children, Path>,
1631
- Path
1632
- >
1633
- & BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>
1634
- : NodeMethodWithInitial<
1635
- Node,
1636
- WithNodeValue<Node, [
1637
- states: (
1638
- builder: FullParallelBuilder<Children, Path>
1639
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
1640
- ]>,
1641
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>,
1642
- WithNodeInput<Node, [
1643
- states: (
1644
- builder: FullParallelBuilder<Children, Path>
1645
- ) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>, boolean>
1646
- ]>,
1647
- Path
1648
- >
1649
- : Node extends { readonly states: infer Children extends Machine.StateSchemas } ?
1650
- & NestedTargetMethod<
1651
- Node,
1652
- BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>,
1653
- BranchTargetResultWithPrefix<AllStates, Children, Path>,
1654
- Path
1655
- >
1656
- & BranchTargetBuilderWithPrefix<AllStates, Children, Path, Source>
1657
- : NodeMethod<
1658
- Node,
1659
- WithNodeValue<Node, []>,
1660
- Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>,
1661
- WithNodeInput<Node, []>
1662
- >
1663
- : never
1664
-
1665
- type BranchTargetBuilderForRoot<
1666
- States extends Machine.StateSchemas,
1667
- Root extends ActiveStateKey<States>,
1668
- Source extends Machine.StateNodeIdentifier<States>
1669
- > = {
1670
- readonly [Key in Root]: BranchTargetMethod<States, States, Key, "", Source>
1671
- }
1672
-
1673
- type HistoryContainingKey<States extends Machine.StateSchemas> = {
1674
- readonly [Key in Extract<keyof States, string>]: States[Key] extends Machine.HistoryStateNodeConfig ? Key
1675
- : States[Key] extends { readonly states: infer Children extends Machine.StateSchemas } ?
1676
- [Machine.HistoryIdentifier<Children>] extends [never] ? never : Key
1677
- : never
1678
- }[Extract<keyof States, string>]
1679
-
1680
- type HistoryTargetBuilderWithPrefix<
1681
- AllStates extends Machine.StateSchemas,
1063
+ type HistorySnapshotRegions<
1682
1064
  States extends Machine.StateSchemas,
1683
- Prefix extends string
1065
+ Prefix extends string,
1066
+ Owner extends string
1684
1067
  > = {
1685
- readonly [Key in HistoryContainingKey<States>]: States[Key] extends Machine.HistoryStateNodeConfig ?
1686
- () => Machine.HistoryTarget<
1687
- AllStates,
1688
- Extract<Machine.JoinPath<Prefix, Key>, Machine.HistoryIdentifier<AllStates>>
1689
- >
1690
- : States[Key] extends { readonly states: infer Children extends Machine.StateSchemas } ?
1691
- HistoryTargetBuilderWithPrefix<AllStates, Children, Machine.JoinPath<Prefix, Key>>
1692
- : never
1068
+ readonly [Key in ActiveStateKey<States>]: Owner extends
1069
+ | Machine.JoinPath<Prefix, Key>
1070
+ | (Machine.JoinPath<Prefix, Key> extends "" ? string : `${Machine.JoinPath<Prefix, Key>}.${string}`) ?
1071
+ HistorySnapshotResult<States, Key, Prefix, Owner>
1072
+ : FullSnapshotResult<States, Key, Prefix>
1693
1073
  }
1694
1074
 
1075
+ type ParentPath<Path extends string> = Machine.ImmediateParentStateIdentifier<Path>
1076
+
1695
1077
  type HasDirectShallowHistory<States extends Machine.StateSchemas> = {
1696
1078
  readonly [Key in HistoryStateKey<States>]: States[Key] extends { readonly history: "deep" } ? never : Key
1697
1079
  }[HistoryStateKey<States>] extends never ? false : true
@@ -1762,7 +1144,7 @@ type SpawnError<Options extends SpawnOptions> = SpawnIdError<Options>
1762
1144
  type SpawnResult<State, Event, Error, Requirements, Output, SpawnError, InitialError = never> = Effect.Effect<
1763
1145
  MachineRef<State, Event, Error, Output>,
1764
1146
  SpawnError | InitialError,
1765
- MachineRuntimeRequirement | SpawnRequirements<Requirements>
1147
+ MachineRuntime | SpawnRequirements<Requirements>
1766
1148
  >
1767
1149
 
1768
1150
  /**
@@ -2290,10 +1672,11 @@ type InvokeLifecycleId = string & { readonly [ChildAddressTypeId]?: never }
2290
1672
  *
2291
1673
  * **Details**
2292
1674
  *
2293
- * The descriptor carries the child's address and complete machine type. Pass
2294
- * a descriptor for the same id and machine to inline `invoke`, `sendTo`, and
2295
- * child lookup APIs so state, event, error, and output types are inferred
2296
- * without separate annotations.
1675
+ * The descriptor carries the child's address and complete machine type.
1676
+ * Register it in `make({ children })` to invoke it by `src`, and pass a
1677
+ * descriptor for the same id and machine to `sendTo` and child lookup APIs, so
1678
+ * state, event, error, and output types are inferred without separate
1679
+ * annotations.
2297
1680
  *
2298
1681
  * @category models
2299
1682
  * @since 0.4.0
@@ -2307,8 +1690,8 @@ export interface ChildMachine<Id extends string, M extends Machine.Any> {
2307
1690
  /** Complete machine definition carried by this descriptor. */
2308
1691
  readonly machine: M
2309
1692
 
2310
- /** @internal */
2311
- readonly [ChildMachineLogicTypeId]: (input?: unknown) => Logic<any, any, any, any, any, any>
1693
+ /** @internal Brand of descriptors built by `child` and `childFamily`. */
1694
+ readonly [ChildMachineLogicTypeId]: typeof ChildMachineLogicTypeId
2312
1695
  }
2313
1696
 
2314
1697
  /**
@@ -2407,7 +1790,7 @@ export declare namespace ChildMachine {
2407
1790
  */
2408
1791
  export type StartRequirements<Child extends Any> = Child extends ChildMachine<string, infer M> ? Exclude<
2409
1792
  ExcludeCompatibleRuntime<
2410
- Exclude<ExecutionServices<Machine.InitialServices<M> | Machine.Services<M>>, MachineRuntimeRequirement>,
1793
+ Exclude<ExecutionServices<Machine.InitialServices<M> | Machine.Services<M>>, MachineRuntime>,
2411
1794
  Machine.Event<M>,
2412
1795
  Machine.EmittedEvent<M>
2413
1796
  >,
@@ -2547,16 +1930,6 @@ export interface SpawnOptions {
2547
1930
  readonly id?: string
2548
1931
  }
2549
1932
 
2550
- /**
2551
- * Options for spawning child processes with a parent-local id.
2552
- *
2553
- * @category models
2554
- * @since 0.4.0
2555
- */
2556
- export interface SpawnIdOptions extends SpawnOptions {
2557
- readonly id: string
2558
- }
2559
-
2560
1933
  /**
2561
1934
  * Namespace containing type-level members associated with `Machine`.
2562
1935
  *
@@ -2865,7 +2238,19 @@ export declare namespace Machine {
2865
2238
  /** Identifies whether an event protocol is accepted publicly or only inside a machine. */
2866
2239
  export type EventProtocolKind = "public" | "internal" | "emitted"
2867
2240
 
2868
- type EventConstructorInput<EventSchema extends TaggedSchema> = Omit<EventSchema["~type.make.in"], "_tag">
2241
+ /**
2242
+ * Fields accepted by the constructor of one event in an event protocol.
2243
+ *
2244
+ * **Details**
2245
+ *
2246
+ * The input is the event schema's constructor input without `_tag`, which
2247
+ * the constructor supplies. When every field is optional, so is the
2248
+ * constructor's argument.
2249
+ *
2250
+ * @category utility types
2251
+ * @since 0.23.0
2252
+ */
2253
+ export type EventConstructorInput<EventSchema extends TaggedSchema> = Omit<EventSchema["~type.make.in"], "_tag">
2869
2254
 
2870
2255
  type EventConstructor<
2871
2256
  EventSchema extends TaggedSchema,
@@ -2937,7 +2322,7 @@ export declare namespace Machine {
2937
2322
  }
2938
2323
  }
2939
2324
 
2940
- /** A schema or an existing protocol accepted by an event builder. */
2325
+ /** A schema or an existing protocol accepted by `eventsFromSchemas` and its internal and emitted counterparts. */
2941
2326
  export type EventProtocolInput<Kind extends EventProtocolKind> = TaggedSchema | EventProtocol.Any<Kind>
2942
2327
 
2943
2328
  type EventProtocolInputSchemas<
@@ -3135,8 +2520,8 @@ export declare namespace Machine {
3135
2520
  * Transient decision pseudo-state resolved immediately when targeted.
3136
2521
  *
3137
2522
  * Choice nodes have no value and never belong to an active configuration.
3138
- * Their required `choice` implementation uses ordinary TypeScript or an
3139
- * Effect to select a typed target.
2523
+ * Their required `choice` transition selects a typed destination
2524
+ * synchronously.
3140
2525
  *
3141
2526
  * @category models
3142
2527
  * @since 0.4.0
@@ -3173,30 +2558,14 @@ export declare namespace Machine {
3173
2558
  export type StateTree = Readonly<Record<string, TaggedSchema | StateNodeConfig>>
3174
2559
 
3175
2560
  /**
3176
- * State schema definitions accepted by `make`.
2561
+ * State tree used as the topology parameter of machine types. A machine's
2562
+ * tree holds its root node under the `""` key.
3177
2563
  *
3178
2564
  * @category models
3179
2565
  * @since 0.4.0
3180
2566
  */
3181
2567
  export type StateSchemas = StateTree
3182
2568
 
3183
- /**
3184
- * Builder for initial state snapshots generated by `states`.
3185
- *
3186
- * **When to use**
3187
- *
3188
- * Use when you need the type of the `initial` property returned by
3189
- * `states` or want to expose an initial snapshot builder from a helper.
3190
- *
3191
- * **Details**
3192
- *
3193
- * Initial builders enforce the declared initial child for compound states and
3194
- * require every direct region for parallel states.
3195
- *
3196
- * @category utility types
3197
- * @since 0.4.0
3198
- */
3199
-
3200
2569
  /**
3201
2570
  * Typed snapshot access shared by state descriptors.
3202
2571
  *
@@ -3473,7 +2842,17 @@ export declare namespace Machine {
3473
2842
  readonly outcome: "element" | "done" | "failure" | "snapshot"
3474
2843
  }
3475
2844
 
3476
- /** Static topology selected by a transition branch. */
2845
+ /**
2846
+ * Static topology selected by a transition branch.
2847
+ *
2848
+ * **Details**
2849
+ *
2850
+ * `kind` is `"state"` or `"choice"` for the path named by `target`,
2851
+ * `"history"` for `history`, `"state"` with the root path `""` for
2852
+ * `initialize`, and `"update"` for an `update` without a destination. A
2853
+ * `{ stay: true }` entry, or a transition with only `reenter: true`, has kind
2854
+ * `"none"` and no path. The machine's initial entry has kind `"initial"`.
2855
+ */
3477
2856
  export interface TransitionTargetSelection<
3478
2857
  Path extends string | undefined = string | undefined,
3479
2858
  Kind extends Topology.TargetSelectionKind = Topology.TargetSelectionKind,
@@ -3494,8 +2873,8 @@ export declare namespace Machine {
3494
2873
  }
3495
2874
  | {
3496
2875
  readonly type: "branch"
2876
+ /** The entry as written: `target:Paid`, `target:Paid+update:root`, `update:root`, `history:X`, `initialize`, or `stay`. */
3497
2877
  readonly key: string
3498
- readonly title: string
3499
2878
  readonly target: Path | undefined
3500
2879
  readonly selection: TransitionTargetSelection<Path | undefined>
3501
2880
  readonly updates: ReadonlyArray<string>
@@ -3504,7 +2883,7 @@ export declare namespace Machine {
3504
2883
  /** The statically selected root entry for machine startup. */
3505
2884
  export interface InitialDefinition<Path extends string = string> {
3506
2885
  readonly target: Path
3507
- readonly selection: TransitionTargetSelection<Path, "state" | "initial", "initial">
2886
+ readonly selection: TransitionTargetSelection<Path, "initial", "initial">
3508
2887
  }
3509
2888
 
3510
2889
  /**
@@ -3513,9 +2892,11 @@ export declare namespace Machine {
3513
2892
  * **Details**
3514
2893
  *
3515
2894
  * Every branch exposes its static selection without executing its resolver.
3516
- * A compound local or branch target covers its descendants. An `update`
3517
- * selection keeps `target` undefined and records its value owner in
3518
- * `selection.path`; `none` identifies an explicitly targetless branch.
2895
+ * Selecting a compound or parallel state also covers the descendants the
2896
+ * transition enters through it. An `update` selection keeps `target`
2897
+ * undefined and records its value owner in `selection.path`. A
2898
+ * `{ stay: true }` entry keeps `target` undefined and has
2899
+ * `selection.kind` `"none"`.
3519
2900
  *
3520
2901
  * @category models
3521
2902
  * @since 0.4.0
@@ -3561,7 +2942,7 @@ export declare namespace Machine {
3561
2942
  readonly reenter: boolean
3562
2943
  /** Zero-based index of the selected static branch. */
3563
2944
  readonly branchIndex: number
3564
- /** Stable key of a named branch, or `undefined` for a direct transition. */
2945
+ /** The selected `branches` entry as written, such as `target:Paid`, or `undefined` for a direct transition. */
3565
2946
  readonly branchKey: string | undefined
3566
2947
  /** Path returned by the handler, including a choice or history pseudo-state. */
3567
2948
  readonly target: TargetPath | undefined
@@ -3575,7 +2956,8 @@ export declare namespace Machine {
3575
2956
  }
3576
2957
 
3577
2958
  /**
3578
- * Constructor arguments for a machine initial state function.
2959
+ * Startup arguments: the decoded input when the machine declares an input
2960
+ * schema, and none otherwise.
3579
2961
  *
3580
2962
  * @category utility types
3581
2963
  * @since 0.4.0
@@ -4390,7 +3772,7 @@ export declare namespace Machine {
4390
3772
  : never)
4391
3773
 
4392
3774
  /**
4393
- * Opaque state construction returned by a builder's `.from` method.
3775
+ * Opaque state construction returned by a history default's `target`.
4394
3776
  *
4395
3777
  * The machine resolves the instruction through the selected state schema
4396
3778
  * while planning. Its decoded value is intentionally unavailable until
@@ -4400,7 +3782,7 @@ export declare namespace Machine {
4400
3782
  * @since 0.4.0
4401
3783
  */
4402
3784
  export interface StateConstruction<out Result> {
4403
- readonly [Topology.StateConstructionTypeId]: Result
3785
+ readonly [StateConstructionTypeId]: Result
4404
3786
  }
4405
3787
 
4406
3788
  /**
@@ -4414,7 +3796,7 @@ export declare namespace Machine {
4414
3796
  StateId extends StateIdentifier<States>
4415
3797
  > {
4416
3798
  readonly [Topology.TargetTypeId]: typeof Topology.TargetTypeId
4417
- readonly [Topology.TargetSnapshotTypeId]?: SnapshotByIdentifier<States, StateId>
3799
+ readonly [TargetSnapshotTypeId]?: SnapshotByIdentifier<States, StateId>
4418
3800
  readonly path: StateId
4419
3801
  readonly value: StateByIdentifier<States, StateId>
4420
3802
  readonly values?: Partial<
@@ -4435,7 +3817,7 @@ export declare namespace Machine {
4435
3817
  States extends StateSchemas,
4436
3818
  StateId extends ValuedStateIdentifier<States>
4437
3819
  > {
4438
- readonly [Topology.StateUpdateTypeId]: {
3820
+ readonly [StateUpdateTypeId]: {
4439
3821
  readonly states: Types.Covariant<States>
4440
3822
  readonly owner: Types.Covariant<StateId>
4441
3823
  }
@@ -4453,25 +3835,13 @@ export declare namespace Machine {
4453
3835
  States extends StateSchemas,
4454
3836
  Owner extends ValuedStateIdentifier<States>
4455
3837
  > {
4456
- readonly [Topology.CombinedTargetTypeId]: {
3838
+ readonly [CombinedTargetTypeId]: {
4457
3839
  readonly result: Types.Covariant<Result>
4458
3840
  readonly states: Types.Covariant<States>
4459
3841
  readonly owner: Types.Covariant<Owner>
4460
3842
  }
4461
3843
  }
4462
3844
 
4463
- /** @internal */
4464
- type StateUpdateBuilder<
4465
- States extends StateSchemas,
4466
- StateId extends ValuedStateIdentifier<States>
4467
- > = {
4468
- readonly decoded: (value: StateByIdentifier<States, StateId>) => StateUpdate<States, StateId>
4469
- readonly from: FromCallable<
4470
- readonly [input: SchemaByIdentifier<States, StateId>["~type.make.in"]],
4471
- StateUpdate<States, StateId>
4472
- >
4473
- }
4474
-
4475
3845
  /**
4476
3846
  * Opaque result returned by an explicitly targetless transition.
4477
3847
  *
@@ -4482,12 +3852,12 @@ export declare namespace Machine {
4482
3852
  * @since 0.10.0
4483
3853
  */
4484
3854
  export interface NoTarget {
4485
- readonly [Topology.NoTargetTypeId]: typeof Topology.NoTargetTypeId
3855
+ readonly [NoTargetTypeId]: typeof NoTargetTypeId
4486
3856
  }
4487
3857
 
4488
3858
  /**
4489
- * Opaque result returned when a declinable transition does not accept the
4490
- * current event or lifecycle outcome.
3859
+ * Opaque result of `select.decline()`, when a transition does not accept the
3860
+ * current event.
4491
3861
  *
4492
3862
  * Declining selects no transition and discards operations enqueued by that
4493
3863
  * resolver. Hierarchical event and eventless dispatch continues with the
@@ -4497,10 +3867,14 @@ export declare namespace Machine {
4497
3867
  * @since 0.17.0
4498
3868
  */
4499
3869
  export interface Declined {
4500
- readonly [Topology.DeclinedTypeId]: typeof Topology.DeclinedTypeId
3870
+ readonly [DeclinedTypeId]: typeof DeclinedTypeId
4501
3871
  }
4502
3872
 
4503
- /** Static acceptance contract of one transition definition. */
3873
+ /**
3874
+ * Static acceptance contract of one transition definition: `"declinable"`
3875
+ * when it has a `guard` or lists `{ decline: true }` in `branches`, so it may
3876
+ * leave the event to the next candidate, and `"required"` otherwise.
3877
+ */
4504
3878
  export type TransitionAcceptance = "required" | "declinable"
4505
3879
 
4506
3880
  /**
@@ -4517,7 +3891,7 @@ export declare namespace Machine {
4517
3891
  States extends StateSchemas,
4518
3892
  HistoryId extends HistoryIdentifier<States>
4519
3893
  > {
4520
- readonly [Topology.HistoryTargetTypeId]: typeof Topology.HistoryTargetTypeId
3894
+ readonly [HistoryTargetTypeId]: typeof HistoryTargetTypeId
4521
3895
  readonly path: HistoryId
4522
3896
  readonly parent: Extract<ParentPath<HistoryId>, StateIdentifier<States>>
4523
3897
  }
@@ -4531,17 +3905,17 @@ export declare namespace Machine {
4531
3905
  */
4532
3906
  export interface InitialTarget<StateId extends string> {
4533
3907
  readonly [Topology.TargetTypeId]: typeof Topology.TargetTypeId
4534
- readonly [Topology.TargetSnapshotTypeId]?: never
4535
- readonly [Topology.InitialTargetTypeId]: typeof Topology.InitialTargetTypeId
3908
+ readonly [TargetSnapshotTypeId]?: never
3909
+ readonly [InitialTargetTypeId]: typeof InitialTargetTypeId
4536
3910
  readonly _tag: "InitialTarget"
4537
3911
  readonly path: StateId
4538
3912
  readonly value: never
4539
3913
  readonly values?: never
4540
3914
  }
4541
3915
 
4542
- /** Branded transient target instruction used while constructing initial states. */
3916
+ /** Branded instruction that enters a choice pseudo-state, before its parent is checked against a machine. */
4543
3917
  export interface ChoiceTargetInstruction<ChoiceId extends string = string> {
4544
- readonly [Topology.ChoiceTargetTypeId]: typeof Topology.ChoiceTargetTypeId
3918
+ readonly [ChoiceTargetTypeId]: typeof ChoiceTargetTypeId
4545
3919
  readonly path: ChoiceId
4546
3920
  readonly parent: ParentPath<ChoiceId>
4547
3921
  readonly values?: Readonly<Record<string, unknown>>
@@ -4555,26 +3929,9 @@ export declare namespace Machine {
4555
3929
  readonly parent: Extract<ParentPath<ChoiceId>, StateIdentifier<States>>
4556
3930
  }
4557
3931
 
4558
- /** Builder containing only history pseudo-state paths. */
4559
- export type HistoryTargetBuilder<States extends StateSchemas> = HistoryTargetBuilderWithPrefix<States, States, "">
4560
-
4561
- /**
4562
- * Builder for complete transition snapshots.
4563
- *
4564
- * **When to use**
4565
- *
4566
- * Use when a transition enters an inactive root or otherwise needs to provide
4567
- * every active child below the selected root.
4568
- *
4569
- * @category utility types
4570
- * @since 0.4.0
4571
- */
4572
- export type FullTargetBuilder<States extends StateSchemas> = [InitialEntryStateKey<States>] extends [never] ?
4573
- FullSnapshotBuilderWithPrefix<States>
4574
- : FullSnapshotBuilderWithPrefix<States> & FullInitialTargetBuilder<States>
4575
-
4576
3932
  /**
4577
- * Builder for a complete fallback configuration containing a history owner.
3933
+ * Function that constructs a complete fallback configuration containing a
3934
+ * history owner, supplied as `target` to a history default.
4578
3935
  *
4579
3936
  * @category utility types
4580
3937
  * @since 0.4.0
@@ -4586,151 +3943,6 @@ export declare namespace Machine {
4586
3943
  construction: HistoryConstruction<States[""], Owner>
4587
3944
  ) => StateConstruction<CompleteSnapshotContaining<States, Owner>>
4588
3945
 
4589
- /**
4590
- * Builder for source-local transition targets.
4591
- *
4592
- * **When to use**
4593
- *
4594
- * Use when a transition stays inside the nearest active compound ancestor of
4595
- * the source state and should preserve active ancestor and sibling values.
4596
- *
4597
- * @category utility types
4598
- * @since 0.4.0
4599
- */
4600
- export type LocalTargetBuilder<
4601
- States extends StateSchemas,
4602
- Source extends StateNodeIdentifier<States>
4603
- > = NearestCompoundScope<States, Source> extends infer Scope ? [Scope] extends [never] ? {}
4604
- : Scope extends StateIdentifier<States> ? LocalTargetBuilderForScope<States, Scope, Source>
4605
- : {}
4606
- : {}
4607
-
4608
- /**
4609
- * Builder for partial transition targets within the active source root.
4610
- *
4611
- * **When to use**
4612
- *
4613
- * Use when a transition should replace one descendant of the active source
4614
- * root while preserving unmentioned active ancestors or parallel regions.
4615
- *
4616
- * @category utility types
4617
- * @since 0.4.0
4618
- */
4619
- export type BranchTargetBuilder<
4620
- States extends StateSchemas,
4621
- Source extends StateNodeIdentifier<States>
4622
- > = BranchTargetBuilderForRoot<
4623
- States,
4624
- Extract<"" extends keyof States ? "" : RootStateIdentifier<Source>, ActiveStateKey<States>>,
4625
- Source
4626
- >
4627
-
4628
- /**
4629
- * Machine-bound target builders available in transition contexts.
4630
- *
4631
- * **Details**
4632
- *
4633
- * `none()` handles without selecting a destination, `local` targets the
4634
- * nearest compound scope for the source state, `branch` targets descendants
4635
- * of the source root, and `full` builds complete snapshots for any root.
4636
- *
4637
- * These builders control how the next active configuration is assembled; they
4638
- * do not directly control state re-entry. Exit and entry paths are derived
4639
- * from the previous and next active paths. Shared active ancestors remain
4640
- * entered even when a `full` target supplies their values again. Use an event
4641
- * transition with `reenter: true` when the source should explicitly exit and
4642
- * enter again.
4643
- *
4644
- * @category models
4645
- * @since 0.4.0
4646
- */
4647
- export interface TargetBuilder<
4648
- in out States extends StateSchemas,
4649
- in out Source extends StateNodeIdentifier<States>
4650
- > {
4651
- /**
4652
- * Selects an explicitly targetless transition.
4653
- *
4654
- * The event or lifecycle outcome is handled and queued operations are
4655
- * retained, while the current state configuration remains the transition
4656
- * result.
4657
- *
4658
- * @since 0.10.0
4659
- */
4660
- readonly none: () => NoTarget
4661
-
4662
- /**
4663
- * Moves to another state in the same local group. The value of the state
4664
- * containing that group, and values in other active branches, are kept.
4665
- *
4666
- * @since 0.4.0
4667
- */
4668
- readonly local: LocalTargetBuilder<States, Source>
4669
-
4670
- /**
4671
- * Moves to a state elsewhere under the current top-level state. Parent
4672
- * values change only when their builder methods are explicitly called;
4673
- * other active branches are kept.
4674
- *
4675
- * @since 0.4.0
4676
- */
4677
- readonly branch: BranchTargetBuilder<States, Source>
4678
-
4679
- /**
4680
- * Moves to any top-level state by building its complete active state
4681
- * configuration.
4682
- *
4683
- * **Details**
4684
- *
4685
- * When the target contains nested states, an active child must be selected.
4686
- * When it contains parallel states, an active state must be provided for
4687
- * every region.
4688
- *
4689
- * @since 0.4.0
4690
- */
4691
- readonly full: FullTargetBuilder<States>
4692
-
4693
- /** Restores a declared shallow or deep history pseudo-state. */
4694
- readonly history: HistoryTargetBuilder<States>
4695
- }
4696
-
4697
- /**
4698
- * Opaque exact destination selected while a machine definition is captured.
4699
- * The selection contains topology only; state values are constructed later
4700
- * by the selected branch's resolver.
4701
- *
4702
- * @category models
4703
- * @since 0.14.0
4704
- */
4705
- export interface TargetSelection<
4706
- out Result,
4707
- out Path extends string | undefined = string | undefined,
4708
- out Kind extends Topology.TargetSelectionKind = Topology.TargetSelectionKind,
4709
- out Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined
4710
- > {
4711
- readonly [Topology.TargetSelectionTypeId]: typeof Topology.TargetSelectionTypeId
4712
- readonly kind: Kind
4713
- readonly scope: Scope
4714
- readonly path: Path
4715
- readonly "~effect/Machine/TargetSelectionResult"?: Types.Covariant<Result>
4716
- }
4717
-
4718
- type SelectionValue<
4719
- Builder,
4720
- Path extends string,
4721
- Kind extends Topology.TargetSelectionKind = "state",
4722
- Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined
4723
- > = TargetSelection<Builder, Path, Kind, Scope>
4724
-
4725
- type SelectionMethod<
4726
- Builder,
4727
- Path extends string,
4728
- Kind extends Topology.TargetSelectionKind = "state",
4729
- Scope extends Topology.TargetSelectionScope | undefined = Topology.TargetSelectionScope | undefined
4730
- > = () => SelectionValue<Builder, Path, Kind, Scope>
4731
-
4732
- type RootBuilder<Builder> = Builder extends { readonly "": infer Root } ? Root : never
4733
-
4734
3946
  /**
4735
3947
  * Context passed to a state/event handler.
4736
3948
  *
@@ -5087,7 +4299,7 @@ export declare namespace Machine {
5087
4299
  export type StateActionResult<E, R> = undefined
5088
4300
 
5089
4301
  /**
5090
- * Return value accepted from a machine initial state function.
4302
+ * Initial target that a machine resolves at startup.
5091
4303
  *
5092
4304
  * @category utility types
5093
4305
  * @since 0.4.0
@@ -5095,15 +4307,14 @@ export declare namespace Machine {
5095
4307
  export type InitialResult<States extends StateSchemas, E, R> = InitialTarget<StateIdentifier<States>>
5096
4308
 
5097
4309
  /**
5098
- * Return value accepted from transition handlers.
4310
+ * Result that a transition declaration resolves to.
5099
4311
  *
5100
4312
  * **Details**
5101
4313
  *
5102
- * Handlers return snapshots for complete state replacement, target builder
5103
- * results for path-safe partial transitions, state-value updates, or
5104
- * an explicit targetless result. In a machine definition, select `{ none: true }`;
5105
- * its optional resolver returns `undefined`. Raw decoded state values are
5106
- * not accepted as transition targets.
4314
+ * A transition resolves to a complete snapshot, a target, history, or
4315
+ * choice destination, a state-value update, a target combined with an
4316
+ * owner update, or the targetless result of `{ stay: true }`. Raw decoded
4317
+ * state values are not accepted as transition targets.
5107
4318
  *
5108
4319
  * @category utility types
5109
4320
  * @since 0.4.0
@@ -5128,47 +4339,6 @@ export declare namespace Machine {
5128
4339
  >
5129
4340
  | NoTarget
5130
4341
 
5131
- /** A choice resolver must always select a typed target synchronously. */
5132
- export type ChoiceResult<States extends StateSchemas, E, R> =
5133
- | Snapshot<States>
5134
- | Target<States, StateIdentifier<States>>
5135
- | HistoryTarget<States, HistoryIdentifier<States>>
5136
- | ChoiceTarget<States, ChoiceIdentifier<States>>
5137
- | StateConstruction<
5138
- | Snapshot<States>
5139
- | Target<States, StateIdentifier<States>>
5140
- | HistoryTarget<States, HistoryIdentifier<States>>
5141
- | ChoiceTarget<States, ChoiceIdentifier<States>>
5142
- >
5143
-
5144
- /**
5145
- * Extracts the union of handler return values from a handler map.
5146
- *
5147
- * @category utility types
5148
- * @since 0.4.0
5149
- */
5150
- export type HandlerEffect<Handlers> = Handlers[keyof Handlers]
5151
- /**
5152
- * Extracts the error type from a handler return value.
5153
- *
5154
- * @category utility types
5155
- * @since 0.4.0
5156
- */
5157
- export type HandlerError<Handlers> = Effect.Error<HandlerEffect<Handlers>>
5158
- /**
5159
- * Extracts the service requirements from a handler return value.
5160
- *
5161
- * @category utility types
5162
- * @since 0.4.0
5163
- */
5164
- export type HandlerServices<Handlers> = Effect.Services<HandlerEffect<Handlers>>
5165
- /**
5166
- * Extracts the return value from an initial state function.
5167
- *
5168
- * @category utility types
5169
- * @since 0.4.0
5170
- */
5171
- export type InitialReturn<Initial> = Initial extends (...args: any) => infer Ret ? Ret : never
5172
4342
  /**
5173
4343
  * Extracts the return value from an entry or exit action.
5174
4344
  *
@@ -5240,7 +4410,7 @@ export declare namespace Machine {
5240
4410
  EventInput<InputEvent<M>>,
5241
4411
  Error<M> | ActionError<Services<M>> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError,
5242
4412
  ExcludeCompatibleRuntime<
5243
- Exclude<ExecutionServices<InitialServices<M> | Services<M>>, internalRuntime.MachineRuntime>,
4413
+ Exclude<ExecutionServices<InitialServices<M> | Services<M>>, MachineRuntime>,
5244
4414
  Event<M>,
5245
4415
  EmittedEvent<M>
5246
4416
  >,
@@ -5317,17 +4487,6 @@ export declare namespace Machine {
5317
4487
  readonly [InvokeTypeId]: { readonly requirements: Types.Covariant<infer Requirements> }
5318
4488
  } ? Requirements
5319
4489
  : LogicServicesOf<InvokeLogic<Invoke>>
5320
- /**
5321
- * Extracts events emitted directly by an invoked child.
5322
- *
5323
- * @category utility types
5324
- * @since 0.4.0
5325
- */
5326
- export type InvokeEmits<Invoke> = Invoke extends {
5327
- readonly [InvokeTypeId]: { readonly emits: Types.Covariant<infer Emitted> }
5328
- } ? Emitted
5329
- : Invoke extends { readonly child: ChildMachine<string, infer M> } ? EmittedEvent<M>
5330
- : never
5331
4490
 
5332
4491
  /** Public parent inputs required by an invoked child machine. */
5333
4492
  export type InvokeParentEvents<Invoke> = Invoke extends {
@@ -5385,7 +4544,7 @@ export declare namespace Machine {
5385
4544
  */
5386
4545
  export type InvokeRequirements<Config> = [InvokeReturn<Config>] extends [never] ? never
5387
4546
  :
5388
- | MachineRuntimeRequirement
4547
+ | MachineRuntime
5389
4548
  | InvokeServices<InvokeReturn<Config>>
5390
4549
  | InvokeOutcomeServices<InvokeReturn<Config>>
5391
4550
  /**
@@ -5406,15 +4565,6 @@ export declare namespace Machine {
5406
4565
  export type DoneReturn<Config> = Config extends { readonly onDone?: infer OnDone }
5407
4566
  ? EventTransitionReturn<NonNullable<OnDone>>
5408
4567
  : never
5409
- /**
5410
- * Extracts the return value from a final state output function.
5411
- *
5412
- * @category utility types
5413
- * @since 0.4.0
5414
- */
5415
- export type FinalOutputReturn<Config> = Config extends { readonly output?: infer Output }
5416
- ? NonNullable<Output> extends (...args: any) => infer Ret ? Ret : never
5417
- : never
5418
4568
 
5419
4569
  /**
5420
4570
  * Extracts all service requirements contributed by a state handler config.
@@ -5444,167 +4594,30 @@ export declare namespace Machine {
5444
4594
  Acceptance extends TransitionAcceptance = "required"
5445
4595
  > = Transition<States, StateId, Context, Events, Emits, {}, Reenter, Acceptance>
5446
4596
 
5447
- export type SelectionBuilder<Selection> = Selection extends TargetSelection<infer Builder, any, any, any> ? Builder
5448
- : never
5449
- export type SelectionKind<Selection> = Selection extends TargetSelection<any, any, infer Kind, any> ? Kind : never
5450
- export type SelectionPath<Selection> = Selection extends TargetSelection<any, infer Path, any, any> ? Path : never
5451
- export type TargetBuilderResult<Builder> =
5452
- | (Builder extends (...args: any) => infer Result ? Result : never)
5453
- | (Builder extends { readonly decoded: (...args: any) => infer Result } ? Result : never)
5454
- | (Builder extends { readonly from: (...args: any) => infer Result } ? Result : never)
5455
- export type SelectedTargetResult<Selection> = SelectionBuilder<Selection> extends infer Builder ?
5456
- TargetBuilderResult<Builder>
5457
- : never
5458
-
5459
- /**
5460
- * Destination construction returned when a transition declares one retained
5461
- * valued owner with a `{ target, update }` declaration.
5462
- *
5463
- * @category models
5464
- * @since 0.22.0
5465
- */
5466
- export interface UpdatingStateConstruction<
5467
- Result,
5468
- States extends StateSchemas,
5469
- Owner extends ValuedStateIdentifier<States>
5470
- > {
5471
- /** Combines the selected topology with the required owner replacement. */
5472
- readonly update: (
5473
- update: StateUpdate<States, Owner>
5474
- ) => CombinedTarget<UnwrapConstruction<Result>, States, Owner>
5475
- }
5476
-
5477
- type UpdatingCallable<
5478
- Callable,
5479
- States extends StateSchemas,
5480
- Owner extends ValuedStateIdentifier<States>
5481
- > = Callable extends {
5482
- (...args: infer Arguments1): infer Result1
5483
- (...args: infer Arguments2): infer Result2
5484
- } ? {
5485
- (...args: Arguments1): UpdatingStateConstruction<Result1, States, Owner>
5486
- (...args: Arguments2): UpdatingStateConstruction<Result2, States, Owner>
5487
- }
5488
- : Callable extends (...args: infer Arguments) => infer Result ?
5489
- (...args: Arguments) => UpdatingStateConstruction<Result, States, Owner>
5490
- : never
5491
-
5492
- type UpdatingTargetBuilder<
5493
- Builder,
5494
- States extends StateSchemas,
5495
- Owner extends ValuedStateIdentifier<States>
5496
- > = {
5497
- readonly [Key in keyof Builder]: Key extends "from" | "decoded" ? UpdatingCallable<Builder[Key], States, Owner>
5498
- : Builder[Key]
5499
- }
5500
-
5501
- type SelectionSupportsDefaultConstruction<Selection> = SelectionKind<Selection> extends "none" ? true
5502
- : SelectionBuilder<Selection> extends { readonly from: (...args: infer Args) => any } ? [] extends Args ? true
5503
- : false
5504
- : false
5505
-
5506
- export type TransitionResolveContext<
5507
- Context,
5508
- Selection
5509
- > =
5510
- & Omit<Context, "target">
5511
- & (SelectionKind<Selection> extends "none" ? {} : { readonly target: SelectionBuilder<Selection> })
5512
-
5513
- /** Context capability available only to explicitly declinable resolvers. */
5514
- export interface DeclineCapability {
5515
- /** Declines this candidate and continues hierarchical transition selection. */
5516
- readonly decline: () => Declined
5517
- }
5518
-
5519
- /** One named destination declared by a branching transition. */
5520
- export interface TransitionBranchInput<
5521
- Selection extends TargetSelection<any, any, any> = TargetSelection<any, any, any>
5522
- > {
5523
- /** Exact topology destination available to the branching resolver. */
5524
- readonly target: Selection
5525
- /** Optional human-readable branch label used by visualization tooling. */
5526
- readonly title?: string
5527
- }
5528
-
5529
- /** Opaque evidence that a branching resolver selected one declared branch. */
4597
+ /** Opaque evidence that `resolve` selected one declared branch. */
5530
4598
  export interface SelectedBranch<out Key extends string, out Result> {
5531
- readonly [Topology.SelectedBranchTypeId]: {
4599
+ readonly [SelectedBranchTypeId]: {
5532
4600
  readonly key: Types.Covariant<Key>
5533
4601
  readonly result: Types.Covariant<Result>
5534
4602
  }
5535
4603
  }
5536
4604
 
5537
- type CompletedBranchResult<R> = R extends { readonly update: unknown }
5538
- ? R extends UpdatingStateConstruction<infer Target, infer S, infer Owner>
5539
- ? CombinedTarget<UnwrapConstruction<Target>, S, Owner>
5540
- : R
5541
- : R
5542
- type SelectedConstruction<K extends string, R> = R extends { readonly update: unknown } ?
5543
- R extends UpdatingStateConstruction<infer Target, infer S, infer Owner> ? {
5544
- readonly update: SelectedBranchBuilder<StateUpdateBuilder<S, Owner>, K> extends infer B ? {
5545
- readonly [M in keyof B]:
5546
- StateUpdateBuilder<S, Owner>[Extract<M, keyof StateUpdateBuilder<S, Owner>>] extends
5547
- (...args: infer A) => unknown
5548
- ? (...args: A) => SelectedBranch<K, CombinedTarget<UnwrapConstruction<Target>, S, Owner>>
5549
- : never
5550
- } :
5551
- never
5552
- }
5553
- : SelectedBranch<K, R> :
5554
- SelectedBranch<K, R>
5555
- type SelectedBranchCallable<Callable, Key extends string> = Callable extends {
5556
- (...args: infer Arguments1): infer Result1
5557
- (...args: infer Arguments2): infer Result2
5558
- } ? {
5559
- (...args: Arguments1): SelectedConstruction<Key, Result1>
5560
- (...args: Arguments2): SelectedConstruction<Key, Result2>
5561
- }
5562
- : Callable extends (...args: infer Arguments) => infer Result ?
5563
- (...args: Arguments) => SelectedConstruction<Key, Result>
5564
- : {}
5565
-
5566
- type SelectedBranchBuilderProperties<Builder, Key extends string> = {
5567
- readonly [Property in keyof Builder]: Builder[Property] extends (...args: any) => any ?
5568
- SelectedBranchCallable<Builder[Property], Key>
5569
- : Builder[Property]
5570
- }
5571
-
5572
- /** Target-specific builder that brands every construction with its branch key. */
5573
- export type SelectedBranchBuilder<Builder, Key extends string> =
5574
- & SelectedBranchCallable<Builder, Key>
5575
- & SelectedBranchBuilderProperties<Builder, Key>
5576
-
5577
- export type BranchSelectors<Branches extends Readonly<Record<string, TransitionBranchInput>>> = {
5578
- readonly [Key in Extract<keyof Branches, string>]: SelectedBranchBuilder<
5579
- SelectionBuilder<Branches[Key]["target"]>,
5580
- Key
5581
- >
5582
- }
5583
-
5584
- export type BranchSelectionResult<Branches extends Readonly<Record<string, TransitionBranchInput>>> = {
5585
- readonly [Key in Extract<keyof Branches, string>]: SelectedBranch<
5586
- Key,
5587
- CompletedBranchResult<SelectedTargetResult<Branches[Key]["target"]>>
5588
- >
5589
- }[Extract<keyof Branches, string>]
5590
-
5591
- export type TransitionBranchesResolveContext<
5592
- Context,
5593
- Branches extends Readonly<Record<string, TransitionBranchInput>>
5594
- > = Omit<Context, "target"> & { readonly select: BranchSelectors<Branches> }
5595
-
5596
- export type InvokeTransition<
5597
- States extends StateSchemas,
5598
- Events extends ReadonlyArray<TaggedSchema>,
5599
- Emits extends ReadonlyArray<TaggedSchema>,
5600
- StateId extends StateNodeIdentifier<States>,
5601
- Context
5602
- > = TransitionConfig<States, Events, Emits, StateId, Context, true, TransitionAcceptance>
5603
-
5604
4605
  export type InvokeSource<Value, Context> = Value | ((context: Context) => Value)
5605
4606
 
5606
- /** Inline state-owned work that runs for the lifetime of its active state. */
5607
- interface InvokeOwned<
4607
+ /**
4608
+ * State-owned work that runs for the lifetime of its active state.
4609
+ *
4610
+ * **Details**
4611
+ *
4612
+ * Every `invoke` entry carries this type-level marker, which records the
4613
+ * state that owns the entry together with the machine's state schemas and
4614
+ * event protocols. The marker property is optional and is never set at
4615
+ * runtime.
4616
+ *
4617
+ * @category models
4618
+ * @since 0.23.0
4619
+ */
4620
+ export interface InvokeOwned<
5608
4621
  States extends StateSchemas,
5609
4622
  Events extends ReadonlyArray<TaggedSchema>,
5610
4623
  Emits extends ReadonlyArray<TaggedSchema>,
@@ -5801,7 +4814,7 @@ export declare namespace Machine {
5801
4814
  > {
5802
4815
  /** Lifecycle event that attempted to restore this history node. */
5803
4816
  readonly event: LifecycleEvent<Events>
5804
- /** Complete target builder rooted at the history owner. */
4817
+ /** Constructs the complete root configuration that contains the history owner. */
5805
4818
  readonly target: HistoryDefaultTargetBuilder<States, ParentId>
5806
4819
  /** State path whose child configuration is restored by this history node. */
5807
4820
  readonly owner: ParentId
@@ -5829,9 +4842,16 @@ export declare namespace Machine {
5829
4842
  /**
5830
4843
  * Fallback implementation for one direct history pseudo-state.
5831
4844
  *
4845
+ * **Details**
4846
+ *
4847
+ * `default` runs only when the history state is entered before its owner has
4848
+ * recorded a configuration, and returns the complete configuration to enter.
4849
+ *
5832
4850
  * @inline
4851
+ * @category models
4852
+ * @since 0.23.0
5833
4853
  */
5834
- interface HistoryDefaultEntry<
4854
+ export interface HistoryDefaultEntry<
5835
4855
  States extends StateSchemas,
5836
4856
  Events extends ReadonlyArray<TaggedSchema>,
5837
4857
  Emits extends ReadonlyArray<TaggedSchema>,
@@ -5856,8 +4876,18 @@ export declare namespace Machine {
5856
4876
  readonly [Key in HistoryStateKey<Children>]?: HistoryDefaultEntry<States, Events, Emits, ParentId>
5857
4877
  }
5858
4878
 
5859
- /** Required implementation for a choice pseudo-state. */
5860
- interface ChoiceStateConfig<
4879
+ /**
4880
+ * Required implementation for a choice pseudo-state.
4881
+ *
4882
+ * **Details**
4883
+ *
4884
+ * A choice state declares only `choice`, the transition that resolves it to
4885
+ * a concrete destination. Every other handler key is rejected.
4886
+ *
4887
+ * @category models
4888
+ * @since 0.23.0
4889
+ */
4890
+ export interface ChoiceStateConfig<
5861
4891
  States extends StateSchemas,
5862
4892
  Events extends ReadonlyArray<TaggedSchema>,
5863
4893
  Emits extends ReadonlyArray<TaggedSchema>,
@@ -5888,44 +4918,6 @@ export declare namespace Machine {
5888
4918
  readonly [Key in keyof Config as Key extends "states" | "initial" | "root" ? never : Key]: Config[Key]
5889
4919
  }
5890
4920
 
5891
- type HandlerNodeChildrenConfig<Config> = "states" extends keyof Config ?
5892
- Config extends { readonly states?: infer Children } ? NonNullable<Children>
5893
- : never
5894
- : never
5895
-
5896
- type HandlerNodeByPath<States extends StateSchemas, Path extends string> = "" extends keyof States ?
5897
- Path extends "" ? States[""]
5898
- : States[""] extends { readonly states: infer Children extends StateSchemas } ? HandlerNodeByPath<Children, Path>
5899
- : never
5900
- : Path extends `${infer Head}.${infer Rest}` ? Head extends keyof States ? States[Head] extends {
5901
- readonly states: infer Children extends StateSchemas
5902
- } ? HandlerNodeByPath<Children, Rest>
5903
- : never
5904
- : never
5905
- : Path extends keyof States ? States[Path]
5906
- : never
5907
-
5908
- // Resolve only the supplied branch for a flattened state-node path. Keeping
5909
- // this recursion on the finite path avoids recursively expanding an open
5910
- // generic handler config.
5911
- type HandlerConfigAtPath<Config, Path extends string> = [Config] extends [never] ? never :
5912
- "" extends keyof Config ? Path extends "" ? Config[""]
5913
- : HandlerConfigAtPath<HandlerNodeChildrenConfig<Config[""]>, Path>
5914
- : Path extends `${infer Head}.${infer Rest}` ?
5915
- Head extends keyof Config ? HandlerConfigAtPath<HandlerNodeChildrenConfig<Config[Head]>, Rest>
5916
- : never
5917
- : Path extends keyof Config ? Config[Path]
5918
- : never
5919
-
5920
- // Rebuild the public nested handler shape so branded validation errors stay
5921
- // attached to the exact property that introduced them.
5922
- type HandlerValidationAtPath<Path extends string, Validation> = Path extends `${infer Head}.${infer Rest}` ? {
5923
- readonly [Key in Head]?: {
5924
- readonly states: HandlerValidationAtPath<Rest, Validation>
5925
- }
5926
- }
5927
- : { readonly [Key in Path]?: Validation }
5928
-
5929
4921
  type HandlerNodeConfigKey =
5930
4922
  | "always"
5931
4923
  | "choice"
@@ -6040,42 +5032,6 @@ export declare namespace Machine {
6040
5032
  }
6041
5033
  : unknown
6042
5034
 
6043
- type TransitionResultInitialTargetPath<Result> = IsAny<Result> extends true ? never
6044
- : Result extends Effect.Effect<infer Success, any, any> ? TransitionResultInitialTargetPath<Success>
6045
- : Result extends SelectedBranch<any, infer Selected> ? TransitionResultInitialTargetPath<Selected>
6046
- : Result extends StateConstruction<infer Constructed> ? TransitionResultInitialTargetPath<Constructed>
6047
- : Result extends {
6048
- readonly [Topology.InitialTargetTypeId]: typeof Topology.InitialTargetTypeId
6049
- readonly _tag: "InitialTarget"
6050
- } ? Result extends { readonly path: infer Path extends string } ? Path : never
6051
- : never
6052
-
6053
- type HandlerConfigInitialTargetPath<Config> = TransitionResultInitialTargetPath<
6054
- | EventHandlerReturn<Config>
6055
- | AlwaysReturn<Config>
6056
- | DoneReturn<Config>
6057
- | ChoiceReturn<Config>
6058
- | InvokeOutcomeReturn<InvokeReturn<Config>>
6059
- >
6060
-
6061
- type RequiredInitializersForTargetPath<
6062
- AllStates extends StateSchemas,
6063
- Path
6064
- > = string extends Path ? never : Path extends StateIdentifier<AllStates> ? InitializerClosureForNode<
6065
- AllStates,
6066
- NodeByIdentifier<AllStates, Path>,
6067
- Path
6068
- >
6069
- : never
6070
-
6071
- type HandlerTreeInitialTargetPath<Config> = string extends keyof Config ? never
6072
- : Config extends object ? {
6073
- readonly [Key in keyof Config]:
6074
- | HandlerConfigInitialTargetPath<HandlerConfigPart<Config[Key]>>
6075
- | (Config[Key] extends { readonly states: infer Children } ? HandlerTreeInitialTargetPath<Children> : never)
6076
- }[keyof Config]
6077
- : never
6078
-
6079
5035
  type HandlerChildrenValidation<
6080
5036
  Node,
6081
5037
  Prefix extends string,
@@ -6207,34 +5163,6 @@ export declare namespace Machine {
6207
5163
  > = [Incompatible] extends [never] ? unknown
6208
5164
  : HandlerValidationError<"Handler config requires an incompatible machine runtime", StateId, Incompatible>
6209
5165
 
6210
- type RootInitialTargetValidation<States extends StateSchemas, Config> =
6211
- RequiredInitializersForTargetPath<States, HandlerTreeInitialTargetPath<{ readonly "": Config }>> extends
6212
- infer Required ? Types.UnionToIntersection<
6213
- Required extends string ?
6214
- HandlerConfigAtPath<{ readonly "": Config }, Required> extends infer NodeConfig ?
6215
- [NodeConfig] extends [never] ? RootInitializeError<Required>
6216
- : "initial" extends keyof NodeConfig ? never
6217
- : RootInitializeError<Required>
6218
- : never :
6219
- unknown
6220
- > :
6221
- unknown
6222
-
6223
- type RootInitializeError<Path extends string> = Path extends "" ? {
6224
- readonly initialize: HandlerValidationError<
6225
- "State requires initialize because a transition enters its declared initial configuration",
6226
- Path
6227
- >
6228
- } :
6229
- {
6230
- readonly states: HandlerValidationAtPath<Path, {
6231
- readonly initialize: HandlerValidationError<
6232
- "State requires initialize because a transition enters its declared initial configuration",
6233
- Path
6234
- >
6235
- }>
6236
- }
6237
-
6238
5166
  type HandlerTreeValidation<
6239
5167
  States extends StateSchemas,
6240
5168
  Node,
@@ -6389,50 +5317,12 @@ export declare namespace Machine {
6389
5317
  : never)
6390
5318
  }[Extract<keyof Config & keyof Nodes, string>]
6391
5319
 
6392
- type HandleTreeResult<
6393
- AllStates extends StateSchemas,
6394
- Events extends ReadonlyArray<TaggedSchema>,
6395
- Emits extends ReadonlyArray<TaggedSchema>,
6396
- Input extends Schema.Top,
6397
- UnhandledStates extends StateIdentifier<AllStates>,
6398
- E,
6399
- R,
6400
- InitialE,
6401
- InitialR,
6402
- FinalStates extends StateIdentifier<AllStates>,
6403
- Output,
6404
- OutputStates extends StateIdentifier<AllStates>,
6405
- InputEvents extends ReadonlyArray<TaggedSchema>,
6406
- ParentEvents extends ReadonlyArray<TaggedSchema>,
6407
- Config
6408
- > = Machine<
6409
- AllStates,
6410
- Events,
6411
- Input,
6412
- Exclude<UnhandledStates, HandlerTreeEvidence<AllStates, Config>["stateId"]>,
6413
- E | HandlerTreeEvidence<AllStates, Config>["error"],
6414
- ExcludeCompatibleRuntime<
6415
- R | HandlerTreeEvidence<AllStates, Config>["services"],
6416
- EventOf<Events>,
6417
- EmittedEventOf<Emits>
6418
- >,
6419
- InitialE,
6420
- InitialR,
6421
- FinalStates,
6422
- Output,
6423
- Emits,
6424
- OutputStates | Extract<HandlerTreeEvidence<AllStates, Config>["outputState"], StateIdentifier<AllStates>>,
6425
- InputEvents,
6426
- ParentEvents
5320
+ // Evaluated once per handled config and read through each machine channel.
5321
+ type HandleEvidence<S extends StateSchemas, C, R> = HandlerTreeEvidence<
5322
+ S,
5323
+ { readonly "": NormalizeObjectConfig<C, R> }
6427
5324
  >
6428
5325
 
6429
- type ObjectCompoundPath<S extends StateSchemas> = {
6430
- readonly [P in StateIdentifier<S>]: NodeByIdentifier<S, P> extends {
6431
- /** Child handlers nested according to the declared root topology. */
6432
- readonly states: StateSchemas
6433
- } ? P :
6434
- never
6435
- }[StateIdentifier<S>]
6436
5326
  type LazyProgramValue = Effect.Effect<unknown, unknown, unknown> | Stream.Stream<unknown, unknown, unknown>
6437
5327
 
6438
5328
  /** Registered lazy programs and their optional explicit input adapters. */
@@ -6443,7 +5333,7 @@ export declare namespace Machine {
6443
5333
  export type LogicSources = Readonly<Record<string, unknown>>
6444
5334
  export type ValidateLogicSources<Sources> = {
6445
5335
  readonly [K in keyof Sources]: InvokeResolvedSource<Sources[K]> extends {
6446
- /** Enters a compound or parallel subtree through its declared initialization. */
5336
+ /** Produces the first state of the registered logic. */
6447
5337
  readonly initial: (...args: never[]) => Effect.Effect<unknown, unknown, unknown>
6448
5338
  readonly run: (...args: never[]) => Effect.Effect<unknown, unknown, unknown>
6449
5339
  } ? unknown
@@ -6464,92 +5354,6 @@ export declare namespace Machine {
6464
5354
  Paths
6465
5355
  >
6466
5356
  type DestinationPath<S extends StateSchemas> = Exclude<StateNodeIdentifier<S>, "">
6467
- type RootSchemas<Root extends StateNodeConfig> = { readonly "": Root }
6468
-
6469
- /** A topology declaration; its state values are constructed by a resolver. */
6470
- export type BranchDeclaration<Root extends StateNodeConfig, S extends StateSchemas = RootSchemas<Root>> =
6471
- & {
6472
- /** Optional presentation label for this named branch. */
6473
- readonly title?: string
6474
- }
6475
- & (
6476
- | {
6477
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6478
- readonly target: ReferenceUnion<S, DestinationPath<S>>
6479
- /**
6480
- * Replaces the complete value of a retained ancestor of the source and target without replacing its active
6481
- * children. A choice target resolves after the update, and every branch it can reach must stay below the owner.
6482
- */
6483
- readonly update?: ReferenceUnion<S, ValuedStateIdentifier<S>>
6484
- /** Enters a compound or parallel subtree through its declared initialization. */
6485
- readonly initial?: never
6486
- /** Restores the declared history reference, using its fallback on first entry. */
6487
- readonly history?: never
6488
- /** Accepts the event without selecting a new destination. */
6489
- readonly none?: never
6490
- /** Reconstructs root and its initial children from fresh machine input. */
6491
- readonly initialize?: never
6492
- }
6493
- | {
6494
- /** Reconstructs root and its initial children from fresh machine input supplied by the resolver. */
6495
- readonly initialize: true
6496
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6497
- readonly target?: never
6498
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6499
- readonly update?: never
6500
- /** Enters a compound or parallel subtree through its declared initialization. */
6501
- readonly initial?: never
6502
- /** Restores the declared history reference, using its fallback on first entry. */
6503
- readonly history?: never
6504
- /** Accepts the event without selecting a new destination. */
6505
- readonly none?: never
6506
- }
6507
- | {
6508
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6509
- readonly update: ReferenceUnion<S, ValuedStateIdentifier<S>>
6510
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6511
- readonly target?: never
6512
- /** Enters a compound or parallel subtree through its declared initialization. */
6513
- readonly initial?: never
6514
- /** Restores the declared history reference, using its fallback on first entry. */
6515
- readonly history?: never
6516
- /** Accepts the event without selecting a new destination. */
6517
- readonly none?: never
6518
- /** Reconstructs root and its initial children from fresh machine input. */
6519
- readonly initialize?: never
6520
- }
6521
- | {
6522
- /** Restores the declared history reference, using its fallback on first entry. */
6523
- readonly history: ReferenceUnion<S, HistoryIdentifier<S>>
6524
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6525
- readonly target?: never
6526
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6527
- readonly update?: never
6528
- /** Enters a compound or parallel subtree through its declared initialization. */
6529
- readonly initial?: never
6530
- /** Accepts the event without selecting a new destination. */
6531
- readonly none?: never
6532
- /** Reconstructs root and its initial children from fresh machine input. */
6533
- readonly initialize?: never
6534
- }
6535
- | {
6536
- /** Accepts the event without selecting a new destination. */
6537
- readonly none: true
6538
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6539
- readonly target?: never
6540
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6541
- readonly update?: never
6542
- /** Enters a compound or parallel subtree through its declared initialization. */
6543
- readonly initial?: never
6544
- /** Restores the declared history reference, using its fallback on first entry. */
6545
- readonly history?: never
6546
- /** Reconstructs root and its initial children from fresh machine input. */
6547
- readonly initialize?: never
6548
- }
6549
- )
6550
- export type BranchDefinitions<Root extends StateNodeConfig> = Readonly<
6551
- Record<string, Readonly<Record<string, BranchDeclaration<Root>>>>
6552
- >
6553
5357
  /** Source programs and named topology declarations captured by a machine definition. */
6554
5358
  export interface Registrations {
6555
5359
  /** Lazy Effects or functions with one required input, invoked by registered name. */
@@ -6562,12 +5366,9 @@ export declare namespace Machine {
6562
5366
  readonly logic?: LogicSources
6563
5367
  /** Child machine descriptors registered for state-owned invocation. */
6564
5368
  readonly children?: ChildSources
6565
- /** Named groups of inspectable destinations used by transition resolvers. */
6566
- readonly branches?: Readonly<Record<string, Readonly<Record<string, unknown>>>>
6567
5369
  }
6568
5370
  type RegisteredInput<R> = R extends { readonly "~input": infer I extends Schema.Top } ? I : typeof Schema.Void
6569
5371
  type Registered<R, Kind extends PropertyKey> = Kind extends keyof R ? NonNullable<R[Kind]> : {}
6570
- type RefPath<R> = PathOf<R>
6571
5372
  type ConstructionData<Node> = [NodeSchema<Node>] extends [never] ? { readonly data?: never; readonly decoded?: never }
6572
5373
  :
6573
5374
  | (
@@ -6616,86 +5417,68 @@ export declare namespace Machine {
6616
5417
  /** Fresh machine input used by root construction and root initial callbacks. */ readonly input:
6617
5418
  RegisteredInput<R>["Type"]
6618
5419
  })
6619
- type ObjectSelection<
6620
- S extends StateSchemas,
6621
- Src extends StateNodeIdentifier<S>,
6622
- P extends StateNodeIdentifier<S>,
6623
- R
6624
- > = P extends "" ? ConstructionCall<RootInput<R>, InitialTarget<P>>
6625
- : P extends ChoiceIdentifier<S> ? () => ChoiceTarget<S, P>
6626
- : P extends StateIdentifier<S> ? ConstructionCall<
6627
- ConstructionObject<
6628
- NodeByIdentifier<S, P>,
6629
- Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never
6630
- > & { readonly update?: never },
6631
- Target<S, P>
6632
- >
6633
- : never
6634
- type SelectionOf<S extends StateSchemas, Src extends StateNodeIdentifier<S>, D, R = {}> = D extends {
6635
- readonly initialize: true
6636
- } ? TargetSelection<ObjectSelection<S, Src, Extract<"", StateNodeIdentifier<S>>, R>, "", "state", "branch">
6637
- : D extends {
6638
- readonly target: infer Ref
6639
- } ?
6640
- RefPath<Ref> extends infer P extends StateNodeIdentifier<S> ?
6641
- D extends { readonly update: infer Update }
6642
- ? RefPath<Update> extends
6643
- infer Owner extends Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>
6644
- ? P extends StateIdentifier<S> ? TargetSelection<
6645
- ConstructionCall<
6646
- ConstructionObject<
6647
- NodeByIdentifier<S, P>,
6648
- Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never
6649
- > & {
6650
- readonly update: ConstructionData<NodeByIdentifier<S, Owner>>
6651
- },
6652
- CombinedTarget<Target<S, P>, S, Owner>
6653
- >,
6654
- P,
6655
- "state",
6656
- "branch"
6657
- >
6658
- : P extends ChoiceIdentifier<S> ? TargetSelection<
6659
- (construction: {
6660
- readonly update: ConstructionData<NodeByIdentifier<S, Owner>>
6661
- }) => CombinedTarget<ChoiceTarget<S, P>, S, Owner>,
6662
- P,
6663
- "choice",
6664
- "branch"
6665
- > :
6666
- never
6667
- : never
6668
- : TargetSelection<
6669
- ObjectSelection<S, Src, P, R>,
6670
- P,
6671
- P extends ChoiceIdentifier<S> ? "choice" : "state",
6672
- "branch"
6673
- >
6674
- : never
6675
- : D extends { readonly history: infer Ref }
6676
- ? RefPath<Ref> extends infer P extends HistoryIdentifier<S>
6677
- ? TargetSelection<() => HistoryTarget<S, P>, P, "history", "full"> :
6678
- never
6679
- : D extends { readonly update: infer Ref }
6680
- ? RefPath<Ref> extends infer P extends Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>
6681
- ? TargetSelection<
6682
- ConstructionCall<ConstructionData<NodeByIdentifier<S, P>>, StateUpdate<S, P>>,
6683
- P,
6684
- "update",
6685
- "branch"
6686
- > :
6687
- never
6688
- : D extends { readonly none: true } ? TargetSelection<() => NoTarget, never, "none", "local">
5420
+ type UpdateValue<Node> = OrdinaryData<NodeMakeInput<Node>> | {
5421
+ readonly decoded: true
5422
+ readonly data: NodeValue<Node>
5423
+ }
5424
+ type TargetConstruction<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends DestinationPath<S>> =
5425
+ P extends StateIdentifier<S> ?
5426
+ ConstructionObject<NodeByIdentifier<S, P>, Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never>
5427
+ : {}
5428
+ type TargetArguments<A> = {} extends A ? [construction?: A & { readonly update?: never }]
5429
+ : [construction: A & { readonly update?: never }]
5430
+ type TargetResult<S extends StateSchemas, P extends string> = P extends ChoiceIdentifier<S> ? ChoiceTarget<S, P>
5431
+ : P extends StateIdentifier<S> ? Target<S, P>
6689
5432
  : never
6690
- type BuilderArgs<B, K extends PropertyKey> = K extends keyof B
6691
- ? B[K] extends (...args: infer A) => unknown ? A : never
6692
- : never
6693
- type ObjectConstruction<C, B> = {
6694
- readonly [M in Extract<keyof B, "from" | "decoded">]: BuilderArgs<B, M> extends readonly [unknown?] ?
6695
- & { readonly [K in M]: (context: C) => BuilderArgs<B, M>[0] }
6696
- & { readonly [K in Exclude<"from" | "decoded", M>]?: never }
6697
- : never
6698
- }[Extract<keyof B, "from" | "decoded">]
5433
+ type OnePath<P extends string> = Types.IsUnion<P> extends true
5434
+ ? { readonly [K in `select.target takes one path, got: ${JoinUnion<P>}. Call it once per path`]: never }
5435
+ : unknown
5436
+ type OneOwner<O extends string> = Types.IsUnion<O> extends true ? `update takes one owner, got: ${JoinUnion<O>}`
5437
+ : unknown
5438
+ /**
5439
+ * Selects one entry of a transition's `branches` list. The compiler checks that `resolve` selects exactly the
5440
+ * declared entries, so each call here must match one of them.
5441
+ *
5442
+ * @category models
5443
+ * @since 0.47.0
5444
+ */
5445
+ export interface BranchSelect<S extends StateSchemas, Src extends StateNodeIdentifier<S>, R> {
5446
+ /** Selects `{ target }`, or `{ target, update }` when the construction has an `update` record. */
5447
+ readonly target: {
5448
+ <P extends DestinationPath<S>, O extends ReferenceUnion<S, TargetOwner<S, Src, P>>>(
5449
+ path: P & OnePath<P>,
5450
+ construction: TargetConstruction<S, Src, P> & {
5451
+ /** The new value of the retained owner named by this branch. */
5452
+ readonly update:
5453
+ & { readonly [Owner in O]: UpdateValue<NodeByIdentifier<S, Extract<PathOf<Owner>, StateIdentifier<S>>>> }
5454
+ & OneOwner<O>
5455
+ }
5456
+ ): SelectedBranch<
5457
+ `target:${P}+update:${O}`,
5458
+ CombinedTarget<TargetResult<S, P>, S, Extract<PathOf<O>, ValuedStateIdentifier<S>>>
5459
+ >
5460
+ <P extends DestinationPath<S>>(
5461
+ path: P & OnePath<P>,
5462
+ ...construction: TargetArguments<TargetConstruction<S, Src, P>>
5463
+ ): SelectedBranch<`target:${P}`, TargetResult<S, P>>
5464
+ }
5465
+ /** Selects `{ update }`, replacing the value of one retained source or ancestor. */
5466
+ readonly update: <O extends ReferenceUnion<S, UpdatableOwner<S, Src>>>(
5467
+ updates:
5468
+ & { readonly [Owner in O]: UpdateValue<NodeByIdentifier<S, Extract<PathOf<Owner>, StateIdentifier<S>>>> }
5469
+ & OneOwner<O>
5470
+ ) => SelectedBranch<`update:${O}`, StateUpdate<S, Extract<PathOf<O>, ValuedStateIdentifier<S>>>>
5471
+ /** Selects `{ history }`. */
5472
+ readonly history: <P extends ReferenceUnion<S, HistoryIdentifier<S>>>(
5473
+ path: P
5474
+ ) => SelectedBranch<`history:${P}`, HistoryTarget<S, Extract<PathOf<P>, HistoryIdentifier<S>>>>
5475
+ /** Selects `{ initialize: true }`. */
5476
+ readonly initialize: ConstructionCall<RootInput<R>, SelectedBranch<"initialize", InitialTarget<"">>>
5477
+ /** Selects `{ stay: true }`. */
5478
+ readonly stay: () => SelectedBranch<"stay", NoTarget>
5479
+ /** Selects `{ decline: true }`, passing the event on to the next candidate. */
5480
+ readonly decline: () => SelectedBranch<"decline", Declined>
5481
+ }
6699
5482
  type ObjectPolicy<C, Reenter extends boolean, Acceptance extends TransitionAcceptance> = {
6700
5483
  /** Set to true to exit and reenter the handler source. */
6701
5484
  readonly reenter?: Reenter extends true ? boolean : never
@@ -6726,147 +5509,121 @@ export declare namespace Machine {
6726
5509
  */
6727
5510
  readonly initialize: RegisteredInput<R> extends typeof Schema.Void ? true
6728
5511
  : DataValue<C, RegisteredInput<R>["Type"]>
5512
+ /** Selects a declared descendant, constructing the values it requires. */
6729
5513
  readonly target?: never
5514
+ /** Replaces the value of one retained state without replacing its active children. */
6730
5515
  readonly update?: never
5516
+ /** Restores the declared history reference, using its fallback on first entry. */
5517
+ readonly history?: never
5518
+ /** Accepts the event and stays in the current states. */
5519
+ readonly stay?: never
5520
+ /** The destinations this transition can select, each one checked against `resolve`. */
6731
5521
  readonly branches?: never
5522
+ /** Selects one declared branch and may enqueue synchronous commands. */
6732
5523
  readonly resolve?: never
6733
- readonly history?: never
6734
- readonly none?: never
6735
5524
  }
5525
+ type OwnerUpdates<S extends StateSchemas, Owners extends ValuedStateIdentifier<S>, C> = {
5526
+ readonly [O in Owners as PathName<O>]?: ShortConstruction<C, NodeByIdentifier<S, O>>
5527
+ }
5528
+ type TargetOwner<S extends StateSchemas, Src extends StateNodeIdentifier<S>, P extends string> = Src extends
5529
+ ChoiceIdentifier<S> ? never
5530
+ : Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>
5531
+ type UpdatableOwner<S extends StateSchemas, Src extends StateNodeIdentifier<S>> = Src extends ChoiceIdentifier<S> ?
5532
+ never
5533
+ : Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>
6736
5534
  type InlineDestination<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = {
6737
5535
  readonly [P in DestinationPath<S>]:
6738
5536
  & {
6739
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
5537
+ /** Selects a declared descendant, constructing the values it requires. */
6740
5538
  readonly target: ReferenceAt<S, P>
6741
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6742
- readonly update?: never
6743
- /** Enters a compound or parallel subtree through its declared initialization. */
6744
- readonly initial?: never
5539
+ /**
5540
+ * Replaces the value of one retained ancestor of the source and target without replacing its active children.
5541
+ * A choice target resolves after the update, and every branch it can reach must stay below the owner.
5542
+ */
5543
+ readonly update?: OwnerUpdates<S, TargetOwner<S, Src, P>, C>
5544
+ /** Reconstructs root and its initial children from fresh machine input. */
5545
+ readonly initialize?: never
6745
5546
  /** Restores the declared history reference, using its fallback on first entry. */
6746
5547
  readonly history?: never
6747
- /** Accepts the event without selecting a new destination. */
6748
- readonly none?: never
6749
- /** Named groups of inspectable destinations used by transition resolvers. */
5548
+ /** Accepts the event and stays in the current states. */
5549
+ readonly stay?: never
5550
+ /** The destinations this transition can select, each one checked against `resolve`. */
6750
5551
  readonly branches?: never
6751
5552
  /** Selects one declared branch and may enqueue synchronous commands. */
6752
5553
  readonly resolve?: never
6753
- /** Set to true when the resolver can explicitly return decline(). */
6754
- readonly declinable?: never
6755
5554
  }
6756
5555
  & InlineDestinationConstruction<S, Src, P, C>
6757
5556
  }[DestinationPath<S>]
6758
- type InlinePairConstruction<
5557
+ // A misspelled target matches this member, so validation can name the declared paths instead of `never`.
5558
+ type InlineUnknownTarget<S extends StateSchemas> = {
5559
+ /** Selects a declared descendant, constructing the values it requires. */
5560
+ readonly target: ReferenceUnion<S, DestinationPath<S>> | (string & {})
5561
+ readonly update?: never
5562
+ readonly initialize?: never
5563
+ readonly history?: never
5564
+ readonly stay?: never
5565
+ readonly branches?: never
5566
+ readonly resolve?: never
5567
+ }
5568
+ type InlineUpdate<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = [UpdatableOwner<S, Src>] extends
5569
+ [never] ? never : {
5570
+ /** Replaces the value of one retained source or ancestor without replacing its active children. */
5571
+ readonly update: OwnerUpdates<S, UpdatableOwner<S, Src>, C>
5572
+ /** Selects a declared descendant, constructing the values it requires. */
5573
+ readonly target?: never
5574
+ /** Reconstructs root and its initial children from fresh machine input. */
5575
+ readonly initialize?: never
5576
+ /** Restores the declared history reference, using its fallback on first entry. */
5577
+ readonly history?: never
5578
+ /** Accepts the event and stays in the current states. */
5579
+ readonly stay?: never
5580
+ /** The destinations this transition can select, each one checked against `resolve`. */
5581
+ readonly branches?: never
5582
+ /** Selects one declared branch and may enqueue synchronous commands. */
5583
+ readonly resolve?: never
5584
+ }
5585
+ /**
5586
+ * One destination a `resolve` function can select. Here `update` names the owner as a string, because the value is
5587
+ * passed to the `select` call.
5588
+ *
5589
+ * @category models
5590
+ * @since 0.47.0
5591
+ */
5592
+ export type BranchEntry<
6759
5593
  S extends StateSchemas,
6760
5594
  Src extends StateNodeIdentifier<S>,
6761
- P extends string,
6762
- Owner extends ValuedStateIdentifier<S>,
6763
- C
6764
- > = P extends StateIdentifier<S> ?
6765
- | {
6766
- readonly from: (
6767
- context: C
6768
- ) => {
6769
- readonly target: [NodeSchema<NodeByIdentifier<S, P>>] extends [never] ? undefined
6770
- : NodeMakeInput<NodeByIdentifier<S, P>>
6771
- readonly update: SchemaByIdentifier<S, Owner>["~type.make.in"]
6772
- }
6773
- readonly decoded?: never
6774
- }
6775
- | ([NodeSchema<NodeByIdentifier<S, P>>] extends [never] ? never
6776
- : {
6777
- readonly decoded: (
6778
- context: C
6779
- ) => { readonly target: NodeValue<NodeByIdentifier<S, P>>; readonly update: StateByIdentifier<S, Owner> }
6780
- readonly from?: never
6781
- })
6782
- : P extends ChoiceIdentifier<S> ? ObjectConstruction<C, StateUpdateBuilder<S, Owner>>
6783
- : never
6784
- type InlineCombined<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = Src extends ChoiceIdentifier<S> ?
6785
- never :
6786
- [Extract<ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>] extends [never] ? never :
6787
- {
5595
+ Acceptance extends TransitionAcceptance
5596
+ > =
5597
+ | {
6788
5598
  readonly [P in DestinationPath<S>]: {
6789
- readonly [Owner in Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>]:
6790
- & {
6791
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6792
- readonly target: ReferenceAt<S, P>
6793
- /**
6794
- * Replaces the complete value of a retained ancestor of the source and target without replacing its active
6795
- * children. A choice target resolves after the update, and every branch it can reach must stay below the
6796
- * owner; `data` then constructs only the owner value.
6797
- */
6798
- readonly update: ReferenceAt<S, Owner>
6799
- /** Enters a compound or parallel subtree through its declared initialization. */
6800
- readonly initial?: never
6801
- /** Restores the declared history reference, using its fallback on first entry. */
6802
- readonly history?: never
6803
- /** Accepts the event without selecting a new destination. */
6804
- readonly none?: never
6805
- /** Named groups of inspectable destinations used by transition resolvers. */
6806
- readonly branches?: never
6807
- /** Selects one declared branch and may enqueue synchronous commands. */
6808
- readonly resolve?: never
6809
- /** Set to true when the resolver can explicitly return decline(). */
6810
- readonly declinable?: never
6811
- }
6812
- & InlinePairConstruction<S, Src, P, Owner, C>
6813
- }[Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>]
5599
+ /** Selects a declared descendant through `select.target`. */
5600
+ readonly target: ReferenceAt<S, P>
5601
+ /** The retained ancestor that this branch's `select.target` call updates. */
5602
+ readonly update?: ReferenceUnion<S, TargetOwner<S, Src, P>>
5603
+ }
6814
5604
  }[DestinationPath<S>]
6815
- type InlineUpdate<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = Src extends ChoiceIdentifier<S> ?
6816
- never :
6817
- {
6818
- readonly [P in Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>]:
6819
- & {
6820
- /** Set to true to exit and reenter the handler source. */
6821
- readonly reenter?: P extends Src ? never : boolean
6822
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6823
- readonly update: ReferenceAt<S, P>
6824
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6825
- readonly target?: never
6826
- /** Enters a compound or parallel subtree through its declared initialization. */
6827
- readonly initial?: never
6828
- /** Restores the declared history reference, using its fallback on first entry. */
6829
- readonly history?: never
6830
- /** Accepts the event without selecting a new destination. */
6831
- readonly none?: never
6832
- /** Named groups of inspectable destinations used by transition resolvers. */
6833
- readonly branches?: never
6834
- /** Selects one declared branch and may enqueue synchronous commands. */
6835
- readonly resolve?: never
6836
- /** Set to true when the resolver can explicitly return decline(). */
6837
- readonly declinable?: never
6838
- }
6839
- & ObjectConstruction<C, StateUpdateBuilder<S, P>>
6840
- }[Extract<Src | ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>]
6841
- type BranchSelections<S extends StateSchemas, Src extends StateNodeIdentifier<S>, Group, R> = {
6842
- readonly [K in Extract<keyof Group, string>]: {
6843
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6844
- readonly target: SelectionOf<S, Src, Group[K], R>
5605
+ | ([UpdatableOwner<S, Src>] extends [never] ? never : {
5606
+ /** The retained state updated through `select.update`. */
5607
+ readonly update: ReferenceUnion<S, UpdatableOwner<S, Src>>
5608
+ readonly target?: never
5609
+ })
5610
+ | {
5611
+ /** Restores this history reference through `select.history`. */
5612
+ readonly history: ReferenceUnion<S, HistoryIdentifier<S>>
6845
5613
  }
6846
- }
6847
- type ObjectBranchResolver<
6848
- Ev extends ReadonlyArray<TaggedSchema>,
6849
- Em extends ReadonlyArray<TaggedSchema>,
6850
- C,
6851
- B extends Readonly<Record<string, TransitionBranchInput>>,
6852
- Declinable extends boolean
6853
- > = (
6854
- context: C & { readonly select: BranchSelectors<B> } & DeclineCapability,
6855
- enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>
6856
- ) => BranchSelectionResult<B> | (Declinable extends true ? Declined : never)
6857
- type InvalidBranchSelection<S extends StateSchemas, Src extends StateNodeIdentifier<S>, Group, R> = {
6858
- readonly [K in keyof Group]: Src extends ChoiceIdentifier<S> ? Group[K] extends {
6859
- /** Accepts the event without selecting a new destination. */
6860
- readonly none: true
6861
- } | {
6862
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6863
- readonly update: unknown
6864
- } ? K
6865
- : [SelectionBuilder<SelectionOf<S, Src, Group[K], R>>] extends [never] ? K
6866
- : never
6867
- : [SelectionBuilder<SelectionOf<S, Src, Group[K], R>>] extends [never] ? K
6868
- : never
6869
- }[keyof Group]
5614
+ | {
5615
+ /** Reconstructs root from fresh machine input through `select.initialize`. */
5616
+ readonly initialize: true
5617
+ }
5618
+ | (Src extends ChoiceIdentifier<S> ? never : {
5619
+ /** Accepts the event and stays in the current states through `select.stay`. */
5620
+ readonly stay: true
5621
+ })
5622
+ | (Acceptance extends "declinable" ? {
5623
+ /** Passes the event on to the next candidate through `select.decline`. */
5624
+ readonly decline: true
5625
+ } :
5626
+ never)
6870
5627
  type ObjectBranches<
6871
5628
  S extends StateSchemas,
6872
5629
  Src extends StateNodeIdentifier<S>,
@@ -6874,41 +5631,40 @@ export declare namespace Machine {
6874
5631
  Ev extends ReadonlyArray<TaggedSchema>,
6875
5632
  Em extends ReadonlyArray<TaggedSchema>,
6876
5633
  R,
5634
+ Reenter extends boolean,
6877
5635
  Acceptance extends TransitionAcceptance
6878
5636
  > = {
6879
- readonly [K in Extract<keyof Registered<R, "branches">, string>]:
6880
- & ([InvalidBranchSelection<S, Src, Registered<R, "branches">[K], R>] extends [never] ? unknown : never)
6881
- & {
6882
- /** Named groups of inspectable destinations used by transition resolvers. */
6883
- readonly branches: K
6884
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6885
- readonly target?: never
6886
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6887
- readonly update?: never
6888
- /** Enters a compound or parallel subtree through its declared initialization. */
6889
- readonly initial?: never
6890
- /** Restores the declared history reference, using its fallback on first entry. */
6891
- readonly history?: never
6892
- /** Accepts the event without selecting a new destination. */
6893
- readonly none?: never
6894
- /** Constructs schema make input from the typed source context. */
6895
- readonly from?: never
6896
- /** Supplies an already decoded schema value from the typed source context. */
6897
- readonly decoded?: never
6898
- }
6899
- & {
6900
- /** Set to true when the resolver can explicitly return decline(). */
6901
- readonly declinable?: "declinable" extends Acceptance ? boolean : false
6902
- /** Selects one declared branch and may enqueue synchronous commands. */
6903
- readonly resolve: ObjectBranchResolver<
6904
- Ev,
6905
- Em,
6906
- C,
6907
- BranchSelections<S, Src, Registered<R, "branches">[K], R>,
6908
- true
6909
- >
6910
- }
6911
- }[Extract<keyof Registered<R, "branches">, string>]
5637
+ /** The destinations this transition can select, each one checked against `resolve`. */
5638
+ readonly branches?: ReadonlyArray<BranchEntry<S, Src, Acceptance>>
5639
+ /** Selects one declared branch and may enqueue synchronous commands. */
5640
+ readonly resolve?: (
5641
+ context: C & {
5642
+ /** Selects one of the declared `branches`. */
5643
+ readonly select: BranchSelect<S, Src, R>
5644
+ },
5645
+ enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>
5646
+ ) => unknown
5647
+ /** Set to true to exit and reenter the handler source. */
5648
+ readonly reenter?: Reenter extends true ? boolean : never
5649
+ /** Branch on the condition inside `resolve`, returning `select.decline()`. */
5650
+ readonly guard?: never
5651
+ /** Enqueue commands inside `resolve`. */
5652
+ readonly commands?: never
5653
+ /** Constructs values through the `select` calls inside `resolve`. */
5654
+ readonly data?: never
5655
+ /** Constructs values through the `select` calls inside `resolve`. */
5656
+ readonly decoded?: never
5657
+ /** Selects a declared descendant, constructing the values it requires. */
5658
+ readonly target?: never
5659
+ /** Replaces the value of one retained state without replacing its active children. */
5660
+ readonly update?: never
5661
+ /** Reconstructs root and its initial children from fresh machine input. */
5662
+ readonly initialize?: never
5663
+ /** Restores the declared history reference, using its fallback on first entry. */
5664
+ readonly history?: never
5665
+ /** Accepts the event and stays in the current states. */
5666
+ readonly stay?: never
5667
+ }
6912
5668
  type DataValue<C, A> = A | ((context: C) => A)
6913
5669
  type DeclarationData<T> = T extends { readonly from: (context: infer C) => infer A }
6914
5670
  ? Omit<T, "from" | "decoded"> & { readonly data: DataValue<C, A>; readonly decoded?: false }
@@ -6932,63 +5688,71 @@ export declare namespace Machine {
6932
5688
  Reenter extends boolean = false,
6933
5689
  Acceptance extends TransitionAcceptance = "required"
6934
5690
  > =
6935
- & ObjectPolicy<C, Reenter, Acceptance>
6936
- & DeclarationData<
6937
- (
5691
+ | (
5692
+ & ObjectPolicy<C, Reenter, Acceptance>
5693
+ & {
5694
+ /** Enqueues synchronous commands when this transition is selected. */
5695
+ readonly commands?: (context: C, enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>) => void
5696
+ }
5697
+ & DeclarationData<
6938
5698
  | InlineDestination<S, Src, C>
5699
+ | InlineUnknownTarget<S>
6939
5700
  | InlineUpdate<S, Src, C>
6940
- | InlineCombined<S, Src, C>
6941
5701
  | InlineRoot<C, R>
6942
5702
  | {
6943
5703
  /** Restores the declared history reference, using its fallback on first entry. */
6944
5704
  readonly history: ReferenceUnion<S, HistoryIdentifier<S>>
6945
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
5705
+ /** Selects a declared descendant, constructing the values it requires. */
6946
5706
  readonly target?: never
6947
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
5707
+ /** Replaces the value of one retained state without replacing its active children. */
6948
5708
  readonly update?: never
6949
- /** Enters a compound or parallel subtree through its declared initialization. */
6950
- readonly initial?: never
6951
- /** Accepts the event without selecting a new destination. */
6952
- readonly none?: never
6953
- /** Named groups of inspectable destinations used by transition resolvers. */
5709
+ /** Reconstructs root and its initial children from fresh machine input. */
5710
+ readonly initialize?: never
5711
+ /** Accepts the event and stays in the current states. */
5712
+ readonly stay?: never
5713
+ /** The destinations this transition can select, each one checked against `resolve`. */
6954
5714
  readonly branches?: never
6955
5715
  /** Selects one declared branch and may enqueue synchronous commands. */
6956
5716
  readonly resolve?: never
6957
- /** Constructs schema make input from the typed source context. */
6958
- readonly from?: never
6959
- /** Supplies an already decoded schema value from the typed source context. */
6960
- readonly decoded?: never
6961
- /** Set to true when the resolver can explicitly return decline(). */
6962
- readonly declinable?: never
6963
5717
  }
6964
5718
  | (Src extends ChoiceIdentifier<S> ? never : {
6965
- /** Accepts the event without selecting a new destination. */
6966
- readonly none: true
6967
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
5719
+ /** Accepts the event and stays in the current states. */
5720
+ readonly stay: true
5721
+ /** Selects a declared descendant, constructing the values it requires. */
6968
5722
  readonly target?: never
6969
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
5723
+ /** Replaces the value of one retained state without replacing its active children. */
6970
5724
  readonly update?: never
6971
- /** Enters a compound or parallel subtree through its declared initialization. */
6972
- readonly initial?: never
5725
+ /** Reconstructs root and its initial children from fresh machine input. */
5726
+ readonly initialize?: never
6973
5727
  /** Restores the declared history reference, using its fallback on first entry. */
6974
5728
  readonly history?: never
6975
- /** Named groups of inspectable destinations used by transition resolvers. */
5729
+ /** The destinations this transition can select, each one checked against `resolve`. */
6976
5730
  readonly branches?: never
6977
- /** Constructs schema make input from the typed source context. */
6978
- readonly from?: never
6979
- /** Supplies an already decoded schema value from the typed source context. */
6980
- readonly decoded?: never
6981
- /** Set to true when the resolver can explicitly return decline(). */
6982
- readonly declinable?: "declinable" extends Acceptance ? boolean : false
6983
5731
  /** Selects one declared branch and may enqueue synchronous commands. */
6984
- readonly resolve?: (
6985
- context: C & DeclineCapability,
6986
- enqueue: Enqueue<EventOf<Ev>, EmittedEventOf<Em>>
6987
- ) => undefined | Declined
5732
+ readonly resolve?: never
6988
5733
  })
6989
- | ObjectBranches<S, Src, C, Ev, Em, R, Acceptance>
6990
- )
6991
- >
5734
+ | (Src extends ChoiceIdentifier<S> ? never : Reenter extends true ? {
5735
+ /** Exits and reenters the source. */
5736
+ readonly reenter: true
5737
+ /** Selects a declared descendant, constructing the values it requires. */
5738
+ readonly target?: never
5739
+ /** Replaces the value of one retained state without replacing its active children. */
5740
+ readonly update?: never
5741
+ /** Reconstructs root and its initial children from fresh machine input. */
5742
+ readonly initialize?: never
5743
+ /** Restores the declared history reference, using its fallback on first entry. */
5744
+ readonly history?: never
5745
+ /** Accepts the event and stays in the current states. */
5746
+ readonly stay?: never
5747
+ /** The destinations this transition can select, each one checked against `resolve`. */
5748
+ readonly branches?: never
5749
+ /** Selects one declared branch and may enqueue synchronous commands. */
5750
+ readonly resolve?: never
5751
+ } :
5752
+ never)
5753
+ >
5754
+ )
5755
+ | ObjectBranches<S, Src, C, Ev, Em, R, Reenter, Acceptance>
6992
5756
  type SourceValue<R, K extends PropertyKey> = {
6993
5757
  readonly [Kind in "effects" | "streams" | "timers" | "logic" | "children"]: K extends keyof Registered<R, Kind>
6994
5758
  ? Registered<R, Kind>[K]
@@ -7062,7 +5826,7 @@ export declare namespace Machine {
7062
5826
  Em,
7063
5827
  R,
7064
5828
  true,
7065
- TransitionAcceptance
5829
+ "required"
7066
5830
  >
7067
5831
  } :
7068
5832
  Channel extends "onFailure" ? {
@@ -7075,7 +5839,7 @@ export declare namespace Machine {
7075
5839
  Em,
7076
5840
  R,
7077
5841
  true,
7078
- TransitionAcceptance
5842
+ "required"
7079
5843
  >
7080
5844
  } :
7081
5845
  Channel extends "onElement" ? {
@@ -7088,7 +5852,7 @@ export declare namespace Machine {
7088
5852
  Em,
7089
5853
  R,
7090
5854
  true,
7091
- TransitionAcceptance
5855
+ "required"
7092
5856
  >
7093
5857
  } :
7094
5858
  {
@@ -7101,7 +5865,7 @@ export declare namespace Machine {
7101
5865
  Em,
7102
5866
  R,
7103
5867
  true,
7104
- TransitionAcceptance
5868
+ "required"
7105
5869
  >
7106
5870
  }
7107
5871
  type RegisteredInvokeError<R, K extends PropertyKey> = SourceKind<R, K> extends "children"
@@ -7325,6 +6089,8 @@ export declare namespace Machine {
7325
6089
  readonly exit?: never /** Constructs the decoded output declared by the state schema. */
7326
6090
  readonly output?: never
7327
6091
  }
6092
+ type StateFieldError<Kind extends string, Src extends string, Field extends string, Fix extends string> =
6093
+ `${Kind} state "${PathName<Src>}" cannot declare ${Field}. ${Fix}`
7328
6094
  /**
7329
6095
  * Handlers for a node of the declared root tree.
7330
6096
  *
@@ -7361,13 +6127,13 @@ export declare namespace Machine {
7361
6127
  /** Required total transition for a transient choice state. */
7362
6128
  readonly choice: Transition<S, Src, ChoiceContext<S, Ev, Em, Src, In, Pa>, Ev, Em, R>
7363
6129
  /** Event handlers keyed by the public or internal event tag. */
7364
- readonly on?: never
6130
+ readonly on?: StateFieldError<"Choice", Src, "on", "Declare one transition in choice">
7365
6131
  /** Eventless transition evaluated during stabilization. */
7366
- readonly always?: never
6132
+ readonly always?: StateFieldError<"Choice", Src, "always", "Declare one transition in choice">
7367
6133
  /** Handles successful invocation or state completion with its exact output type. */
7368
- readonly onDone?: never
6134
+ readonly onDone?: StateFieldError<"Choice", Src, "onDone", "Declare one transition in choice">
7369
6135
  /** One registered invocation or an array with distinct lifecycle identities. */
7370
- readonly invoke?: never
6136
+ readonly invoke?: StateFieldError<"Choice", Src, "invoke", "Declare one transition in choice">
7371
6137
  /** Child handlers nested according to the declared root topology. */
7372
6138
  readonly states?: never
7373
6139
  /** Restores the declared history reference, using its fallback on first entry. */
@@ -7375,15 +6141,15 @@ export declare namespace Machine {
7375
6141
  }
7376
6142
  : Src extends StateIdentifier<S> ? Node extends { readonly type: "final" } ? {
7377
6143
  /** Event handlers keyed by the public or internal event tag. */
7378
- readonly on?: never
6144
+ readonly on?: StateFieldError<"Final", Src, "on", "A final state has no outgoing work">
7379
6145
  /** Eventless transition evaluated during stabilization. */
7380
- readonly always?: never
6146
+ readonly always?: StateFieldError<"Final", Src, "always", "A final state has no outgoing work">
7381
6147
  /** Handles successful invocation or state completion with its exact output type. */
7382
- readonly onDone?: never
6148
+ readonly onDone?: StateFieldError<"Final", Src, "onDone", "A final state has no outgoing work">
7383
6149
  /** Required total transition for a transient choice state. */
7384
6150
  readonly choice?: never
7385
6151
  /** One registered invocation or an array with distinct lifecycle identities. */
7386
- readonly invoke?: never
6152
+ readonly invoke?: StateFieldError<"Final", Src, "invoke", "A final state has no outgoing work">
7387
6153
  /** Child handlers nested according to the declared root topology. */
7388
6154
  readonly states?: never
7389
6155
  /** Restores the declared history reference, using its fallback on first entry. */
@@ -7401,7 +6167,7 @@ export declare namespace Machine {
7401
6167
  Em,
7402
6168
  R,
7403
6169
  true,
7404
- TransitionAcceptance
6170
+ "declinable"
7405
6171
  >
7406
6172
  }
7407
6173
  /** Eventless transition evaluated during stabilization. */
@@ -7413,7 +6179,7 @@ export declare namespace Machine {
7413
6179
  Em,
7414
6180
  R,
7415
6181
  false,
7416
- TransitionAcceptance
6182
+ "declinable"
7417
6183
  >
7418
6184
  /** Handles successful invocation or state completion with its exact output type. */
7419
6185
  readonly onDone?: Transition<
@@ -7424,7 +6190,7 @@ export declare namespace Machine {
7424
6190
  Em,
7425
6191
  R,
7426
6192
  false,
7427
- TransitionAcceptance
6193
+ "required"
7428
6194
  >
7429
6195
  /** Required total transition for a transient choice state. */
7430
6196
  readonly choice?: never
@@ -7450,9 +6216,163 @@ export declare namespace Machine {
7450
6216
  readonly history?: never
7451
6217
  }) :
7452
6218
  never)
7453
- type ValidateObjectTransition<T> =
6219
+ type LastOfUnion<U> = Types.UnionToIntersection<U extends unknown ? () => U : never> extends () => infer Last ? Last
6220
+ : never
6221
+ type JoinUnion<U extends string> = [U] extends [never] ? ""
6222
+ : LastOfUnion<U> extends infer Last extends string
6223
+ ? [Exclude<U, Last>] extends [never] ? Last : `${JoinUnion<Exclude<U, Last>>}, ${Last}`
6224
+ : never
6225
+ type BranchEntryKey<Entry> = Entry extends
6226
+ { readonly target: infer P extends string; readonly update: infer O extends string } ? `target:${P}+update:${O}`
6227
+ : Entry extends { readonly target: infer P extends string } ? `target:${P}`
6228
+ : Entry extends { readonly update: infer O extends string } ? `update:${O}`
6229
+ : Entry extends { readonly history: infer P extends string } ? `history:${P}`
6230
+ : Entry extends { readonly initialize: true } ? "initialize"
6231
+ : Entry extends { readonly stay: true } ? "stay"
6232
+ : Entry extends { readonly decline: true } ? "decline"
6233
+ : never
6234
+ type BranchLabel<Key extends string> = Key extends `target:${infer P}+update:${infer O}`
6235
+ ? `{ target: "${P}", update: "${O}" }`
6236
+ : Key extends `target:${infer P}` ? `{ target: "${P}" }`
6237
+ : Key extends `update:${infer O}` ? `{ update: "${O}" }`
6238
+ : Key extends `history:${infer P}` ? `{ history: "${P}" }`
6239
+ : Key extends "initialize" | "stay" | "decline" ? `{ ${Key}: true }`
6240
+ : never
6241
+ type BranchEntryKeyAt<B extends ReadonlyArray<unknown>, K> = K extends keyof B ? BranchEntryKey<B[K]> : never
6242
+ type DuplicateBranchKey<B extends ReadonlyArray<unknown>, Indices extends keyof B = Extract<keyof B, `${number}`>> = {
6243
+ readonly [K in Indices]: BranchEntryKeyAt<B, K> extends BranchEntryKeyAt<B, Exclude<Indices, K>>
6244
+ ? BranchEntryKeyAt<B, K>
6245
+ : never
6246
+ }[Indices]
6247
+ type SelectedBranchKey<Result> = Result extends SelectedBranch<infer Key, any> ? Key : never
6248
+ type ValidateBranchSelection<B extends ReadonlyArray<unknown>, Result> = number extends B["length"] ?
6249
+ { readonly branches: "branches must list its entries inline" }
6250
+ : B["length"] extends 0 ? { readonly branches: "branches needs at least one entry" }
6251
+ : [DuplicateBranchKey<B>] extends [never] ?
6252
+ 0 extends 1 & Result ? { readonly resolve: "resolve must return a select call, got any" }
6253
+ : unknown extends Result ? { readonly resolve: "resolve must return a select call, got unknown" }
6254
+ : [Exclude<Result, SelectedBranch<any, any>>] extends [never] ?
6255
+ [Exclude<SelectedBranchKey<Result>, BranchEntryKey<B[number]>>] extends [never] ?
6256
+ [Exclude<BranchEntryKey<B[number]>, SelectedBranchKey<Result>>] extends [never] ? unknown : {
6257
+ readonly branches: `Declared branch ${BranchLabel<
6258
+ Exclude<BranchEntryKey<B[number]>, SelectedBranchKey<Result>>
6259
+ > extends infer Label extends string ? JoinUnion<Label>
6260
+ : never} is never selected by resolve`
6261
+ }
6262
+ : {
6263
+ readonly resolve: `resolve selects undeclared ${BranchLabel<
6264
+ Exclude<SelectedBranchKey<Result>, BranchEntryKey<B[number]>>
6265
+ > extends infer Label extends string ? JoinUnion<Label>
6266
+ : never}. Add it to branches`
6267
+ }
6268
+ : { readonly resolve: "resolve must return a select call on every path" }
6269
+ : {
6270
+ readonly branches: `Declared branch ${BranchLabel<DuplicateBranchKey<B>> extends infer Label extends string
6271
+ ? JoinUnion<Label>
6272
+ : never} appears more than once`
6273
+ }
6274
+ type ValidateBranches<T> = T extends { readonly branches: infer B extends ReadonlyArray<unknown> } ?
6275
+ T extends { readonly resolve: (...args: any[]) => infer Result } ? ValidateBranchSelection<B, Result>
6276
+ : { readonly branches: "branches needs a resolve that selects one of them" }
6277
+ : T extends { readonly resolve: unknown } ?
6278
+ { readonly resolve: "resolve needs a branches list. Add: branches: [...]" }
6279
+ : unknown
6280
+ type UpdatableNames<S extends StateSchemas, Src extends string, T> = T extends {
6281
+ readonly target: infer Target extends string
6282
+ } ? PathName<TargetOwner<S, Extract<Src, StateNodeIdentifier<S>>, PathOf<Target>>>
6283
+ : PathName<UpdatableOwner<S, Extract<Src, StateNodeIdentifier<S>>>>
6284
+ type ValidateOwnerNames<U, Allowed extends string> = [Exclude<keyof U, Allowed>] extends [never] ? unknown : {
6285
+ readonly update: `Cannot update "${JoinUnion<Extract<Exclude<keyof U, Allowed>, string>>}". ${[Allowed] extends
6286
+ [never] ? "No retained state can be updated here"
6287
+ : `Updatable here: ${JoinUnion<Allowed>}`}`
6288
+ }
6289
+ type ValidateUpdateOwners<T, S extends StateSchemas, Src extends string> = T extends { readonly update: infer U } ?
6290
+ Types.IsUnion<keyof U> extends true ?
6291
+ { readonly update: `update takes one owner, got: ${JoinUnion<Extract<keyof U, string>>}` }
6292
+ : [keyof U] extends [never] ? { readonly update: "update takes one owner, got none" }
6293
+ :
6294
+ & ValidateOwnerNames<U, UpdatableNames<S, Src, T>>
6295
+ & (T extends { readonly reenter: true } ? keyof U extends PathName<Src> ? {
6296
+ readonly reenter: `Cannot reenter "${PathName<Src>}" while updating it. Update it or reenter it`
6297
+ } :
6298
+ unknown :
6299
+ unknown)
6300
+ : unknown
6301
+ type ValidateCommands<T> = T extends { readonly commands: (...args: any[]) => infer Result } ?
6302
+ [Result] extends [void | undefined] ? unknown
6303
+ : { readonly commands: "commands must not return a value. Enqueue work with its second argument" }
6304
+ : unknown
6305
+ type DestinationNames<S extends StateSchemas> = ReferenceUnion<S, Exclude<DestinationPath<S>, HistoryIdentifier<S>>>
6306
+ type UnknownTargetMessage<P extends string, S extends StateSchemas> = P extends "root"
6307
+ ? `Cannot target "root". Reconstruct it with initialize, or update it with update: { root: ... }`
6308
+ : P extends ReferenceUnion<S, HistoryIdentifier<S>> ?
6309
+ `"${P}" is a history state. Restore it with: { history: "${P}" }`
6310
+ : `Unknown target "${P}". Declared: ${JoinUnion<DestinationNames<S>>}`
6311
+ // A property-level message would collapse with the declared literal to `never`, so these replace the whole value.
6312
+ type ValidateTarget<T, S extends StateSchemas, Src extends string> = T extends {
6313
+ readonly target: infer P extends string
6314
+ } ? string extends P ? unknown
6315
+ : P extends DestinationNames<S> ? ValidateTargetAncestors<S, Src, P> & ValidateTargetData<T, S, P>
6316
+ : UnknownTargetMessage<P, S>
6317
+ : unknown
6318
+ // A known target also matches the misspelled-target member, which cannot require its values.
6319
+ type ValidateTargetData<T, S extends StateSchemas, P extends string> = "data" extends keyof T ? unknown
6320
+ : PathOf<P> extends infer Id extends StateIdentifier<S> ?
6321
+ [NodeSchema<NodeByIdentifier<S, Id>>] extends [never] ? unknown
6322
+ : {} extends NodeMakeInput<NodeByIdentifier<S, Id>> ? unknown
6323
+ : `Target "${P}" requires data`
6324
+ : unknown
6325
+ // Entering below an inactive valued state has no value for it, so that state must be the target. Anything below the
6326
+ // source or a parallel state may already be active, so only a state that is certainly inactive is reported here.
6327
+ type HasParallelAncestor<S extends StateSchemas, Id extends string> = true extends {
6328
+ [A in Extract<ParentStateIdentifier<Id>, StateIdentifier<S>>]: NodeByIdentifier<S, A> extends
6329
+ { readonly type: "parallel" } ? true : false
6330
+ }[Extract<ParentStateIdentifier<Id>, StateIdentifier<S>>] ? true :
6331
+ false
6332
+ type InactiveValuedAncestor<S extends StateSchemas, Src extends string, P extends string> = {
6333
+ [
6334
+ A in Exclude<
6335
+ Extract<ParentStateIdentifier<PathOf<P>>, ValuedStateIdentifier<S>>,
6336
+ Src | ParentStateIdentifier<Src> | JoinPath<Src, string>
6337
+ >
6338
+ ]: HasParallelAncestor<S, A> extends true ? never : A
6339
+ }[
6340
+ Exclude<
6341
+ Extract<ParentStateIdentifier<PathOf<P>>, ValuedStateIdentifier<S>>,
6342
+ Src | ParentStateIdentifier<Src> | JoinPath<Src, string>
6343
+ >
6344
+ ]
6345
+ type ValidateTargetAncestors<S extends StateSchemas, Src extends string, P extends string> =
6346
+ [InactiveValuedAncestor<S, Src, P>] extends [never] ? unknown :
6347
+ `Target "${P}" enters "${JoinUnion<
6348
+ PathName<InactiveValuedAncestor<S, Src, P>>
6349
+ >}", which needs a value. Target that state and construct "${P}" with states`
6350
+ type ValidateBranchEntries<T, S extends StateSchemas, Src extends string> = T extends {
6351
+ readonly branches: infer B extends ReadonlyArray<unknown>
6352
+ } ? {
6353
+ readonly branches: {
6354
+ readonly [K in keyof B]:
6355
+ & (B[K] extends { readonly target: infer P extends string } ?
6356
+ P extends DestinationNames<S> ? ValidateTargetAncestors<S, Src, P> : UnknownTargetMessage<P, S>
6357
+ : unknown)
6358
+ & (B[K] extends { readonly update: infer O extends string } ? O extends UpdatableNames<S, Src, B[K]> ? unknown
6359
+ : `Cannot update "${O}". ${[UpdatableNames<S, Src, B[K]>] extends [never] ?
6360
+ "No retained state can be updated here"
6361
+ : `Updatable here: ${JoinUnion<UpdatableNames<S, Src, B[K]>>}`}` :
6362
+ unknown)
6363
+ }
6364
+ }
6365
+ : unknown
6366
+ type ValidateDestination<T> = Extract<
6367
+ keyof T,
6368
+ "target" | "update" | "initialize" | "history" | "stay" | "branches" | "resolve"
6369
+ > extends never ? T extends { readonly reenter: true } ? unknown : {
6370
+ readonly target: "A transition needs one of: target, update, initialize, history, stay, reenter: true, branches"
6371
+ }
6372
+ : unknown
6373
+ type ValidateObjectTransition<T, S extends StateSchemas, Src extends string> =
7454
6374
  & ("initialize" extends keyof T ? {
7455
- readonly [K in Exclude<keyof T, "initialize" | "guard" | "reenter">]: never
6375
+ readonly [K in Exclude<keyof T, "initialize" | "guard" | "reenter" | "commands">]: never
7456
6376
  }
7457
6377
  : unknown)
7458
6378
  & {
@@ -7463,38 +6383,23 @@ export declare namespace Machine {
7463
6383
  | "update"
7464
6384
  | "initialize"
7465
6385
  | "history"
7466
- | "none"
6386
+ | "stay"
7467
6387
  | "branches"
7468
6388
  | "data"
7469
6389
  | "decoded"
7470
6390
  | "resolve"
7471
6391
  | "guard"
7472
6392
  | "reenter"
7473
- | "declinable"
6393
+ | "commands"
7474
6394
  >
7475
6395
  ]: never
7476
6396
  }
7477
- & (T extends {
7478
- /** Set to true when the resolver can explicitly return decline(). */
7479
- readonly declinable: infer D
7480
- } ? boolean extends D ? {
7481
- /** Set to true when the resolver can explicitly return decline(). */
7482
- readonly declinable: never
7483
- } :
7484
- unknown
7485
- : unknown)
7486
- & (T extends {
7487
- /** Set to true when the resolver can explicitly return decline(). */
7488
- readonly declinable: true
7489
- } ? unknown
7490
- : T extends {
7491
- /** Selects one declared branch and may enqueue synchronous commands. */
7492
- readonly resolve: (...args: any[]) => infer Result
7493
- } ? [Extract<Result, Declined>] extends [never] ? unknown : {
7494
- /** Selects one declared branch and may enqueue synchronous commands. */
7495
- readonly resolve: never
7496
- }
7497
- : unknown)
6397
+ & ValidateDestination<T>
6398
+ & ValidateTarget<T, S, Src>
6399
+ & ValidateBranches<T>
6400
+ & ValidateBranchEntries<T, S, Src>
6401
+ & ValidateUpdateOwners<T, S, Src>
6402
+ & ValidateCommands<T>
7498
6403
  type AllowedInvokeChannels<R, K extends PropertyKey> =
7499
6404
  | ([InvokeOutput<ResolvedInvoke<R, K>>] extends [never] ? never : "onDone")
7500
6405
  | ([RegisteredInvokeError<R, K>] extends [never] ? never : "onFailure")
@@ -7525,28 +6430,45 @@ export declare namespace Machine {
7525
6430
  [Id] extends [never] ? never
7526
6431
  : Id extends LiteralInvokeIdAt<I, Exclude<Extract<keyof I, `${number}`>, K>, R> ? Id
7527
6432
  : never
7528
- : never
7529
- type ValidateInvokeEntry<I, R, Duplicate extends string, Root> = I extends {
7530
- /** Name of the source registered in make. */
7531
- readonly src: infer Src extends PropertyKey
7532
- } ? {
7533
- readonly [K in keyof I]: [Duplicate] extends [never] ? ValidateInvokeField<I, K, R, Extract<Src, string>, Root>
7534
- : K extends ("id" extends keyof I ? "id" : "src") ? InvocationDefinitionError<
7535
- `Invocation id '${Duplicate}' is declared more than once in this state`,
7536
- Extract<Src, string>,
7537
- K
7538
- >
7539
- : ValidateInvokeField<I, K, R, Extract<Src, string>, Root>
7540
- } :
7541
- never
7542
- type ValidateInvokeField<I, K extends keyof I, R, Src extends string, Root> = K extends
7543
- AllowedInvokeChannels<R, Src> ? ValidateObjectTransition<I[K]> & ValidateChoiceUpdate<I[K], R, Root>
6433
+ : never
6434
+ type ValidateInvokeEntry<I, R, Duplicate extends string, Root, S extends StateSchemas, Path extends string> =
6435
+ I extends {
6436
+ /** Name of the source registered in make. */
6437
+ readonly src: infer Src extends PropertyKey
6438
+ } ? Src extends SourceKeys<R> ? {
6439
+ readonly [K in keyof I]: [Duplicate] extends [never] ?
6440
+ ValidateInvokeField<I, K, R, Extract<Src, string>, Root, S, Path>
6441
+ : K extends ("id" extends keyof I ? "id" : "src") ? InvocationDefinitionError<
6442
+ `Invocation id '${Duplicate}' is declared more than once in this state`,
6443
+ Extract<Src, string>,
6444
+ K
6445
+ >
6446
+ : ValidateInvokeField<I, K, R, Extract<Src, string>, Root, S, Path>
6447
+ }
6448
+ : UnknownSourceMessage<R>
6449
+ : never
6450
+ type ValidateInvokeField<
6451
+ I,
6452
+ K extends keyof I,
6453
+ R,
6454
+ Src extends string,
6455
+ Root,
6456
+ S extends StateSchemas,
6457
+ Path extends string
6458
+ > = K extends AllowedInvokeChannels<R, Src> ?
6459
+ ValidateObjectTransition<I[K], S, Path> & ValidateChoiceUpdate<I[K], Root>
7544
6460
  : K extends "src" | "id" | "address" | "input" ? unknown
7545
6461
  : InvokeFieldError<K, Src>
7546
- type ValidateObjectInvoke<I, R, Root> = I extends ReadonlyArray<unknown> ?
7547
- number extends I["length"] ? { readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, never, Root> }
7548
- : { readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, DuplicateInvokeId<I, K, R>, Root> } :
7549
- ValidateInvokeEntry<I, R, never, Root>
6462
+ type UnknownSourceMessage<R> = [Extract<SourceKeys<R>, string>] extends [never]
6463
+ ? "Unknown source. Register it in make with effects, streams, timers, logic, or children"
6464
+ : `Unknown source. Registered: ${JoinUnion<Extract<SourceKeys<R>, string>>}`
6465
+ // Each array entry keeps its declaration: a config array is also checked against the element type of this tuple,
6466
+ // so an entry carrying only validation keys would reject outcome keys such as `resolve` as excess properties.
6467
+ type ValidateObjectInvoke<I, R, Root, S extends StateSchemas, Path extends string> = I extends
6468
+ ReadonlyArray<unknown> ?
6469
+ number extends I["length"] ? { readonly [K in keyof I]: I[K] & ValidateInvokeEntry<I[K], R, never, Root, S, Path> }
6470
+ : { readonly [K in keyof I]: I[K] & ValidateInvokeEntry<I[K], R, DuplicateInvokeId<I, K, R>, Root, S, Path> } :
6471
+ ValidateInvokeEntry<I, R, never, Root, S, Path>
7550
6472
  // Handler config of a dotted state path, read from the root handler config.
7551
6473
  type HandlerConfigAt<Config, Path extends string> = Config extends { readonly states: infer Children } ?
7552
6474
  Path extends `${infer Head}.${infer Rest}` ? Head extends keyof Children ? HandlerConfigAt<Children[Head], Rest>
@@ -7559,15 +6481,15 @@ export declare namespace Machine {
7559
6481
  readonly choice: infer Choice
7560
6482
  } ? Choice
7561
6483
  : never
7562
- type ChoiceBranchDeclaration<Choice, R> = Choice extends {
7563
- /** Named groups of inspectable destinations used by transition resolvers. */
7564
- readonly branches: infer G extends keyof Registered<R, "branches">
7565
- } ? {
7566
- readonly [K in Extract<keyof Registered<R, "branches">[G], string>]: {
7567
- readonly label: `branch '${K}'`
7568
- readonly declaration: Registered<R, "branches">[G][K]
7569
- }
7570
- }[Extract<keyof Registered<R, "branches">[G], string>]
6484
+ type ChoiceBranchDeclaration<Choice> = Choice extends {
6485
+ /** The destinations this transition can select, each one checked against `resolve`. */
6486
+ readonly branches: infer B extends ReadonlyArray<unknown>
6487
+ } ? B[number] extends infer Entry ? Entry extends unknown ? {
6488
+ readonly label: `branch ${BranchLabel<BranchEntryKey<Entry>>}`
6489
+ readonly declaration: Entry
6490
+ }
6491
+ : never
6492
+ : never
7571
6493
  : { readonly label: "transition"; readonly declaration: Choice }
7572
6494
  type IsBelowOwner<Path extends string, Owner extends string> = Owner extends "" ? Path extends "" ? false : true
7573
6495
  : Path extends `${Owner}.${string}` ? true
@@ -7579,15 +6501,15 @@ export declare namespace Machine {
7579
6501
  PathName<Path>
7580
6502
  >
7581
6503
  // Every branch reachable from a choice entered with an owner update must stay below that owner.
7582
- type ChoiceUpdateEscape<Root, R, Choice extends string, Owner extends string, Visited extends string = never> =
6504
+ type ChoiceUpdateEscape<Root, Choice extends string, Owner extends string, Visited extends string = never> =
7583
6505
  Choice extends Visited ? never
7584
- : ChoiceBranchDeclaration<ChoiceConfigAt<Root, Choice>, R> extends infer Branch ?
6506
+ : ChoiceBranchDeclaration<ChoiceConfigAt<Root, Choice>> extends infer Branch ?
7585
6507
  Branch extends { readonly label: infer Label extends string; readonly declaration: infer D } ? D extends {
7586
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6508
+ /** Selects a declared descendant, constructing the values it requires. */
7587
6509
  readonly target: infer Ref extends string
7588
6510
  } ?
7589
6511
  [ChoiceConfigAt<Root, PathOf<Ref>>] extends [never] ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label>
7590
- : ChoiceUpdateEscape<Root, R, PathOf<Ref>, Owner, Visited | Choice>
6512
+ : ChoiceUpdateEscape<Root, PathOf<Ref>, Owner, Visited | Choice>
7591
6513
  : D extends {
7592
6514
  /** Restores the declared history reference, using its fallback on first entry. */
7593
6515
  readonly history: infer Ref extends string
@@ -7599,26 +6521,25 @@ export declare namespace Machine {
7599
6521
  : never
7600
6522
  : never
7601
6523
  : never
7602
- type ChoiceUpdateEscapeOf<D, R, Root> = D extends {
7603
- /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
6524
+ type OwnerNameOf<Update> = Update extends string ? Update : Extract<keyof Update, string>
6525
+ type ChoiceUpdateEscapeOf<D, Root> = D extends {
6526
+ /** Selects a declared descendant, constructing the values it requires. */
7604
6527
  readonly target: infer Ref extends string
7605
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
7606
- readonly update: infer Owner extends string
6528
+ /** Replaces the value of one retained state without replacing its active children. */
6529
+ readonly update: infer Update
7607
6530
  } ? [ChoiceConfigAt<Root, PathOf<Ref>>] extends [never] ? never
7608
- : ChoiceUpdateEscape<Root, R, PathOf<Ref>, PathOf<Owner>>
6531
+ : ChoiceUpdateEscape<Root, PathOf<Ref>, PathOf<OwnerNameOf<Update>>>
7609
6532
  : never
7610
- type ValidateChoiceUpdate<T, R, Root> = T extends {
7611
- /** Named groups of inspectable destinations used by transition resolvers. */
7612
- readonly branches: infer G extends keyof Registered<R, "branches">
7613
- } ? {
7614
- readonly [K in keyof Registered<R, "branches">[G]]: ChoiceUpdateEscapeOf<Registered<R, "branches">[G][K], R, Root>
7615
- }[keyof Registered<R, "branches">[G]] extends infer Escape ? [Escape] extends [never] ? unknown : {
7616
- /** Named groups of inspectable destinations used by transition resolvers. */
6533
+ type ValidateChoiceUpdate<T, Root> = T extends {
6534
+ /** The destinations this transition can select, each one checked against `resolve`. */
6535
+ readonly branches: infer B extends ReadonlyArray<unknown>
6536
+ } ? ChoiceUpdateEscapeOf<B[number], Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
6537
+ /** The destinations this transition can select, each one checked against `resolve`. */
7617
6538
  readonly branches: Escape
7618
6539
  }
7619
6540
  : never
7620
- : ChoiceUpdateEscapeOf<T, R, Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
7621
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
6541
+ : ChoiceUpdateEscapeOf<T, Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
6542
+ /** Replaces the value of one retained state without replacing its active children. */
7622
6543
  readonly update: Escape
7623
6544
  }
7624
6545
  : never
@@ -7627,16 +6548,21 @@ export declare namespace Machine {
7627
6548
  | (C extends { readonly states: infer Children }
7628
6549
  ? { readonly [K in keyof Children]: ObjectDeclarations<Children[K]> }[keyof Children]
7629
6550
  : never)
7630
- type ValidateObjectConfig<C, R, Root = C> = [ObjectDeclarations<C>] extends [never] ? unknown : {
7631
- readonly [K in keyof C]: K extends "states" ? { readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R, Root> }
7632
- : K extends "on" ? {
7633
- readonly [P in keyof C[K]]: ValidateObjectTransition<C[K][P]> & ValidateChoiceUpdate<C[K][P], R, Root>
6551
+ type ValidateObjectConfig<C, R, S extends StateSchemas, Path extends string = "", Root = C> =
6552
+ [ObjectDeclarations<C>] extends [never] ? unknown : {
6553
+ readonly [K in keyof C]: K extends "states" ? {
6554
+ readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R, S, JoinPath<Path, Extract<P, string>>, Root>
7634
6555
  }
7635
- : K extends "always" | "onDone" ? ValidateObjectTransition<C[K]> & ValidateChoiceUpdate<C[K], R, Root>
7636
- : K extends "choice" ? ValidateObjectTransition<C[K]>
7637
- : K extends "invoke" ? ValidateObjectInvoke<C[K], R, Root>
7638
- : unknown
7639
- }
6556
+ : K extends "on" ? {
6557
+ readonly [P in keyof C[K]]:
6558
+ & ValidateObjectTransition<C[K][P], S, Path>
6559
+ & ValidateChoiceUpdate<C[K][P], Root>
6560
+ }
6561
+ : K extends "always" | "onDone" ? ValidateObjectTransition<C[K], S, Path> & ValidateChoiceUpdate<C[K], Root>
6562
+ : K extends "choice" ? ValidateObjectTransition<C[K], S, Path>
6563
+ : K extends "invoke" ? ValidateObjectInvoke<C[K], R, Root, S, Path>
6564
+ : unknown
6565
+ }
7640
6566
  type NormalizeObjectInvoke<I, R> = I extends ReadonlyArray<unknown> ?
7641
6567
  { readonly [K in keyof I]: NormalizeObjectInvoke<I[K], R> }
7642
6568
  : I extends {
@@ -7651,13 +6577,19 @@ export declare namespace Machine {
7651
6577
  }
7652
6578
  // Reverse-map authored fields to avoid expanding every possible transition.
7653
6579
  // Retain missing fields from H for required handlers and editor completion.
7654
- type HandlerShape<C, H> =
6580
+ // Intersecting a misspelled `src` with its declared literals is `never`, so that invocation takes the message instead.
6581
+ type InvokeShape<I, H, R> = I extends ReadonlyArray<{ readonly src: infer Src }> ?
6582
+ [Exclude<Src, SourceKeys<R>>] extends [never] ? H : UnknownSourceMessage<R>
6583
+ : I extends { readonly src: infer Src } ? [Src] extends [SourceKeys<R>] ? H : UnknownSourceMessage<R>
6584
+ : H
6585
+ type HandlerShape<C, H, R> =
7655
6586
  & {
7656
6587
  readonly [K in keyof C]: K extends keyof H ? K extends "states" ? {
7657
6588
  readonly [P in keyof C[K]]: P extends keyof NonNullable<H[K]>
7658
- ? HandlerShape<C[K][P], NonNullable<NonNullable<H[K]>[P]>>
6589
+ ? HandlerShape<C[K][P], NonNullable<NonNullable<H[K]>[P]>, R>
7659
6590
  : never
7660
6591
  }
6592
+ : K extends "invoke" ? InvokeShape<C[K], H[K], R>
7661
6593
  : H[K]
7662
6594
  : never
7663
6595
  }
@@ -7681,17 +6613,21 @@ export declare namespace Machine {
7681
6613
  Pa extends ReadonlyArray<TaggedSchema>,
7682
6614
  R
7683
6615
  > {
6616
+ // Returns Machine itself: an alias would keep the handler config as a type
6617
+ // argument, so exported declarations would print every handler's context.
7684
6618
  <const C>(
7685
6619
  config:
7686
6620
  & C
7687
6621
  & (C extends (...args: never[]) => unknown ? never : unknown)
6622
+ // Checked first, so an invalid declaration reports the message that names its fix.
6623
+ & ValidateObjectConfig<NoInfer<C>, R, S>
7688
6624
  & HandlerShape<
7689
6625
  C,
7690
6626
  & StateHandler<S, S[""], Ev, Em, Extract<"", StateNodeIdentifier<S>>, In, Pa, R & { readonly "~input": I }>
7691
- & RootConstruction<S[""], I["Type"]>
6627
+ & RootConstruction<S[""], I["Type"]>,
6628
+ R
7692
6629
  >
7693
6630
  & RootConstruction<S[""], I["Type"]>
7694
- & ValidateObjectConfig<NoInfer<C>, R>
7695
6631
  & RootHandlerValidation<
7696
6632
  S,
7697
6633
  Ev,
@@ -7703,22 +6639,25 @@ export declare namespace Machine {
7703
6639
  StateIdentifier<S>
7704
6640
  >
7705
6641
  >
7706
- ): HandleTreeResult<
6642
+ ): Machine<
7707
6643
  S,
7708
6644
  Ev,
7709
- Em,
7710
6645
  I,
7711
- StateIdentifier<S>,
7712
- never,
7713
- never,
6646
+ Exclude<StateIdentifier<S>, HandleEvidence<S, C, R>["stateId"]>,
6647
+ HandleEvidence<S, C, R>["error"],
6648
+ ExcludeCompatibleRuntime<
6649
+ HandleEvidence<S, C, R>["services"],
6650
+ EventOf<Ev>,
6651
+ EmittedEventOf<Em>
6652
+ >,
7714
6653
  IE,
7715
6654
  IR,
7716
6655
  Final,
7717
6656
  Out,
7718
- never,
6657
+ Em,
6658
+ Extract<HandleEvidence<S, C, R>["outputState"], StateIdentifier<S>>,
7719
6659
  In,
7720
- Pa,
7721
- { readonly "": NormalizeObjectConfig<C, R> }
6660
+ Pa
7722
6661
  >
7723
6662
  }
7724
6663
 
@@ -7816,27 +6755,9 @@ export declare namespace Machine {
7816
6755
  readonly on?: EventHandlerMap<States, Events, Emits, StateId, EventTag, E, R>
7817
6756
  }
7818
6757
 
7819
- /**
7820
- * Runtime handler table stored on a machine.
7821
- *
7822
- * @category models
7823
- * @since 0.4.0
7824
- */
7825
- export type StateConfigs<
7826
- States extends StateSchemas,
7827
- Events extends ReadonlyArray<TaggedSchema>,
7828
- Emits extends ReadonlyArray<TaggedSchema>,
7829
- StateId extends StateIdentifier<States>,
7830
- EventTag extends TagOf<Events[number]>,
7831
- E,
7832
- R
7833
- > = Readonly<
7834
- Record<
7835
- PropertyKey,
7836
- | StateConfig<States, Events, Emits, StateId, EventTag, E, R>
7837
- | ChoiceStateConfig<States, Events, Emits, ChoiceIdentifier<States>>
7838
- >
7839
- >
6758
+ // An explicit export makes this ambient namespace export only the members marked `export`; the rest stay private.
6759
+ // oxlint-disable-next-line typescript/no-useless-empty-export -- the rule assumes module scope.
6760
+ export {}
7840
6761
  }
7841
6762
 
7842
6763
  type StateSource = State<any> | Machine.Any
@@ -7883,8 +6804,8 @@ export declare namespace Snapshot {
7883
6804
  /**
7884
6805
  * Extracts the decoded value owned by a schema-backed state path.
7885
6806
  *
7886
- * The source may be the object returned by {@link states} or a machine
7887
- * definition. Control-only state paths are intentionally excluded.
6807
+ * The source may be a descriptor returned by {@link state} or a machine.
6808
+ * Control-only state paths are intentionally excluded.
7888
6809
  *
7889
6810
  * @category utility types
7890
6811
  * @since 0.18.0
@@ -7897,9 +6818,8 @@ export type Value<
7897
6818
  /**
7898
6819
  * Extracts the logical snapshot rooted at a state path.
7899
6820
  *
7900
- * The source may be the object returned by {@link states} or a machine
7901
- * definition. This is the type-level counterpart of
7902
- * `State.getSnapshot`.
6821
+ * The source may be a descriptor returned by {@link state} or a machine.
6822
+ * This is the type-level counterpart of a descriptor's `getSnapshot`.
7903
6823
  *
7904
6824
  * @category utility types
7905
6825
  * @since 0.18.0
@@ -7965,16 +6885,13 @@ export const isFinal: <
7965
6885
  * can be declared inline or reused by mounting a descriptor in multiple places.
7966
6886
  * Initial edges and value constructors belong in the handler tree.
7967
6887
  *
7968
- * **Example** (Repeated compound state)
6888
+ * **Example** (Reusing one subtree in two parallel regions)
7969
6889
  *
7970
- * ```ts
6890
+ * ```ts import.meta.vitest
7971
6891
  * import { Machine } from "@typeonce/effect-machine"
7972
- * import { Schema } from "effect"
6892
+ * import { Effect, Schema } from "effect"
7973
6893
  *
7974
- * const TradingState = Schema.TaggedUnion({
7975
- * InSession: {},
7976
- * Applying: {}
7977
- * })
6894
+ * const TradingState = Schema.TaggedUnion({ InSession: {}, Applying: {} })
7978
6895
  * const TradingSlot = Machine.state({
7979
6896
  * states: {
7980
6897
  * Idle: {},
@@ -7982,13 +6899,21 @@ export const isFinal: <
7982
6899
  * Applying: TradingState.cases.Applying
7983
6900
  * }
7984
6901
  * })
6902
+ * const States = Machine.state({ type: "parallel", states: { slot1: TradingSlot, slot2: TradingSlot } })
7985
6903
  *
7986
- * const States = Machine.state({
6904
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
7987
6905
  * states: {
7988
- * slot1: TradingSlot,
7989
- * slot2: TradingSlot
6906
+ * slot1: { initial: { target: "slot1.Idle" } },
6907
+ * slot2: { initial: { target: "slot2.Idle" } }
7990
6908
  * }
7991
6909
  * })
6910
+ *
6911
+ * const paths = Effect.map(Machine.planInitial(machine), ({ state }) => [
6912
+ * state.states.slot1.state.path,
6913
+ * state.states.slot2.state.path
6914
+ * ])
6915
+ *
6916
+ * await Effect.runPromise(paths) // => ["slot1.Idle", "slot2.Idle"]
7992
6917
  * ```
7993
6918
  *
7994
6919
  * @category constructors
@@ -8020,8 +6945,7 @@ type MakeConfig<
8020
6945
  Streams extends Machine.StreamSources,
8021
6946
  Timers extends Machine.TimerSources,
8022
6947
  Logics extends Machine.LogicSources,
8023
- Children extends Machine.ChildSources,
8024
- Branches extends Machine.BranchDefinitions<Root>
6948
+ Children extends Machine.ChildSources
8025
6949
  > = {
8026
6950
  /** Lazy Effects or functions with one required input, invoked by registered name. */
8027
6951
  readonly effects?: Effects & Machine.ValidatePrograms<Effects>
@@ -8033,10 +6957,6 @@ type MakeConfig<
8033
6957
  readonly logic?: Logics & Machine.ValidatePrograms<Logics> & Machine.ValidateLogicSources<NoInfer<Logics>>
8034
6958
  /** Child machine descriptors registered for state-owned invocation. */
8035
6959
  readonly children?: Children
8036
- /** Named groups of inspectable destinations used by transition resolvers. */
8037
- readonly branches?:
8038
- & Branches
8039
- & { readonly [K in keyof Branches]: ValidateTransitionBranchRecord<NoInfer<Branches[K]>> }
8040
6960
  /** Stable definition identifier used by inspection and visualization. */
8041
6961
  readonly id?: string
8042
6962
  /** State topology and value schemas, captured by a `Machine.state` descriptor. */
@@ -8075,8 +6995,7 @@ type MakeResult<
8075
6995
  Streams extends Machine.StreamSources,
8076
6996
  Timers extends Machine.TimerSources,
8077
6997
  Logics extends Machine.LogicSources,
8078
- Children extends Machine.ChildSources,
8079
- Branches extends Readonly<Record<string, Readonly<Record<string, unknown>>>>
6998
+ Children extends Machine.ChildSources
8080
6999
  > = Definition<
8081
7000
  { readonly "": Root },
8082
7001
  readonly [...InputEvents, ...InternalEvents],
@@ -8099,13 +7018,11 @@ type MakeResult<
8099
7018
  readonly logic: Logics
8100
7019
  /** Child machine descriptors registered for state-owned invocation. */
8101
7020
  readonly children: Children
8102
- /** Named groups of inspectable destinations used by transition resolvers. */
8103
- readonly branches: Branches
8104
7021
  }
8105
7022
  >
8106
7023
 
8107
7024
  /** @inline */
8108
- interface Make {
7025
+ type Make = {
8109
7026
  /** @param config Complete schema-first machine definition. */
8110
7027
  <
8111
7028
  const Root extends Machine.StateNodeConfig,
@@ -8120,8 +7037,7 @@ interface Make {
8120
7037
  const Streams extends Machine.StreamSources = {},
8121
7038
  const Timers extends Machine.TimerSources = {},
8122
7039
  const Logics extends Machine.LogicSources = {},
8123
- const Children extends Machine.ChildSources = {},
8124
- const Branches extends Machine.BranchDefinitions<NoInfer<Root>> = {}
7040
+ const Children extends Machine.ChildSources = {}
8125
7041
  >(
8126
7042
  config:
8127
7043
  & MakeConfig<
@@ -8137,8 +7053,7 @@ interface Make {
8137
7053
  Streams,
8138
7054
  Timers,
8139
7055
  Logics,
8140
- Children,
8141
- Branches
7056
+ Children
8142
7057
  >
8143
7058
  & UniqueSourceNames<NoInfer<Effects>, NoInfer<Streams>, NoInfer<Timers>, NoInfer<Logics>, NoInfer<Children>>
8144
7059
  ): MakeResult<
@@ -8154,8 +7069,7 @@ interface Make {
8154
7069
  Streams,
8155
7070
  Timers,
8156
7071
  Logics,
8157
- Children,
8158
- Branches
7072
+ Children
8159
7073
  >
8160
7074
  }
8161
7075
 
@@ -8164,16 +7078,16 @@ interface Make {
8164
7078
  *
8165
7079
  * **Details**
8166
7080
  *
8167
- * State and event schemas provide runtime boundary validation while their
8168
- * decoded types drive handler, state, event, target, error, and service
8169
- * inference. State-tree validation is applied whether `states` comes from
8170
- * `states` or is passed inline. Call `handle` on the returned definition
8171
- * to implement state behavior with ordinary TypeScript control flow.
7081
+ * `root` is the `Machine.state` descriptor of the complete state tree. State
7082
+ * and event schemas provide runtime boundary validation while their decoded
7083
+ * types drive handler, state, event, target, error, and service inference.
7084
+ * Call `handle` on the returned {@link Definition} to declare the initial
7085
+ * target and the behavior of each state.
8172
7086
  *
8173
- * `initial` is a target-first callback. Its outer selector runs once while the
8174
- * definition is captured; an attached `.resolve(...)` callback remains lazy
8175
- * until initial planning. Return a bare selected state when its schema supports
8176
- * default construction.
7087
+ * Register Effects, Streams, timers, logic, and child machines under
7088
+ * `effects`, `streams`, `timers`, `logic`, and `children`. A state invokes a
7089
+ * registered source by name with `invoke: { src }`, and only invoked sources
7090
+ * add to the machine's requirements.
8177
7091
  *
8178
7092
  * `Machine.events` defines the public input protocol. `Machine.internalEvents`
8179
7093
  * adds raised events and other machine-local deliveries.
@@ -8184,42 +7098,82 @@ interface Make {
8184
7098
  * schemas opaquely for runtime validation. Public and internal tags must be
8185
7099
  * disjoint.
8186
7100
  *
8187
- * **Example** (Typed counter machine)
7101
+ * **Gotchas**
7102
+ *
7103
+ * Source names must be unique across all five registries. A top-level state
7104
+ * cannot be named `root`, because `root` names the root state.
7105
+ *
7106
+ * **Example** (Invoking a registered Effect)
8188
7107
  *
8189
- * ```ts
7108
+ * ```ts import.meta.vitest
8190
7109
  * import { Machine } from "@typeonce/effect-machine"
8191
- * import { Schema } from "effect"
8192
- * class Count extends Schema.TaggedClass<Count>("Count")("Count", {
8193
- * value: Schema.Number
8194
- * }) {
8195
- * }
8196
- * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", {
8197
- * by: Schema.Number
8198
- * }) {
8199
- * }
7110
+ * import { Effect, Option, Schema } from "effect"
7111
+ *
7112
+ * const Lookup = Schema.TaggedUnion({ Loading: { id: Schema.String }, Ready: { name: Schema.String } })
7113
+ * const States = Machine.state({ states: { Idle: {}, Loading: Lookup.cases.Loading, Ready: Lookup.cases.Ready } })
7114
+ * const Events = Machine.events({ Load: { id: Schema.String } })
7115
+ *
7116
+ * const machine = Machine.make({
7117
+ * root: States,
7118
+ * events: Events,
7119
+ * effects: { findName: (id: string) => Effect.succeed(`User ${id}`) }
7120
+ * }).handle({
7121
+ * initial: { target: "Idle" },
7122
+ * states: {
7123
+ * Idle: { on: { Load: { target: "Loading", data: ({ event }) => ({ id: event.id }) } } },
7124
+ * Loading: {
7125
+ * invoke: {
7126
+ * src: "findName",
7127
+ * input: ({ state }) => state.id,
7128
+ * onDone: { target: "Ready", data: ({ output }) => ({ name: output }) }
7129
+ * }
7130
+ * }
7131
+ * }
7132
+ * })
7133
+ *
7134
+ * const name = Effect.scoped(Effect.gen(function*() {
7135
+ * const ref = yield* Machine.start(machine)
7136
+ * yield* ref.send(Events.Load({ id: "1" }))
7137
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
7138
+ * return States.get(ready.state, "Ready").pipe(Option.map((state) => state.name))
7139
+ * }))
7140
+ *
7141
+ * await Effect.runPromise(name) // => Option.some("User 1")
7142
+ * ```
7143
+ *
7144
+ * **Example** (Counting with schema classes)
7145
+ *
7146
+ * ```ts import.meta.vitest
7147
+ * import { Machine } from "@typeonce/effect-machine"
7148
+ * import { Effect, Option, Schema } from "effect"
7149
+ *
7150
+ * class Count extends Schema.TaggedClass<Count>("Count")("Count", { value: Schema.Number }) {}
7151
+ * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", { by: Schema.Number }) {}
7152
+ *
8200
7153
  * const States = Machine.state({ states: { Count } })
8201
- * const Events = Machine.eventsFromSchemas(Increment)
8202
7154
  * const counter = Machine.make({
8203
7155
  * root: States,
8204
- * events: Events
7156
+ * events: Machine.eventsFromSchemas(Increment)
8205
7157
  * }).handle({
8206
- * initial: {
8207
- * target: "Count",
8208
- * decoded: true,
8209
- * data: new Count({ value: 0 })
8210
- * },
7158
+ * initial: { target: "Count", decoded: true, data: new Count({ value: 0 }) },
8211
7159
  * states: {
8212
7160
  * Count: {
8213
7161
  * on: {
8214
7162
  * Increment: {
8215
- * update: "Count",
8216
- * decoded: true,
8217
- * data: ({ event, state }) => new Count({ value: state.value + event.by })
7163
+ * update: { Count: { decoded: true, data: ({ event, state }) => new Count({ value: state.value + event.by }) } }
8218
7164
  * }
8219
7165
  * }
8220
7166
  * }
8221
7167
  * }
8222
7168
  * })
7169
+ *
7170
+ * const value = Effect.gen(function*() {
7171
+ * const initial = yield* Machine.planInitial(counter)
7172
+ * const planned = yield* Machine.plan(counter, initial.state, new Increment({ by: 2 }))
7173
+ * return States.get(planned.next, "Count").pipe(Option.map((count) => count.value))
7174
+ * })
7175
+ *
7176
+ * await Effect.runPromise(value) // => Option.some(2)
8223
7177
  * ```
8224
7178
  *
8225
7179
  * @see {@link state} for typed state-tree helpers.
@@ -8239,31 +7193,6 @@ export type EventOf<Protocol extends Machine.EventProtocol.Any> = Machine.EventO
8239
7193
  Machine.EventProtocolSchemas<Protocol>
8240
7194
  >
8241
7195
 
8242
- /**
8243
- * Defines a public event protocol and returns deferred constructors for every
8244
- * statically finite configured event tag.
8245
- *
8246
- * Constructor inputs retain their schema-derived required fields, defaults,
8247
- * and transformations. Construction is deferred until delivery so failures
8248
- * enter the machine's `MachineSchemaDecodeError` channel rather than throwing
8249
- * at the call site.
8250
- *
8251
- * **Example**
8252
- *
8253
- * ```ts
8254
- * export const Event = Machine.eventsFromSchemas(
8255
- * Schema.TaggedUnion({
8256
- * Increment: { by: Schema.Number },
8257
- * Reset: {}
8258
- * })
8259
- * )
8260
- * const machine = Machine.make({ events: Event, ... })
8261
- * yield* ref.send(Event.Increment({ by: 1 }))
8262
- * ```
8263
- *
8264
- * @category constructors
8265
- * @since 0.10.0
8266
- */
8267
7196
  type EventFieldsSchemas<Cases extends Readonly<Record<string, Schema.Struct.Fields>>> = keyof Cases extends never
8268
7197
  ? readonly []
8269
7198
  : readonly [
@@ -8278,15 +7207,25 @@ type ValidateEventFields<Cases> = {
8278
7207
  : unknown
8279
7208
  }
8280
7209
 
8281
- /** Defines a public event protocol from tagged field records.
7210
+ /**
7211
+ * Defines a public event protocol from tagged field records.
7212
+ *
7213
+ * Constructors defer schema validation until delivery. Use
7214
+ * {@link eventsFromSchemas} when importing existing tagged schemas or protocol
7215
+ * descriptors.
7216
+ *
7217
+ * **Example** (Defining events from fields)
7218
+ *
7219
+ * ```ts import.meta.vitest
7220
+ * import { Machine } from "@typeonce/effect-machine"
7221
+ * import { Schema } from "effect"
8282
7222
  *
8283
- * ```ts
8284
7223
  * const Events = Machine.events({ Increment: { by: Schema.Number }, Reset: {} })
8285
- * const increment = Events.Increment({ by: 1 })
7224
+ *
7225
+ * Events.Increment({ by: 1 })._tag // => "Increment"
7226
+ * Events.Reset()._tag // => "Reset"
8286
7227
  * ```
8287
7228
  *
8288
- * Constructors defer schema validation until delivery. Use eventsFromSchemas
8289
- * when importing existing tagged schemas or protocol descriptors.
8290
7229
  * @category constructors
8291
7230
  * @since 0.32.0
8292
7231
  */
@@ -8294,7 +7233,45 @@ export const events: <const Cases extends Readonly<Record<string, Schema.Struct.
8294
7233
  cases: Cases & ValidateEventFields<NoInfer<Cases>> & ValidateEventProtocolBuilder<"public", EventFieldsSchemas<Cases>>
8295
7234
  ) => Machine.EventProtocol<"public", EventFieldsSchemas<Cases>> = internal.eventsFromFields
8296
7235
 
8297
- /** Imports existing schemas and protocols without rebuilding their contracts.
7236
+ /**
7237
+ * Defines a public event protocol from existing tagged schemas or protocol
7238
+ * descriptors, without rebuilding their contracts, and returns deferred
7239
+ * constructors for every statically finite configured event tag.
7240
+ *
7241
+ * Constructor inputs retain their schema-derived required fields, defaults,
7242
+ * and transformations. Construction is deferred until delivery so failures
7243
+ * enter the machine's `MachineSchemaDecodeError` channel rather than throwing
7244
+ * at the call site.
7245
+ *
7246
+ * **Example** (Reusing a tagged union as the event protocol)
7247
+ *
7248
+ * ```ts import.meta.vitest
7249
+ * import { Machine } from "@typeonce/effect-machine"
7250
+ * import { Effect, Schema } from "effect"
7251
+ *
7252
+ * const Event = Machine.eventsFromSchemas(
7253
+ * Schema.TaggedUnion({
7254
+ * Increment: { by: Schema.Number },
7255
+ * Reset: {}
7256
+ * })
7257
+ * )
7258
+ * const machine = Machine.make({ root: Machine.state({ fields: { count: Schema.Number } }), events: Event }).handle({
7259
+ * root: { count: 0 },
7260
+ * on: {
7261
+ * Increment: { update: { root: ({ root, event }) => ({ count: root.count + event.by }) } },
7262
+ * Reset: { update: { root: { count: 0 } } }
7263
+ * }
7264
+ * })
7265
+ *
7266
+ * const count = Effect.scoped(Effect.gen(function*() {
7267
+ * const ref = yield* Machine.start(machine)
7268
+ * yield* ref.send(Event.Increment({ by: 1 }))
7269
+ * return (yield* ref.state).value.count
7270
+ * }))
7271
+ *
7272
+ * await Effect.runPromise(count) // => 1
7273
+ * ```
7274
+ *
8298
7275
  * @category constructors
8299
7276
  * @since 0.32.0
8300
7277
  */
@@ -8337,21 +7314,38 @@ export const optionalParent: <const Events extends ReadonlyArray<Machine.TaggedS
8337
7314
  *
8338
7315
  * Use these constructors for raised events and other machine-local deliveries.
8339
7316
  * Construction failures are reported through the
8340
- * owning machine's `MachineSchemaDecodeError` channel.
7317
+ * owning machine's `MachineSchemaDecodeError` channel. Use
7318
+ * {@link internalEventsFromSchemas} when importing existing tagged schemas or
7319
+ * protocol descriptors.
8341
7320
  *
8342
- * **Example**
7321
+ * **Example** (Raising an internal event)
8343
7322
  *
8344
- * ```ts
8345
- * const Internal = Machine.internalEventsFromSchemas(
8346
- * Schema.TaggedUnion({
8347
- * Loaded: { value: Schema.String },
8348
- * Failed: { message: Schema.String }
8349
- * })
8350
- * )
8351
- * const machine = Machine.make({ internalEvents: Internal, ... })
7323
+ * ```ts import.meta.vitest
7324
+ * import { Machine } from "@typeonce/effect-machine"
7325
+ * import { Effect, Schema } from "effect"
7326
+ *
7327
+ * const Events = Machine.events({ Load: { value: Schema.String } })
7328
+ * const Internal = Machine.internalEvents({ Loaded: { value: Schema.String }, Failed: { message: Schema.String } })
7329
+ * const machine = Machine.make({
7330
+ * root: Machine.state({ fields: { value: Schema.String } }),
7331
+ * events: Events,
7332
+ * internalEvents: Internal
7333
+ * }).handle({
7334
+ * root: { value: "" },
7335
+ * on: {
7336
+ * Load: { stay: true, commands: ({ event }, enqueue) => enqueue.raise(Internal.Loaded({ value: event.value })) },
7337
+ * Loaded: { update: { root: ({ event }) => ({ value: event.value }) } },
7338
+ * Failed: { stay: true }
7339
+ * }
7340
+ * })
8352
7341
  *
8353
- * // Inside a transition callback:
8354
- * enqueue.raise(Internal.Loaded({ value }))
7342
+ * const value = Effect.gen(function*() {
7343
+ * const initial = yield* Machine.planInitial(machine)
7344
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Load({ value: "ready" }))
7345
+ * return planned.next.value.value
7346
+ * })
7347
+ *
7348
+ * await Effect.runPromise(value) // => "ready"
8355
7349
  * ```
8356
7350
  *
8357
7351
  * @category constructors
@@ -8364,7 +7358,10 @@ export const internalEvents: <const Cases extends Readonly<Record<string, Schema
8364
7358
  & ValidateEventProtocolBuilder<"internal", EventFieldsSchemas<Cases>>
8365
7359
  ) => Machine.EventProtocol<"internal", EventFieldsSchemas<Cases>> = internal.internalEventsFromFields
8366
7360
 
8367
- /** Imports existing schemas and protocols without rebuilding their contracts.
7361
+ /**
7362
+ * Defines an internal event protocol from existing tagged schemas or protocol
7363
+ * descriptors, without rebuilding their contracts.
7364
+ *
8368
7365
  * @category constructors
8369
7366
  * @since 0.32.0
8370
7367
  */
@@ -8378,17 +7375,37 @@ export const internalEventsFromSchemas: {
8378
7375
  * Defines the ephemeral notifications a machine may publish to external
8379
7376
  * observers. Emitted events are separate from machine input and are never sent
8380
7377
  * implicitly to a parent machine. Observe them through `MachineRef.emissions` or
8381
- * the AtomMachine emission stream adapters.
7378
+ * the AtomMachine emission stream adapters. Use {@link emittedEventsFromSchemas}
7379
+ * when importing existing tagged schemas or protocol descriptors.
8382
7380
  *
8383
- * **Example**
7381
+ * **Example** (Emitting an event to observers)
8384
7382
  *
8385
- * ```ts
8386
- * const Emitted = Machine.emittedEventsFromSchemas(
8387
- * Schema.TaggedUnion({
8388
- * Saved: { id: Schema.String }
8389
- * })
8390
- * )
8391
- * const machine = Machine.make({ emittedEvents: Emitted, ... })
7383
+ * ```ts import.meta.vitest
7384
+ * import { Machine } from "@typeonce/effect-machine"
7385
+ * import { Effect, Schema } from "effect"
7386
+ *
7387
+ * const Events = Machine.events({ Save: { id: Schema.String } })
7388
+ * const Emitted = Machine.emittedEvents({ Saved: { id: Schema.String } })
7389
+ * const machine = Machine.make({
7390
+ * root: Machine.state({ states: { Idle: {} } }),
7391
+ * events: Events,
7392
+ * emittedEvents: Emitted
7393
+ * }).handle({
7394
+ * initial: { target: "Idle" },
7395
+ * states: {
7396
+ * Idle: {
7397
+ * on: { Save: { stay: true, commands: ({ event }, enqueue) => enqueue.emit(Emitted.Saved({ id: event.id })) } }
7398
+ * }
7399
+ * }
7400
+ * })
7401
+ *
7402
+ * const emitted = Effect.gen(function*() {
7403
+ * const initial = yield* Machine.planInitial(machine)
7404
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Save({ id: "a" }))
7405
+ * return planned.emittedEvents.length
7406
+ * })
7407
+ *
7408
+ * await Effect.runPromise(emitted) // => 1
8392
7409
  * ```
8393
7410
  *
8394
7411
  * @category constructors
@@ -8401,7 +7418,10 @@ export const emittedEvents: <const Cases extends Readonly<Record<string, Schema.
8401
7418
  & ValidateEventProtocolBuilder<"emitted", EventFieldsSchemas<Cases>>
8402
7419
  ) => Machine.EventProtocol<"emitted", EventFieldsSchemas<Cases>> = internal.emittedEventsFromFields
8403
7420
 
8404
- /** Imports existing schemas and protocols without rebuilding their contracts.
7421
+ /**
7422
+ * Defines an emitted event protocol from existing tagged schemas or protocol
7423
+ * descriptors, without rebuilding their contracts.
7424
+ *
8405
7425
  * @category constructors
8406
7426
  * @since 0.32.0
8407
7427
  */
@@ -8437,29 +7457,24 @@ export const emittedEventsFromSchemas: {
8437
7457
  * Define an explicit JSON codec or keep process-local capabilities outside the
8438
7458
  * logical snapshot.
8439
7459
  *
8440
- * **Example**
7460
+ * **Example** (Encoding a snapshot for storage)
8441
7461
  *
8442
- * ```ts
7462
+ * ```ts import.meta.vitest
8443
7463
  * import { Machine } from "@typeonce/effect-machine"
8444
- * import { Effect, Schema } from "effect"
8445
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
8446
- * }
8447
- * const States = Machine.state({ states: { Idle } })
8448
- * const machine = Machine.make({
8449
- * root: States,
8450
- * events: Machine.eventsFromSchemas()
8451
- * }).handle({
8452
- * initial: {
8453
- * target: "Idle"
8454
- * },
8455
- * states: {
8456
- * Idle: {}
8457
- * }
7464
+ * import { Effect } from "effect"
7465
+ *
7466
+ * const States = Machine.state({ states: { Idle: {} } })
7467
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
7468
+ * initial: { target: "Idle" }
8458
7469
  * })
7470
+ *
8459
7471
  * const encoded = Effect.gen(function*() {
8460
7472
  * const initial = yield* Machine.planInitial(machine)
8461
- * return yield* Machine.encodeSnapshot(machine, initial.state)
7473
+ * const snapshot = yield* Machine.encodeSnapshot(machine, initial.state)
7474
+ * return typeof snapshot
8462
7475
  * })
7476
+ *
7477
+ * await Effect.runPromise(encoded) // => "object"
8463
7478
  * ```
8464
7479
  *
8465
7480
  * @see {@link decodeSnapshot} for restoring an encoded snapshot.
@@ -8524,30 +7539,25 @@ export const encodeSnapshot: <
8524
7539
  * Decoding restores logical statechart data only. It does not restart invoked
8525
7540
  * processes, recreate spawned children, or restore a previous `MachineRef`.
8526
7541
  *
8527
- * **Example**
7542
+ * **Example** (Restoring an encoded snapshot)
8528
7543
  *
8529
- * ```ts
7544
+ * ```ts import.meta.vitest
8530
7545
  * import { Machine } from "@typeonce/effect-machine"
8531
- * import { Effect, Schema } from "effect"
8532
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
8533
- * }
8534
- * const States = Machine.state({ states: { Idle } })
8535
- * const machine = Machine.make({
8536
- * root: States,
8537
- * events: Machine.eventsFromSchemas()
8538
- * }).handle({
8539
- * initial: {
8540
- * target: "Idle"
8541
- * },
8542
- * states: {
8543
- * Idle: {}
8544
- * }
7546
+ * import { Effect } from "effect"
7547
+ *
7548
+ * const States = Machine.state({ states: { Idle: {} } })
7549
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
7550
+ * initial: { target: "Idle" }
8545
7551
  * })
8546
- * const roundTrip = Effect.gen(function*() {
7552
+ *
7553
+ * const path = Effect.gen(function*() {
8547
7554
  * const initial = yield* Machine.planInitial(machine)
8548
7555
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
8549
- * return yield* Machine.decodeSnapshot(machine, encoded)
7556
+ * const decoded = yield* Machine.decodeSnapshot(machine, encoded)
7557
+ * return decoded.state.path
8550
7558
  * })
7559
+ *
7560
+ * await Effect.runPromise(path) // => "Idle"
8551
7561
  * ```
8552
7562
  *
8553
7563
  * @see {@link encodeSnapshot} for creating the normalized representation.
@@ -8593,35 +7603,6 @@ export const decodeSnapshot: <
8593
7603
  Machine.SnapshotDecodingServices<States>
8594
7604
  > = internal.decodeSnapshot
8595
7605
 
8596
- type TransitionBranchRecordError<Message extends string, Key extends PropertyKey = never> = {
8597
- readonly "~effect/Machine/TransitionBranchRecordError": Message
8598
- readonly key: Key
8599
- }
8600
-
8601
- type InvalidStaticTransitionBranchKey<Branches> = Extract<
8602
- keyof Branches,
8603
- "" | number | symbol | `${number}` | "NaN" | "Infinity" | "-Infinity"
8604
- >
8605
-
8606
- type ValidateTransitionBranchRecord<Branches> = [keyof Branches] extends [never] ?
8607
- TransitionBranchRecordError<"Branch records must contain at least one branch">
8608
- : [InvalidStaticTransitionBranchKey<Branches>] extends [never] ? {
8609
- readonly [K in keyof Branches]:
8610
- & {
8611
- readonly [
8612
- Extra in Exclude<
8613
- keyof Branches[K],
8614
- "target" | "update" | "initialize" | "initial" | "history" | "none" | "title"
8615
- >
8616
- ]: never
8617
- }
8618
- & (Branches[K] extends { readonly title: "" } ? { readonly title: never } : unknown)
8619
- } :
8620
- TransitionBranchRecordError<
8621
- "Branch keys must be non-empty, non-numeric strings",
8622
- InvalidStaticTransitionBranchKey<Branches>
8623
- >
8624
-
8625
7606
  /**
8626
7607
  * Plans the initial state for a machine without executing machine commands.
8627
7608
  *
@@ -8640,26 +7621,20 @@ type ValidateTransitionBranchRecord<Branches> = [keyof Branches] extends [never]
8640
7621
  * protocol. Manual planners may inspect commands but need running machine targets
8641
7622
  * to execute child-addressed operations.
8642
7623
  *
8643
- * **Example**
7624
+ * **Example** (Planning startup without running the machine)
8644
7625
  *
8645
- * ```ts
7626
+ * ```ts import.meta.vitest
8646
7627
  * import { Machine } from "@typeonce/effect-machine"
8647
- * import { Effect, Schema } from "effect"
8648
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
8649
- * }
8650
- * const States = Machine.state({ states: { Idle } })
8651
- * const machine = Machine.make({
8652
- * root: States,
8653
- * events: Machine.eventsFromSchemas()
8654
- * }).handle({
8655
- * initial: {
8656
- * target: "Idle"
8657
- * },
8658
- * states: {
8659
- * Idle: {}
8660
- * }
7628
+ * import { Effect } from "effect"
7629
+ *
7630
+ * const States = Machine.state({ states: { Idle: {} } })
7631
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
7632
+ * initial: { target: "Idle" }
8661
7633
  * })
8662
- * const initialState = Effect.map(Machine.planInitial(machine), (plan) => plan.state)
7634
+ *
7635
+ * const path = Effect.map(Machine.planInitial(machine), (plan) => plan.state.state.path)
7636
+ *
7637
+ * await Effect.runPromise(path) // => "Idle"
8663
7638
  * ```
8664
7639
  *
8665
7640
  * @see {@link plan} for planning a received event.
@@ -8769,9 +7744,9 @@ export const stateNodes: <M extends Machine.Any>(machine: M) => ReadonlyArray<
8769
7744
  /**
8770
7745
  * Returns the statically selected root entry used during machine startup.
8771
7746
  *
8772
- * This function does not execute the initial resolver or require machine
8773
- * input. `kind: "initial"` means that the selected root enters its declared
8774
- * initial configuration.
7747
+ * This function does not construct initial state values or require machine
7748
+ * input. `kind: "initial"` means that the root enters its declared initial
7749
+ * configuration.
8775
7750
  *
8776
7751
  * @category getters
8777
7752
  * @since 0.14.0
@@ -8785,7 +7760,8 @@ export const initialDefinition: <M extends Machine.Any>(machine: M) => Machine.I
8785
7760
  *
8786
7761
  * **Details**
8787
7762
  *
8788
- * The returned tuple retains the schemas supplied to {@link events}, including
7763
+ * The returned tuple retains the schemas supplied to {@link events} or
7764
+ * {@link eventsFromSchemas}, including
8789
7765
  * grouped tagged unions. Internal and emitted event schemas are excluded. This
8790
7766
  * getter is intended for tooling that needs to describe or construct valid
8791
7767
  * external inputs without reaching into the opaque event protocol.
@@ -8797,16 +7773,16 @@ export const inputEventSchemas: <M extends Machine.Any>(machine: M) => Machine.I
8797
7773
  internal.inputEventSchemas
8798
7774
 
8799
7775
  /**
8800
- * Returns every registered transition handler in state definition order.
7776
+ * Returns every declared transition in state definition order.
8801
7777
  *
8802
7778
  * **Details**
8803
7779
  *
8804
- * Event handlers retain their handler-key order within each source state and
8805
- * are followed by eventless and completion handlers. This function does not
7780
+ * Event transitions retain their key order within each source state and are
7781
+ * followed by eventless and completion transitions. This function does not
8806
7782
  * execute resolvers. Every branch exposes its static selection. State updates
8807
7783
  * retain the updated owner in `selection.path` while leaving `target`
8808
7784
  * undefined because they do not change topology. `acceptance` reports whether
8809
- * the resolver may decline the transition.
7785
+ * the transition may decline the event.
8810
7786
  *
8811
7787
  * @category getters
8812
7788
  * @since 0.4.0
@@ -8824,7 +7800,7 @@ export const transitionDefinitions: <M extends Machine.Any>(machine: M) => Reado
8824
7800
  *
8825
7801
  * **Details**
8826
7802
  *
8827
- * Static inline invocation definitions expose stable ownership and lifecycle
7803
+ * Static invocation definitions expose stable ownership and lifecycle
8828
7804
  * metadata without serializing runtime values. Function-valued sources are
8829
7805
  * represented as dynamic and are never evaluated during inspection.
8830
7806
  *
@@ -8862,7 +7838,7 @@ export const configuration: <M extends Machine.Any>(
8862
7838
  * Returns event tags with at least one structurally eligible handler in the
8863
7839
  * current state snapshot.
8864
7840
  *
8865
- * A `declinable` handler may still reject a concrete event at planning time,
7841
+ * A handler with `guard` or `{ decline: true }` may still reject a concrete event at planning time,
8866
7842
  * so this is a static candidate query rather than a guarantee that every value
8867
7843
  * with the returned tag will be handled.
8868
7844
  *
@@ -8910,9 +7886,10 @@ export const enabled: <
8910
7886
  *
8911
7887
  * **Details**
8912
7888
  *
8913
- * Required handlers are accepted from their structural eligibility.
8914
- * Declinable handlers run their resolver only far enough to decide whether
8915
- * they accept the event. Any commands, emissions, or raised events collected
7889
+ * Required transitions are accepted from their structural eligibility.
7890
+ * Declinable transitions, which have a `guard` or a `{ decline: true }` entry,
7891
+ * run their guard or resolver only far enough to decide whether they accept
7892
+ * the event. Any commands, emissions, or raised events collected
8916
7893
  * during that check are discarded.
8917
7894
  *
8918
7895
  * Event input is decoded through the machine's public and internal event protocols.
@@ -8930,9 +7907,9 @@ export const enabled: <
8930
7907
  * Synchronous transition resolvers cannot execute it. Querying an internal event
8931
7908
  * does not make that event available to `MachineRef.send`.
8932
7909
  *
8933
- * **Example**
7910
+ * **Example** (Checking an event against the current state)
8934
7911
  *
8935
- * ```ts
7912
+ * ```ts import.meta.vitest
8936
7913
  * import { Machine } from "@typeonce/effect-machine"
8937
7914
  * import { Effect, Schema } from "effect"
8938
7915
  *
@@ -8944,13 +7921,15 @@ export const enabled: <
8944
7921
  * internalEvents
8945
7922
  * }).handle({
8946
7923
  * initial: { target: "Idle" },
8947
- * states: { Idle: { on: { Loaded: { none: true } } } }
7924
+ * states: { Idle: { on: { Loaded: { stay: true } } } }
8948
7925
  * })
8949
7926
  *
8950
- * export const canLoad = Effect.gen(function*() {
7927
+ * const canLoad = Effect.gen(function*() {
8951
7928
  * const initial = yield* Machine.planInitial(machine)
8952
7929
  * return yield* Machine.can(machine, initial.state, internalEvents.Loaded())
8953
7930
  * })
7931
+ *
7932
+ * await Effect.runPromise(canLoad) // => true
8954
7933
  * ```
8955
7934
  *
8956
7935
  * @category getters
@@ -9053,38 +8032,30 @@ export const can: {
9053
8032
  * `emittedEvents`. Events with no enabled transition are ignored and produce
9054
8033
  * an unchanged plan.
9055
8034
  *
9056
- * **Example**
8035
+ * **Example** (Planning one event without running the machine)
9057
8036
  *
9058
- * ```ts
8037
+ * ```ts import.meta.vitest
9059
8038
  * import { Machine } from "@typeonce/effect-machine"
9060
- * import { Effect, Schema } from "effect"
9061
- * class Off extends Schema.TaggedClass<Off>("Off")("Off", {}) {
9062
- * }
9063
- * class On extends Schema.TaggedClass<On>("On")("On", {}) {
9064
- * }
9065
- * class Toggle extends Schema.TaggedClass<Toggle>("Toggle")("Toggle", {}) {
9066
- * }
9067
- * const States = Machine.state({ states: { Off, On } })
8039
+ * import { Effect } from "effect"
8040
+ *
8041
+ * const Events = Machine.events({ Toggle: {} })
9068
8042
  * const machine = Machine.make({
9069
- * root: States,
9070
- * events: Machine.eventsFromSchemas(Toggle)
8043
+ * root: Machine.state({ states: { Off: {}, On: {} } }),
8044
+ * events: Events
9071
8045
  * }).handle({
9072
- * initial: {
9073
- * target: "Off"
9074
- * },
8046
+ * initial: { target: "Off" },
9075
8047
  * states: {
9076
- * Off: {
9077
- * on: {
9078
- * Toggle: { target: "On" }
9079
- * }
9080
- * },
9081
- * On: {}
8048
+ * Off: { on: { Toggle: { target: "On" } } }
9082
8049
  * }
9083
8050
  * })
9084
- * const nextState = Effect.gen(function*() {
8051
+ *
8052
+ * const path = Effect.gen(function*() {
9085
8053
  * const initial = yield* Machine.planInitial(machine)
9086
- * return (yield* Machine.plan(machine, initial.state, new Toggle({}))).next
8054
+ * const planned = yield* Machine.plan(machine, initial.state, Events.Toggle())
8055
+ * return planned.next.state.path
9087
8056
  * })
8057
+ *
8058
+ * await Effect.runPromise(path) // => "On"
9088
8059
  * ```
9089
8060
  *
9090
8061
  * @see {@link planInitial} for planning machine startup.
@@ -9192,8 +8163,11 @@ export const plan: <
9192
8163
  * which machine will eventually own it. Prefer typed output, typed child
9193
8164
  * addresses, or invocation lifecycle transitions when possible.
9194
8165
  *
9195
- * Use an inline `invoke` with an `effect` source for one-shot work.
9196
- * @see {@link transition} for event-driven state.
8166
+ * For one-shot work, register an Effect in `make({ effects })` and invoke it
8167
+ * with `invoke: { src }` instead. Register logic in `make({ logic })` to run it
8168
+ * for the lifetime of one state.
8169
+ *
8170
+ * @see {@link make} for registering sources that states invoke by name.
9197
8171
  * @category constructors
9198
8172
  * @since 0.4.0
9199
8173
  */
@@ -9206,7 +8180,7 @@ export const logic: <
9206
8180
  InitialError = never,
9207
8181
  InitialRequirements = never
9208
8182
  >(options: {
9209
- /** Enters a compound or parallel subtree through its declared initialization. */
8183
+ /** The first state, or an Effect that produces it from the process scope before `run` starts. */
9210
8184
  readonly initial:
9211
8185
  | State
9212
8186
  | ((
@@ -9321,11 +8295,11 @@ export const sendTo: {
9321
8295
  <Child extends ChildMachine.Any>(
9322
8296
  child: Child,
9323
8297
  event: ChildMachine.Event<Child>
9324
- ): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>
8298
+ ): Effect.Effect<void, StoppedError, MachineRuntime>
9325
8299
  <Address extends ChildAddress<never>>(
9326
8300
  id: Address,
9327
8301
  event: ChildAddress.Event<Address>
9328
- ): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>
8302
+ ): Effect.Effect<void, StoppedError, MachineRuntime>
9329
8303
  } = internal.sendTo
9330
8304
 
9331
8305
  /**
@@ -9335,8 +8309,8 @@ export const sendTo: {
9335
8309
  * @since 0.4.0
9336
8310
  */
9337
8311
  export const stopChild: {
9338
- <Event>(child: ChildAddress<Event>): Effect.Effect<void, never, MachineRuntimeRequirement>
9339
- <Child extends ChildMachine.Any>(child: Child): Effect.Effect<void, never, MachineRuntimeRequirement>
8312
+ <Event>(child: ChildAddress<Event>): Effect.Effect<void, never, MachineRuntime>
8313
+ <Child extends ChildMachine.Any>(child: Child): Effect.Effect<void, never, MachineRuntime>
9340
8314
  } = internal.stopChild
9341
8315
 
9342
8316
  /**
@@ -9366,9 +8340,31 @@ export const watch: <State, Event, Error = never, Output = never>(
9366
8340
  * Type predicates narrow the returned snapshot. Intermediate microsteps and
9367
8341
  * historical snapshots are not observed.
9368
8342
  *
9369
- * @example
9370
- * ```ts
9371
- * const snapshot = yield* Machine.waitFor(ref, isReady).pipe(Effect.timeout("5 seconds"))
8343
+ * **Example** (Waiting for a state with a timeout)
8344
+ *
8345
+ * ```ts import.meta.vitest
8346
+ * import { Machine } from "@typeonce/effect-machine"
8347
+ * import { Effect } from "effect"
8348
+ *
8349
+ * const Events = Machine.events({ Finish: {} })
8350
+ * const machine = Machine.make({
8351
+ * root: Machine.state({ states: { Working: {}, Ready: {} } }),
8352
+ * events: Events
8353
+ * }).handle({
8354
+ * initial: { target: "Working" },
8355
+ * states: {
8356
+ * Working: { on: { Finish: { target: "Ready" } } }
8357
+ * }
8358
+ * })
8359
+ *
8360
+ * const path = Effect.scoped(Effect.gen(function*() {
8361
+ * const ref = yield* Machine.start(machine)
8362
+ * yield* ref.send(Events.Finish())
8363
+ * const ready = yield* Machine.waitFor(ref, ({ state }) => state.state.path === "Ready").pipe(Effect.timeout("5 seconds"))
8364
+ * return ready.state.state.path
8365
+ * }))
8366
+ *
8367
+ * await Effect.runPromise(path) // => "Ready"
9372
8368
  * ```
9373
8369
  * @category combinators
9374
8370
  * @since 0.37.0
@@ -9407,15 +8403,41 @@ export const waitFor: {
9407
8403
  * `prepared.start` is one-shot and scoped: the `Scope` that first evaluates it
9408
8404
  * owns the machine, and closing that `Scope` is equivalent to `ref.stop`.
9409
8405
  *
9410
- * ```ts
9411
- * const prepared = yield* Machine.prepare(machine)
8406
+ * **Example** (Observing emissions before startup)
9412
8407
  *
9413
- * yield* prepared.emissions.pipe(
9414
- * Stream.runForEach(handleEmission),
9415
- * Effect.forkScoped({ startImmediately: true })
9416
- * )
8408
+ * ```ts import.meta.vitest
8409
+ * import { Machine } from "@typeonce/effect-machine"
8410
+ * import { Effect, Stream } from "effect"
8411
+ *
8412
+ * const Emitted = Machine.emittedEvents({ Started: {} })
8413
+ * const machine = Machine.make({
8414
+ * root: Machine.state({ states: { Idle: {} } }),
8415
+ * events: Machine.events({}),
8416
+ * emittedEvents: Emitted
8417
+ * }).handle({
8418
+ * initial: { target: "Idle" },
8419
+ * states: {
8420
+ * Idle: {
8421
+ * entry: (_, enqueue) => {
8422
+ * enqueue.emit(Emitted.Started())
8423
+ * }
8424
+ * }
8425
+ * }
8426
+ * })
9417
8427
  *
9418
- * const ref = yield* prepared.start
8428
+ * const emitted = Effect.scoped(Effect.gen(function*() {
8429
+ * const prepared = yield* Machine.prepare(machine)
8430
+ * const seen: Array<string> = []
8431
+ * yield* prepared.emissions.pipe(
8432
+ * Stream.runForEach((event) => Effect.sync(() => seen.push(event._tag))),
8433
+ * Effect.forkScoped({ startImmediately: true })
8434
+ * )
8435
+ * yield* prepared.start
8436
+ * yield* Effect.yieldNow
8437
+ * return seen
8438
+ * }))
8439
+ *
8440
+ * await Effect.runPromise(emitted) // => ["Started"]
9419
8441
  * ```
9420
8442
  *
9421
8443
  * @category constructors
@@ -9513,29 +8535,23 @@ export const prepare: <
9513
8535
  * rather than being returned by `send`. Sending after the machine reaches any
9514
8536
  * terminal state fails immediately with `StoppedError`.
9515
8537
  *
9516
- * **Example**
8538
+ * **Example** (Starting a machine in a scope)
9517
8539
  *
9518
- * ```ts
8540
+ * ```ts import.meta.vitest
9519
8541
  * import { Machine } from "@typeonce/effect-machine"
9520
- * import { Effect, Schema } from "effect"
9521
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
9522
- * }
9523
- * const States = Machine.state({ states: { Idle } })
9524
- * const machine = Machine.make({
9525
- * root: States,
9526
- * events: Machine.eventsFromSchemas()
9527
- * }).handle({
9528
- * initial: {
9529
- * target: "Idle"
9530
- * },
9531
- * states: {
9532
- * Idle: {}
9533
- * }
8542
+ * import { Effect } from "effect"
8543
+ *
8544
+ * const States = Machine.state({ states: { Idle: {} } })
8545
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
8546
+ * initial: { target: "Idle" }
9534
8547
  * })
9535
- * const state = Effect.scoped(Effect.gen(function*() {
8548
+ *
8549
+ * const path = Effect.scoped(Effect.gen(function*() {
9536
8550
  * const ref = yield* Machine.start(machine)
9537
- * return yield* ref.state
8551
+ * return (yield* ref.state).state.path
9538
8552
  * }))
8553
+ *
8554
+ * await Effect.runPromise(path) // => "Idle"
9539
8555
  * ```
9540
8556
  *
9541
8557
  * @see {@link plan} for inspecting the same transition plan without executing it.
@@ -9616,7 +8632,7 @@ export const start: <
9616
8632
  * the `Scope` is equivalent to `ref.stop`.
9617
8633
  *
9618
8634
  * `resume` validates and normalizes the supplied snapshot before publishing it
9619
- * as the first state. It does not call the machine's initial function, replay
8635
+ * as the first state. It does not construct the declared initial state, replay
9620
8636
  * entry or transition actions, re-deliver raised or emitted events, or
9621
8637
  * re-evaluate historical completion and eventless transitions. Active-state
9622
8638
  * invokes start once in ancestor and document order with {@link InitialEvent};
@@ -9634,31 +8650,26 @@ export const start: <
9634
8650
  * evaluated merely because the runtime was resumed; only ordinary subsequent
9635
8651
  * transition planning can enter and stabilize states.
9636
8652
  *
9637
- * **Example**
8653
+ * **Example** (Resuming from a decoded snapshot)
9638
8654
  *
9639
- * ```ts
8655
+ * ```ts import.meta.vitest
9640
8656
  * import { Machine } from "@typeonce/effect-machine"
9641
- * import { Effect, Schema } from "effect"
9642
- * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {
9643
- * }
9644
- * const States = Machine.state({ states: { Idle } })
9645
- * const machine = Machine.make({
9646
- * root: States,
9647
- * events: Machine.eventsFromSchemas()
9648
- * }).handle({
9649
- * initial: {
9650
- * target: "Idle"
9651
- * },
9652
- * states: {
9653
- * Idle: {}
9654
- * }
8657
+ * import { Effect } from "effect"
8658
+ *
8659
+ * const States = Machine.state({ states: { Idle: {} } })
8660
+ * const machine = Machine.make({ root: States, events: Machine.events({}) }).handle({
8661
+ * initial: { target: "Idle" }
9655
8662
  * })
9656
- * const resumed = Effect.scoped(Effect.gen(function*() {
8663
+ *
8664
+ * const path = Effect.scoped(Effect.gen(function*() {
9657
8665
  * const initial = yield* Machine.planInitial(machine)
9658
8666
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
9659
8667
  * const snapshot = yield* Machine.decodeSnapshot(machine, encoded)
9660
- * return yield* Machine.resume(machine, snapshot)
8668
+ * const ref = yield* Machine.resume(machine, snapshot)
8669
+ * return (yield* ref.state).state.path
9661
8670
  * }))
8671
+ *
8672
+ * await Effect.runPromise(path) // => "Idle"
9662
8673
  * ```
9663
8674
  *
9664
8675
  * @see {@link decodeSnapshot} for the schema and transport boundary.