@typeonce/effect-machine 0.33.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 -636
  2. package/dist/Machine.d.ts +815 -583
  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 +140 -278
  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 +62 -62
  85. package/package.json +1 -1
  86. package/src/Machine.ts +1514 -2312
  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 +199 -409
  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
@@ -6,23 +6,26 @@ import { hasProperty } from "effect/Predicate";
6
6
  import * as Schema from "effect/Schema";
7
7
  import * as Activities from "./activities.js";
8
8
  import * as Configuration from "./configuration.js";
9
+ import * as Declaration from "./declaration.js";
9
10
  import * as InvocationDefinition from "./invocationDefinition.js";
10
11
  import * as internalPlanner from "./planner.js";
11
12
  import * as internalProcess from "./process.js";
12
13
  import * as Protocol from "./protocol.js";
13
- import * as internalRuntime from "./runtime.js";
14
+ import * as internalRuntime from "./runtimeProtocol.js";
14
15
  import * as Serialization from "./serialization.js";
15
16
  import * as StateDefinition from "./stateDefinition.js";
16
17
  import { ChildMachineLogicTypeId } from "./symbols.js";
17
18
  import { getLocalTargetScope, getTargetBuilderNode, makeSnapshotBuilder, makeTargetBuilder, withFrom } from "./targetBuilder.js";
19
+ import * as TargetReference from "./targetReference.js";
18
20
  import * as Topology from "./topology.js";
19
21
  export { ChildAlreadyExistsError, InfiniteTransitionError, MachineSchemaDecodeError, MachineSchemaEncodeError, ProcessLocalError, StartupError, StoppedError } from "./errors.js";
20
22
  export { ChildMachineLogicTypeId, InitialEventTypeId, SnapshotBuilderStateTypeId } from "./symbols.js";
23
+ /** Internal seam for the public target-reference factory and its opaque brand. */
24
+ export const TargetReferenceTypeId = TargetReference.TypeId;
25
+ export const targets = TargetReference.make;
21
26
  const TypeId = "~effect/Machine";
22
27
  const ParentTypeId = "~effect/Machine/Parent";
23
28
  export const InvokeTypeId = Symbol.for("effect/Machine/Invoke");
24
- export const TransitionTypeId = Symbol.for("effect/Machine/Transition");
25
- const InvokeBuilderDescriptorTypeId = Symbol("effect/Machine/InvokeBuilderDescriptor");
26
29
  const ChildMachineTypeId = "~effect/Machine/ChildMachine";
27
30
  const Proto = {
28
31
  ...Inspectable.BaseProto,
@@ -52,32 +55,10 @@ const makeWithHandlers = (self, handlers) => {
52
55
  Protocol.copyProtocol(self, machine);
53
56
  return machine;
54
57
  };
55
- const TransitionBuilderDescriptorTypeId = Symbol("effect/Machine/TransitionBuilderDescriptor");
56
58
  const InitialBuilderDescriptorTypeId = Symbol("effect/Machine/InitialBuilderDescriptor");
57
59
  const plainTargetSelection = (selection) => selection.kind === "none"
58
60
  ? Topology.noneTargetSelection
59
61
  : Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, selection.updatePath);
60
- const transitionOptions = (options) => {
61
- const configuration = typeof options === "object" && options !== null
62
- ? options
63
- : {};
64
- if (hasProperty(configuration, "reenter")) {
65
- throw new Error("Use .reenter() before construction instead of the resolver reenter option");
66
- }
67
- return { declinable: configuration.declinable === true };
68
- };
69
- const makeDirectTransitionDescriptor = (selection, resolve, options, reenterSource = false) => {
70
- const shared = {
71
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
72
- type: "direct",
73
- selection: plainTargetSelection(selection),
74
- reenterSource,
75
- ...transitionOptions(options)
76
- };
77
- return resolve === undefined
78
- ? Object.freeze(shared)
79
- : Object.freeze({ ...shared, resolver: resolve });
80
- };
81
62
  // The authored callback crosses an erased schema boundary here. Each builder
82
63
  // retains its construction mode, and planning validates both resulting values.
83
64
  const constructSelectionValue = (selection, context, method, value) => {
@@ -88,36 +69,6 @@ const constructSelectionValue = (selection, context, method, value) => {
88
69
  const values = value;
89
70
  return context.target[method](values.target).update(context.owner[method](values.update));
90
71
  };
91
- const guardedSelection = (selection, predicate, reenterSource) => {
92
- const wrap = (resolve, options) => makeDirectTransitionDescriptor(selection, (context, enqueue) => predicate(context) ? resolve(context, enqueue) : Topology.makeDeclined(), { ...transitionOptions(options), declinable: true }, reenterSource);
93
- return Object.freeze({
94
- ...wrap((context) => selection.kind === "none" ? undefined : constructSelectedTarget(context.target)),
95
- from: (value) => wrap((context) => constructSelectionValue(selection, context, "from", value(context))),
96
- decoded: (value) => wrap((context) => constructSelectionValue(selection, context, "decoded", value(context))),
97
- resolve: wrap
98
- });
99
- };
100
- const decorateTransitionSelection = (selection, reenterSource = false) => Object.freeze({
101
- ...selection,
102
- ...(reenterSource ? makeDirectTransitionDescriptor(selection, undefined, undefined, true) : {}),
103
- guard: (predicate) => guardedSelection(selection, predicate, reenterSource),
104
- from: (value) => makeDirectTransitionDescriptor(selection, (context) => constructSelectionValue(selection, context, "from", value(context)), undefined, reenterSource),
105
- decoded: (value) => makeDirectTransitionDescriptor(selection, (context) => constructSelectionValue(selection, context, "decoded", value(context)), undefined, reenterSource),
106
- resolve: (resolve, options) => makeDirectTransitionDescriptor(selection, resolve, options, reenterSource),
107
- reenter: () => decorateTransitionSelection(selection, true),
108
- updating: (owner) => {
109
- if (typeof owner !== "function") {
110
- throw new Error("Machine updating owner must be a state selector");
111
- }
112
- const ownerSelection = owner();
113
- if (!Topology.isTargetSelection(ownerSelection) || ownerSelection.kind !== "state" ||
114
- ownerSelection.scope !== "branch") {
115
- throw new Error("Machine updating owner must be addressed by one branch state selector");
116
- }
117
- return decorateTransitionSelection(Topology.makeTargetSelection(selection.kind, selection.path, selection.scope, ownerSelection.path), reenterSource);
118
- }
119
- });
120
- const noneTransitionSelection = decorateTransitionSelection(Topology.noneTargetSelection);
121
72
  const makeInitialBuilderDescriptor = (selection, resolve) => Object.freeze({
122
73
  [InitialBuilderDescriptorTypeId]: InitialBuilderDescriptorTypeId,
123
74
  selection: plainTargetSelection(selection),
@@ -148,71 +99,6 @@ const decorateInitialSelectorNode = (node) => {
148
99
  }
149
100
  return node;
150
101
  };
151
- const decorateTransitionSelectorNode = (node) => {
152
- if (Topology.isTargetSelection(node)) {
153
- if (node.kind === "state" && node.scope === "full" && hasProperty(node, "initial")) {
154
- return Object.freeze({
155
- ...decorateTransitionSelection(node),
156
- initial: decorateTransitionSelection(node.initial)
157
- });
158
- }
159
- return node === Topology.noneTargetSelection ? noneTransitionSelection : decorateTransitionSelection(node);
160
- }
161
- if (typeof node === "function") {
162
- const wrapped = ((...args) => decorateTransitionSelection(node(...args)));
163
- for (const key of Object.keys(node)) {
164
- wrapped[key] = decorateTransitionSelectorNode(node[key]);
165
- }
166
- return Object.freeze(wrapped);
167
- }
168
- if (typeof node === "object" && node !== null) {
169
- const wrapped = {};
170
- for (const key of Object.keys(node)) {
171
- wrapped[key] = decorateTransitionSelectorNode(node[key]);
172
- }
173
- return Object.freeze(wrapped);
174
- }
175
- return node;
176
- };
177
- const decorateBranches = (declarations, reenterSource = false) => Object.freeze({
178
- reenter: () => decorateBranches(declarations, true),
179
- resolve: (resolve, options) => Object.freeze({
180
- [TransitionBuilderDescriptorTypeId]: TransitionBuilderDescriptorTypeId,
181
- type: "branches",
182
- declarations,
183
- resolve,
184
- reenterSource,
185
- ...transitionOptions(options)
186
- })
187
- });
188
- const makeTransitionSelector = (stateNodes, source) => Object.freeze({
189
- ...decorateTransitionSelectorNode(makeTargetSelector(stateNodes, source)),
190
- branches: (declarations) => decorateBranches(declarations)
191
- });
192
- const normalizeTransitionBuilder = (transition, stateNodes, path) => {
193
- const result = transition(makeTransitionSelector(stateNodes, path));
194
- if (Topology.isTargetSelection(result) && !hasProperty(result, TransitionBuilderDescriptorTypeId)) {
195
- const selection = plainTargetSelection(result);
196
- return { target: () => selection };
197
- }
198
- if (!hasProperty(result, TransitionBuilderDescriptorTypeId))
199
- return result;
200
- const descriptor = result;
201
- if (descriptor.type === "branches") {
202
- return {
203
- branches: () => descriptor.declarations,
204
- resolve: descriptor.resolve,
205
- reenter: descriptor.reenterSource,
206
- declinable: descriptor.declinable
207
- };
208
- }
209
- return {
210
- target: () => descriptor.selection,
211
- resolve: descriptor.resolver,
212
- reenter: descriptor.reenterSource,
213
- declinable: descriptor.declinable
214
- };
215
- };
216
102
  const transitionTargetSelection = (selection) => Object.freeze({
217
103
  path: selection.path,
218
104
  kind: selection.kind,
@@ -221,90 +107,8 @@ const transitionTargetSelection = (selection) => Object.freeze({
221
107
  const selectionUpdates = (selection) => selection.updatePath === undefined ?
222
108
  selection.kind === "update" && selection.path !== undefined ? [selection.path] : []
223
109
  : [selection.updatePath];
224
- const makeSelectionMethod = (kind, path, scope) => () => Topology.makeTargetSelection(kind, path, scope);
225
110
  const makeSelectionValue = (kind, path, scope) => Topology.makeTargetSelection(kind, path, scope);
226
111
  const makeStateUpdateSelection = (path, scope) => Topology.makeTargetSelection("update", path, scope);
227
- const addSelectionChildren = (builder, stateNodes, parent, scope, source) => {
228
- for (const node of stateNodes.byPath.values()) {
229
- if (node.parent !== parent || node.type === "history")
230
- continue;
231
- builder[node.key] = makeSelectionNode(stateNodes, node.path, scope, source);
232
- }
233
- };
234
- const makeSelectionNode = (stateNodes, path, scope, source) => {
235
- const node = getTargetBuilderNode(stateNodes, path);
236
- const kind = node.type === "choice" ? "choice" : "state";
237
- const method = makeSelectionMethod(kind, path, scope);
238
- if (node.type !== "atomic" && node.type !== "final" && node.type !== "choice" && node.type !== "history") {
239
- Object.defineProperty(method, "initial", {
240
- value: makeSelectionValue("initial", path, scope),
241
- enumerable: true
242
- });
243
- if (scope === "local" || scope === "branch") {
244
- addSelectionChildren(method, stateNodes, path, scope, source);
245
- }
246
- if (scope === "branch" && source !== undefined && node.schema !== undefined &&
247
- (source === path || Configuration.isDescendantOf(source, path)) &&
248
- getTargetBuilderNode(stateNodes, source).type !== "choice") {
249
- Object.defineProperty(method, "update", {
250
- value: makeStateUpdateSelection(path, "branch"),
251
- enumerable: true
252
- });
253
- }
254
- }
255
- if (node.type === "atomic" && scope === "branch" && source === path && node.schema !== undefined) {
256
- Object.defineProperty(method, "update", { value: makeStateUpdateSelection(path, "branch"), enumerable: true });
257
- }
258
- return method;
259
- };
260
- const makeHistorySelectionTree = (stateNodes, parent) => {
261
- const builder = {};
262
- for (const node of stateNodes.byPath.values()) {
263
- if (node.parent !== parent)
264
- continue;
265
- if (node.type === "history") {
266
- builder[node.key] = makeSelectionValue("history", node.path, "full");
267
- }
268
- else if (node.type !== "choice") {
269
- const children = makeHistorySelectionTree(stateNodes, node.path);
270
- if (Object.keys(children).length > 0)
271
- builder[node.key] = children;
272
- }
273
- }
274
- return builder;
275
- };
276
- const makeTargetSelector = (stateNodes, source) => {
277
- const full = Object.assign({}, makeSelectionValue("state", "", "full"), {
278
- initial: makeSelectionValue("initial", "", "full")
279
- });
280
- const branch = {};
281
- const root = getTargetBuilderNode(stateNodes, stateNodes.roots[0]);
282
- addSelectionChildren(branch, stateNodes, root.path, "branch", source);
283
- const local = {};
284
- const localScope = getLocalTargetScope(stateNodes, source);
285
- if (localScope !== undefined) {
286
- const localScopeNode = getTargetBuilderNode(stateNodes, localScope);
287
- if (localScopeNode.schema !== undefined) {
288
- local.with = makeSelectionValue("state", localScope, "local");
289
- if (getTargetBuilderNode(stateNodes, source).type !== "choice") {
290
- local.update = makeStateUpdateSelection(localScope, "local");
291
- }
292
- }
293
- addSelectionChildren(local, stateNodes, localScope, "local");
294
- }
295
- return {
296
- none: Topology.noneTargetSelection,
297
- self: getTargetBuilderNode(stateNodes, source).schema === undefined ||
298
- getTargetBuilderNode(stateNodes, source).type === "final"
299
- ? {}
300
- : { update: makeStateUpdateSelection(source, "branch") },
301
- root: makeSelectionNode(stateNodes, root.path, "branch", source),
302
- local,
303
- branch,
304
- full,
305
- history: makeHistorySelectionTree(stateNodes, "")
306
- };
307
- };
308
112
  const captureDefinitionBranch = (branch, selector, stateNodes, path, trigger) => {
309
113
  if (typeof branch !== "object" || branch === null || !hasProperty(branch, "target") ||
310
114
  typeof branch.target !== "function") {
@@ -436,7 +240,12 @@ const runCapturedBranch = (branch, context, enqueue, stateNodes, source) => {
436
240
  const selectedTarget = getSelectionBuilder(context.target, branch.selection, stateNodes, source);
437
241
  if (branch.resolve === undefined)
438
242
  return constructSelectedTarget(selectedTarget);
439
- const resolverContext = { ...context };
243
+ // This fresh context is owned by this evaluation and can be retained by user callbacks.
244
+ const resolverContext = {
245
+ ...context,
246
+ root: source === "" ? context.state : context.ancestors[""],
247
+ decline: Topology.makeDeclined
248
+ };
440
249
  if (branch.selection.kind === "none")
441
250
  delete resolverContext.target;
442
251
  else
@@ -452,8 +261,6 @@ const runCapturedBranch = (branch, context, enqueue, stateNodes, source) => {
452
261
  resolverContext.current = context.ancestors[ownerPath];
453
262
  resolverContext.owner = getSelectionBuilder(context.target, makeStateUpdateSelection(ownerPath, "branch"), stateNodes, source);
454
263
  }
455
- if (branch.declinable === true)
456
- resolverContext.decline = Topology.makeDeclined;
457
264
  const resolved = branch.resolve(resolverContext, enqueue);
458
265
  if (Topology.isDeclined(resolved)) {
459
266
  if (branch.declinable !== true) {
@@ -492,21 +299,23 @@ const captureNamedBranches = (declarations, path, trigger) => {
492
299
  if (!Topology.isTargetSelection(target)) {
493
300
  throw new Error(`Machine transition branch "${key}" must select exactly one target`);
494
301
  }
495
- if (target.updatePath !== undefined) {
496
- throw new Error(`Machine transition branch "${key}" cannot declare an updating target`);
497
- }
498
- if (hasProperty(target, TransitionBuilderDescriptorTypeId)) {
499
- throw new Error(`Machine transition branch "${key}" requires a topology selection; apply .reenter() to .branches(...)`);
500
- }
501
302
  if (title !== undefined && (typeof title !== "string" || title.length === 0)) {
502
303
  throw new Error(`Machine transition branch "${key}" title must be a non-empty string`);
503
304
  }
504
305
  return Object.freeze({ key, title: title ?? key, selection: plainTargetSelection(target) });
505
306
  }));
506
307
  };
507
- const wrapSelectedBranchBuilder = (builder, owner, branchIndex, branchKey) => {
308
+ const wrapSelectedBranchBuilder = (builder, owner, branchIndex, branchKey, updateBuilder) => {
508
309
  if (typeof builder === "function") {
509
- const wrapped = (...args) => Topology.makeSelectedBranch(owner, branchIndex, branchKey, builder(...args));
310
+ const wrapped = (...args) => {
311
+ const result = builder(...args);
312
+ if (updateBuilder !== undefined) {
313
+ return Object.freeze({
314
+ update: Object.freeze(Object.fromEntries(Object.getOwnPropertyNames(updateBuilder).map((method) => [method, (value) => Topology.makeSelectedBranch(owner, branchIndex, branchKey, result.update(updateBuilder[method](value)))])))
315
+ });
316
+ }
317
+ return Topology.makeSelectedBranch(owner, branchIndex, branchKey, result);
318
+ };
510
319
  for (const property of Reflect.ownKeys(builder)) {
511
320
  if (property === "length" || property === "name" || property === "prototype" || property === "caller" ||
512
321
  property === "arguments")
@@ -515,7 +324,7 @@ const wrapSelectedBranchBuilder = (builder, owner, branchIndex, branchKey) => {
515
324
  if (descriptor === undefined)
516
325
  continue;
517
326
  if ("value" in descriptor && typeof descriptor.value === "function") {
518
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey);
327
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder);
519
328
  }
520
329
  Object.defineProperty(wrapped, property, descriptor);
521
330
  }
@@ -528,7 +337,7 @@ const wrapSelectedBranchBuilder = (builder, owner, branchIndex, branchKey) => {
528
337
  if (descriptor === undefined)
529
338
  continue;
530
339
  if ("value" in descriptor && typeof descriptor.value === "function") {
531
- descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey);
340
+ descriptor.value = wrapSelectedBranchBuilder(descriptor.value, owner, branchIndex, branchKey, updateBuilder);
532
341
  }
533
342
  Object.defineProperty(wrapped, property, descriptor);
534
343
  }
@@ -540,7 +349,9 @@ const makeBranchSelectors = (context, branches, owner, stateNodes, source) => {
540
349
  const select = Object.create(null);
541
350
  for (let branchIndex = 0; branchIndex < branches.length; branchIndex++) {
542
351
  const branch = branches[branchIndex];
543
- select[branch.key] = wrapSelectedBranchBuilder(getSelectionBuilder(context.target, branch.selection, stateNodes, source), owner, branchIndex, branch.key);
352
+ select[branch.key] = wrapSelectedBranchBuilder(getSelectionBuilder(context.target, branch.selection, stateNodes, source), owner, branchIndex, branch.key, branch.selection.updatePath === undefined
353
+ ? undefined
354
+ : getSelectionBuilder(context.target, makeStateUpdateSelection(branch.selection.updatePath, "branch"), stateNodes, source));
544
355
  }
545
356
  return Object.freeze(select);
546
357
  };
@@ -556,16 +367,100 @@ const validateSelectedBranchResult = (result, selection, stateNodes) => {
556
367
  }
557
368
  validateResolvedSelection(result, selection, stateNodes);
558
369
  };
559
- const captureTransition = (rawTransition, stateNodes, path, trigger) => {
560
- if (typeof rawTransition !== "function") {
561
- throw new Error(`Machine transition for state "${path}" on "${String(trigger)}" must be a target-first callback`);
370
+ // Invocation input contexts do not pass through captured transition evaluation.
371
+ const objectContext = (context, path) => ({
372
+ ...context,
373
+ root: path === "" ? context.state : context.ancestors[""]
374
+ });
375
+ const normalizeObjectTransition = (raw, declaration, path, stateNodes) => {
376
+ if (typeof raw !== "object" || raw === null)
377
+ throw new Error(`Machine transition for "${path}" must be an object`);
378
+ const config = { ...raw };
379
+ const allowed = [
380
+ "target",
381
+ "update",
382
+ "initial",
383
+ "history",
384
+ "none",
385
+ "branches",
386
+ "from",
387
+ "decoded",
388
+ "resolve",
389
+ "guard",
390
+ "reenter",
391
+ "declinable"
392
+ ];
393
+ for (const key of Reflect.ownKeys(config)) {
394
+ if (typeof key !== "string" || !allowed.includes(key)) {
395
+ throw new Error("Machine transition contains an unknown field");
396
+ }
397
+ }
398
+ for (const key of ["from", "decoded", "resolve", "guard"]) {
399
+ if (config[key] !== undefined && typeof config[key] !== "function") {
400
+ throw new Error(`Machine transition ${key} must be a function`);
401
+ }
402
+ }
403
+ const guard = typeof config.guard === "function" ? config.guard : undefined;
404
+ const resolve = typeof config.resolve === "function" ? config.resolve : undefined;
405
+ const construct = typeof config.from === "function"
406
+ ? config.from
407
+ : typeof config.decoded === "function"
408
+ ? config.decoded
409
+ : undefined;
410
+ const methods = ["from", "decoded", "resolve"].filter((key) => config[key] !== undefined);
411
+ if (methods.length > 1)
412
+ throw new Error("Machine transition construction methods are mutually exclusive");
413
+ const guarded = guard !== undefined;
414
+ const declinable = guarded || config.declinable === true;
415
+ if (typeof config.branches === "string") {
416
+ const group = declaration.branches.get(config.branches);
417
+ if (group === undefined || resolve === undefined) {
418
+ throw new Error("Machine branching transition requires a registered group and resolver");
419
+ }
420
+ if (["target", "update", "initial", "history", "none", "from", "decoded"].some((key) => config[key] !== undefined))
421
+ throw new Error("Machine branching transition cannot redeclare its destination");
422
+ const entries = Object.fromEntries(Object.entries(group).map(([key, spec]) => [key, {
423
+ title: spec.title,
424
+ target: captureDefinitionBranch({ target: () => Declaration.selection(declaration, spec) }, undefined, stateNodes, path, key).selection
425
+ }]));
426
+ return {
427
+ branches: () => entries,
428
+ reenter: config.reenter,
429
+ declinable,
430
+ resolve: (context, enqueue) => {
431
+ return guarded && !guard(context) ? Topology.makeDeclined() : resolve(context, enqueue);
432
+ }
433
+ };
434
+ }
435
+ const selection = Declaration.selection(declaration, config);
436
+ if (resolve !== undefined && selection.kind !== "none") {
437
+ throw new Error("Machine advanced construction requires a declared branch group");
562
438
  }
563
- const transition = normalizeTransitionBuilder(rawTransition, stateNodes, path);
439
+ const method = config.from !== undefined ? "from" : config.decoded !== undefined ? "decoded" : undefined;
440
+ return {
441
+ target: () => selection,
442
+ reenter: config.reenter,
443
+ declinable,
444
+ ...(!guarded && method === undefined && resolve === undefined ? {} : {
445
+ resolve: (context, enqueue) => {
446
+ if (guarded && !guard(context))
447
+ return Topology.makeDeclined();
448
+ if (method !== undefined && construct !== undefined) {
449
+ return constructSelectionValue(selection, context, method, construct(context));
450
+ }
451
+ if (resolve !== undefined)
452
+ return resolve(context, enqueue);
453
+ return selection.kind === "none" ? undefined : constructSelectedTarget(context.target);
454
+ }
455
+ })
456
+ };
457
+ };
458
+ const captureTransition = (rawTransition, stateNodes, path, declaration, trigger) => {
459
+ const transition = normalizeObjectTransition(rawTransition, declaration, path, stateNodes);
564
460
  if (typeof transition !== "object" || transition === null) {
565
461
  throw new Error(`Machine transition for state "${path}" on "${String(trigger)}" must be an object`);
566
462
  }
567
463
  const definition = transition;
568
- const selector = makeTargetSelector(stateNodes, path);
569
464
  const reenter = definition.reenter === true;
570
465
  const declinable = definition.declinable === true;
571
466
  if (hasProperty(definition, "branches")) {
@@ -574,14 +469,16 @@ const captureTransition = (rawTransition, stateNodes, path, trigger) => {
574
469
  throw new Error(`Machine branching transition for state "${path}" on "${String(trigger)}" requires branches and resolve`);
575
470
  }
576
471
  const resolve = branching.resolve;
577
- const branches = captureNamedBranches(branching.branches(selector), path, trigger);
472
+ const branches = captureNamedBranches(branching.branches(), path, trigger);
578
473
  const owner = Object.freeze({});
579
474
  const evaluate = (context, enqueue) => {
580
- const resolverContext = { ...context };
475
+ const resolverContext = {
476
+ ...context,
477
+ root: path === "" ? context.state : context.ancestors[""],
478
+ decline: Topology.makeDeclined
479
+ };
581
480
  delete resolverContext.target;
582
481
  resolverContext.select = makeBranchSelectors(context, branches, owner, stateNodes, path);
583
- if (declinable)
584
- resolverContext.decline = Topology.makeDeclined;
585
482
  const selected = resolve(resolverContext, enqueue);
586
483
  if (Topology.isDeclined(selected)) {
587
484
  if (!declinable) {
@@ -621,7 +518,7 @@ const captureTransition = (rawTransition, stateNodes, path, trigger) => {
621
518
  transition: (context, enqueue) => evaluate(context, enqueue).result
622
519
  };
623
520
  }
624
- const branch = captureDefinitionBranch(transition, selector, stateNodes, path, trigger);
521
+ const branch = captureDefinitionBranch(transition, undefined, stateNodes, path, trigger);
625
522
  const evaluate = (context, enqueue) => ({
626
523
  result: runCapturedBranch(branch, context, enqueue, stateNodes, path),
627
524
  branchIndex: 0,
@@ -641,67 +538,32 @@ const captureTransition = (rawTransition, stateNodes, path, trigger) => {
641
538
  transition: (context, enqueue) => evaluate(context, enqueue).result
642
539
  };
643
540
  };
644
- const captureEventHandlers = (on, stateNodes, path) => {
541
+ const captureEventHandlers = (on, stateNodes, path, declaration) => {
645
542
  // The machine owns its dispatch table. Compiled plans may snapshot these
646
543
  // definitions, so retaining caller-owned containers would let strategies
647
544
  // observe different handlers after an unsafe external mutation.
648
545
  const captured = Object.create(null);
649
546
  for (const event of Reflect.ownKeys(on)) {
650
- captured[event] = captureTransition(on[event], stateNodes, path, event);
547
+ captured[event] = captureTransition(on[event], stateNodes, path, declaration, event);
651
548
  }
652
549
  return captured;
653
550
  };
654
- const makeInvokeBuilder = (config, channels) => {
655
- const builder = {
656
- [InvokeBuilderDescriptorTypeId]: InvokeBuilderDescriptorTypeId,
657
- config
658
- };
659
- for (const channel of channels) {
660
- if (!hasProperty(config, channel)) {
661
- builder[channel] = (handler) => makeInvokeBuilder({ ...config, [channel]: handler }, channels);
662
- }
663
- }
664
- return Object.freeze(builder);
665
- };
666
- const invokeSelector = Object.freeze({
667
- effect: (id, effect) => makeInvokeBuilder({ id, effect }, ["onDone", "onFailure"]),
668
- stream: (id, stream) => makeInvokeBuilder({ id, stream }, ["onElement", "onDone", "onFailure"]),
669
- timer: (id, after) => makeInvokeBuilder({ id, after }, ["onDone"]),
670
- logic: (id, options) => makeInvokeBuilder({ id, ...options }, ["onSnapshot", "onDone", "onFailure"]),
671
- child: (child, options) => makeInvokeBuilder(options === undefined ? { child } : { child, ...options }, [
672
- "onSnapshot",
673
- "onDone",
674
- "onFailure"
675
- ])
676
- });
677
- const invokeBuilderConfig = (value, path) => {
678
- if (typeof value !== "object" || value === null ||
679
- !hasProperty(value, InvokeBuilderDescriptorTypeId) ||
680
- value[InvokeBuilderDescriptorTypeId] !== InvokeBuilderDescriptorTypeId) {
681
- throw new Error(`Machine invocation for state "${path}" must be constructed from its source selector`);
682
- }
683
- return value.config;
684
- };
685
- const captureInvokeDefinition = (invoke, stateNodes, path) => {
686
- if (typeof invoke !== "function") {
687
- throw new Error(`Machine invocation for state "${path}" must be a source-first callback`);
688
- }
689
- const authored = invoke(invokeSelector);
690
- const definitions = Array.isArray(authored) ? authored : [authored];
551
+ const captureInvokeDefinition = (invoke, stateNodes, path, declaration) => {
552
+ const definitions = Array.isArray(invoke) ? invoke : [invoke];
691
553
  const capturedDefinitions = definitions.map((definition) => {
692
- const captured = { ...invokeBuilderConfig(definition, path) };
554
+ const captured = Declaration.invocation(declaration, definition, path, (context) => objectContext(context, path));
693
555
  for (const key of ["onElement", "onDone", "onFailure", "onSnapshot"]) {
694
556
  if (captured[key] !== undefined) {
695
- captured[key] = captureTransition(captured[key], stateNodes, path, key);
557
+ captured[key] = captureTransition(captured[key], stateNodes, path, declaration, key);
696
558
  }
697
559
  }
698
560
  return InvocationDefinition.capture(captured, path);
699
561
  });
700
- if (Array.isArray(authored))
562
+ if (Array.isArray(invoke))
701
563
  return Object.freeze(capturedDefinitions);
702
564
  return capturedDefinitions[0];
703
565
  };
704
- const flattenHandlers = (handlers, stateNodes, states, prefix, config) => {
566
+ const flattenHandlers = (handlers, stateNodes, states, prefix, declaration, config) => {
705
567
  for (const key of Object.keys(config)) {
706
568
  const path = prefix === "" ? key : `${prefix}.${key}`;
707
569
  if (!hasProperty(states, key)) {
@@ -720,20 +582,20 @@ const flattenHandlers = (handlers, stateNodes, states, prefix, config) => {
720
582
  }
721
583
  const on = stateConfig.on;
722
584
  if (typeof on === "object" && on !== null) {
723
- const capturedOn = captureEventHandlers(on, stateNodes, path);
585
+ const capturedOn = captureEventHandlers(on, stateNodes, path, declaration);
724
586
  stateConfig.on = capturedOn;
725
587
  }
726
588
  if (stateConfig.always !== undefined) {
727
- stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, "always");
589
+ stateConfig.always = captureTransition(stateConfig.always, stateNodes, path, declaration, "always");
728
590
  }
729
591
  if (stateConfig.onDone !== undefined) {
730
- stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, "done");
592
+ stateConfig.onDone = captureTransition(stateConfig.onDone, stateNodes, path, declaration, "done");
731
593
  }
732
594
  if (stateConfig.choice !== undefined) {
733
- stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, "choice");
595
+ stateConfig.choice = captureTransition(stateConfig.choice, stateNodes, path, declaration, "choice");
734
596
  }
735
597
  if (stateConfig.invoke !== undefined) {
736
- stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path);
598
+ stateConfig.invoke = captureInvokeDefinition(stateConfig.invoke, stateNodes, path, declaration);
737
599
  }
738
600
  const node = stateNodes.byPath.get(path);
739
601
  if (node?.type === "choice") {
@@ -753,13 +615,13 @@ const flattenHandlers = (handlers, stateNodes, states, prefix, config) => {
753
615
  if (typeof childConfig !== "object" || childConfig === null) {
754
616
  throw new Error(`Machine expected state "${path}" child handlers to be an object`);
755
617
  }
756
- flattenHandlers(handlers, stateNodes, node.states, path, childConfig);
618
+ flattenHandlers(handlers, stateNodes, node.states, path, declaration, childConfig);
757
619
  }
758
620
  }
759
621
  };
760
- const makeHandle = (self) => ((config) => {
622
+ const makeHandle = (self, declaration) => ((config) => {
761
623
  const handlers = Object.create(null);
762
- flattenHandlers(handlers, self.stateNodes, self.states, "", { "": config });
624
+ flattenHandlers(handlers, self.stateNodes, self.states, "", declaration, { "": config });
763
625
  return makeWithHandlers(self, handlers);
764
626
  });
765
627
  export const isMachine = (u) => hasProperty(u, TypeId) && u[TypeId] === TypeId;
@@ -865,7 +727,7 @@ export const make = (config) => {
865
727
  self.initialDefinition = compiledInitial.definition;
866
728
  self.makeTargetBuilder = makeTargetBuilder(states, self.stateNodes);
867
729
  self.handlers = Object.create(null);
868
- self.handle = makeHandle(self);
730
+ self.handle = makeHandle(self, Declaration.capture(config.root, config));
869
731
  Protocol.setProtocol(self);
870
732
  return self;
871
733
  };