@typeonce/effect-machine 0.35.0 → 0.37.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 (72) hide show
  1. package/README.md +45 -7
  2. package/dist/Machine.d.ts +143 -136
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +25 -0
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/command.d.ts +0 -1
  7. package/dist/internal/machine/command.d.ts.map +1 -1
  8. package/dist/internal/machine/command.js +0 -14
  9. package/dist/internal/machine/command.js.map +1 -1
  10. package/dist/internal/machine/configuration.d.ts.map +1 -1
  11. package/dist/internal/machine/configuration.js +15 -2
  12. package/dist/internal/machine/configuration.js.map +1 -1
  13. package/dist/internal/machine/construction.d.ts +9 -0
  14. package/dist/internal/machine/construction.d.ts.map +1 -0
  15. package/dist/internal/machine/construction.js +132 -0
  16. package/dist/internal/machine/construction.js.map +1 -0
  17. package/dist/internal/machine/declaration.d.ts +1 -0
  18. package/dist/internal/machine/declaration.d.ts.map +1 -1
  19. package/dist/internal/machine/declaration.js +4 -8
  20. package/dist/internal/machine/declaration.js.map +1 -1
  21. package/dist/internal/machine/executionPlan.d.ts.map +1 -1
  22. package/dist/internal/machine/executionPlan.js +13 -9
  23. package/dist/internal/machine/executionPlan.js.map +1 -1
  24. package/dist/internal/machine/implementation.d.ts +2 -3
  25. package/dist/internal/machine/implementation.d.ts.map +1 -1
  26. package/dist/internal/machine/implementation.js.map +1 -1
  27. package/dist/internal/machine/invocation.d.ts +1 -0
  28. package/dist/internal/machine/invocation.d.ts.map +1 -1
  29. package/dist/internal/machine/invocation.js +26 -3
  30. package/dist/internal/machine/invocation.js.map +1 -1
  31. package/dist/internal/machine/invocationDefinition.d.ts +3 -1
  32. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  33. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  34. package/dist/internal/machine/machine.d.ts +6 -0
  35. package/dist/internal/machine/machine.d.ts.map +1 -1
  36. package/dist/internal/machine/machine.js +70 -168
  37. package/dist/internal/machine/machine.js.map +1 -1
  38. package/dist/internal/machine/observation.d.ts +3 -0
  39. package/dist/internal/machine/observation.d.ts.map +1 -0
  40. package/dist/internal/machine/observation.js +28 -0
  41. package/dist/internal/machine/observation.js.map +1 -0
  42. package/dist/internal/machine/planner.d.ts.map +1 -1
  43. package/dist/internal/machine/planner.js +63 -17
  44. package/dist/internal/machine/planner.js.map +1 -1
  45. package/dist/internal/machine/topology.d.ts +6 -0
  46. package/dist/internal/machine/topology.d.ts.map +1 -1
  47. package/dist/internal/machine/topology.js.map +1 -1
  48. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  49. package/dist/internal/testing/machine/finiteModel.js +36 -76
  50. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  51. package/docs/agent-guide.md +57 -34
  52. package/docs/root-api.md +143 -190
  53. package/package.json +1 -1
  54. package/src/Machine.ts +223 -144
  55. package/src/internal/machine/command.ts +0 -16
  56. package/src/internal/machine/configuration.ts +13 -10
  57. package/src/internal/machine/construction.ts +147 -0
  58. package/src/internal/machine/declaration.ts +5 -7
  59. package/src/internal/machine/executionPlan.ts +13 -9
  60. package/src/internal/machine/implementation.ts +2 -3
  61. package/src/internal/machine/invocation.ts +34 -3
  62. package/src/internal/machine/invocationDefinition.ts +1 -0
  63. package/src/internal/machine/machine.ts +89 -223
  64. package/src/internal/machine/observation.ts +39 -0
  65. package/src/internal/machine/planner.ts +69 -18
  66. package/src/internal/machine/topology.ts +4 -0
  67. package/src/internal/testing/machine/finiteModel.ts +44 -122
  68. package/dist/internal/machine/targetBuilder.d.ts +0 -16
  69. package/dist/internal/machine/targetBuilder.d.ts.map +0 -1
  70. package/dist/internal/machine/targetBuilder.js +0 -333
  71. package/dist/internal/machine/targetBuilder.js.map +0 -1
  72. package/src/internal/machine/targetBuilder.ts +0 -525
@@ -0,0 +1,147 @@
1
+ /** Converts public construction objects into owned planner instructions. */
2
+ import type { Machine } from "../../Machine.js"
3
+ import * as Topology from "./topology.js"
4
+
5
+ export const record = (value: unknown): Readonly<Record<string, unknown>> => {
6
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
7
+ throw new Error("Machine construction must be an object")
8
+ }
9
+ return value as Readonly<Record<string, unknown>>
10
+ }
11
+
12
+ const nodeValue = (node: Machine.StateNode, config: Readonly<Record<string, unknown>>): unknown => {
13
+ if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
14
+ throw new Error("Machine decoded construction flag must be a boolean")
15
+ }
16
+ if (node.schema === undefined) {
17
+ if (Object.hasOwn(config, "data") || Object.hasOwn(config, "decoded")) {
18
+ throw new Error(`Machine structural state "${node.path}" cannot construct data`)
19
+ }
20
+ return undefined
21
+ }
22
+ if (config.decoded === true) {
23
+ if (!Object.hasOwn(config, "data")) throw new Error("Machine decoded construction requires data")
24
+ return config.data
25
+ }
26
+ return Topology.makeStateInput(Object.hasOwn(config, "data") ? config.data : {})
27
+ }
28
+
29
+ export const target = (
30
+ nodes: Machine.StateNodes,
31
+ path: string,
32
+ raw: unknown = {},
33
+ source?: string
34
+ ): unknown => {
35
+ const selectedNode = nodes.byPath.get(path)
36
+ if (selectedNode?.type === "atomic" || selectedNode?.type === "final") {
37
+ const config = record(raw)
38
+ if (Reflect.ownKeys(config).some((key) => key !== "data" && key !== "decoded")) {
39
+ throw new Error("Machine leaf construction accepts only data and decoded")
40
+ }
41
+ return Topology.makeTarget(path, nodeValue(selectedNode, config) as { readonly _tag: PropertyKey })
42
+ }
43
+ const children = new Map<string, unknown>()
44
+ const visit = (path: string, raw: unknown): unknown => {
45
+ const config = record(raw)
46
+ if (Reflect.ownKeys(config).some((key) => key !== "data" && key !== "decoded" && key !== "states")) {
47
+ throw new Error("Machine state construction accepts only data, decoded, and states")
48
+ }
49
+ const node = nodes.byPath.get(path)
50
+ if (node === undefined || node.type === "history") throw new Error(`Machine invalid construction state "${path}"`)
51
+ const value = nodeValue(node, config)
52
+ if (Object.hasOwn(config, "states")) {
53
+ if (node.type !== "compound" && node.type !== "parallel") {
54
+ throw new Error(`Machine state "${path}" has no child construction`)
55
+ }
56
+ const states = record(config.states)
57
+ const keys = Reflect.ownKeys(states)
58
+ const active = node.children.filter((child) => nodes.byPath.get(child)?.type !== "history")
59
+ if (
60
+ node.type === "compound"
61
+ ? keys.length !== 1
62
+ : keys.length !== active.length &&
63
+ !(keys.length === 1 && source !== undefined && (source === path || source.startsWith(`${path}.`)))
64
+ ) {
65
+ throw new Error(
66
+ `Machine explicit states for "${path}" must select ${node.type === "compound" ? "one child" : "every region"}`
67
+ )
68
+ }
69
+ for (const key of keys) {
70
+ const child = path === "" ? String(key) : `${path}.${String(key)}`
71
+ if (
72
+ typeof key !== "string" ||
73
+ !(nodes.byPath.get(child)?.parent === path && nodes.byPath.get(child)?.type !== "history")
74
+ ) throw new Error(`Machine unknown child "${String(key)}"`)
75
+ children.set(child, visit(child, states[key]))
76
+ }
77
+ }
78
+ return value
79
+ }
80
+ const value = visit(path, raw)
81
+ const values = new Map(children)
82
+ values.set(path, value)
83
+ let selected = path
84
+ let config = record(raw)
85
+ while (config.states !== undefined) {
86
+ const node = nodes.byPath.get(selected)!
87
+ const states = record(config.states)
88
+ const keys = Object.keys(states)
89
+ if (
90
+ keys.length !== 1 ||
91
+ (node.type === "parallel" &&
92
+ !(source !== undefined && (source === selected || source.startsWith(`${selected}.`))))
93
+ ) break
94
+ const key = keys[0]!
95
+ selected = selected === "" ? key : `${selected}.${key}`
96
+ config = record(states[key])
97
+ }
98
+ const node = nodes.byPath.get(selected)!
99
+ const selectedValue = values.get(selected)
100
+ const ancestors = Object.fromEntries(
101
+ [...values].filter(([p, v]) => v !== undefined && p !== selected && !p.startsWith(`${selected}.`))
102
+ )
103
+ if (node.type === "choice") return Topology.makeChoiceTarget(selected, node.parent ?? "", ancestors)
104
+ if (node.type === "atomic" || node.type === "final") {
105
+ return Topology.makeTarget(selected, selectedValue as { readonly _tag: PropertyKey }, {
106
+ values: ancestors as Readonly<Record<string, { readonly _tag: PropertyKey }>>
107
+ })
108
+ }
109
+ const descendants = new Map([...children].filter(([p]) => p.startsWith(`${selected}.`)))
110
+ return {
111
+ ...Topology.makeInitialTarget(selected, selectedValue, ancestors),
112
+ ...(descendants.size === 0 ? {} : { children: descendants })
113
+ }
114
+ }
115
+
116
+ export const update = (nodes: Machine.StateNodes, path: string, raw: unknown): Topology.StateUpdate => {
117
+ const config = record(raw)
118
+ if (Reflect.ownKeys(config).some((key) => key !== "data" && key !== "decoded")) {
119
+ throw new Error("Machine update construction accepts only data and decoded")
120
+ }
121
+ const node = nodes.byPath.get(path)
122
+ if (node?.schema === undefined) throw new Error("Machine update requires a valued state")
123
+ return Topology.makeStateUpdate(path, nodeValue(node, config))
124
+ }
125
+
126
+ /** History fallbacks construct a complete tree, including the history owner. */
127
+ export const snapshot = (nodes: Machine.StateNodes, raw: unknown, path = ""): unknown => {
128
+ const config = record(raw)
129
+ const node = nodes.byPath.get(path)!
130
+ target(nodes, path, config)
131
+ const value = nodeValue(node, config)
132
+ if (node.type === "choice") return Topology.makeChoiceTarget(path, node.parent!)
133
+ if (node.type === "atomic" || node.type === "final") return { path, value }
134
+ if (config.states === undefined) {
135
+ throw new Error("Machine history fallback requires a complete explicit tree")
136
+ }
137
+ const states = record(config.states)
138
+ const children = Object.fromEntries(
139
+ Object.entries(states).map(([key, child]) => [
140
+ key,
141
+ snapshot(nodes, child, path === "" ? key : `${path}.${key}`)
142
+ ])
143
+ )
144
+ return node.type === "parallel" ?
145
+ { path, value, states: children }
146
+ : { path, value, state: Object.values(children)[0] }
147
+ }
@@ -12,6 +12,7 @@ interface Source {
12
12
  readonly value: unknown
13
13
  }
14
14
  export interface Declaration {
15
+ readonly initialize?: (input: unknown) => unknown
15
16
  readonly root: State<Machine.StateNodeConfig>
16
17
  readonly sources: ReadonlyMap<string, Source>
17
18
  readonly branches: ReadonlyMap<string, Readonly<Record<string, Readonly<Record<string, unknown>>>>>
@@ -50,7 +51,7 @@ export const capture = (
50
51
  const spec = { ...record(value, `Machine branch "${name}.${key}" must be a declaration`) }
51
52
  for (const field of Reflect.ownKeys(spec)) {
52
53
  if (
53
- typeof field !== "string" || !["target", "update", "initial", "history", "none", "title"].includes(field)
54
+ typeof field !== "string" || !["target", "update", "history", "none", "title"].includes(field)
54
55
  ) {
55
56
  throw new Error(`Machine branch "${name}.${key}" contains an unknown declaration field`)
56
57
  }
@@ -76,7 +77,7 @@ export const selection = (
76
77
  declaration: Declaration,
77
78
  config: Readonly<Record<string, unknown>>
78
79
  ): Topology.TargetSelection => {
79
- const keys = ["target", "initial", "history", "none"].filter((key) => config[key] !== undefined)
80
+ const keys = ["target", "history", "none"].filter((key) => config[key] !== undefined)
80
81
  if (keys.length === 0 && config.update !== undefined) {
81
82
  const owner = reference(config.update, declaration.root)
82
83
  if (owner.kind !== "state") throw new Error("Machine update requires an active state reference")
@@ -91,17 +92,13 @@ export const selection = (
91
92
  return Topology.noneTargetSelection
92
93
  }
93
94
  const ref = reference(config[key], declaration.root)
94
- if (ref.path === "") throw new Error("Machine root data changes use update; transitions select a descendant")
95
95
  if ((key === "history") !== (ref.kind === "history")) {
96
96
  throw new Error("Machine history references require a history transition")
97
97
  }
98
- if (key === "initial" && ref.kind !== "state") {
99
- throw new Error("Machine initial entry requires an active state reference")
100
- }
101
98
  const update = config.update === undefined ? undefined : reference(config.update, declaration.root).path
102
99
  if (update !== undefined && key !== "target") throw new Error("Machine owner updates require an ordinary destination")
103
100
  return Topology.makeTargetSelection(
104
- key === "initial" ? "initial" : ref.kind,
101
+ ref.kind,
105
102
  ref.path,
106
103
  key === "history" ? "full" : "branch",
107
104
  update
@@ -134,6 +131,7 @@ export const invocation = (
134
131
  const field = { effects: "effect", streams: "stream", timers: "after", logic: "logic" }[source.kind]
135
132
  return {
136
133
  ...rest,
134
+ sourceName: src,
137
135
  id: rest.id ?? src,
138
136
  [field]: !parameterized && (source.kind === "timers" || source.kind === "logic") ? source.value : resolve
139
137
  }
@@ -6,7 +6,7 @@
6
6
 
7
7
  import * as Effect from "effect/Effect"
8
8
  import type { Machine, MachineTarget } from "../../Machine.js"
9
- import { getTargetBuilder, type RuntimeCommand } from "./command.js"
9
+ import { type RuntimeCommand } from "./command.js"
10
10
  import {
11
11
  type ActiveConfiguration,
12
12
  compareDocumentOrder,
@@ -391,7 +391,6 @@ const makeIndexedTransitionContext = (
391
391
  event: any,
392
392
  machineReferences?: PlanningMachineReferences
393
393
  ): any => {
394
- const source = descriptor.nodes[sourceIndex]!
395
394
  const parentIndex = descriptor.parentIndices[sourceIndex]!
396
395
  const ancestors: Record<string, unknown> = {}
397
396
  for (const ancestorIndex of descriptor.ancestorIndices[sourceIndex]!) {
@@ -405,8 +404,7 @@ const makeIndexedTransitionContext = (
405
404
  containingState: parentIndex < 0 ? undefined : configuration.values[parentIndex],
406
405
  ancestors,
407
406
  event,
408
- snapshot: snapshotFromIndexedState(descriptor, configuration),
409
- target: getTargetBuilder(machine, source.path)
407
+ snapshot: snapshotFromIndexedState(descriptor, configuration)
410
408
  }
411
409
  }
412
410
 
@@ -539,7 +537,8 @@ const normalizeIndexedTargetStateSync = (
539
537
  const targetIndex = isTarget(target) ? descriptor.indexByPath.get(String(target.path)) : undefined
540
538
  if (
541
539
  targetIndex === activeLeafIndex && current.active[activeLeafIndex] === 1 && isTarget(target) &&
542
- target[TargetSnapshotTypeId] === undefined && target.values === undefined && current.completedOrder.length === 0
540
+ target[TargetSnapshotTypeId] === undefined && target.values === undefined && current.completedOrder.length === 0 &&
541
+ descriptor.valued[activeLeafIndex]
543
542
  ) {
544
543
  const values = current.values.slice()
545
544
  values[activeLeafIndex] = decodeStateValueSync(
@@ -601,7 +600,12 @@ const collectIndexedEvaluatedTransition = (
601
600
  const initialResolution = unresolvedTarget !== undefined && isInitialTarget(unresolvedTarget)
602
601
  ? resolveInitialTarget(
603
602
  machine,
604
- activeConfigurationFromIndexedState(descriptor, state),
603
+ (() => {
604
+ const current = activeConfigurationFromIndexedState(descriptor, state)
605
+ return update === undefined
606
+ ? current
607
+ : { ...current, values: new Map(current.values).set(update.path, update.value) }
608
+ })(),
605
609
  unresolvedTarget,
606
610
  (selection.context as any).event
607
611
  )
@@ -830,8 +834,7 @@ const planIndexedFlatState = (
830
834
  containingState: undefined,
831
835
  ancestors: {},
832
836
  event,
833
- snapshot: snapshotFromIndexedState(descriptor, current),
834
- target: getTargetBuilder(machine, sourcePath)
837
+ snapshot: snapshotFromIndexedState(descriptor, current)
835
838
  },
836
839
  transition.evaluate
837
840
  )
@@ -861,7 +864,8 @@ const planIndexedFlatState = (
861
864
  ? target[TargetSnapshotTypeId] === undefined && target.values === undefined
862
865
  : !("state" in target) && !("states" in target) && !("completed" in target) && !("history" in target)
863
866
  if (
864
- targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0
867
+ targetIndex === sourceIndex && isSimpleTarget && current.completedOrder.length === 0 &&
868
+ descriptor.valued[sourceIndex]
865
869
  ) {
866
870
  updateOwnedIndexedValue(
867
871
  current,
@@ -28,13 +28,12 @@ export interface CapturedStateConfig {
28
28
  /**
29
29
  * Captured machine implementation consumed by semantic layers.
30
30
  *
31
- * The public erased view retains its existing fields for compatibility. Internal
32
- * code enters through this view so handler lookup cannot silently produce `any`.
31
+ * Internal code enters through this view so handler lookup cannot silently
32
+ * produce `any`.
33
33
  * Construction captures these containers before handing the machine to a planner.
34
34
  */
35
35
  export interface MachineInternal extends Machine.Any {
36
36
  readonly handlers: Readonly<Record<string, CapturedStateConfig | undefined>>
37
- readonly makeTargetBuilder: (source: string) => Machine.TargetBuilder<any, any>
38
37
  }
39
38
 
40
39
  /** The single conversion from an erased public machine to its captured implementation. */
@@ -19,6 +19,7 @@ import { ChildMachineLogicTypeId } from "./symbols.js"
19
19
  /** @internal */
20
20
  export interface AnyConfig {
21
21
  readonly id: string
22
+ readonly sourceName?: string | undefined
22
23
  readonly address?: string
23
24
  readonly descriptor?: ChildMachine.Any
24
25
  readonly src: () => Runtime.ProcessLogic<any, any, any, any, any, any>
@@ -82,6 +83,7 @@ const resolveOne = (
82
83
  if ("effect" in raw) {
83
84
  return {
84
85
  id: String(raw.id),
86
+ sourceName: raw.sourceName,
85
87
  src: () =>
86
88
  oneShot(raw.effect(context) as Effect.Effect<any, any, any>) as unknown as Runtime.ProcessLogic<
87
89
  any,
@@ -100,6 +102,7 @@ const resolveOne = (
100
102
  if ("after" in raw) {
101
103
  return {
102
104
  id: String(raw.id),
105
+ sourceName: raw.sourceName,
103
106
  src: () =>
104
107
  oneShot(Effect.sleep(resolveValue(raw.after, context) as any)) as unknown as Runtime.ProcessLogic<
105
108
  any,
@@ -117,6 +120,7 @@ const resolveOne = (
117
120
  const id = String(raw.id)
118
121
  return {
119
122
  id,
123
+ sourceName: raw.sourceName,
120
124
  src: () =>
121
125
  streamLogic(raw.stream(context), path, id) as unknown as Runtime.ProcessLogic<any, any, any, any, any, any>,
122
126
  onDone: raw.onDone,
@@ -192,11 +196,37 @@ const startResolved = (
192
196
  onDone: unknown,
193
197
  onFailure: unknown,
194
198
  onSnapshot: unknown,
195
- activityKind?: Inspection.Activity["kind"]
199
+ activityKind?: Inspection.Activity["kind"],
200
+ sourceName?: string
196
201
  ): Effect.Effect<void, any, any> =>
197
202
  Effect.suspend(() => {
198
203
  const key = makeKey(path, invokeId)
199
- return ownedChildren.spawn(src, {
204
+ // Source construction keeps its startup failure boundary. Only the hosted
205
+ // program is wrapped; child statecharts retain their execution descriptors.
206
+ const tracedSource = activityKind === undefined ? src : () => {
207
+ const logic = src()
208
+ return {
209
+ ...logic,
210
+ run: (context: Runtime.ProcessContext<any, any>) =>
211
+ Effect.withSpan(
212
+ Effect.suspend(() => logic.run(context)),
213
+ "Machine.invoke",
214
+ {
215
+ attributes: {
216
+ "machine.id": scope.self.id,
217
+ "machine.sessionId": scope.self.sessionId,
218
+ "machine.state.path": path,
219
+ "machine.invoke.id": invokeId,
220
+ "machine.invoke.source": sourceName ?? invokeId,
221
+ "machine.invoke.kind": activityKind,
222
+ "machine.invoke.sessionId": context.self.sessionId
223
+ },
224
+ captureStackTrace: false
225
+ }
226
+ )
227
+ }
228
+ }
229
+ return ownedChildren.spawn(tracedSource, {
200
230
  key,
201
231
  path,
202
232
  id: childId,
@@ -260,7 +290,8 @@ const start = (
260
290
  config.onDone,
261
291
  config.onFailure,
262
292
  config.onSnapshot,
263
- config.activityKind
293
+ config.activityKind,
294
+ config.sourceName
264
295
  )
265
296
  }
266
297
 
@@ -16,6 +16,7 @@ interface Outcomes {
16
16
 
17
17
  export type InvocationDefinition =
18
18
  & Outcomes
19
+ & { readonly sourceName?: string }
19
20
  & (
20
21
  | { readonly id: string; readonly effect: (context: Context) => Effect.Effect<unknown, unknown, unknown> }
21
22
  | { readonly id: string; readonly stream: (context: Context) => Stream.Stream<unknown, unknown, unknown> }