@typeonce/effect-machine 0.38.1 → 0.39.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 (61) hide show
  1. package/README.md +42 -35
  2. package/dist/Machine.d.ts +62 -88
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +11 -24
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/atom.d.ts.map +1 -1
  7. package/dist/internal/machine/atom.js.map +1 -1
  8. package/dist/internal/machine/declaration.d.ts +10 -3
  9. package/dist/internal/machine/declaration.d.ts.map +1 -1
  10. package/dist/internal/machine/declaration.js +47 -16
  11. package/dist/internal/machine/declaration.js.map +1 -1
  12. package/dist/internal/machine/errors.d.ts +15 -1
  13. package/dist/internal/machine/errors.d.ts.map +1 -1
  14. package/dist/internal/machine/errors.js +10 -0
  15. package/dist/internal/machine/errors.js.map +1 -1
  16. package/dist/internal/machine/initialDeclaration.d.ts +2 -2
  17. package/dist/internal/machine/initialDeclaration.d.ts.map +1 -1
  18. package/dist/internal/machine/initialDeclaration.js +8 -9
  19. package/dist/internal/machine/initialDeclaration.js.map +1 -1
  20. package/dist/internal/machine/machine.d.ts +26 -76
  21. package/dist/internal/machine/machine.d.ts.map +1 -1
  22. package/dist/internal/machine/machine.js +21 -16
  23. package/dist/internal/machine/machine.js.map +1 -1
  24. package/dist/internal/machine/planner.d.ts +216 -31
  25. package/dist/internal/machine/planner.d.ts.map +1 -1
  26. package/dist/internal/machine/planner.js +6 -12
  27. package/dist/internal/machine/planner.js.map +1 -1
  28. package/dist/internal/machine/process.d.ts +5 -9
  29. package/dist/internal/machine/process.d.ts.map +1 -1
  30. package/dist/internal/machine/process.js +19 -32
  31. package/dist/internal/machine/process.js.map +1 -1
  32. package/dist/internal/testing/machine/finiteModel.d.ts.map +1 -1
  33. package/dist/internal/testing/machine/finiteModel.js +9 -12
  34. package/dist/internal/testing/machine/finiteModel.js.map +1 -1
  35. package/dist/testing/MachineTest.d.ts +7 -7
  36. package/dist/testing/MachineTest.js +7 -7
  37. package/dist/unstable/cluster/ClusterMachine.d.ts +1 -1
  38. package/dist/unstable/cluster/ClusterMachine.js +1 -1
  39. package/dist/unstable/reactivity/AtomMachine.d.ts +3 -3
  40. package/dist/unstable/reactivity/AtomMachine.js +3 -3
  41. package/docs/agent-guide.md +23 -30
  42. package/docs/machine-review.md +5 -6
  43. package/docs/root-api.md +27 -19
  44. package/package.json +1 -1
  45. package/src/Machine.ts +125 -163
  46. package/src/internal/machine/atom.ts +4 -7
  47. package/src/internal/machine/declaration.ts +56 -17
  48. package/src/internal/machine/errors.ts +22 -1
  49. package/src/internal/machine/initialDeclaration.ts +10 -12
  50. package/src/internal/machine/machine.ts +85 -465
  51. package/src/internal/machine/planner.ts +84 -190
  52. package/src/internal/machine/process.ts +80 -279
  53. package/src/internal/testing/machine/finiteModel.ts +7 -11
  54. package/src/testing/MachineTest.ts +7 -7
  55. package/src/unstable/cluster/ClusterMachine.ts +1 -1
  56. package/src/unstable/reactivity/AtomMachine.ts +3 -3
  57. package/dist/internal/machine/targetReference.d.ts +0 -15
  58. package/dist/internal/machine/targetReference.d.ts.map +0 -1
  59. package/dist/internal/machine/targetReference.js +0 -41
  60. package/dist/internal/machine/targetReference.js.map +0 -1
  61. package/src/internal/machine/targetReference.ts +0 -55
@@ -1,9 +1,8 @@
1
1
  /** Captures reusable sources and topology declarations before handler compilation. */
2
2
  import * as Effect from "effect/Effect"
3
- import { hasProperty } from "effect/Predicate"
3
+ import * as Schema from "effect/Schema"
4
4
  import * as Stream from "effect/Stream"
5
- import type { Machine, State } from "../../Machine.js"
6
- import * as Reference from "./targetReference.js"
5
+ import type { Machine } from "../../Machine.js"
7
6
  import * as Topology from "./topology.js"
8
7
 
9
8
  type SourceKind = "effects" | "streams" | "timers" | "logic" | "children"
@@ -11,9 +10,14 @@ interface Source {
11
10
  readonly kind: SourceKind
12
11
  readonly value: unknown
13
12
  }
13
+ type PathKind = "state" | "choice" | "history"
14
14
  export interface Declaration {
15
15
  readonly initialize?: (input: unknown) => unknown
16
- readonly root: State<Machine.StateNodeConfig>
16
+ readonly root: Machine.Any["root"]
17
+ /** Whether the machine declares an input schema used by `initialize`. */
18
+ readonly input: boolean
19
+ /** Declared state paths keyed by internal identifier; the root is `""`. */
20
+ readonly paths: ReadonlyMap<string, PathKind>
17
21
  readonly sources: ReadonlyMap<string, Source>
18
22
  readonly branches: ReadonlyMap<string, Readonly<Record<string, Readonly<Record<string, unknown>>>>>
19
23
  }
@@ -21,10 +25,29 @@ const record = (value: unknown, message: string): Record<string, unknown> => {
21
25
  if (typeof value !== "object" || value === null || Array.isArray(value)) throw new Error(message)
22
26
  return value as Record<string, unknown>
23
27
  }
28
+ /** The root node's public path name. Top-level states cannot use it. */
29
+ export const rootPathName = "root"
30
+ const collectPaths = (root: Machine.Any["root"]): ReadonlyMap<string, PathKind> => {
31
+ const paths = new Map<string, PathKind>()
32
+ const visit = (node: Machine.StateNodeConfig | Machine.TaggedSchema, path: string): void => {
33
+ const type = !Schema.isSchema(node) && "type" in node ? node.type : undefined
34
+ paths.set(path, type === "history" || type === "choice" ? type : "state")
35
+ if (!Schema.isSchema(node) && "states" in node) {
36
+ for (const [key, child] of Object.entries(node.states)) visit(child, path === "" ? key : `${path}.${key}`)
37
+ }
38
+ }
39
+ visit(root.node, "")
40
+ if (paths.has(rootPathName)) {
41
+ throw new Error(`Machine top-level state name "${rootPathName}" is reserved for the root`)
42
+ }
43
+ return paths
44
+ }
24
45
  export const capture = (
25
- root: State<Machine.StateNodeConfig>,
46
+ root: Machine.Any["root"],
26
47
  config: Readonly<Record<string, unknown>>
27
48
  ): Declaration => {
49
+ const paths = collectPaths(root)
50
+ const input = config.input !== undefined
28
51
  const sources = new Map<string, Source>()
29
52
  for (const kind of ["effects", "streams", "timers", "logic", "children"] as const) {
30
53
  if (config[kind] === undefined) continue
@@ -51,35 +74,44 @@ export const capture = (
51
74
  const spec = { ...record(value, `Machine branch "${name}.${key}" must be a declaration`) }
52
75
  for (const field of Reflect.ownKeys(spec)) {
53
76
  if (
54
- typeof field !== "string" || !["target", "update", "history", "none", "title"].includes(field)
77
+ typeof field !== "string" ||
78
+ !["target", "update", "history", "none", "initialize", "title"].includes(field)
55
79
  ) {
56
80
  throw new Error(`Machine branch "${name}.${key}" contains an unknown declaration field`)
57
81
  }
58
82
  }
83
+ if (spec.initialize !== undefined && spec.initialize !== true) {
84
+ throw new Error(`Machine branch "${name}.${key}" declares initialize: true; its resolver supplies input`)
85
+ }
59
86
  if (spec.title !== undefined && (typeof spec.title !== "string" || spec.title.length === 0)) {
60
87
  throw new Error("Machine branch title must be a non-empty string")
61
88
  }
62
- selection({ root, sources, branches }, spec)
89
+ selection({ root, input, paths, sources, branches }, spec)
63
90
  return [key, Object.freeze(spec)]
64
91
  })))
65
92
  )
66
93
  }
67
94
  }
68
- return { root, sources, branches }
95
+ return { root, input, paths, sources, branches }
69
96
  }
70
- const reference = (value: unknown, root: Declaration["root"]): Reference.Reference[typeof Reference.TypeId] => {
71
- if (!hasProperty(value, Reference.TypeId)) throw new Error("Machine target must be a declared state reference")
72
- const ref = (value as Reference.Reference)[Reference.TypeId]
73
- if (ref.root !== root) throw new Error("Machine target reference belongs to a different root descriptor")
74
- return ref
97
+ const reference = (
98
+ value: unknown,
99
+ declaration: Declaration
100
+ ): { readonly path: string; readonly kind: PathKind } => {
101
+ const path = value === rootPathName ? "" : typeof value === "string" && value !== "" ? value : undefined
102
+ const kind = path === undefined ? undefined : declaration.paths.get(path)
103
+ if (path === undefined || kind === undefined) {
104
+ throw new Error(`Machine target ${String(value)} is not a declared state path`)
105
+ }
106
+ return { path, kind }
75
107
  }
76
108
  export const selection = (
77
109
  declaration: Declaration,
78
110
  config: Readonly<Record<string, unknown>>
79
111
  ): Topology.TargetSelection => {
80
- const keys = ["target", "history", "none"].filter((key) => config[key] !== undefined)
112
+ const keys = ["target", "history", "none", "initialize"].filter((key) => config[key] !== undefined)
81
113
  if (keys.length === 0 && config.update !== undefined) {
82
- const owner = reference(config.update, declaration.root)
114
+ const owner = reference(config.update, declaration)
83
115
  if (owner.kind !== "state") throw new Error("Machine update requires an active state reference")
84
116
  return Topology.makeTargetSelection("update", owner.path, "branch")
85
117
  }
@@ -91,11 +123,18 @@ export const selection = (
91
123
  }
92
124
  return Topology.noneTargetSelection
93
125
  }
94
- const ref = reference(config[key], declaration.root)
126
+ if (key === "initialize") {
127
+ if (config.update !== undefined) throw new Error("Machine initialize cannot update a retained owner")
128
+ return Topology.makeTargetSelection("state", "", "branch")
129
+ }
130
+ const ref = reference(config[key], declaration)
131
+ if (key === "target" && ref.path === "") {
132
+ throw new Error("Machine root is not a destination; use initialize to reconstruct it from machine input")
133
+ }
95
134
  if ((key === "history") !== (ref.kind === "history")) {
96
135
  throw new Error("Machine history references require a history transition")
97
136
  }
98
- const update = config.update === undefined ? undefined : reference(config.update, declaration.root).path
137
+ const update = config.update === undefined ? undefined : reference(config.update, declaration).path
99
138
  if (update !== undefined && key !== "target") throw new Error("Machine owner updates require an ordinary destination")
100
139
  return Topology.makeTargetSelection(
101
140
  ref.kind,
@@ -1,5 +1,6 @@
1
- import type * as Cause from "effect/Cause"
1
+ import * as Cause from "effect/Cause"
2
2
  import * as Data from "effect/Data"
3
+ import * as Effect from "effect/Effect"
3
4
  import type * as Schema from "effect/Schema"
4
5
 
5
6
  /**
@@ -85,3 +86,23 @@ export class ProcessLocalError extends Data.TaggedError("ProcessLocalError")<{
85
86
  * @since 0.4.0
86
87
  */
87
88
  export class StoppedError extends Data.TaggedError("StoppedError") {}
89
+
90
+ /**
91
+ * Failures that synchronous planning reports through the typed error channel.
92
+ * Every other planning throw is a defect.
93
+ */
94
+ export type PlanningError = InfiniteTransitionError | MachineSchemaDecodeError
95
+
96
+ export const isPlanningError = (error: unknown): error is PlanningError =>
97
+ error instanceof InfiniteTransitionError || error instanceof MachineSchemaDecodeError
98
+
99
+ /** Converts a synchronous planning throw into a typed failure or a defect. */
100
+ export const failPlanning = (error: unknown): Effect.Effect<never, PlanningError> =>
101
+ isPlanningError(error) ? Effect.fail(error) : Effect.die(error)
102
+
103
+ /**
104
+ * Classifies a synchronous initial-planning throw. Planning failures stay
105
+ * typed; any other throw is preserved as the defect cause of a `StartupError`.
106
+ */
107
+ export const toStartupFailure = (error: unknown): PlanningError | StartupError =>
108
+ isPlanningError(error) || error instanceof StartupError ? error : new StartupError({ cause: Cause.die(error) })
@@ -1,9 +1,8 @@
1
1
  /** Captures handler-owned initial edges before compiling executable topology. */
2
2
  import { hasProperty } from "effect/Predicate"
3
3
  import * as Schema from "effect/Schema"
4
- import type { Machine, State } from "../../Machine.js"
4
+ import type { Machine } from "../../Machine.js"
5
5
  import { SnapshotBuilderStateTypeId } from "./symbols.js"
6
- import * as Reference from "./targetReference.js"
7
6
  import * as Topology from "./topology.js"
8
7
 
9
8
  const initializers = new WeakSet<object>()
@@ -52,7 +51,7 @@ interface Captured {
52
51
  readonly handlers: Record<string, unknown>
53
52
  }
54
53
  export const capture = (
55
- root: State<Machine.StateNodeConfig>,
54
+ root: Machine.Any["root"],
56
55
  handler: Readonly<Record<string, unknown>>
57
56
  ): Captured => {
58
57
  const visit = (
@@ -96,18 +95,17 @@ export const capture = (
96
95
  if (Reflect.ownKeys(edge).some((key) => !["target", "data", "decoded"].includes(String(key)))) {
97
96
  throw new Error("Machine initial edge accepts only target, data, and decoded")
98
97
  }
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
98
  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}"`)
99
+ const key = typeof edge.target === "string" && edge.target.startsWith(prefix)
100
+ ? edge.target.slice(prefix.length)
101
+ : undefined
102
+ const selected = key === undefined || !Object.hasOwn(node.states, key) ? undefined : node.states[key]!
103
+ const kind = selected === undefined || Schema.isSchema(selected) ? "state" : selected.type
104
+ if (key === undefined || selected === undefined || kind === "history") {
105
+ throw new Error(`Machine initial target must be a direct child of "${path === "" ? "root" : path}"`)
108
106
  }
109
107
  initialKey = key
110
- if (ref.kind === "choice" && (hasProperty(edge, "data") || hasProperty(edge, "decoded"))) {
108
+ if (kind === "choice" && (hasProperty(edge, "data") || hasProperty(edge, "decoded"))) {
111
109
  throw new Error("Machine choice initial edges cannot construct data")
112
110
  }
113
111
  const construct = edgeConstruction(edge)