@typeonce/effect-machine 0.34.0 → 0.36.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.
- package/README.md +98 -33
- package/dist/Machine.d.ts +408 -483
- package/dist/Machine.d.ts.map +1 -1
- package/dist/Machine.js +126 -87
- package/dist/Machine.js.map +1 -1
- package/dist/internal/machine/command.d.ts +0 -1
- package/dist/internal/machine/command.d.ts.map +1 -1
- package/dist/internal/machine/command.js +0 -14
- package/dist/internal/machine/command.js.map +1 -1
- package/dist/internal/machine/configuration.d.ts +0 -1
- package/dist/internal/machine/configuration.d.ts.map +1 -1
- package/dist/internal/machine/configuration.js +15 -21
- package/dist/internal/machine/configuration.js.map +1 -1
- package/dist/internal/machine/construction.d.ts +9 -0
- package/dist/internal/machine/construction.d.ts.map +1 -0
- package/dist/internal/machine/construction.js +132 -0
- package/dist/internal/machine/construction.js.map +1 -0
- package/dist/internal/machine/declaration.d.ts +1 -0
- package/dist/internal/machine/declaration.d.ts.map +1 -1
- package/dist/internal/machine/declaration.js +3 -8
- package/dist/internal/machine/declaration.js.map +1 -1
- package/dist/internal/machine/executionPlan.d.ts.map +1 -1
- package/dist/internal/machine/executionPlan.js +21 -27
- package/dist/internal/machine/executionPlan.js.map +1 -1
- package/dist/internal/machine/implementation.d.ts +2 -3
- package/dist/internal/machine/implementation.d.ts.map +1 -1
- package/dist/internal/machine/implementation.js.map +1 -1
- package/dist/internal/machine/initialDeclaration.d.ts +14 -0
- package/dist/internal/machine/initialDeclaration.d.ts.map +1 -0
- package/dist/internal/machine/initialDeclaration.js +137 -0
- package/dist/internal/machine/initialDeclaration.js.map +1 -0
- package/dist/internal/machine/machine.d.ts +0 -2
- package/dist/internal/machine/machine.d.ts.map +1 -1
- package/dist/internal/machine/machine.js +101 -282
- package/dist/internal/machine/machine.js.map +1 -1
- package/dist/internal/machine/planner.d.ts +8 -0
- package/dist/internal/machine/planner.d.ts.map +1 -1
- package/dist/internal/machine/planner.js +86 -82
- package/dist/internal/machine/planner.js.map +1 -1
- package/dist/internal/machine/protocol.d.ts +1 -1
- package/dist/internal/machine/protocol.d.ts.map +1 -1
- package/dist/internal/machine/protocol.js.map +1 -1
- package/dist/internal/machine/stateDefinition.d.ts +1 -1
- package/dist/internal/machine/stateDefinition.d.ts.map +1 -1
- package/dist/internal/machine/stateDefinition.js +1 -13
- package/dist/internal/machine/stateDefinition.js.map +1 -1
- package/dist/internal/machine/targetReference.d.ts.map +1 -1
- package/dist/internal/machine/targetReference.js +14 -4
- package/dist/internal/machine/targetReference.js.map +1 -1
- package/dist/internal/machine/topology.d.ts +6 -0
- package/dist/internal/machine/topology.d.ts.map +1 -1
- package/dist/internal/machine/topology.js +3 -2
- package/dist/internal/machine/topology.js.map +1 -1
- package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
- package/dist/internal/testing/machine/finiteModel.js +51 -82
- package/dist/internal/testing/machine/finiteModel.js.map +1 -1
- package/dist/internal/testing/machine/verification.d.ts.map +1 -1
- package/dist/internal/testing/machine/verification.js +7 -1
- package/dist/internal/testing/machine/verification.js.map +1 -1
- package/dist/testing/MachineTest.d.ts +105 -73
- package/dist/testing/MachineTest.d.ts.map +1 -1
- package/dist/testing/MachineTest.js +105 -73
- package/dist/testing/MachineTest.js.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.d.ts +13 -8
- package/dist/unstable/cluster/ClusterMachine.d.ts.map +1 -1
- package/dist/unstable/cluster/ClusterMachine.js +13 -8
- package/dist/unstable/cluster/ClusterMachine.js.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.d.ts +41 -24
- package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
- package/dist/unstable/reactivity/AtomMachine.js +41 -24
- package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
- package/docs/agent-guide.md +37 -34
- package/docs/root-api.md +143 -190
- package/package.json +1 -1
- package/src/Machine.ts +631 -872
- package/src/internal/machine/command.ts +0 -16
- package/src/internal/machine/configuration.ts +13 -30
- package/src/internal/machine/construction.ts +147 -0
- package/src/internal/machine/declaration.ts +4 -7
- package/src/internal/machine/executionPlan.ts +20 -25
- package/src/internal/machine/implementation.ts +2 -3
- package/src/internal/machine/initialDeclaration.ts +157 -0
- package/src/internal/machine/machine.ts +118 -396
- package/src/internal/machine/planner.ts +97 -99
- package/src/internal/machine/protocol.ts +3 -3
- package/src/internal/machine/stateDefinition.ts +1 -15
- package/src/internal/machine/targetReference.ts +19 -4
- package/src/internal/machine/topology.ts +7 -2
- package/src/internal/testing/machine/finiteModel.ts +60 -132
- package/src/internal/testing/machine/verification.ts +7 -1
- package/src/testing/MachineTest.ts +105 -73
- package/src/unstable/cluster/ClusterMachine.ts +13 -8
- package/src/unstable/reactivity/AtomMachine.ts +41 -24
- package/dist/internal/machine/targetBuilder.d.ts +0 -16
- package/dist/internal/machine/targetBuilder.d.ts.map +0 -1
- package/dist/internal/machine/targetBuilder.js +0 -333
- package/dist/internal/machine/targetBuilder.js.map +0 -1
- package/src/internal/machine/targetBuilder.ts +0 -525
|
@@ -16,22 +16,6 @@ export interface Collected<Event> {
|
|
|
16
16
|
readonly emittedEvents: Array<unknown>
|
|
17
17
|
}
|
|
18
18
|
|
|
19
|
-
const targetBuilderCache = new WeakMap<object, Map<string, unknown>>()
|
|
20
|
-
|
|
21
|
-
export const getTargetBuilder = (machine: Machine.Any, path: string): any => {
|
|
22
|
-
let byPath = targetBuilderCache.get(machine)
|
|
23
|
-
if (byPath === undefined) {
|
|
24
|
-
byPath = new Map()
|
|
25
|
-
targetBuilderCache.set(machine, byPath)
|
|
26
|
-
}
|
|
27
|
-
if (byPath.has(path)) {
|
|
28
|
-
return byPath.get(path)
|
|
29
|
-
}
|
|
30
|
-
const builder = machine.makeTargetBuilder(path as any)
|
|
31
|
-
byPath.set(path, builder)
|
|
32
|
-
return builder
|
|
33
|
-
}
|
|
34
|
-
|
|
35
19
|
export const makeCollector = <Event>(machine: Machine.Any): Collected<Event> => {
|
|
36
20
|
const commands: Array<RuntimeCommand> = []
|
|
37
21
|
const raisedEvents: Array<Event> = []
|
|
@@ -672,26 +672,6 @@ export const normalizeConfigurationEffect = <const States extends Machine.StateS
|
|
|
672
672
|
})
|
|
673
673
|
)
|
|
674
674
|
|
|
675
|
-
export const validateInitialConfiguration = (machine: Machine.Any, configuration: ActiveConfiguration): void => {
|
|
676
|
-
for (const path of configuration.active) {
|
|
677
|
-
const node = getNode(machine, path)
|
|
678
|
-
if (node.type === "compound") {
|
|
679
|
-
const child = node.children.find((child) => configuration.active.has(child))
|
|
680
|
-
const initialNode = node.initial === undefined ? undefined : getNode(machine, node.initial)
|
|
681
|
-
if (initialNode?.type === "choice" ? child === undefined : child !== node.initial) {
|
|
682
|
-
throw new Error(`Machine initial state "${node.path}" must enter initial child "${node.initial}"`)
|
|
683
|
-
}
|
|
684
|
-
}
|
|
685
|
-
if (node.type === "parallel") {
|
|
686
|
-
for (const child of node.children) {
|
|
687
|
-
if (!configuration.active.has(child)) {
|
|
688
|
-
throw new Error(`Machine initial state "${node.path}" must enter child region "${child}"`)
|
|
689
|
-
}
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
}
|
|
693
|
-
}
|
|
694
|
-
|
|
695
675
|
/** Capture every history register whose owning parent exits in this microstep.
|
|
696
676
|
* The control record is deliberately independent from effects/actions: it is
|
|
697
677
|
* part of the logical snapshot and is therefore preserved by pure planning. */
|
|
@@ -1011,7 +991,7 @@ const configurationFromTargetPathSync = (
|
|
|
1011
991
|
|
|
1012
992
|
for (const ancestor of paths) {
|
|
1013
993
|
const ancestorNode = getNode(machine, ancestor)
|
|
1014
|
-
if (ancestorNode.type !== "parallel") continue
|
|
994
|
+
if (ancestorNode.type !== "parallel" || ancestor === node.path) continue
|
|
1015
995
|
for (const child of ancestorNode.children) {
|
|
1016
996
|
if (pathSet.has(child) || !current.active.has(child)) continue
|
|
1017
997
|
for (const activePath of current.active) {
|
|
@@ -1036,15 +1016,18 @@ export const configurationFromInitialTargetSync = (
|
|
|
1036
1016
|
machine: Machine.Any,
|
|
1037
1017
|
current: ActiveConfiguration,
|
|
1038
1018
|
target: InitialTargetInstruction
|
|
1039
|
-
): ActiveConfiguration =>
|
|
1040
|
-
configurationFromTargetPathSync(
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1019
|
+
): ActiveConfiguration => {
|
|
1020
|
+
const partial = configurationFromTargetPathSync(machine, current, target.path, target.value, target.values, true)
|
|
1021
|
+
if (target.children === undefined) return partial
|
|
1022
|
+
const active = new Set(partial.active)
|
|
1023
|
+
const values = new Map(partial.values)
|
|
1024
|
+
for (const [path, value] of target.children) {
|
|
1025
|
+
const node = getNode(machine, path)
|
|
1026
|
+
active.add(path)
|
|
1027
|
+
if (node.schema !== undefined) values.set(path, decodeStateValueSync(machine, node, value))
|
|
1028
|
+
}
|
|
1029
|
+
return { ...partial, active, values }
|
|
1030
|
+
}
|
|
1048
1031
|
|
|
1049
1032
|
const configurationFromTargetSnapshotSync = (
|
|
1050
1033
|
machine: Machine.Any,
|
|
@@ -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", "
|
|
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", "
|
|
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
|
-
|
|
101
|
+
ref.kind,
|
|
105
102
|
ref.path,
|
|
106
103
|
key === "history" ? "full" : "branch",
|
|
107
104
|
update
|
|
@@ -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 {
|
|
9
|
+
import { type RuntimeCommand } from "./command.js"
|
|
10
10
|
import {
|
|
11
11
|
type ActiveConfiguration,
|
|
12
12
|
compareDocumentOrder,
|
|
@@ -20,11 +20,11 @@ import {
|
|
|
20
20
|
normalizeTargetConfigurationSync,
|
|
21
21
|
type PlanningMachineReferences,
|
|
22
22
|
snapshotFromConfiguration,
|
|
23
|
-
validateInitialConfiguration,
|
|
24
23
|
withMachineReferences
|
|
25
24
|
} from "./configuration.js"
|
|
26
25
|
import { InfiniteTransitionError, StoppedError } from "./errors.js"
|
|
27
26
|
import { type CapturedStateConfig, toImpl } from "./implementation.js"
|
|
27
|
+
import { isDataInitializer } from "./initialDeclaration.js"
|
|
28
28
|
import * as InvocationEvent from "./invocationEvent.js"
|
|
29
29
|
import {
|
|
30
30
|
broadenTransitionBoundary,
|
|
@@ -39,6 +39,7 @@ import {
|
|
|
39
39
|
normalizeTransition,
|
|
40
40
|
planConfiguration,
|
|
41
41
|
removeConflictingTransitions,
|
|
42
|
+
resolveInitialConfiguration,
|
|
42
43
|
resolveInitialTarget,
|
|
43
44
|
type SelectedTransition,
|
|
44
45
|
sortEntryPaths,
|
|
@@ -213,7 +214,8 @@ const compileIndexedExecutionDescriptor = (
|
|
|
213
214
|
// the hierarchical planner so their entry and exit boundaries stay explicit.
|
|
214
215
|
flat: nodes.every((node) => node.parent === undefined && (node.type === "atomic" || node.type === "final")) || (
|
|
215
216
|
nodes[0]?.path === "" && nodes[0].type === "compound" && nodes[0].schema === undefined &&
|
|
216
|
-
(toImpl(machine).handlers[""] === undefined ||
|
|
217
|
+
(toImpl(machine).handlers[""] === undefined ||
|
|
218
|
+
Reflect.ownKeys(toImpl(machine).handlers[""]!).every((key) => key === "initialize")) &&
|
|
217
219
|
nodes.slice(1).every((node) => node.parent === "" && (node.type === "atomic" || node.type === "final")) &&
|
|
218
220
|
[...transitionsByPath.values()].every((events) =>
|
|
219
221
|
[...events.values()].every((transition) =>
|
|
@@ -389,7 +391,6 @@ const makeIndexedTransitionContext = (
|
|
|
389
391
|
event: any,
|
|
390
392
|
machineReferences?: PlanningMachineReferences
|
|
391
393
|
): any => {
|
|
392
|
-
const source = descriptor.nodes[sourceIndex]!
|
|
393
394
|
const parentIndex = descriptor.parentIndices[sourceIndex]!
|
|
394
395
|
const ancestors: Record<string, unknown> = {}
|
|
395
396
|
for (const ancestorIndex of descriptor.ancestorIndices[sourceIndex]!) {
|
|
@@ -403,8 +404,7 @@ const makeIndexedTransitionContext = (
|
|
|
403
404
|
containingState: parentIndex < 0 ? undefined : configuration.values[parentIndex],
|
|
404
405
|
ancestors,
|
|
405
406
|
event,
|
|
406
|
-
snapshot: snapshotFromIndexedState(descriptor, configuration)
|
|
407
|
-
target: getTargetBuilder(machine, source.path)
|
|
407
|
+
snapshot: snapshotFromIndexedState(descriptor, configuration)
|
|
408
408
|
}
|
|
409
409
|
}
|
|
410
410
|
|
|
@@ -599,7 +599,12 @@ const collectIndexedEvaluatedTransition = (
|
|
|
599
599
|
const initialResolution = unresolvedTarget !== undefined && isInitialTarget(unresolvedTarget)
|
|
600
600
|
? resolveInitialTarget(
|
|
601
601
|
machine,
|
|
602
|
-
|
|
602
|
+
(() => {
|
|
603
|
+
const current = activeConfigurationFromIndexedState(descriptor, state)
|
|
604
|
+
return update === undefined
|
|
605
|
+
? current
|
|
606
|
+
: { ...current, values: new Map(current.values).set(update.path, update.value) }
|
|
607
|
+
})(),
|
|
603
608
|
unresolvedTarget,
|
|
604
609
|
(selection.context as any).event
|
|
605
610
|
)
|
|
@@ -828,8 +833,7 @@ const planIndexedFlatState = (
|
|
|
828
833
|
containingState: undefined,
|
|
829
834
|
ancestors: {},
|
|
830
835
|
event,
|
|
831
|
-
snapshot: snapshotFromIndexedState(descriptor, current)
|
|
832
|
-
target: getTargetBuilder(machine, sourcePath)
|
|
836
|
+
snapshot: snapshotFromIndexedState(descriptor, current)
|
|
833
837
|
},
|
|
834
838
|
transition.evaluate
|
|
835
839
|
)
|
|
@@ -1130,10 +1134,10 @@ const makeIndexedExecutionPlan = (
|
|
|
1130
1134
|
snapshot: (state) => snapshotFromIndexedState(indexed, state as OwnedIndexedState),
|
|
1131
1135
|
plan: (state, event, retainMicrosteps = false, machineReferences) =>
|
|
1132
1136
|
planIndexedState(machine, indexed, state as OwnedIndexedState, event, retainMicrosteps, machineReferences),
|
|
1133
|
-
//
|
|
1134
|
-
//
|
|
1137
|
+
// Only captured data constructors can use indexed startup. Unknown initializer
|
|
1138
|
+
// protocols retain generic startup so commands and emissions cannot be dropped.
|
|
1135
1139
|
...(Object.values(toImpl(machine).handlers as Record<string, CapturedStateConfig>).some((config) =>
|
|
1136
|
-
|
|
1140
|
+
config.initialize !== undefined && !isDataInitializer(config.initialize)
|
|
1137
1141
|
) ?
|
|
1138
1142
|
{} :
|
|
1139
1143
|
{
|
|
@@ -1144,8 +1148,8 @@ const makeIndexedExecutionPlan = (
|
|
|
1144
1148
|
? (decodeInputSync(machine, machine.input, undefined), args)
|
|
1145
1149
|
: [decodeInputSync(machine, machine.input, args[0])]
|
|
1146
1150
|
const initial = machine.initial(...inputArgs as any)
|
|
1147
|
-
const
|
|
1148
|
-
?
|
|
1151
|
+
const normalized = isInitialTarget(initial)
|
|
1152
|
+
? resolveInitialConfiguration(
|
|
1149
1153
|
machine,
|
|
1150
1154
|
{
|
|
1151
1155
|
active: new Set(),
|
|
@@ -1156,20 +1160,11 @@ const makeIndexedExecutionPlan = (
|
|
|
1156
1160
|
},
|
|
1157
1161
|
initial,
|
|
1158
1162
|
InitialEvent
|
|
1159
|
-
).
|
|
1160
|
-
: initial
|
|
1161
|
-
const normalized = isInitialTarget(initial)
|
|
1162
|
-
? normalizeTargetConfigurationSync(machine, {
|
|
1163
|
-
active: new Set(),
|
|
1164
|
-
values: new Map(),
|
|
1165
|
-
outputs: new Map(),
|
|
1166
|
-
history: new Map()
|
|
1167
|
-
}, resolved)
|
|
1168
|
-
: normalizeConfigurationSync(machine, resolved as Machine.Snapshot<any>)
|
|
1163
|
+
).configuration
|
|
1164
|
+
: normalizeConfigurationSync(machine, initial as Machine.Snapshot<any>)
|
|
1169
1165
|
const active = machineReferences === undefined
|
|
1170
1166
|
? normalized
|
|
1171
1167
|
: withMachineReferences(normalized, machineReferences)
|
|
1172
|
-
if (machine.initialDefinition.selection.kind === "initial") validateInitialConfiguration(machine, active)
|
|
1173
1168
|
const completed = completeConfigurationSync(machine, active, InitialEvent).configuration
|
|
1174
1169
|
const configuration = ownedIndexedStateFromActive(indexed, completed)
|
|
1175
1170
|
const state = snapshotFromIndexedState(indexed, configuration)
|
|
@@ -28,13 +28,12 @@ export interface CapturedStateConfig {
|
|
|
28
28
|
/**
|
|
29
29
|
* Captured machine implementation consumed by semantic layers.
|
|
30
30
|
*
|
|
31
|
-
*
|
|
32
|
-
*
|
|
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. */
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
/** Captures handler-owned initial edges before compiling executable topology. */
|
|
2
|
+
import { hasProperty } from "effect/Predicate"
|
|
3
|
+
import * as Schema from "effect/Schema"
|
|
4
|
+
import type { Machine, State } from "../../Machine.js"
|
|
5
|
+
import { SnapshotBuilderStateTypeId } from "./symbols.js"
|
|
6
|
+
import * as Reference from "./targetReference.js"
|
|
7
|
+
import * as Topology from "./topology.js"
|
|
8
|
+
|
|
9
|
+
const initializers = new WeakSet<object>()
|
|
10
|
+
|
|
11
|
+
export const isDataInitializer = (value: object): boolean => initializers.has(value)
|
|
12
|
+
|
|
13
|
+
type Context = Readonly<Record<string, unknown>>
|
|
14
|
+
type Constructor = (context: Context) => unknown
|
|
15
|
+
const record = (value: unknown, label: string): Readonly<Record<string, unknown>> => {
|
|
16
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
17
|
+
throw new Error(`Machine ${label} must be an object`)
|
|
18
|
+
}
|
|
19
|
+
return value as Readonly<Record<string, unknown>>
|
|
20
|
+
}
|
|
21
|
+
const evaluate = (value: unknown): Constructor => typeof value === "function" ? value as Constructor : () => value
|
|
22
|
+
|
|
23
|
+
/** Only the outer declaration is interpreted; callback results are ordinary data. */
|
|
24
|
+
export const construction = (value: unknown): Constructor => {
|
|
25
|
+
const descriptor = typeof value === "object" && value !== null &&
|
|
26
|
+
hasProperty(value, "decoded") && value.decoded === true && hasProperty(value, "data")
|
|
27
|
+
if (descriptor) {
|
|
28
|
+
const config = record(value, "decoded construction")
|
|
29
|
+
if (Reflect.ownKeys(config).some((key) => key !== "decoded" && key !== "data")) {
|
|
30
|
+
throw new Error("Machine decoded construction accepts only decoded and data")
|
|
31
|
+
}
|
|
32
|
+
return evaluate(config.data)
|
|
33
|
+
}
|
|
34
|
+
const resolve = evaluate(value)
|
|
35
|
+
return (context) => Topology.makeStateInput(value === undefined ? {} : resolve(context))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export const edgeConstruction = (config: Readonly<Record<string, unknown>>): Constructor => {
|
|
39
|
+
if (config.decoded !== undefined && typeof config.decoded !== "boolean") {
|
|
40
|
+
throw new Error("Machine decoded construction flag must be a boolean")
|
|
41
|
+
}
|
|
42
|
+
if (config.decoded === true) {
|
|
43
|
+
if (!hasProperty(config, "data")) throw new Error("Machine decoded construction requires data")
|
|
44
|
+
return evaluate(config.data)
|
|
45
|
+
}
|
|
46
|
+
const resolve = evaluate(config.data)
|
|
47
|
+
return (context) => Topology.makeStateInput(hasProperty(config, "data") ? resolve(context) : {})
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
interface Captured {
|
|
51
|
+
readonly node: Machine.StateNodeConfig | Machine.TaggedSchema
|
|
52
|
+
readonly handlers: Record<string, unknown>
|
|
53
|
+
}
|
|
54
|
+
export const capture = (
|
|
55
|
+
root: State<Machine.StateNodeConfig>,
|
|
56
|
+
handler: Readonly<Record<string, unknown>>
|
|
57
|
+
): Captured => {
|
|
58
|
+
const visit = (
|
|
59
|
+
node: Machine.StateNodeConfig | Machine.TaggedSchema,
|
|
60
|
+
raw: Readonly<Record<string, unknown>>,
|
|
61
|
+
path: string
|
|
62
|
+
): Captured => {
|
|
63
|
+
if (hasProperty(raw, "initialize")) throw new Error("Machine child construction belongs in initial declarations")
|
|
64
|
+
if (path !== "" && hasProperty(raw, "root")) {
|
|
65
|
+
throw new Error("Machine root construction belongs at the root handler")
|
|
66
|
+
}
|
|
67
|
+
const { initial, root: _root, states: rawChildren, ...handlers } = raw
|
|
68
|
+
if (Schema.isSchema(node) || !("states" in node)) {
|
|
69
|
+
if (initial !== undefined) throw new Error(`Machine state "${path}" cannot declare initial children`)
|
|
70
|
+
if (rawChildren !== undefined) throw new Error(`Machine state "${path}" has no children`)
|
|
71
|
+
return { node, handlers }
|
|
72
|
+
}
|
|
73
|
+
const childHandlers = rawChildren === undefined ? {} : record(rawChildren, "child handlers")
|
|
74
|
+
for (const key of Object.keys(childHandlers)) {
|
|
75
|
+
if (!Object.prototype.hasOwnProperty.call(node.states, key)) throw new Error(`Machine unknown child "${key}"`)
|
|
76
|
+
}
|
|
77
|
+
const states: Record<string, Machine.StateNodeConfig | Machine.TaggedSchema> = Object.create(null)
|
|
78
|
+
const children: Record<string, unknown> = Object.create(null)
|
|
79
|
+
const constructors: Record<string, Constructor> = Object.create(null)
|
|
80
|
+
const parallel = node.type === "parallel"
|
|
81
|
+
let initialKey: string | undefined
|
|
82
|
+
if (parallel) {
|
|
83
|
+
const regions = initial === undefined ? {} : record(initial, "parallel initial regions")
|
|
84
|
+
for (const [key, value] of Object.entries(regions)) {
|
|
85
|
+
const child = node.states[key]
|
|
86
|
+
if (child === undefined || (!Schema.isSchema(child) && (child.type === "history" || child.type === "choice"))) {
|
|
87
|
+
throw new Error(`Machine invalid initial region "${key}"`)
|
|
88
|
+
}
|
|
89
|
+
if (!Schema.isSchema(child) && (!("schema" in child) || child.schema === undefined)) {
|
|
90
|
+
throw new Error(`Machine schema-less region "${key}" cannot construct data`)
|
|
91
|
+
}
|
|
92
|
+
constructors[key] = construction(value)
|
|
93
|
+
}
|
|
94
|
+
} else {
|
|
95
|
+
const edge = record(initial, `initial edge for "${path}"`)
|
|
96
|
+
if (Reflect.ownKeys(edge).some((key) => !["target", "data", "decoded"].includes(String(key)))) {
|
|
97
|
+
throw new Error("Machine initial edge accepts only target, data, and decoded")
|
|
98
|
+
}
|
|
99
|
+
if (!hasProperty(edge.target, Reference.TypeId)) throw new Error("Machine initial requires a target reference")
|
|
100
|
+
const ref = (edge.target as Reference.Reference)[Reference.TypeId]
|
|
101
|
+
const prefix = path === "" ? "" : `${path}.`
|
|
102
|
+
const key = ref.path.slice(prefix.length)
|
|
103
|
+
if (
|
|
104
|
+
ref.root !== root || !ref.path.startsWith(prefix) || key.includes(".") || !(key in node.states) ||
|
|
105
|
+
ref.kind === "history"
|
|
106
|
+
) {
|
|
107
|
+
throw new Error(`Machine initial target must be a direct child of "${path}"`)
|
|
108
|
+
}
|
|
109
|
+
initialKey = key
|
|
110
|
+
if (ref.kind === "choice" && (hasProperty(edge, "data") || hasProperty(edge, "decoded"))) {
|
|
111
|
+
throw new Error("Machine choice initial edges cannot construct data")
|
|
112
|
+
}
|
|
113
|
+
const construct = edgeConstruction(edge)
|
|
114
|
+
const child = node.states[key]!
|
|
115
|
+
if (
|
|
116
|
+
hasProperty(edge, "data") && !Schema.isSchema(child) && (!("schema" in child) || child.schema === undefined)
|
|
117
|
+
) {
|
|
118
|
+
throw new Error(`Machine schema-less initial child "${key}" cannot construct data`)
|
|
119
|
+
}
|
|
120
|
+
if (hasProperty(edge, "data")) constructors[key] = construct
|
|
121
|
+
}
|
|
122
|
+
for (const [key, child] of Object.entries(node.states)) {
|
|
123
|
+
const childPath = path === "" ? key : `${path}.${key}`
|
|
124
|
+
const captured = visit(
|
|
125
|
+
child,
|
|
126
|
+
childHandlers[key] === undefined ? {} : record(childHandlers[key], "state handler"),
|
|
127
|
+
childPath
|
|
128
|
+
)
|
|
129
|
+
states[key] = captured.node
|
|
130
|
+
// History configuration is owned by its parent, not a state handler.
|
|
131
|
+
if (
|
|
132
|
+
(Schema.isSchema(child) || child.type !== "history") &&
|
|
133
|
+
(childHandlers[key] !== undefined || (!Schema.isSchema(child) && "states" in child))
|
|
134
|
+
) children[key] = captured.handlers
|
|
135
|
+
}
|
|
136
|
+
const compiled = Object.freeze({
|
|
137
|
+
...node,
|
|
138
|
+
states: Object.freeze(states),
|
|
139
|
+
...(parallel ? {} : { initial: initialKey })
|
|
140
|
+
})
|
|
141
|
+
const entries = Object.entries(constructors)
|
|
142
|
+
const initialize = (context: Context) => {
|
|
143
|
+
const ancestors = typeof context.ancestors === "object" && context.ancestors !== null
|
|
144
|
+
? context.ancestors as Readonly<Record<string, unknown>> :
|
|
145
|
+
{}
|
|
146
|
+
const scoped = { ...context, root: path === "" ? context.state : ancestors[""] }
|
|
147
|
+
const values = Object.fromEntries(entries.map(([key, construct]) => [key, construct(scoped)]))
|
|
148
|
+
return { [SnapshotBuilderStateTypeId]: values }
|
|
149
|
+
}
|
|
150
|
+
initializers.add(initialize)
|
|
151
|
+
return {
|
|
152
|
+
node: compiled,
|
|
153
|
+
handlers: { ...handlers, ...(entries.length === 0 ? {} : { initialize }), states: children }
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return visit(root.node, handler, "")
|
|
157
|
+
}
|