@typeonce/effect-machine 0.41.1 → 0.43.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 (67) hide show
  1. package/README.md +31 -4
  2. package/dist/Machine.d.ts +159 -27
  3. package/dist/Machine.d.ts.map +1 -1
  4. package/dist/Machine.js +20 -6
  5. package/dist/Machine.js.map +1 -1
  6. package/dist/internal/machine/atom.d.ts +3 -7
  7. package/dist/internal/machine/atom.d.ts.map +1 -1
  8. package/dist/internal/machine/atom.js +153 -87
  9. package/dist/internal/machine/atom.js.map +1 -1
  10. package/dist/internal/machine/childRegistry.d.ts +7 -0
  11. package/dist/internal/machine/childRegistry.d.ts.map +1 -1
  12. package/dist/internal/machine/childRegistry.js +7 -0
  13. package/dist/internal/machine/childRegistry.js.map +1 -1
  14. package/dist/internal/machine/invocation.d.ts.map +1 -1
  15. package/dist/internal/machine/invocation.js +13 -2
  16. package/dist/internal/machine/invocation.js.map +1 -1
  17. package/dist/internal/machine/invocationDefinition.d.ts +7 -0
  18. package/dist/internal/machine/invocationDefinition.d.ts.map +1 -1
  19. package/dist/internal/machine/invocationDefinition.js +16 -0
  20. package/dist/internal/machine/invocationDefinition.js.map +1 -1
  21. package/dist/internal/machine/machine.d.ts.map +1 -1
  22. package/dist/internal/machine/machine.js +69 -6
  23. package/dist/internal/machine/machine.js.map +1 -1
  24. package/dist/internal/machine/plannedSnapshot.d.ts +30 -0
  25. package/dist/internal/machine/plannedSnapshot.d.ts.map +1 -0
  26. package/dist/internal/machine/plannedSnapshot.js +103 -0
  27. package/dist/internal/machine/plannedSnapshot.js.map +1 -0
  28. package/dist/internal/machine/planner.d.ts +5 -0
  29. package/dist/internal/machine/planner.d.ts.map +1 -1
  30. package/dist/internal/machine/planner.js +1 -1
  31. package/dist/internal/machine/planner.js.map +1 -1
  32. package/dist/internal/machine/runtime.d.ts +5 -4
  33. package/dist/internal/machine/runtime.d.ts.map +1 -1
  34. package/dist/internal/machine/runtime.js +60 -15
  35. package/dist/internal/machine/runtime.js.map +1 -1
  36. package/dist/internal/machine/runtimeCompiled.js +2 -2
  37. package/dist/internal/machine/runtimeCompiled.js.map +1 -1
  38. package/dist/internal/machine/runtimeGeneric.js +1 -1
  39. package/dist/internal/machine/runtimeGeneric.js.map +1 -1
  40. package/dist/internal/machine/runtimeProtocol.d.ts +2 -1
  41. package/dist/internal/machine/runtimeProtocol.d.ts.map +1 -1
  42. package/dist/internal/machine/runtimeProtocol.js +2 -2
  43. package/dist/internal/machine/runtimeProtocol.js.map +1 -1
  44. package/dist/testing/MachineTest.d.ts +2 -2
  45. package/dist/testing/MachineTest.js +2 -2
  46. package/dist/unstable/reactivity/AtomMachine.d.ts +95 -19
  47. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  48. package/dist/unstable/reactivity/AtomMachine.js +13 -7
  49. package/dist/unstable/reactivity/AtomMachine.js.map +1 -1
  50. package/docs/agent-guide.md +28 -5
  51. package/docs/effect-atom-react.md +262 -14
  52. package/docs/machine-review.md +18 -4
  53. package/package.json +1 -1
  54. package/src/Machine.ts +229 -32
  55. package/src/internal/machine/atom.ts +305 -113
  56. package/src/internal/machine/childRegistry.ts +9 -0
  57. package/src/internal/machine/invocation.ts +17 -2
  58. package/src/internal/machine/invocationDefinition.ts +19 -0
  59. package/src/internal/machine/machine.ts +65 -2
  60. package/src/internal/machine/plannedSnapshot.ts +113 -0
  61. package/src/internal/machine/planner.ts +1 -1
  62. package/src/internal/machine/runtime.ts +101 -28
  63. package/src/internal/machine/runtimeCompiled.ts +2 -2
  64. package/src/internal/machine/runtimeGeneric.ts +1 -1
  65. package/src/internal/machine/runtimeProtocol.ts +4 -2
  66. package/src/testing/MachineTest.ts +2 -2
  67. package/src/unstable/reactivity/AtomMachine.ts +104 -20
@@ -53,23 +53,125 @@ export const useAuthMachine = Auth.useMachine
53
53
  function AuthRoute({ input, attemptId }: Props) {
54
54
  return (
55
55
  <Auth.Provider key={attemptId} input={input}>
56
- <Suspense fallback={<Loading />}>
57
- <AuthCard />
58
- </Suspense>
56
+ <AuthCard />
59
57
  </Auth.Provider>
60
58
  )
61
59
  }
62
60
  ```
63
61
 
64
62
  Input is startup-only. Send events to update the existing workflow; change the
65
- Provider's React key to create a new one. Keep the Provider above Suspense so
66
- suspension does not discard the owner. Supply an Atom RegistryProvider at the
67
- application boundary. The same factory used by two Providers creates isolated
63
+ Provider's React key to create a new one. `MachineState` does not suspend, so
64
+ the first paint needs no Suspense boundary. Custom readers that use
65
+ `useAtomSuspense` still suspend during startup; keep the Provider above their
66
+ Suspense boundary so suspension does not discard the owner. Supply an Atom
67
+ RegistryProvider at the application boundary. The same factory used by two Providers creates isolated
68
68
  machines, even when their inputs are equal.
69
69
 
70
70
  `useMachineAtom(() => makeMachine(input))` remains available for custom owners.
71
71
  It mounts the reference after commit without reading `result` or `snapshot`.
72
72
 
73
+ ## Per-owner capabilities
74
+
75
+ A router, a callback owned by a component, or another per-instance capability
76
+ is a service, never a schema field or startup input. Declare the service, let a
77
+ state invoke the work that needs it, and provide the implementation from the
78
+ React owner:
79
+
80
+ ```tsx
81
+ import { Machine } from "@typeonce/effect-machine"
82
+ import { AtomMachine } from "@typeonce/effect-machine/reactivity"
83
+ import { useMachineAtom } from "@typeonce/effect-machine-react"
84
+ import { Context, Effect, Layer } from "effect"
85
+ import { Atom } from "effect/reactivity"
86
+ import { AppLayer } from "../lib/app-layer"
87
+
88
+ export class Navigation extends Context.Service<Navigation, {
89
+ readonly push: (href: string) => Effect.Effect<void>
90
+ }>()("Navigation") {}
91
+
92
+ export const OnboardingMachine = Machine.make({
93
+ root: Machine.state({
94
+ states: { Editing: {}, Leaving: {}, Done: { type: "final" } }
95
+ }),
96
+ events: Machine.events({ Submit: {} }),
97
+ effects: {
98
+ navigateNext: Effect.flatMap(Navigation, (navigation) =>
99
+ navigation.push("/onboarding/next"))
100
+ }
101
+ }).handle({
102
+ initial: { target: "Editing" },
103
+ states: {
104
+ Editing: { on: { Submit: { target: "Leaving" } } },
105
+ Leaving: { invoke: { src: "navigateNext", onDone: { target: "Done" } } },
106
+ Done: {}
107
+ }
108
+ })
109
+
110
+ function OnboardingRoute() {
111
+ const router = useRouter()
112
+ const machine = useMachineAtom(() =>
113
+ AtomMachine
114
+ .bind(Atom.runtime(Layer.merge(
115
+ AppLayer,
116
+ Layer.succeed(Navigation, {
117
+ push: (href) => Effect.sync(() => router.push(href))
118
+ })
119
+ )))
120
+ .make(OnboardingMachine)
121
+ )
122
+
123
+ return <OnboardingForm machine={machine} />
124
+ }
125
+ ```
126
+
127
+ The requirement stays on the machine type. Binding the machine to a runtime
128
+ without `Navigation`, such as the application-wide `MachineAtoms`, is a compile
129
+ error. Snapshots contain only schema data, so `Machine.encodeSnapshot` keeps
130
+ working, and tests substitute the capability with `Layer.mock(Navigation, ...)`.
131
+
132
+ Create the runtime inside the `useMachineAtom` factory so each owner builds it
133
+ once. `Atom.runtime` builds layers through the registry's memo map: the shared
134
+ `AppLayer` is built once per registry and reused, and each owner builds only its
135
+ own capability layer. Use `Layer.provideMerge(ownerLayer, AppLayer)` when the
136
+ owner layer itself needs application services.
137
+
138
+ To share the owner-bound machine with a subtree, declare the capability as the
139
+ second, `Layer`-typed parameter of a `createMachineContext` factory. The first
140
+ parameter is the startup input; `OnboardingMachine` has none, so it is `void`:
141
+
142
+ ```tsx
143
+ import { createMachineContext } from "@typeonce/effect-machine-react"
144
+
145
+ const navigationLayer = (router: Router) =>
146
+ Layer.succeed(Navigation, {
147
+ push: (href) => Effect.sync(() => router.push(href))
148
+ })
149
+
150
+ export const Onboarding = createMachineContext(
151
+ (_: void, navigation: Layer.Layer<Navigation>) =>
152
+ AtomMachine
153
+ .bind(Atom.runtime(Layer.provideMerge(navigation, AppLayer)))
154
+ .make(OnboardingMachine)
155
+ )
156
+
157
+ function OnboardingRoute() {
158
+ return (
159
+ <Onboarding.Provider layer={navigationLayer(useRouter())}>
160
+ <OnboardingForm />
161
+ </Onboarding.Provider>
162
+ )
163
+ }
164
+ ```
165
+
166
+ The Provider requires a `layer` prop of exactly the declared `Layer` type, and
167
+ an `input` prop when the first parameter is the machine's input, as in
168
+ `(input: SignInInput, navigation: Layer.Layer<Navigation>)`. A factory without
169
+ a layer parameter has a Provider without a `layer` prop. Like `input`, the
170
+ layer is read once, when the Provider mounts: a new router instance does not
171
+ rebuild the running machine. Change the Provider's React `key` to create a new
172
+ owner with a new layer. Binding still checks the machine's requirements, so a
173
+ layer type that omits `Navigation` is a compile error.
174
+
73
175
  ## Render state-owned data
74
176
 
75
177
  Render a typed path in the smallest component that needs it:
@@ -88,11 +190,30 @@ function EditingFields() {
88
190
  ```
89
191
 
90
192
  `MachineState` subscribes only its renderer. The path determines the callback's
91
- snapshot type. Startup suspends, failures reach the nearest error boundary,
92
- and an inactive path renders `inactive` (null by default).
193
+ snapshot type. It does not suspend: until the machine has a snapshot it renders
194
+ `pending`, and an inactive path renders `inactive` (both null by default).
195
+ Startup and runtime failures reach the nearest error boundary. Once a snapshot
196
+ has rendered, the renderer keeps it while the machine is still starting, for
197
+ example while a bound runtime layer builds after hydration.
93
198
 
94
- For custom hooks, `useAtomSuspense(AtomMachine.selectSnapshot(machine, path)).value`
95
- returns an Option of the selected snapshot.
199
+ `MachineState` also renders a child machine. Pass the child bridge; paths and
200
+ the snapshot are then the child's, and `inactive` also renders while the state
201
+ that owns the child is not active:
202
+
203
+ ```tsx
204
+ <MachineState machine={machine.child(QuantityChild)} path="" inactive={null}>
205
+ {(snapshot) => <NumberField value={snapshot.value.quantity} />}
206
+ </MachineState>
207
+ ```
208
+
209
+ For custom hooks, `useMachineResult(atom)` reads any result atom, such as
210
+ `AtomMachine.selectSnapshot(machine, path)`, `matches`, or `can`, with the same
211
+ rendering semantics as `MachineState`: it does not suspend, serves the planned
212
+ value during server rendering and hydration, and keeps the last `Success` while
213
+ the machine is still starting. Prefer it to `useAtomValue`, which returns
214
+ `Initial` again after hydration and makes the renderer replace hydrated markup.
215
+ `useAtomSuspense(AtomMachine.selectSnapshot(machine, path)).value` returns an
216
+ Option of the selected snapshot for readers inside a Suspense boundary.
96
217
 
97
218
  `AtomMachine.select` returns the selected state value.
98
219
  `AtomMachine.selectSnapshot` also retains the selected state's child topology.
@@ -159,6 +280,14 @@ function SubmitButton() {
159
280
  `useAtomSet` mounts the writable atom and does not subscribe the component to
160
281
  its value.
161
282
 
283
+ Writes made while the machine is still starting, for example while a bound
284
+ `Atom.runtime` layer is building after hydration, are held and delivered in
285
+ write order once the machine is ready. The write result stays waiting until
286
+ the event is delivered and fails with the startup error if startup fails.
287
+ Writes after the machine stopped or completed fail with `StoppedError`. The
288
+ same applies to `stop` and to child `send` and `stop`; a child command fails
289
+ with `ChildNotActiveError` when the state that owns the child is not active.
290
+
162
291
  ## Query concrete event acceptance
163
292
 
164
293
  `AtomMachine.can` turns one concrete event input into a reusable machine
@@ -206,6 +335,47 @@ const submitAllowed = AtomMachine.can(submitEvent)
206
335
  Changes to `draftAtom` recompute acceptance. The event atom contains the event
207
336
  input itself rather than an `AsyncResult`.
208
337
 
338
+ `can` is `true` whenever the active configuration selects a transition. A
339
+ `{ none: true }` branch is a selected transition: it accepts the event without
340
+ changing state. A resolver that falls back to a `none` branch therefore keeps
341
+ the button enabled:
342
+
343
+ ```ts
344
+ // Before: an incomplete form still accepts Submitted, so `can` is true.
345
+ // In make: branches: { submit: { review: { target: "Reviewing" }, incomplete: { none: true } } }
346
+ Submitted: {
347
+ branches: "submit",
348
+ resolve: ({ state, select }) =>
349
+ state.email.length > 0 ? select.review() : select.incomplete()
350
+ }
351
+ ```
352
+
353
+ When the event must be refused, decline it. Use `guard` for an ordinary
354
+ transition, or `declinable: true` with `decline()` in a resolver:
355
+
356
+ ```ts
357
+ // After: an incomplete form declines Submitted, so `can` is false.
358
+ Submitted: { target: "Reviewing", guard: ({ state }) => state.email.length > 0 }
359
+
360
+ // A resolver that needs commands or construction declines explicitly.
361
+ // In make: branches: { submit: { review: { target: "Reviewing" } } }
362
+ Submitted: {
363
+ branches: "submit",
364
+ declinable: true,
365
+ resolve: ({ state, select, decline }) =>
366
+ state.email.length > 0 ? select.review() : decline()
367
+ }
368
+ ```
369
+
370
+ Keep `none` for events that are deliberately accepted and ignored. The
371
+ `effect-machine/no-conditional-none-branch` lint rule reports the conditional
372
+ fallback.
373
+
374
+ Query acceptance during render through `AtomMachine.can(event)(machine)`. Do
375
+ not call `Effect.runSync(Machine.can(...))` in a component: the atom shares the
376
+ running machine's snapshot, suspends during startup, and recomputes when the
377
+ snapshot changes.
378
+
209
379
  ## Whole-result and custom selections
210
380
 
211
381
  Reading the full result is correct when a component renders the complete
@@ -310,7 +480,8 @@ const editing = useAtomSuspense(
310
480
  ```
311
481
 
312
482
  An inactive child or path returns `Option.none()`. Re-entry follows the
313
- replacement child instance.
483
+ replacement child instance. `MachineState` accepts the child bridge directly
484
+ and renders `inactive` in both cases.
314
485
 
315
486
  Use `AtomMachine.familyChild` when a parent owns a runtime-sized set of keyed
316
487
  children:
@@ -328,6 +499,45 @@ export const plantAtoms = AtomMachine.familyChild(CentralMachineAtom, {
328
499
  })
329
500
  ```
330
501
 
502
+ ## Generic helpers
503
+
504
+ Use `AtomMachine.MachineAtom.Any` and `AtomMachine.ChildMachineAtom.Any` to
505
+ accept any bridge, including bridges for machines without events. Recover the
506
+ exact types with the namespace extractors:
507
+
508
+ ```ts
509
+ function StateView<A extends AtomMachine.MachineAtom.Any>(props: {
510
+ readonly machine: A
511
+ readonly render: (state: AtomMachine.MachineAtom.State<A>) => React.ReactNode
512
+ }) {
513
+ const state = useAtomSuspense(props.machine.result).value
514
+ return props.render(state)
515
+ }
516
+
517
+ type AuthEvent = AtomMachine.MachineAtom.Event<typeof AuthMachineAtom>
518
+ type EditorState = AtomMachine.ChildMachineAtom.State<
519
+ AtomMachine.ChildOf<typeof AuthMachineAtom, typeof Editor>
520
+ >
521
+ ```
522
+
523
+ ## Keep workflow effects out of emissions
524
+
525
+ Emissions are ephemeral notifications for observers. They are not replayed, so
526
+ a subscriber that mounts late never sees an earlier emission. Do not drive work
527
+ the workflow depends on, such as navigation, from emissions. Invoke that work
528
+ from the state that requires it through a capability service, as in
529
+ [Per-owner capabilities](#per-owner-capabilities); the machine then decides when
530
+ it runs, what cancels it, and how failure changes the workflow.
531
+
532
+ An emission that only feeds UI feedback has two stream-atom details:
533
+
534
+ - `Atom.make(AtomMachine.emissions(machine))` publishes each emission as a
535
+ waiting `Success`, then publishes the last emission again, no longer waiting,
536
+ when the machine completes. Handlers must tolerate that repeated value.
537
+ - `useAtomSubscribe(atom, f)` subscribes after commit without reading the atom.
538
+ Pass `{ immediate: true }` so a lazy emissions atom starts; without it the
539
+ callback never runs. The callback then also receives the initial result.
540
+
331
541
  ## Registry and rendering semantics
332
542
 
333
543
  A `MachineAtom` identifies one machine per `AtomRegistry`. Passing the same
@@ -337,6 +547,44 @@ after its final subscription and configured idle retention expire.
337
547
  `registry.dispose()` stops it immediately.
338
548
 
339
549
  `useMachineAtom` does not start a machine during server rendering because
340
- React effects do not run on the server. Reading a machine atom during server
341
- render follows `@effect/atom-react` server-read behavior, so choose an explicit
342
- client boundary when server startup would be undesirable.
550
+ React effects do not run on the server. Server reads never start a machine
551
+ either. Every bridge atom carries an Effect Atom server value, which
552
+ `@effect/atom-react` hooks read during server rendering and hydration, and
553
+ `Atom.getServerValue` reads directly:
554
+
555
+ | Atom | Server value |
556
+ | ----------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
557
+ | `ref`, `send`, `stop` | `Initial` |
558
+ | `snapshot` | `Success({ status: "active", state })`, waiting |
559
+ | `result` | `Success(state)`, waiting |
560
+ | `select`, `selectSnapshot`, `matches`, `can` | the projection of `state`, waiting |
561
+ | `child(Child).result` and child projections | `Success(Option.some(childState))` when the planned state invokes `Child`, otherwise `Success(Option.none())` |
562
+ | `family` and `familyChild` projections | the server value of the projected bridge atom |
563
+
564
+ `state` is the machine's planned startup state: the state `Machine.planInitial`
565
+ settles into with the bridge's input, without running startup commands,
566
+ invocations, or services. A resumed bridge uses its resumed snapshot. Children
567
+ spawned at runtime or through child families are `Option.none()`. When the
568
+ startup state cannot be planned synchronously, for example because the input
569
+ is invalid, every server value is `Initial`. Each bridge plans at most once,
570
+ on its first server read.
571
+
572
+ ## Server rendering and hydration
573
+
574
+ Render state slots with `MachineState` and no Suspense boundary:
575
+
576
+ ```tsx
577
+ <Onboarding.Provider input={input}>
578
+ <MachineState machine={Onboarding.useMachine()} path="Editing">
579
+ {(editing) => <input value={editing.value.email} onChange={onChange} />}
580
+ </MachineState>
581
+ </Onboarding.Provider>
582
+ ```
583
+
584
+ The server renders the planned `Editing` snapshot. Hydration renders the same
585
+ markup, then the Provider mounts the machine and the same component tree
586
+ receives live snapshots. The input keeps its DOM node, typed text, and focus.
587
+
588
+ Do not wrap hydrated forms in a Suspense boundary that a startup read can
589
+ trigger. A suspended boundary replaces its server-rendered content with the
590
+ fallback and later mounts new DOM nodes, discarding typed text and focus.
@@ -11,10 +11,10 @@ patterns.
11
11
  Run the recommended rules from
12
12
  [`@typeonce/oxlint-plugin-effect-machine`](../../oxlint-plugin/README.md) before
13
13
  the manual review. They catch provable duplicate invocation identities,
14
- asynchronous work, browser access, nondeterminism, and redundant resolvers in
15
- direct same-module machine definitions. Continue with this review for
16
- cross-module ownership and architectural questions that syntax alone cannot
17
- answer.
14
+ asynchronous work, browser access, nondeterminism, redundant resolvers, and
15
+ conditional `none` fallbacks in direct same-module machine definitions.
16
+ Continue with this review for cross-module ownership and architectural
17
+ questions that syntax alone cannot answer.
18
18
 
19
19
  ## Review the responsibility boundaries
20
20
 
@@ -43,6 +43,12 @@ constructors derived from those declarations. Avoid an extra branch group for
43
43
  an ordinary transition. Use `reenter: true` when the source must restart.
44
44
  An empty targetless resolver simplifies to `{ none: true }`.
45
45
 
46
+ A `{ none: true }` branch accepts its event, so `Machine.can` and
47
+ `AtomMachine.can` return `true` when a resolver selects it. Review check: for
48
+ every event that enables or disables a control, refuse it with `guard` or with
49
+ `declinable: true` and `decline()`. Keep `none` only for events that are
50
+ deliberately accepted and ignored.
51
+
46
52
  ## Choose React ownership or keyed family lookup
47
53
 
48
54
  Use `useMachineAtom` when one React subtree owns the workflow, including a
@@ -187,6 +193,14 @@ Review check: search components, hooks, and atom modules for service calls,
187
193
  `Effect.run*`, promises, browser APIs, analytics, timers, and chains of `send`
188
194
  calls. Move workflow coordination into states, transitions, and invoked work.
189
195
 
196
+ Per-instance capabilities, such as a router or a component callback, are
197
+ services provided by the React owner, not schema fields or startup input. A
198
+ function in state data or input cannot be encoded by `Machine.encodeSnapshot`.
199
+ Review check: search schemas for `Schema.declare` guards that accept functions
200
+ and move each one to a service, as in
201
+ [Per-owner capabilities](./effect-atom-react.md#per-owner-capabilities). Do not
202
+ drive navigation or other workflow effects from emissions.
203
+
190
204
  ## Report findings
191
205
 
192
206
  For each issue, cite the file and line, name the violated boundary, and show the
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@typeonce/effect-machine",
3
- "version": "0.41.1",
3
+ "version": "0.43.0",
4
4
  "description": "Schema-first state machines and statecharts for Effect",
5
5
  "author": "Sandro Maglione",
6
6
  "repository": {