@typeonce/effect-machine 0.34.0 → 0.35.0

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 (71) hide show
  1. package/README.md +93 -29
  2. package/dist/Machine.d.ts +309 -361
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +126 -87
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/configuration.d.ts +0 -1
  7. package/dist/internal/machine/configuration.d.ts.map +1 -1
  8. package/dist/internal/machine/configuration.js +0 -19
  9. package/dist/internal/machine/configuration.js.map +1 -1
  10. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  11. package/dist/internal/machine/executionPlan.js +12 -20
  12. package/dist/internal/machine/executionPlan.js.map +1 -1
  13. package/dist/internal/machine/initialDeclaration.d.ts +14 -0
  14. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
  15. package/dist/internal/machine/initialDeclaration.js +137 -0
  16. package/dist/internal/machine/initialDeclaration.js.map +1 -0
  17. package/dist/internal/machine/machine.d.ts +0 -2
  18. package/dist/internal/machine/machine.d.ts.map +1 -1
  19. package/dist/internal/machine/machine.js +39 -120
  20. package/dist/internal/machine/machine.js.map +1 -1
  21. package/dist/internal/machine/planner.d.ts +8 -0
  22. package/dist/internal/machine/planner.d.ts.map +1 -1
  23. package/dist/internal/machine/planner.js +25 -67
  24. package/dist/internal/machine/planner.js.map +1 -1
  25. package/dist/internal/machine/protocol.d.ts +1 -1
  26. package/dist/internal/machine/protocol.d.ts.map +1 -1
  27. package/dist/internal/machine/protocol.js.map +1 -1
  28. package/dist/internal/machine/stateDefinition.d.ts +1 -1
  29. package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
  30. package/dist/internal/machine/stateDefinition.js +1 -13
  31. package/dist/internal/machine/stateDefinition.js.map +1 -1
  32. package/dist/internal/machine/targetReference.d.ts.map +1 -1
  33. package/dist/internal/machine/targetReference.js +14 -4
  34. package/dist/internal/machine/targetReference.js.map +1 -1
  35. package/dist/internal/machine/topology.d.ts.map +1 -1
  36. package/dist/internal/machine/topology.js +3 -2
  37. package/dist/internal/machine/topology.js.map +1 -1
  38. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  39. package/dist/internal/testing/machine/finiteModel.js +15 -6
  40. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  41. package/dist/internal/testing/machine/verification.d.ts.map +1 -1
  42. package/dist/internal/testing/machine/verification.js +7 -1
  43. package/dist/internal/testing/machine/verification.js.map +1 -1
  44. package/dist/testing/MachineTest.d.ts +105 -73
  45. package/dist/testing/MachineTest.d.ts.map +1 -1
  46. package/dist/testing/MachineTest.js +105 -73
  47. package/dist/testing/MachineTest.js.map +1 -1
  48. package/dist/unstable/cluster/ClusterMachine.d.ts +13 -8
  49. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  50. package/dist/unstable/cluster/ClusterMachine.js +13 -8
  51. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  52. package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
  53. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  54. package/dist/unstable/reactivity/AtomMachine.js +41 -24
  55. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  56. package/package.json +1 -1
  57. package/src/Machine.ts +471 -744
  58. package/src/internal/machine/configuration.ts +0 -20
  59. package/src/internal/machine/executionPlan.ts +11 -18
  60. package/src/internal/machine/initialDeclaration.ts +157 -0
  61. package/src/internal/machine/machine.ts +38 -179
  62. package/src/internal/machine/planner.ts +30 -83
  63. package/src/internal/machine/protocol.ts +3 -3
  64. package/src/internal/machine/stateDefinition.ts +1 -15
  65. package/src/internal/machine/targetReference.ts +19 -4
  66. package/src/internal/machine/topology.ts +3 -2
  67. package/src/internal/testing/machine/finiteModel.ts +16 -10
  68. package/src/internal/testing/machine/verification.ts +7 -1
  69. package/src/testing/MachineTest.ts +105 -73
  70. package/src/unstable/cluster/ClusterMachine.ts +13 -8
  71. package/src/unstable/reactivity/AtomMachine.ts +41 -24
@@ -672,26 +672,6 @@ export const normalizeConfigurationEffect = <const States extends Machine.StateS
672
672
  })
673
673
  )
674
674
 
675
- export const validateInitialConfiguration = (machine: Machine.Any, configuration: ActiveConfiguration): void => {
676
- for (const path of configuration.active) {
677
- const node = getNode(machine, path)
678
- if (node.type === "compound") {
679
- const child = node.children.find((child) => configuration.active.has(child))
680
- const initialNode = node.initial === undefined ? undefined : getNode(machine, node.initial)
681
- if (initialNode?.type === "choice" ? child === undefined : child !== node.initial) {
682
- throw new Error(`Machine initial state "${node.path}" must enter initial child "${node.initial}"`)
683
- }
684
- }
685
- if (node.type === "parallel") {
686
- for (const child of node.children) {
687
- if (!configuration.active.has(child)) {
688
- throw new Error(`Machine initial state "${node.path}" must enter child region "${child}"`)
689
- }
690
- }
691
- }
692
- }
693
- }
694
-
695
675
  /** Capture every history register whose owning parent exits in this microstep.
696
676
  * The control record is deliberately independent from effects/actions: it is
697
677
  * part of the logical snapshot and is therefore preserved by pure planning. */
@@ -20,11 +20,11 @@ import {
20
20
  normalizeTargetConfigurationSync,
21
21
  type PlanningMachineReferences,
22
22
  snapshotFromConfiguration,
23
- validateInitialConfiguration,
24
23
  withMachineReferences
25
24
  } from "./configuration.js"
26
25
  import { InfiniteTransitionError, StoppedError } from "./errors.js"
27
26
  import { type CapturedStateConfig, toImpl } from "./implementation.js"
27
+ import { isDataInitializer } from "./initialDeclaration.js"
28
28
  import * as InvocationEvent from "./invocationEvent.js"
29
29
  import {
30
30
  broadenTransitionBoundary,
@@ -39,6 +39,7 @@ import {
39
39
  normalizeTransition,
40
40
  planConfiguration,
41
41
  removeConflictingTransitions,
42
+ resolveInitialConfiguration,
42
43
  resolveInitialTarget,
43
44
  type SelectedTransition,
44
45
  sortEntryPaths,
@@ -213,7 +214,8 @@ const compileIndexedExecutionDescriptor = (
213
214
  // the hierarchical planner so their entry and exit boundaries stay explicit.
214
215
  flat: nodes.every((node) => node.parent === undefined && (node.type === "atomic" || node.type === "final")) || (
215
216
  nodes[0]?.path === "" && nodes[0].type === "compound" && nodes[0].schema === undefined &&
216
- (toImpl(machine).handlers[""] === undefined || Reflect.ownKeys(toImpl(machine).handlers[""]!).length === 0) &&
217
+ (toImpl(machine).handlers[""] === undefined ||
218
+ Reflect.ownKeys(toImpl(machine).handlers[""]!).every((key) => key === "initialize")) &&
217
219
  nodes.slice(1).every((node) => node.parent === "" && (node.type === "atomic" || node.type === "final")) &&
218
220
  [...transitionsByPath.values()].every((events) =>
219
221
  [...events.values()].every((transition) =>
@@ -1130,10 +1132,10 @@ const makeIndexedExecutionPlan = (
1130
1132
  snapshot: (state) => snapshotFromIndexedState(indexed, state as OwnedIndexedState),
1131
1133
  plan: (state, event, retainMicrosteps = false, machineReferences) =>
1132
1134
  planIndexedState(machine, indexed, state as OwnedIndexedState, event, retainMicrosteps, machineReferences),
1133
- // Initializers may enqueue commands and emissions. Managed startup owns that
1134
- // work through the generic initial planner; indexed event execution remains valid.
1135
+ // Only captured data constructors can use indexed startup. Unknown initializer
1136
+ // protocols retain generic startup so commands and emissions cannot be dropped.
1135
1137
  ...(Object.values(toImpl(machine).handlers as Record<string, CapturedStateConfig>).some((config) =>
1136
- "initialize" in config
1138
+ config.initialize !== undefined && !isDataInitializer(config.initialize)
1137
1139
  ) ?
1138
1140
  {} :
1139
1141
  {
@@ -1144,8 +1146,8 @@ const makeIndexedExecutionPlan = (
1144
1146
  ? (decodeInputSync(machine, machine.input, undefined), args)
1145
1147
  : [decodeInputSync(machine, machine.input, args[0])]
1146
1148
  const initial = machine.initial(...inputArgs as any)
1147
- const resolved = isInitialTarget(initial)
1148
- ? resolveInitialTarget(
1149
+ const normalized = isInitialTarget(initial)
1150
+ ? resolveInitialConfiguration(
1149
1151
  machine,
1150
1152
  {
1151
1153
  active: new Set(),
@@ -1156,20 +1158,11 @@ const makeIndexedExecutionPlan = (
1156
1158
  },
1157
1159
  initial,
1158
1160
  InitialEvent
1159
- ).target
1160
- : initial
1161
- const normalized = isInitialTarget(initial)
1162
- ? normalizeTargetConfigurationSync(machine, {
1163
- active: new Set(),
1164
- values: new Map(),
1165
- outputs: new Map(),
1166
- history: new Map()
1167
- }, resolved)
1168
- : normalizeConfigurationSync(machine, resolved as Machine.Snapshot<any>)
1161
+ ).configuration
1162
+ : normalizeConfigurationSync(machine, initial as Machine.Snapshot<any>)
1169
1163
  const active = machineReferences === undefined
1170
1164
  ? normalized
1171
1165
  : withMachineReferences(normalized, machineReferences)
1172
- if (machine.initialDefinition.selection.kind === "initial") validateInitialConfiguration(machine, active)
1173
1166
  const completed = completeConfigurationSync(machine, active, InitialEvent).configuration
1174
1167
  const configuration = ownedIndexedStateFromActive(indexed, completed)
1175
1168
  const state = snapshotFromIndexedState(indexed, configuration)
@@ -0,0 +1,157 @@
1
+ /** Captures handler-owned initial edges before compiling executable topology. */
2
+ import { hasProperty } from "effect/Predicate"
3
+ import * as Schema from "effect/Schema"
4
+ import type { Machine, State } from "../../Machine.js"
5
+ import { SnapshotBuilderStateTypeId } from "./symbols.js"
6
+ import * as Reference from "./targetReference.js"
7
+ import * as Topology from "./topology.js"
8
+
9
+ const initializers = new WeakSet<object>()
10
+
11
+ export const isDataInitializer = (value: object): boolean => initializers.has(value)
12
+
13
+ type Context = Readonly<Record<string, unknown>>
14
+ type Constructor = (context: Context) => unknown
15
+ const record = (value: unknown, label: string): Readonly<Record<string, unknown>> => {
16
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
17
+ throw new Error(`Machine ${label} must be an object`)
18
+ }
19
+ return value as Readonly<Record<string, unknown>>
20
+ }
21
+ const evaluate = (value: unknown): Constructor => typeof value === "function" ? value as Constructor : () => value
22
+
23
+ /** Only the outer declaration is interpreted; callback results are ordinary data. */
24
+ export const construction = (value: unknown): Constructor => {
25
+ const descriptor = typeof value === "object" && value !== null &&
26
+ hasProperty(value, "decoded") && value.decoded === true && hasProperty(value, "data")
27
+ if (descriptor) {
28
+ const config = record(value, "decoded construction")
29
+ if (Reflect.ownKeys(config).some((key) => key !== "decoded" && key !== "data")) {
30
+ throw new Error("Machine decoded construction accepts only decoded and data")
31
+ }
32
+ return evaluate(config.data)
33
+ }
34
+ const resolve = evaluate(value)
35
+ return (context) => Topology.makeStateInput(value === undefined ? {} : resolve(context))
36
+ }
37
+
38
+ export const edgeConstruction = (config: Readonly<Record<string, unknown>>): Constructor => {
39
+ if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
40
+ throw new Error("Machine decoded construction flag must be a boolean")
41
+ }
42
+ if (config.decoded === true) {
43
+ if (!hasProperty(config, "data")) throw new Error("Machine decoded construction requires data")
44
+ return evaluate(config.data)
45
+ }
46
+ const resolve = evaluate(config.data)
47
+ return (context) => Topology.makeStateInput(hasProperty(config, "data") ? resolve(context) : {})
48
+ }
49
+
50
+ interface Captured {
51
+ readonly node: Machine.StateNodeConfig | Machine.TaggedSchema
52
+ readonly handlers: Record<string, unknown>
53
+ }
54
+ export const capture = (
55
+ root: State<Machine.StateNodeConfig>,
56
+ handler: Readonly<Record<string, unknown>>
57
+ ): Captured => {
58
+ const visit = (
59
+ node: Machine.StateNodeConfig | Machine.TaggedSchema,
60
+ raw: Readonly<Record<string, unknown>>,
61
+ path: string
62
+ ): Captured => {
63
+ if (hasProperty(raw, "initialize")) throw new Error("Machine child construction belongs in initial declarations")
64
+ if (path !== "" && hasProperty(raw, "root")) {
65
+ throw new Error("Machine root construction belongs at the root handler")
66
+ }
67
+ const { initial, root: _root, states: rawChildren, ...handlers } = raw
68
+ if (Schema.isSchema(node) || !("states" in node)) {
69
+ if (initial !== undefined) throw new Error(`Machine state "${path}" cannot declare initial children`)
70
+ if (rawChildren !== undefined) throw new Error(`Machine state "${path}" has no children`)
71
+ return { node, handlers }
72
+ }
73
+ const childHandlers = rawChildren === undefined ? {} : record(rawChildren, "child handlers")
74
+ for (const key of Object.keys(childHandlers)) {
75
+ if (!Object.prototype.hasOwnProperty.call(node.states, key)) throw new Error(`Machine unknown child "${key}"`)
76
+ }
77
+ const states: Record<string, Machine.StateNodeConfig | Machine.TaggedSchema> = Object.create(null)
78
+ const children: Record<string, unknown> = Object.create(null)
79
+ const constructors: Record<string, Constructor> = Object.create(null)
80
+ const parallel = node.type === "parallel"
81
+ let initialKey: string | undefined
82
+ if (parallel) {
83
+ const regions = initial === undefined ? {} : record(initial, "parallel initial regions")
84
+ for (const [key, value] of Object.entries(regions)) {
85
+ const child = node.states[key]
86
+ if (child === undefined || (!Schema.isSchema(child) && (child.type === "history" || child.type === "choice"))) {
87
+ throw new Error(`Machine invalid initial region "${key}"`)
88
+ }
89
+ if (!Schema.isSchema(child) && (!("schema" in child) || child.schema === undefined)) {
90
+ throw new Error(`Machine schema-less region "${key}" cannot construct data`)
91
+ }
92
+ constructors[key] = construction(value)
93
+ }
94
+ } else {
95
+ const edge = record(initial, `initial edge for "${path}"`)
96
+ if (Reflect.ownKeys(edge).some((key) => !["target", "data", "decoded"].includes(String(key)))) {
97
+ throw new Error("Machine initial edge accepts only target, data, and decoded")
98
+ }
99
+ if (!hasProperty(edge.target, Reference.TypeId)) throw new Error("Machine initial requires a target reference")
100
+ const ref = (edge.target as Reference.Reference)[Reference.TypeId]
101
+ const prefix = path === "" ? "" : `${path}.`
102
+ const key = ref.path.slice(prefix.length)
103
+ if (
104
+ ref.root !== root || !ref.path.startsWith(prefix) || key.includes(".") || !(key in node.states) ||
105
+ ref.kind === "history"
106
+ ) {
107
+ throw new Error(`Machine initial target must be a direct child of "${path}"`)
108
+ }
109
+ initialKey = key
110
+ if (ref.kind === "choice" && (hasProperty(edge, "data") || hasProperty(edge, "decoded"))) {
111
+ throw new Error("Machine choice initial edges cannot construct data")
112
+ }
113
+ const construct = edgeConstruction(edge)
114
+ const child = node.states[key]!
115
+ if (
116
+ hasProperty(edge, "data") && !Schema.isSchema(child) && (!("schema" in child) || child.schema === undefined)
117
+ ) {
118
+ throw new Error(`Machine schema-less initial child "${key}" cannot construct data`)
119
+ }
120
+ if (hasProperty(edge, "data")) constructors[key] = construct
121
+ }
122
+ for (const [key, child] of Object.entries(node.states)) {
123
+ const childPath = path === "" ? key : `${path}.${key}`
124
+ const captured = visit(
125
+ child,
126
+ childHandlers[key] === undefined ? {} : record(childHandlers[key], "state handler"),
127
+ childPath
128
+ )
129
+ states[key] = captured.node
130
+ // History configuration is owned by its parent, not a state handler.
131
+ if (
132
+ (Schema.isSchema(child) || child.type !== "history") &&
133
+ (childHandlers[key] !== undefined || (!Schema.isSchema(child) && "states" in child))
134
+ ) children[key] = captured.handlers
135
+ }
136
+ const compiled = Object.freeze({
137
+ ...node,
138
+ states: Object.freeze(states),
139
+ ...(parallel ? {} : { initial: initialKey })
140
+ })
141
+ const entries = Object.entries(constructors)
142
+ const initialize = (context: Context) => {
143
+ const ancestors = typeof context.ancestors === "object" && context.ancestors !== null
144
+ ? context.ancestors as Readonly<Record<string, unknown>> :
145
+ {}
146
+ const scoped = { ...context, root: path === "" ? context.state : ancestors[""] }
147
+ const values = Object.fromEntries(entries.map(([key, construct]) => [key, construct(scoped)]))
148
+ return { [SnapshotBuilderStateTypeId]: values }
149
+ }
150
+ initializers.add(initialize)
151
+ return {
152
+ node: compiled,
153
+ handlers: { ...handlers, ...(entries.length === 0 ? {} : { initialize }), states: children }
154
+ }
155
+ }
156
+ return visit(root.node, handler, "")
157
+ }
@@ -31,6 +31,7 @@ import * as Configuration from "./configuration.js"
31
31
  import * as Declaration from "./declaration.js"
32
32
  import type { ChildAlreadyExistsError, InfiniteTransitionError, StartupError } from "./errors.js"
33
33
  import type { CapturedStateConfig } from "./implementation.js"
34
+ import * as InitialDeclaration from "./initialDeclaration.js"
34
35
  import * as InvocationDefinition from "./invocationDefinition.js"
35
36
  import * as internalPlanner from "./planner.js"
36
37
  import * as internalProcess from "./process.js"
@@ -41,13 +42,7 @@ import * as internalRuntime from "./runtimeProtocol.js"
41
42
  import * as Serialization from "./serialization.js"
42
43
  import * as StateDefinition from "./stateDefinition.js"
43
44
  import { ChildMachineLogicTypeId } from "./symbols.js"
44
- import {
45
- getLocalTargetScope,
46
- getTargetBuilderNode,
47
- makeSnapshotBuilder,
48
- makeTargetBuilder,
49
- withFrom
50
- } from "./targetBuilder.js"
45
+ import { getLocalTargetScope, makeTargetBuilder, withFrom } from "./targetBuilder.js"
51
46
  import * as TargetReference from "./targetReference.js"
52
47
  import * as Topology from "./topology.js"
53
48
 
@@ -97,7 +92,7 @@ const Proto = {
97
92
  }
98
93
 
99
94
  const makeWithHandlers = (
100
- self: Definition.Any,
95
+ self: Machine.Any,
101
96
  handlers: Readonly<Record<string, CapturedStateConfig>>
102
97
  ): Machine.Any => {
103
98
  const machine = Object.create(Proto)
@@ -139,14 +134,6 @@ type CapturedNamedBranch = {
139
134
  readonly selection: Topology.TargetSelection
140
135
  }
141
136
 
142
- const InitialBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/InitialBuilderDescriptor")
143
-
144
- type InitialBuilderDescriptor = {
145
- readonly [InitialBuilderDescriptorTypeId]: typeof InitialBuilderDescriptorTypeId
146
- readonly selection: Topology.TargetSelection
147
- readonly resolve: (context: any) => unknown
148
- }
149
-
150
137
  const plainTargetSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
151
138
  selection.kind === "none"
152
139
  ? Topology.noneTargetSelection
@@ -166,47 +153,6 @@ const constructSelectionValue = (
166
153
  return context.target[method](values.target).update(context.owner[method](values.update))
167
154
  }
168
155
 
169
- const makeInitialBuilderDescriptor = (
170
- selection: Topology.TargetSelection,
171
- resolve: (context: any) => unknown
172
- ): InitialBuilderDescriptor =>
173
- Object.freeze({
174
- [InitialBuilderDescriptorTypeId]: InitialBuilderDescriptorTypeId,
175
- selection: plainTargetSelection(selection),
176
- resolve
177
- })
178
-
179
- const decorateInitialSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
180
- Object.freeze({
181
- ...selection,
182
- from: (value: (context: any) => unknown) =>
183
- makeInitialBuilderDescriptor(selection, (context) => context.target.from(value(context))),
184
- decoded: (value: (context: any) => unknown) =>
185
- makeInitialBuilderDescriptor(selection, (context) => context.target.decoded(value(context))),
186
- resolve: (resolve: (context: any) => unknown) => makeInitialBuilderDescriptor(selection, resolve)
187
- })
188
-
189
- const decorateInitialSelectorNode = (node: unknown): unknown => {
190
- if (Topology.isTargetSelection(node)) return decorateInitialSelection(node)
191
- if (typeof node === "function") {
192
- const wrapped = ((...args: ReadonlyArray<unknown>) => decorateInitialSelection(node(...args))) as
193
- & ((...args: ReadonlyArray<unknown>) => unknown)
194
- & Record<string, unknown>
195
- for (const key of Object.keys(node)) {
196
- wrapped[key] = decorateInitialSelectorNode((node as unknown as Record<string, unknown>)[key])
197
- }
198
- return Object.freeze(wrapped)
199
- }
200
- if (typeof node === "object" && node !== null) {
201
- const wrapped: Record<string, unknown> = {}
202
- for (const key of Object.keys(node)) {
203
- wrapped[key] = decorateInitialSelectorNode((node as Record<string, unknown>)[key])
204
- }
205
- return Object.freeze(wrapped)
206
- }
207
- return node
208
- }
209
-
210
156
  const transitionTargetSelection = (
211
157
  selection: Topology.TargetSelection
212
158
  ): Machine.TransitionTargetSelection =>
@@ -221,12 +167,6 @@ const selectionUpdates = (selection: Topology.TargetSelection): ReadonlyArray<st
221
167
  selection.kind === "update" && selection.path !== undefined ? [selection.path] : []
222
168
  : [selection.updatePath]
223
169
 
224
- const makeSelectionValue = (
225
- kind: Topology.TargetSelectionKind,
226
- path: string | undefined,
227
- scope: Topology.TargetSelectionScope
228
- ): Topology.TargetSelection => Topology.makeTargetSelection(kind, path, scope)
229
-
230
170
  const makeStateUpdateSelection = (
231
171
  path: string,
232
172
  scope: "local" | "branch"
@@ -611,7 +551,7 @@ const normalizeObjectTransition = (
611
551
  "history",
612
552
  "none",
613
553
  "branches",
614
- "from",
554
+ "data",
615
555
  "decoded",
616
556
  "resolve",
617
557
  "guard",
@@ -623,20 +563,21 @@ const normalizeObjectTransition = (
623
563
  throw new Error("Machine transition contains an unknown field")
624
564
  }
625
565
  }
626
- for (const key of ["from", "decoded", "resolve", "guard"]) {
566
+ for (const key of ["resolve", "guard"]) {
627
567
  if (config[key] !== undefined && typeof config[key] !== "function") {
628
568
  throw new Error(`Machine transition ${key} must be a function`)
629
569
  }
630
570
  }
631
571
  const guard = typeof config.guard === "function" ? config.guard : undefined
632
572
  const resolve = typeof config.resolve === "function" ? config.resolve : undefined
633
- const construct = typeof config.from === "function"
634
- ? config.from
635
- : typeof config.decoded === "function"
636
- ? config.decoded
637
- : undefined
638
- const methods = ["from", "decoded", "resolve"].filter((key) => config[key] !== undefined)
639
- if (methods.length > 1) throw new Error("Machine transition construction methods are mutually exclusive")
573
+ if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
574
+ throw new Error("Machine decoded must be a boolean construction flag")
575
+ }
576
+ const hasData = Object.prototype.hasOwnProperty.call(config, "data")
577
+ if (config.decoded === true && !hasData) throw new Error("Machine decoded construction requires data")
578
+ if (hasData && resolve !== undefined) throw new Error("Machine data and resolve are mutually exclusive")
579
+ const data = config.data
580
+ const construct = typeof data === "function" ? data : () => data
640
581
  const guarded = guard !== undefined
641
582
  const declinable = guarded || config.declinable === true
642
583
  if (typeof config.branches === "string") {
@@ -645,7 +586,7 @@ const normalizeObjectTransition = (
645
586
  throw new Error("Machine branching transition requires a registered group and resolver")
646
587
  }
647
588
  if (
648
- ["target", "update", "initial", "history", "none", "from", "decoded"].some((key) => config[key] !== undefined)
589
+ ["target", "update", "initial", "history", "none", "data", "decoded"].some((key) => config[key] !== undefined)
649
590
  ) throw new Error("Machine branching transition cannot redeclare its destination")
650
591
  const entries = Object.fromEntries(
651
592
  Object.entries(group).map(([key, spec]) => [key, {
@@ -672,7 +613,7 @@ const normalizeObjectTransition = (
672
613
  if (resolve !== undefined && selection.kind !== "none") {
673
614
  throw new Error("Machine advanced construction requires a declared branch group")
674
615
  }
675
- const method = config.from !== undefined ? "from" : config.decoded !== undefined ? "decoded" : undefined
616
+ const method = hasData ? config.decoded === true ? "decoded" : "from" : undefined
676
617
  return {
677
618
  target: () => selection,
678
619
  reenter: config.reenter,
@@ -911,9 +852,26 @@ const flattenHandlers = (
911
852
 
912
853
  const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration): Definition.Any["handle"] =>
913
854
  ((config: Record<string, unknown>) => {
855
+ const captured = InitialDeclaration.capture(declaration.root, config)
856
+ const compiled = Object.assign(Object.create(Proto), self)
857
+ Protocol.copyProtocol(self, compiled)
858
+ compiled.states = Object.freeze({ "": captured.node })
859
+ compiled.stateNodes = Topology.compileStateNodes(compiled.states)
860
+ if (compiled.stateNodes.byPath.get("").schema === undefined && config.root !== undefined) {
861
+ throw new Error("Machine schema-less root cannot construct data")
862
+ }
863
+ const constructRoot = compiled.stateNodes.byPath.get("").schema === undefined
864
+ ? () => undefined
865
+ : InitialDeclaration.construction(config.root)
866
+ compiled.initial = (input: unknown) => Topology.makeInitialTarget("", constructRoot({ input }))
867
+ compiled.initialDefinition = Object.freeze({
868
+ target: "",
869
+ selection: Object.freeze({ path: "", kind: "initial", scope: "initial" })
870
+ })
871
+ compiled.makeTargetBuilder = makeTargetBuilder(compiled.states, compiled.stateNodes)
914
872
  const handlers: Record<PropertyKey, CapturedStateConfig> = Object.create(null)
915
- flattenHandlers(handlers, self.stateNodes, self.states, "", declaration, { "": config })
916
- return makeWithHandlers(self, handlers)
873
+ flattenHandlers(handlers, compiled.stateNodes, compiled.states, "", declaration, { "": captured.handlers })
874
+ return makeWithHandlers(compiled, handlers)
917
875
  }) as Definition.Any["handle"]
918
876
 
919
877
  export const isMachine = (
@@ -953,96 +911,6 @@ export const isFinal = <
953
911
  state: Machine.Snapshot<States>
954
912
  ): state is Machine.SnapshotContainingFinal<States, FinalStates> => internalPlanner.isFinal(machine as any, state)
955
913
 
956
- const getInitialSelectionBuilder = (
957
- initialBuilder: Record<string, any>,
958
- selection: Topology.TargetSelection
959
- ): Record<string, any> => {
960
- const path = selection.path
961
- if (path === undefined || path.includes(".")) {
962
- throw new Error("Machine initial target must select one top-level state")
963
- }
964
- const builder = initialBuilder[path]
965
- if (typeof builder !== "object" || builder === null || typeof builder.from !== "function") {
966
- throw new Error(`Machine could not construct selected initial state "${path}"`)
967
- }
968
- return builder
969
- }
970
-
971
- const captureInitialBranch = (
972
- definition: unknown,
973
- initialBuilder: Record<string, any>,
974
- configuration: boolean
975
- ): {
976
- readonly selection: Topology.TargetSelection
977
- readonly resolve?: (context: any) => unknown
978
- readonly builder: Record<string, any>
979
- } => {
980
- if (definition !== undefined && typeof definition !== "function") {
981
- throw new Error("Machine initial definition must be a target-first callback")
982
- }
983
- const selector = decorateInitialSelection(makeSelectionValue(configuration ? "state" : "initial", "", "initial"))
984
- const result = definition === undefined ? selector : definition(selector)
985
- let selection: Topology.TargetSelection
986
- let resolve: ((context: any) => unknown) | undefined
987
- if (Topology.isTargetSelection(result)) {
988
- selection = plainTargetSelection(result)
989
- } else if (hasProperty(result, InitialBuilderDescriptorTypeId)) {
990
- const descriptor = result as InitialBuilderDescriptor
991
- selection = descriptor.selection
992
- resolve = descriptor.resolve
993
- } else {
994
- throw new Error("Machine initial definition must select exactly one target")
995
- }
996
- if (selection.kind !== "state" && selection.kind !== "initial") {
997
- throw new Error("Machine initial target must select a top-level state or its declared initial entry")
998
- }
999
- const captured = {
1000
- selection,
1001
- builder: getInitialSelectionBuilder(initialBuilder, selection)
1002
- }
1003
- return resolve === undefined ? Object.freeze(captured) : Object.freeze({ ...captured, resolve })
1004
- }
1005
-
1006
- const validateInitialSelection = (result: unknown, selection: Topology.TargetSelection): void => {
1007
- if (
1008
- typeof result !== "object" || result === null || !hasProperty(result, "path") || result.path !== selection.path
1009
- ) {
1010
- const resultPath = typeof result === "object" && result !== null && hasProperty(result, "path")
1011
- ? String(result.path)
1012
- : "<invalid>"
1013
- throw new Error(`Machine initial resolver selected "${selection.path}" but constructed "${resultPath}"`)
1014
- }
1015
- }
1016
-
1017
- const compileInitial = (
1018
- definition: unknown,
1019
- states: Machine.StateTree,
1020
- stateNodes: Machine.StateNodes,
1021
- configuration = false
1022
- ): {
1023
- readonly initial: (input?: unknown) => unknown
1024
- readonly definition: Machine.InitialDefinition
1025
- } => {
1026
- const rootNode = getTargetBuilderNode(stateNodes, "")
1027
- const initialBuilder = configuration ?
1028
- makeSnapshotBuilder(states, { mode: "full", prefix: "" }) as Record<string, any>
1029
- : { "": withFrom((value: unknown) => Topology.makeInitialTarget("", value), "leaf", rootNode.schema !== undefined) }
1030
- const branch = captureInitialBranch(definition, initialBuilder, configuration)
1031
- return {
1032
- initial: (input?: unknown) => {
1033
- const result = branch.resolve === undefined
1034
- ? constructSelectedTarget(branch.builder)
1035
- : branch.resolve({ input, target: branch.builder })
1036
- validateInitialSelection(result, branch.selection)
1037
- return result
1038
- },
1039
- definition: Object.freeze({
1040
- target: branch.selection.path!,
1041
- selection: transitionTargetSelection(branch.selection) as Machine.InitialDefinition["selection"]
1042
- })
1043
- }
1044
- }
1045
-
1046
914
  export const state = (node: unknown): State<Machine.StateNodeConfig> => {
1047
915
  const captured = StateDefinition.captureRoot(node) as Machine.StateNodeConfig
1048
916
  const access = makeStateHelpers()
@@ -1115,17 +983,18 @@ export const make = <
1115
983
  readonly logic?: unknown
1116
984
  readonly children?: unknown
1117
985
  readonly branches?: unknown
1118
- readonly initialConfiguration?: unknown
1119
986
  readonly events: Machine.EventProtocol<"public", InputEvents>
1120
987
  readonly internalEvents?: Machine.EventProtocol<"internal", InternalEvents>
1121
988
  readonly emittedEvents?: Machine.EventProtocol<"emitted", Emits>
1122
989
  readonly parent?: ParentDeclaration
1123
990
  readonly input?: Input
1124
- readonly initial: unknown
1125
991
  }
1126
992
  ): MakeResult<States, InputEvents, Emits, Input, InitialE, InitialR, InternalEvents, ParentDeclaration> => {
993
+ if (Object.hasOwn(config, "initial") || Object.hasOwn(config, "initialConfiguration")) {
994
+ throw new Error("Machine initial edges and root data belong in handle")
995
+ }
1127
996
  const states = Object.freeze({ "": config.root.node })
1128
- const self = Object.create(Proto)
997
+ const self = Object.create(PipeablePrototype)
1129
998
  self.states = states
1130
999
  self.root = config.root
1131
1000
  self.events = config.events
@@ -1134,16 +1003,6 @@ export const make = <
1134
1003
  self.parent = config.parent
1135
1004
  self.input = config.input
1136
1005
  self.id = config.id
1137
- self.stateNodes = Topology.compileStateNodes(states)
1138
- const compiledInitial = compileInitial(
1139
- config.initialConfiguration ?? config.initial,
1140
- states,
1141
- self.stateNodes,
1142
- config.initialConfiguration !== undefined
1143
- )
1144
- self.initial = compiledInitial.initial
1145
- self.initialDefinition = compiledInitial.definition
1146
- self.makeTargetBuilder = makeTargetBuilder(states, self.stateNodes)
1147
1006
  self.handlers = Object.create(null)
1148
1007
  self.handle = makeHandle(self, Declaration.capture(config.root, config))
1149
1008
  Protocol.setProtocol(self)