@typeonce/effect-machine 0.32.0 → 0.34.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 (108) hide show
  1. package/README.md +216 -635
  2. package/dist/Machine.d.ts +814 -545
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -8
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/childRegistry.d.ts +1 -1
  7. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  8. package/dist/internal/machine/cluster.d.ts +2 -50
  9. package/dist/internal/machine/cluster.d.ts.map +1 -1
  10. package/dist/internal/machine/cluster.js +4 -27
  11. package/dist/internal/machine/cluster.js.map +1 -1
  12. package/dist/internal/machine/clusterProtocol.d.ts +35 -0
  13. package/dist/internal/machine/clusterProtocol.d.ts.map +1 -0
  14. package/dist/internal/machine/clusterProtocol.js +28 -0
  15. package/dist/internal/machine/clusterProtocol.js.map +1 -0
  16. package/dist/internal/machine/commandRuntime.d.ts +1 -1
  17. package/dist/internal/machine/commandRuntime.d.ts.map +1 -1
  18. package/dist/internal/machine/configuration.d.ts +2 -1
  19. package/dist/internal/machine/configuration.d.ts.map +1 -1
  20. package/dist/internal/machine/configuration.js +38 -45
  21. package/dist/internal/machine/configuration.js.map +1 -1
  22. package/dist/internal/machine/declaration.d.ts +17 -0
  23. package/dist/internal/machine/declaration.d.ts.map +1 -0
  24. package/dist/internal/machine/declaration.js +120 -0
  25. package/dist/internal/machine/declaration.js.map +1 -0
  26. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  27. package/dist/internal/machine/executionPlan.js +5 -4
  28. package/dist/internal/machine/executionPlan.js.map +1 -1
  29. package/dist/internal/machine/implementation.d.ts +34 -0
  30. package/dist/internal/machine/implementation.d.ts.map +1 -0
  31. package/dist/internal/machine/implementation.js +3 -0
  32. package/dist/internal/machine/implementation.js.map +1 -0
  33. package/dist/internal/machine/invocation.d.ts +1 -1
  34. package/dist/internal/machine/invocation.d.ts.map +1 -1
  35. package/dist/internal/machine/invocation.js +1 -1
  36. package/dist/internal/machine/invocation.js.map +1 -1
  37. package/dist/internal/machine/invocationDefinition.d.ts +1 -1
  38. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  39. package/dist/internal/machine/machine.d.ts +13 -2
  40. package/dist/internal/machine/machine.d.ts.map +1 -1
  41. package/dist/internal/machine/machine.js +149 -280
  42. package/dist/internal/machine/machine.js.map +1 -1
  43. package/dist/internal/machine/planner.d.ts.map +1 -1
  44. package/dist/internal/machine/planner.js +12 -11
  45. package/dist/internal/machine/planner.js.map +1 -1
  46. package/dist/internal/machine/process.d.ts +8 -7
  47. package/dist/internal/machine/process.d.ts.map +1 -1
  48. package/dist/internal/machine/process.js +16 -12
  49. package/dist/internal/machine/process.js.map +1 -1
  50. package/dist/internal/machine/runtime.d.ts +2 -230
  51. package/dist/internal/machine/runtime.d.ts.map +1 -1
  52. package/dist/internal/machine/runtime.js +8 -1857
  53. package/dist/internal/machine/runtime.js.map +1 -1
  54. package/dist/internal/machine/runtimeCompiled.d.ts +5 -0
  55. package/dist/internal/machine/runtimeCompiled.d.ts.map +1 -0
  56. package/dist/internal/machine/runtimeCompiled.js +867 -0
  57. package/dist/internal/machine/runtimeCompiled.js.map +1 -0
  58. package/dist/internal/machine/runtimeGeneric.d.ts +3 -0
  59. package/dist/internal/machine/runtimeGeneric.d.ts.map +1 -0
  60. package/dist/internal/machine/runtimeGeneric.js +471 -0
  61. package/dist/internal/machine/runtimeGeneric.js.map +1 -0
  62. package/dist/internal/machine/runtimeProtocol.d.ts +312 -0
  63. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -0
  64. package/dist/internal/machine/runtimeProtocol.js +561 -0
  65. package/dist/internal/machine/runtimeProtocol.js.map +1 -0
  66. package/dist/internal/machine/targetReference.d.ts +15 -0
  67. package/dist/internal/machine/targetReference.d.ts.map +1 -0
  68. package/dist/internal/machine/targetReference.js +31 -0
  69. package/dist/internal/machine/targetReference.js.map +1 -0
  70. package/dist/internal/machine/topology.d.ts.map +1 -1
  71. package/dist/internal/machine/topology.js +2 -1
  72. package/dist/internal/machine/topology.js.map +1 -1
  73. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  74. package/dist/internal/testing/machine/finiteModel.js +38 -40
  75. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  76. package/dist/internal/testing/machine/probe.js +1 -1
  77. package/dist/internal/testing/machine/probe.js.map +1 -1
  78. package/dist/unstable/cluster/ClusterMachine.d.ts +5 -5
  79. package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
  80. package/dist/unstable/cluster/ClusterMachine.js +5 -17
  81. package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
  82. package/docs/agent-guide.md +66 -91
  83. package/docs/machine-review.md +19 -49
  84. package/docs/root-api.md +68 -23
  85. package/package.json +1 -1
  86. package/src/Machine.ts +1387 -2011
  87. package/src/internal/machine/childRegistry.ts +1 -1
  88. package/src/internal/machine/cluster.ts +7 -73
  89. package/src/internal/machine/clusterProtocol.ts +56 -0
  90. package/src/internal/machine/commandRuntime.ts +1 -1
  91. package/src/internal/machine/configuration.ts +53 -45
  92. package/src/internal/machine/declaration.ts +140 -0
  93. package/src/internal/machine/executionPlan.ts +6 -5
  94. package/src/internal/machine/implementation.ts +41 -0
  95. package/src/internal/machine/invocation.ts +3 -3
  96. package/src/internal/machine/invocationDefinition.ts +1 -1
  97. package/src/internal/machine/machine.ts +210 -389
  98. package/src/internal/machine/planner.ts +54 -35
  99. package/src/internal/machine/process.ts +40 -33
  100. package/src/internal/machine/runtime.ts +20 -3037
  101. package/src/internal/machine/runtimeCompiled.ts +1166 -0
  102. package/src/internal/machine/runtimeGeneric.ts +799 -0
  103. package/src/internal/machine/runtimeProtocol.ts +1213 -0
  104. package/src/internal/machine/targetReference.ts +40 -0
  105. package/src/internal/machine/topology.ts +2 -1
  106. package/src/internal/testing/machine/finiteModel.ts +42 -43
  107. package/src/internal/testing/machine/probe.ts +1 -1
  108. package/src/unstable/cluster/ClusterMachine.ts +9 -17
@@ -28,14 +28,16 @@ import type {
28
28
  } from "../../Machine.js"
29
29
  import * as Activities from "./activities.js"
30
30
  import * as Configuration from "./configuration.js"
31
+ import * as Declaration from "./declaration.js"
31
32
  import type { ChildAlreadyExistsError, InfiniteTransitionError, StartupError } from "./errors.js"
33
+ import type { CapturedStateConfig } from "./implementation.js"
32
34
  import * as InvocationDefinition from "./invocationDefinition.js"
33
35
  import * as internalPlanner from "./planner.js"
34
36
  import * as internalProcess from "./process.js"
35
37
  import * as Protocol from "./protocol.js"
36
38
  import type { EnsureExecutable } from "./readiness.js"
37
39
  import type { ExcludeCompatibleRuntime } from "./requirements.js"
38
- import * as internalRuntime from "./runtime.js"
40
+ import * as internalRuntime from "./runtimeProtocol.js"
39
41
  import * as Serialization from "./serialization.js"
40
42
  import * as StateDefinition from "./stateDefinition.js"
41
43
  import { ChildMachineLogicTypeId } from "./symbols.js"
@@ -46,6 +48,7 @@ import {
46
48
  makeTargetBuilder,
47
49
  withFrom
48
50
  } from "./targetBuilder.js"
51
+ import * as TargetReference from "./targetReference.js"
49
52
  import * as Topology from "./topology.js"
50
53
 
51
54
  export {
@@ -59,11 +62,14 @@ export {
59
62
  } from "./errors.js"
60
63
  export { ChildMachineLogicTypeId, InitialEventTypeId, SnapshotBuilderStateTypeId } from "./symbols.js"
61
64
 
65
+ /** Internal seam for the public target-reference factory and its opaque brand. */
66
+ export const TargetReferenceTypeId: typeof TargetReference.TypeId = TargetReference.TypeId
67
+ export const targets: (root: State<Machine.StateNodeConfig>) => { readonly root: TargetReference.Reference } =
68
+ TargetReference.make
69
+
62
70
  const TypeId = "~effect/Machine"
63
71
  const ParentTypeId = "~effect/Machine/Parent"
64
72
  export const InvokeTypeId: unique symbol = Symbol.for("effect/Machine/Invoke")
65
- export const TransitionTypeId: unique symbol = Symbol.for("effect/Machine/Transition")
66
- const InvokeBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/InvokeBuilderDescriptor")
67
73
  const ChildMachineTypeId = "~effect/Machine/ChildMachine"
68
74
  type MachineRuntimeRequirement = internalRuntime.MachineRuntime
69
75
 
@@ -92,7 +98,7 @@ const Proto = {
92
98
 
93
99
  const makeWithHandlers = (
94
100
  self: Definition.Any,
95
- handlers: Machine.StateConfigs<any, any, any, any, any, any, any>
101
+ handlers: Readonly<Record<string, CapturedStateConfig>>
96
102
  ): Machine.Any => {
97
103
  const machine = Object.create(Proto)
98
104
  machine.states = self.states
@@ -133,28 +139,6 @@ type CapturedNamedBranch = {
133
139
  readonly selection: Topology.TargetSelection
134
140
  }
135
141
 
136
- const TransitionBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/TransitionBuilderDescriptor")
137
-
138
- type DirectTransitionDescriptor = {
139
- readonly [TransitionBuilderDescriptorTypeId]: typeof TransitionBuilderDescriptorTypeId
140
- readonly type: "direct"
141
- readonly selection: Topology.TargetSelection
142
- readonly resolver?: (context: any, enqueue: unknown) => unknown
143
- readonly reenter: boolean
144
- readonly declinable: boolean
145
- }
146
-
147
- type BranchesTransitionDescriptor = {
148
- readonly [TransitionBuilderDescriptorTypeId]: typeof TransitionBuilderDescriptorTypeId
149
- readonly type: "branches"
150
- readonly declarations: unknown
151
- readonly resolve: (context: any, enqueue: unknown) => unknown
152
- readonly reenter: boolean
153
- readonly declinable: boolean
154
- }
155
-
156
- type TransitionBuilderDescriptor = DirectTransitionDescriptor | BranchesTransitionDescriptor
157
-
158
142
  const InitialBuilderDescriptorTypeId: unique symbol = Symbol("effect/Machine/InitialBuilderDescriptor")
159
143
 
160
144
  type InitialBuilderDescriptor = {
@@ -168,90 +152,20 @@ const plainTargetSelection = (selection: Topology.TargetSelection): Topology.Tar
168
152
  ? Topology.noneTargetSelection
169
153
  : Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, selection.updatePath)
170
154
 
171
- const transitionOptions = (options: unknown): { readonly reenter: boolean; readonly declinable: boolean } => {
172
- const configuration = typeof options === "object" && options !== null
173
- ? options as { readonly reenter?: unknown; readonly declinable?: unknown }
174
- : {}
175
- return {
176
- reenter: configuration.reenter === true,
177
- declinable: configuration.declinable === true
178
- }
179
- }
180
-
181
- const makeDirectTransitionDescriptor = (
155
+ // The authored callback crosses an erased schema boundary here. Each builder
156
+ // retains its construction mode, and planning validates both resulting values.
157
+ const constructSelectionValue = (
182
158
  selection: Topology.TargetSelection,
183
- resolve: ((context: any, enqueue: unknown) => unknown) | undefined,
184
- options: unknown
185
- ): DirectTransitionDescriptor => {
186
- const shared: Omit<DirectTransitionDescriptor, "resolver"> = {
187
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
188
- type: "direct",
189
- selection: plainTargetSelection(selection),
190
- ...transitionOptions(options)
191
- }
192
- return resolve === undefined
193
- ? Object.freeze(shared)
194
- : Object.freeze({ ...shared, resolver: resolve })
195
- }
196
-
197
- const guardedSelection = (selection: Topology.TargetSelection, predicate: (context: any) => boolean): object => {
198
- const wrap = (resolve: (context: any, enqueue: unknown) => unknown, options?: unknown) =>
199
- makeDirectTransitionDescriptor(
200
- selection,
201
- (context, enqueue) => predicate(context) ? resolve(context, enqueue) : Topology.makeDeclined(),
202
- { ...transitionOptions(options), declinable: true }
203
- )
204
- return Object.freeze({
205
- ...wrap((
206
- context
207
- ) => (selection.kind === "none" ? Topology.makeNoTarget() : constructSelectedTarget(context.target))),
208
- from: (value: (context: any) => unknown) => wrap((context) => context.target.from(value(context))),
209
- decoded: (value: (context: any) => unknown) => wrap((context) => context.target.decoded(value(context))),
210
- resolve: wrap
211
- })
159
+ context: any,
160
+ method: "from" | "decoded",
161
+ value: unknown
162
+ ): unknown => {
163
+ if (selection.kind === "update") return context.owner[method](value)
164
+ if (selection.updatePath === undefined) return context.target[method](value)
165
+ const values = value as { readonly target: unknown; readonly update: unknown }
166
+ return context.target[method](values.target).update(context.owner[method](values.update))
212
167
  }
213
168
 
214
- const decorateTransitionSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
215
- Object.freeze({
216
- ...selection,
217
- guard: (predicate: (context: any) => boolean) => guardedSelection(selection, predicate),
218
- from: (value: (context: any) => unknown) =>
219
- makeDirectTransitionDescriptor(selection, (context) => context.target.from(value(context)), undefined),
220
- decoded: (value: (context: any) => unknown) =>
221
- makeDirectTransitionDescriptor(selection, (context) => context.target.decoded(value(context)), undefined),
222
- resolve: (resolve: (context: any, enqueue: unknown) => unknown, options?: unknown) =>
223
- makeDirectTransitionDescriptor(selection, resolve, options),
224
- reenter: () => makeDirectTransitionDescriptor(selection, undefined, { reenter: true }),
225
- updating: (owner: unknown) => {
226
- if (typeof owner !== "function") {
227
- throw new Error("Machine updating owner must be a state selector")
228
- }
229
- const ownerSelection = owner()
230
- if (
231
- !Topology.isTargetSelection(ownerSelection) || ownerSelection.kind !== "state" ||
232
- ownerSelection.scope !== "branch"
233
- ) {
234
- throw new Error("Machine updating owner must be addressed by one branch state selector")
235
- }
236
- return decorateTransitionSelection(
237
- Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, ownerSelection.path)
238
- )
239
- }
240
- })
241
-
242
- const decorateStateUpdateSelection = (selection: Topology.TargetSelection): Topology.TargetSelection =>
243
- Object.freeze({
244
- ...selection,
245
- from: (value: (context: any) => unknown) =>
246
- makeDirectTransitionDescriptor(selection, (context) => context.owner.from(value(context)), undefined),
247
- decoded: (value: (context: any) => unknown) =>
248
- makeDirectTransitionDescriptor(selection, (context) => context.owner.decoded(value(context)), undefined),
249
- resolve: (resolve: (context: any, enqueue: unknown) => unknown, options?: unknown) =>
250
- makeDirectTransitionDescriptor(selection, resolve, options)
251
- })
252
-
253
- const noneTransitionSelection = decorateTransitionSelection(Topology.noneTargetSelection)
254
-
255
169
  const makeInitialBuilderDescriptor = (
256
170
  selection: Topology.TargetSelection,
257
171
  resolve: (context: any) => unknown
@@ -293,88 +207,6 @@ const decorateInitialSelectorNode = (node: unknown): unknown => {
293
207
  return node
294
208
  }
295
209
 
296
- const decorateTransitionSelectorNode = (node: unknown): unknown => {
297
- if (Topology.isTargetSelection(node)) {
298
- if (node.kind === "state" && node.scope === "full" && hasProperty(node, "initial")) {
299
- return Object.freeze({
300
- ...decorateTransitionSelection(node),
301
- initial: decorateTransitionSelection(node.initial as Topology.TargetSelection)
302
- })
303
- }
304
- if (node.kind === "update") return decorateStateUpdateSelection(node)
305
- return node === Topology.noneTargetSelection ? noneTransitionSelection : decorateTransitionSelection(node)
306
- }
307
- if (typeof node === "function") {
308
- const wrapped = ((...args: ReadonlyArray<unknown>) => decorateTransitionSelection(node(...args))) as
309
- & ((...args: ReadonlyArray<unknown>) => unknown)
310
- & Record<string, unknown>
311
- for (const key of Object.keys(node)) {
312
- wrapped[key] = decorateTransitionSelectorNode((node as unknown as Record<string, unknown>)[key])
313
- }
314
- return Object.freeze(wrapped)
315
- }
316
- if (typeof node === "object" && node !== null) {
317
- const wrapped: Record<string, unknown> = {}
318
- for (const key of Object.keys(node)) {
319
- wrapped[key] = decorateTransitionSelectorNode((node as Record<string, unknown>)[key])
320
- }
321
- return Object.freeze(wrapped)
322
- }
323
- return node
324
- }
325
-
326
- const makeTransitionSelector = (
327
- stateNodes: Machine.StateNodes,
328
- source: string
329
- ): unknown => {
330
- const selector = {
331
- ...decorateTransitionSelectorNode(makeTargetSelector(stateNodes, source)) as Record<string, unknown>
332
- }
333
- selector.branches = (declarations: unknown) =>
334
- Object.freeze({
335
- resolve: (
336
- resolve: (context: any, enqueue: unknown) => unknown,
337
- options?: unknown
338
- ): BranchesTransitionDescriptor =>
339
- Object.freeze({
340
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
341
- type: "branches",
342
- declarations,
343
- resolve,
344
- ...transitionOptions(options)
345
- })
346
- })
347
- return Object.freeze(selector)
348
- }
349
-
350
- const normalizeTransitionBuilder = (
351
- transition: (selector: unknown) => unknown,
352
- stateNodes: Machine.StateNodes,
353
- path: string
354
- ): unknown => {
355
- const result = transition(makeTransitionSelector(stateNodes, path))
356
- if (Topology.isTargetSelection(result)) {
357
- const selection = plainTargetSelection(result)
358
- return { target: () => selection }
359
- }
360
- if (!hasProperty(result, TransitionBuilderDescriptorTypeId)) return result
361
- const descriptor = result as TransitionBuilderDescriptor
362
- if (descriptor.type === "branches") {
363
- return {
364
- branches: () => descriptor.declarations,
365
- resolve: descriptor.resolve,
366
- reenter: descriptor.reenter,
367
- declinable: descriptor.declinable
368
- }
369
- }
370
- return {
371
- target: () => descriptor.selection,
372
- resolve: descriptor.resolver,
373
- reenter: descriptor.reenter,
374
- declinable: descriptor.declinable
375
- }
376
- }
377
-
378
210
  const transitionTargetSelection = (
379
211
  selection: Topology.TargetSelection
380
212
  ): Machine.TransitionTargetSelection =>
@@ -389,13 +221,6 @@ const selectionUpdates = (selection: Topology.TargetSelection): ReadonlyArray<st
389
221
  selection.kind === "update" && selection.path !== undefined ? [selection.path] : []
390
222
  : [selection.updatePath]
391
223
 
392
- const makeSelectionMethod = (
393
- kind: Topology.TargetSelectionKind,
394
- path: string | undefined,
395
- scope: Topology.TargetSelectionScope
396
- ): () => Topology.TargetSelection =>
397
- () => Topology.makeTargetSelection(kind, path, scope)
398
-
399
224
  const makeSelectionValue = (
400
225
  kind: Topology.TargetSelectionKind,
401
226
  path: string | undefined,
@@ -407,106 +232,6 @@ const makeStateUpdateSelection = (
407
232
  scope: "local" | "branch"
408
233
  ): Topology.TargetSelection => Topology.makeTargetSelection("update", path, scope)
409
234
 
410
- const addSelectionChildren = (
411
- builder: Record<string, unknown>,
412
- stateNodes: Machine.StateNodes,
413
- parent: string,
414
- scope: "local" | "branch",
415
- source?: string
416
- ): void => {
417
- for (const node of stateNodes.byPath.values()) {
418
- if (node.parent !== parent || node.type === "history") continue
419
- builder[node.key] = makeSelectionNode(stateNodes, node.path, scope, source)
420
- }
421
- }
422
-
423
- const makeSelectionNode = (
424
- stateNodes: Machine.StateNodes,
425
- path: string,
426
- scope: Topology.TargetSelectionScope,
427
- source?: string
428
- ): unknown => {
429
- const node = getTargetBuilderNode(stateNodes, path)
430
- const kind: Topology.TargetSelectionKind = node.type === "choice" ? "choice" : "state"
431
- const method = makeSelectionMethod(kind, path, scope) as unknown as Record<string, unknown>
432
- if (node.type !== "atomic" && node.type !== "final" && node.type !== "choice" && node.type !== "history") {
433
- Object.defineProperty(method, "initial", {
434
- value: makeSelectionValue("initial", path, scope),
435
- enumerable: true
436
- })
437
- if (scope === "local" || scope === "branch") {
438
- addSelectionChildren(method, stateNodes, path, scope, source)
439
- }
440
- if (
441
- scope === "branch" && source !== undefined && node.schema !== undefined &&
442
- (source === path || Configuration.isDescendantOf(source, path)) &&
443
- getTargetBuilderNode(stateNodes, source).type !== "choice"
444
- ) {
445
- Object.defineProperty(method, "update", {
446
- value: makeStateUpdateSelection(path, "branch"),
447
- enumerable: true
448
- })
449
- }
450
- }
451
- if (node.type === "atomic" && scope === "branch" && source === path && node.schema !== undefined) {
452
- Object.defineProperty(method, "update", { value: makeStateUpdateSelection(path, "branch"), enumerable: true })
453
- }
454
- return method
455
- }
456
-
457
- const makeHistorySelectionTree = (
458
- stateNodes: Machine.StateNodes,
459
- parent: string | undefined
460
- ): Record<string, unknown> => {
461
- const builder: Record<string, unknown> = {}
462
- for (const node of stateNodes.byPath.values()) {
463
- if (node.parent !== parent) continue
464
- if (node.type === "history") {
465
- builder[node.key] = makeSelectionValue("history", node.path, "full")
466
- } else if (node.type !== "choice") {
467
- const children = makeHistorySelectionTree(stateNodes, node.path)
468
- if (Object.keys(children).length > 0) builder[node.key] = children
469
- }
470
- }
471
- return builder
472
- }
473
-
474
- const makeTargetSelector = (
475
- stateNodes: Machine.StateNodes,
476
- source: string
477
- ): unknown => {
478
- const full = Object.assign({}, makeSelectionValue("state", "", "full"), {
479
- initial: makeSelectionValue("initial", "", "full")
480
- })
481
- const branch: Record<string, unknown> = {}
482
- const root = getTargetBuilderNode(stateNodes, stateNodes.roots[0]!)
483
- addSelectionChildren(branch, stateNodes, root.path, "branch", source)
484
- const local: Record<string, unknown> = {}
485
- const localScope = getLocalTargetScope(stateNodes, source)
486
- if (localScope !== undefined) {
487
- const localScopeNode = getTargetBuilderNode(stateNodes, localScope)
488
- if (localScopeNode.schema !== undefined) {
489
- local.with = makeSelectionValue("state", localScope, "local")
490
- if (getTargetBuilderNode(stateNodes, source).type !== "choice") {
491
- local.update = makeStateUpdateSelection(localScope, "local")
492
- }
493
- }
494
- addSelectionChildren(local, stateNodes, localScope, "local")
495
- }
496
- return {
497
- none: Topology.noneTargetSelection,
498
- self: getTargetBuilderNode(stateNodes, source).schema === undefined ||
499
- getTargetBuilderNode(stateNodes, source).type === "final"
500
- ? {}
501
- : { update: makeStateUpdateSelection(source, "branch") },
502
- root: makeSelectionNode(stateNodes, root.path, "branch", source),
503
- local,
504
- branch,
505
- full,
506
- history: makeHistorySelectionTree(stateNodes, "")
507
- }
508
- }
509
-
510
235
  const captureDefinitionBranch = (
511
236
  branch: unknown,
512
237
  selector: unknown,
@@ -678,7 +403,12 @@ const runCapturedBranch = (
678
403
  ): unknown => {
679
404
  const selectedTarget = getSelectionBuilder(context.target, branch.selection, stateNodes, source)
680
405
  if (branch.resolve === undefined) return constructSelectedTarget(selectedTarget)
681
- const resolverContext = { ...context }
406
+ // This fresh context is owned by this evaluation and can be retained by user callbacks.
407
+ const resolverContext: Record<string, any> = {
408
+ ...context,
409
+ root: source === "" ? context.state : context.ancestors[""],
410
+ decline: Topology.makeDeclined
411
+ }
682
412
  if (branch.selection.kind === "none") delete resolverContext.target
683
413
  else resolverContext.target = selectedTarget
684
414
  if (branch.selection.kind === "update") {
@@ -701,7 +431,6 @@ const runCapturedBranch = (
701
431
  source
702
432
  )
703
433
  }
704
- if (branch.declinable === true) resolverContext.decline = Topology.makeDeclined
705
434
  const resolved = branch.resolve(resolverContext, enqueue)
706
435
  if (Topology.isDeclined(resolved)) {
707
436
  if (branch.declinable !== true) {
@@ -750,9 +479,6 @@ const captureNamedBranches = (
750
479
  if (!Topology.isTargetSelection(target)) {
751
480
  throw new Error(`Machine transition branch "${key}" must select exactly one target`)
752
481
  }
753
- if (target.updatePath !== undefined) {
754
- throw new Error(`Machine transition branch "${key}" cannot declare an updating target`)
755
- }
756
482
  if (title !== undefined && (typeof title !== "string" || title.length === 0)) {
757
483
  throw new Error(`Machine transition branch "${key}" title must be a non-empty string`)
758
484
  }
@@ -764,11 +490,32 @@ const wrapSelectedBranchBuilder = (
764
490
  builder: unknown,
765
491
  owner: object,
766
492
  branchIndex: number,
767
- branchKey: string
493
+ branchKey: string,
494
+ updateBuilder?: Record<string, (value: unknown) => unknown>
768
495
  ): unknown => {
769
496
  if (typeof builder === "function") {
770
- const wrapped = (...args: ReadonlyArray<unknown>) =>
771
- Topology.makeSelectedBranch(owner, branchIndex, branchKey, builder(...args))
497
+ const wrapped = (...args: ReadonlyArray<unknown>) => {
498
+ const result = builder(...args)
499
+ if (updateBuilder !== undefined) {
500
+ return Object.freeze({
501
+ update: Object.freeze(
502
+ Object.fromEntries(
503
+ Object.getOwnPropertyNames(updateBuilder).map((
504
+ method
505
+ ) => [method, (value: unknown) =>
506
+ Topology.makeSelectedBranch(
507
+ owner,
508
+ branchIndex,
509
+ branchKey,
510
+ result.update(updateBuilder[method]!(value))
511
+ )]
512
+ )
513
+ )
514
+ )
515
+ })
516
+ }
517
+ return Topology.makeSelectedBranch(owner, branchIndex, branchKey, result)
518
+ }
772
519
  for (const property of Reflect.ownKeys(builder)) {
773
520
  if (
774
521
  property === "length" || property === "name" || property === "prototype" || property === "caller" ||
@@ -777,7 +524,7 @@ const wrapSelectedBranchBuilder = (
777
524
  const descriptor = Object.getOwnPropertyDescriptor(builder, property)
778
525
  if (descriptor === undefined) continue
779
526
  if ("value" in descriptor && typeof descriptor.value === "function") {
780
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey)
527
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
781
528
  }
782
529
  Object.defineProperty(wrapped, property, descriptor)
783
530
  }
@@ -789,7 +536,7 @@ const wrapSelectedBranchBuilder = (
789
536
  const descriptor = Object.getOwnPropertyDescriptor(builder, property)
790
537
  if (descriptor === undefined) continue
791
538
  if ("value" in descriptor && typeof descriptor.value === "function") {
792
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey)
539
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder)
793
540
  }
794
541
  Object.defineProperty(wrapped, property, descriptor)
795
542
  }
@@ -812,7 +559,15 @@ const makeBranchSelectors = (
812
559
  getSelectionBuilder(context.target, branch.selection, stateNodes, source),
813
560
  owner,
814
561
  branchIndex,
815
- branch.key
562
+ branch.key,
563
+ branch.selection.updatePath === undefined
564
+ ? undefined
565
+ : getSelectionBuilder(
566
+ context.target,
567
+ makeStateUpdateSelection(branch.selection.updatePath, "branch"),
568
+ stateNodes,
569
+ source
570
+ ) as Record<string, (value: unknown) => unknown>
816
571
  )
817
572
  }
818
573
  return Object.freeze(select)
@@ -835,23 +590,118 @@ const validateSelectedBranchResult = (
835
590
  validateResolvedSelection(result, selection, stateNodes)
836
591
  }
837
592
 
593
+ // Invocation input contexts do not pass through captured transition evaluation.
594
+ const objectContext = (context: Record<string, any>, path: string): Record<string, any> => ({
595
+ ...context,
596
+ root: path === "" ? context.state : context.ancestors[""]
597
+ })
598
+
599
+ const normalizeObjectTransition = (
600
+ raw: unknown,
601
+ declaration: Declaration.Declaration,
602
+ path: string,
603
+ stateNodes: Machine.StateNodes
604
+ ): Record<string, unknown> => {
605
+ if (typeof raw !== "object" || raw === null) throw new Error(`Machine transition for "${path}" must be an object`)
606
+ const config = { ...raw } as Record<string, unknown>
607
+ const allowed = [
608
+ "target",
609
+ "update",
610
+ "initial",
611
+ "history",
612
+ "none",
613
+ "branches",
614
+ "from",
615
+ "decoded",
616
+ "resolve",
617
+ "guard",
618
+ "reenter",
619
+ "declinable"
620
+ ]
621
+ for (const key of Reflect.ownKeys(config)) {
622
+ if (typeof key !== "string" || !allowed.includes(key)) {
623
+ throw new Error("Machine transition contains an unknown field")
624
+ }
625
+ }
626
+ for (const key of ["from", "decoded", "resolve", "guard"]) {
627
+ if (config[key] !== undefined && typeof config[key] !== "function") {
628
+ throw new Error(`Machine transition ${key} must be a function`)
629
+ }
630
+ }
631
+ const guard = typeof config.guard === "function" ? config.guard : undefined
632
+ 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")
640
+ const guarded = guard !== undefined
641
+ const declinable = guarded || config.declinable === true
642
+ if (typeof config.branches === "string") {
643
+ const group = declaration.branches.get(config.branches)
644
+ if (group === undefined || resolve === undefined) {
645
+ throw new Error("Machine branching transition requires a registered group and resolver")
646
+ }
647
+ if (
648
+ ["target", "update", "initial", "history", "none", "from", "decoded"].some((key) => config[key] !== undefined)
649
+ ) throw new Error("Machine branching transition cannot redeclare its destination")
650
+ const entries = Object.fromEntries(
651
+ Object.entries(group).map(([key, spec]) => [key, {
652
+ title: spec.title,
653
+ target: captureDefinitionBranch(
654
+ { target: () => Declaration.selection(declaration, spec) },
655
+ undefined,
656
+ stateNodes,
657
+ path,
658
+ key
659
+ ).selection
660
+ }])
661
+ )
662
+ return {
663
+ branches: () => entries,
664
+ reenter: config.reenter,
665
+ declinable,
666
+ resolve: (context: Record<string, any>, enqueue: unknown) => {
667
+ return guarded && !guard(context) ? Topology.makeDeclined() : resolve(context, enqueue)
668
+ }
669
+ }
670
+ }
671
+ const selection = Declaration.selection(declaration, config)
672
+ if (resolve !== undefined && selection.kind !== "none") {
673
+ throw new Error("Machine advanced construction requires a declared branch group")
674
+ }
675
+ const method = config.from !== undefined ? "from" : config.decoded !== undefined ? "decoded" : undefined
676
+ return {
677
+ target: () => selection,
678
+ reenter: config.reenter,
679
+ declinable,
680
+ ...(!guarded && method === undefined && resolve === undefined ? {} : {
681
+ resolve: (context: Record<string, any>, enqueue: unknown) => {
682
+ if (guarded && !guard(context)) return Topology.makeDeclined()
683
+ if (method !== undefined && construct !== undefined) {
684
+ return constructSelectionValue(selection, context, method, construct(context))
685
+ }
686
+ if (resolve !== undefined) return resolve(context, enqueue)
687
+ return selection.kind === "none" ? undefined : constructSelectedTarget(context.target)
688
+ }
689
+ })
690
+ }
691
+ }
692
+
838
693
  const captureTransition = (
839
694
  rawTransition: unknown,
840
695
  stateNodes: Machine.StateNodes,
841
696
  path: string,
697
+ declaration: Declaration.Declaration,
842
698
  trigger: PropertyKey
843
699
  ): unknown => {
844
- if (typeof rawTransition !== "function") {
845
- throw new Error(
846
- `Machine transition for state "${path}" on "${String(trigger)}" must be a target-first callback`
847
- )
848
- }
849
- const transition = normalizeTransitionBuilder(rawTransition as (selector: unknown) => unknown, stateNodes, path)
700
+ const transition = normalizeObjectTransition(rawTransition, declaration, path, stateNodes)
850
701
  if (typeof transition !== "object" || transition === null) {
851
702
  throw new Error(`Machine transition for state "${path}" on "${String(trigger)}" must be an object`)
852
703
  }
853
704
  const definition = transition as Record<PropertyKey, unknown>
854
- const selector = makeTargetSelector(stateNodes, path)
855
705
  const reenter = definition.reenter === true
856
706
  const declinable = definition.declinable === true
857
707
  if (hasProperty(definition, "branches")) {
@@ -862,13 +712,16 @@ const captureTransition = (
862
712
  )
863
713
  }
864
714
  const resolve = branching.resolve
865
- const branches = captureNamedBranches(branching.branches(selector), path, trigger)
715
+ const branches = captureNamedBranches(branching.branches(), path, trigger)
866
716
  const owner = Object.freeze({})
867
717
  const evaluate = (context: Record<string, any>, enqueue: unknown) => {
868
- const resolverContext = { ...context }
718
+ const resolverContext: Record<string, any> = {
719
+ ...context,
720
+ root: path === "" ? context.state : context.ancestors[""],
721
+ decline: Topology.makeDeclined
722
+ }
869
723
  delete resolverContext.target
870
724
  resolverContext.select = makeBranchSelectors(context, branches, owner, stateNodes, path)
871
- if (declinable) resolverContext.decline = Topology.makeDeclined
872
725
  const selected = resolve(resolverContext, enqueue)
873
726
  if (Topology.isDeclined(selected)) {
874
727
  if (!declinable) {
@@ -920,7 +773,7 @@ const captureTransition = (
920
773
  transition: (context: Record<string, any>, enqueue: unknown) => evaluate(context, enqueue).result
921
774
  }
922
775
  }
923
- const branch = captureDefinitionBranch(transition, selector, stateNodes, path, trigger)
776
+ const branch = captureDefinitionBranch(transition, undefined, stateNodes, path, trigger)
924
777
  const evaluate = (context: Record<string, any>, enqueue: unknown) => ({
925
778
  result: runCapturedBranch(branch, context, enqueue, stateNodes, path),
926
779
  branchIndex: 0,
@@ -944,94 +797,56 @@ const captureTransition = (
944
797
  const captureEventHandlers = (
945
798
  on: object,
946
799
  stateNodes: Machine.StateNodes,
947
- path: string
800
+ path: string,
801
+ declaration: Declaration.Declaration
948
802
  ): Record<PropertyKey, unknown> => {
949
803
  // The machine owns its dispatch table. Compiled plans may snapshot these
950
804
  // definitions, so retaining caller-owned containers would let strategies
951
805
  // observe different handlers after an unsafe external mutation.
952
806
  const captured: Record<PropertyKey, unknown> = Object.create(null)
953
807
  for (const event of Reflect.ownKeys(on)) {
954
- captured[event] = captureTransition((on as Record<PropertyKey, unknown>)[event], stateNodes, path, event)
808
+ captured[event] = captureTransition(
809
+ (on as Record<PropertyKey, unknown>)[event],
810
+ stateNodes,
811
+ path,
812
+ declaration,
813
+ event
814
+ )
955
815
  }
956
816
  return captured
957
817
  }
958
818
 
959
- interface InvokeBuilderDescriptor {
960
- readonly [InvokeBuilderDescriptorTypeId]: typeof InvokeBuilderDescriptorTypeId
961
- readonly config: Readonly<Record<PropertyKey, unknown>>
962
- }
963
-
964
- type InvokeBuilderChannel = "onDone" | "onFailure" | "onElement" | "onSnapshot"
965
-
966
- const makeInvokeBuilder = (
967
- config: Readonly<Record<PropertyKey, unknown>>,
968
- channels: ReadonlyArray<InvokeBuilderChannel>
969
- ): InvokeBuilderDescriptor => {
970
- const builder: Record<PropertyKey, unknown> = {
971
- [InvokeBuilderDescriptorTypeId]: InvokeBuilderDescriptorTypeId as typeof InvokeBuilderDescriptorTypeId,
972
- config
973
- }
974
- for (const channel of channels) {
975
- if (!hasProperty(config, channel)) {
976
- builder[channel] = (handler: unknown) => makeInvokeBuilder({ ...config, [channel]: handler }, channels)
977
- }
978
- }
979
- return Object.freeze(builder) as unknown as InvokeBuilderDescriptor
980
- }
981
-
982
- const invokeSelector = Object.freeze({
983
- effect: (id: string, effect: unknown) => makeInvokeBuilder({ id, effect }, ["onDone", "onFailure"]),
984
- stream: (id: string, stream: unknown) => makeInvokeBuilder({ id, stream }, ["onElement", "onDone", "onFailure"]),
985
- timer: (id: string, after: unknown) => makeInvokeBuilder({ id, after }, ["onDone"]),
986
- logic: (id: string, options: Readonly<Record<PropertyKey, unknown>>) =>
987
- makeInvokeBuilder({ id, ...options }, ["onSnapshot", "onDone", "onFailure"]),
988
- child: (child: unknown, options?: Readonly<Record<PropertyKey, unknown>>) =>
989
- makeInvokeBuilder(options === undefined ? { child } : { child, ...options }, [
990
- "onSnapshot",
991
- "onDone",
992
- "onFailure"
993
- ])
994
- })
995
-
996
- const invokeBuilderConfig = (value: unknown, path: string): Readonly<Record<PropertyKey, unknown>> => {
997
- if (
998
- typeof value !== "object" || value === null ||
999
- !hasProperty(value, InvokeBuilderDescriptorTypeId) ||
1000
- value[InvokeBuilderDescriptorTypeId] !== InvokeBuilderDescriptorTypeId
1001
- ) {
1002
- throw new Error(`Machine invocation for state "${path}" must be constructed from its source selector`)
1003
- }
1004
- return (value as unknown as InvokeBuilderDescriptor).config
1005
- }
1006
-
1007
819
  const captureInvokeDefinition = (
1008
820
  invoke: unknown,
1009
821
  stateNodes: Machine.StateNodes,
1010
- path: string
822
+ path: string,
823
+ declaration: Declaration.Declaration
1011
824
  ): unknown => {
1012
- if (typeof invoke !== "function") {
1013
- throw new Error(`Machine invocation for state "${path}" must be a source-first callback`)
1014
- }
1015
- const authored = invoke(invokeSelector)
1016
- const definitions = Array.isArray(authored) ? authored : [authored]
825
+ const definitions = Array.isArray(invoke) ? invoke : [invoke]
1017
826
  const capturedDefinitions = definitions.map((definition) => {
1018
- const captured = { ...invokeBuilderConfig(definition, path) }
827
+ const captured = Declaration.invocation(
828
+ declaration,
829
+ definition,
830
+ path,
831
+ (context) => objectContext(context as Record<string, any>, path)
832
+ )
1019
833
  for (const key of ["onElement", "onDone", "onFailure", "onSnapshot"] as const) {
1020
834
  if (captured[key] !== undefined) {
1021
- captured[key] = captureTransition(captured[key], stateNodes, path, key)
835
+ captured[key] = captureTransition(captured[key], stateNodes, path, declaration, key)
1022
836
  }
1023
837
  }
1024
838
  return InvocationDefinition.capture(captured, path)
1025
839
  })
1026
- if (Array.isArray(authored)) return Object.freeze(capturedDefinitions)
840
+ if (Array.isArray(invoke)) return Object.freeze(capturedDefinitions)
1027
841
  return capturedDefinitions[0]
1028
842
  }
1029
843
 
1030
844
  const flattenHandlers = (
1031
- handlers: Record<PropertyKey, Machine.AnyStateConfig>,
845
+ handlers: Record<PropertyKey, CapturedStateConfig>,
1032
846
  stateNodes: Machine.StateNodes,
1033
847
  states: Machine.StateTree,
1034
848
  prefix: string,
849
+ declaration: Declaration.Declaration,
1035
850
  config: Record<string, unknown>
1036
851
  ): void => {
1037
852
  for (const key of Object.keys(config)) {
@@ -1054,20 +869,20 @@ const flattenHandlers = (
1054
869
  }
1055
870
  const on = stateConfig.on
1056
871
  if (typeof on === "object" && on !== null) {
1057
- const capturedOn = captureEventHandlers(on, stateNodes, path)
872
+ const capturedOn = captureEventHandlers(on, stateNodes, path, declaration)
1058
873
  stateConfig.on = capturedOn
1059
874
  }
1060
875
  if (stateConfig.always !== undefined) {
1061
- stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, "always")
876
+ stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, declaration, "always")
1062
877
  }
1063
878
  if (stateConfig.onDone !== undefined) {
1064
- stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, "done")
879
+ stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, declaration, "done")
1065
880
  }
1066
881
  if (stateConfig.choice !== undefined) {
1067
- stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, "choice")
882
+ stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, declaration, "choice")
1068
883
  }
1069
884
  if (stateConfig.invoke !== undefined) {
1070
- stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path)
885
+ stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path, declaration)
1071
886
  }
1072
887
  const node = stateNodes.byPath.get(path)
1073
888
  if (node?.type === "choice") {
@@ -1080,7 +895,7 @@ const flattenHandlers = (
1080
895
  throw new Error(`Machine choice state "${path}" requires a transition`)
1081
896
  }
1082
897
  }
1083
- handlers[path] = stateConfig as Machine.AnyStateConfig
898
+ handlers[path] = stateConfig as CapturedStateConfig
1084
899
  if (childConfig !== undefined) {
1085
900
  const node = Topology.getStateNodeDefinition(path, states[key]!)
1086
901
  if (node.states === undefined) {
@@ -1089,15 +904,15 @@ const flattenHandlers = (
1089
904
  if (typeof childConfig !== "object" || childConfig === null) {
1090
905
  throw new Error(`Machine expected state "${path}" child handlers to be an object`)
1091
906
  }
1092
- flattenHandlers(handlers, stateNodes, node.states, path, childConfig as Record<string, unknown>)
907
+ flattenHandlers(handlers, stateNodes, node.states, path, declaration, childConfig as Record<string, unknown>)
1093
908
  }
1094
909
  }
1095
910
  }
1096
911
 
1097
- const makeHandle = (self: Definition.Any): Definition.Any["handle"] =>
912
+ const makeHandle = (self: Definition.Any, declaration: Declaration.Declaration): Definition.Any["handle"] =>
1098
913
  ((config: Record<string, unknown>) => {
1099
- const handlers: Record<PropertyKey, Machine.AnyStateConfig> = Object.create(null)
1100
- flattenHandlers(handlers, self.stateNodes, self.states, "", { "": config })
914
+ const handlers: Record<PropertyKey, CapturedStateConfig> = Object.create(null)
915
+ flattenHandlers(handlers, self.stateNodes, self.states, "", declaration, { "": config })
1101
916
  return makeWithHandlers(self, handlers)
1102
917
  }) as Definition.Any["handle"]
1103
918
 
@@ -1294,6 +1109,12 @@ export const make = <
1294
1109
  config: {
1295
1110
  readonly id?: string
1296
1111
  readonly root: State<Machine.StateNodeConfig>
1112
+ readonly effects?: unknown
1113
+ readonly streams?: unknown
1114
+ readonly timers?: unknown
1115
+ readonly logic?: unknown
1116
+ readonly children?: unknown
1117
+ readonly branches?: unknown
1297
1118
  readonly initialConfiguration?: unknown
1298
1119
  readonly events: Machine.EventProtocol<"public", InputEvents>
1299
1120
  readonly internalEvents?: Machine.EventProtocol<"internal", InternalEvents>
@@ -1324,7 +1145,7 @@ export const make = <
1324
1145
  self.initialDefinition = compiledInitial.definition
1325
1146
  self.makeTargetBuilder = makeTargetBuilder(states, self.stateNodes)
1326
1147
  self.handlers = Object.create(null)
1327
- self.handle = makeHandle(self)
1148
+ self.handle = makeHandle(self, Declaration.capture(config.root, config))
1328
1149
  Protocol.setProtocol(self)
1329
1150
  return self
1330
1151
  }