@typeonce/effect-machine 0.41.1 → 0.42.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 +2 -7
  7. package/dist/internal/machine/atom.d.ts.map +1 -1
  8. package/dist/internal/machine/atom.js +132 -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 +82 -19
  47. package/dist/unstable/reactivity/AtomMachine.d.ts.map +1 -1
  48. package/dist/unstable/reactivity/AtomMachine.js +0 -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 +207 -11
  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 +263 -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 +90 -20
package/README.md CHANGED
@@ -75,6 +75,11 @@ Root data is shared state. `update: "root"` replaces that value while
75
75
  retaining the active child configuration and its running work. Ordinary
76
76
  transitions target a descendant; the root itself is not a destination.
77
77
 
78
+ A started machine is owned by the enclosing `Scope`. Closing it is equivalent
79
+ to `ref.stop`: invocations are interrupted, owned children stop, and later
80
+ sends fail with `StoppedError`. Own a `Scope` explicitly when a machine must
81
+ outlive the program that started it.
82
+
78
83
  ## Modeling workflow
79
84
 
80
85
  Put data on the lowest state that owns it. Use tagged schemas or `fields` for
@@ -272,6 +277,21 @@ Advanced construction declares both paths in a branch and uses
272
277
  A retained owner must be active for that source and remain active through the
273
278
  transition. A sibling region's value cannot be updated through this operation.
274
279
 
280
+ The destination can be a choice. The owner is updated first, so the choice
281
+ resolver reads the new value, and `data` constructs only the owner value:
282
+
283
+ ```ts
284
+ Bump: {
285
+ target: "Route",
286
+ update: "root",
287
+ data: ({ root }) => ({ count: root.count + 1 })
288
+ }
289
+ ```
290
+
291
+ Every branch the choice can reach, including through nested choices, must stay
292
+ below the owner. A declared branch selects it with
293
+ `select.route({ update: { data: ownerValues } })`.
294
+
275
295
  The runtime transition API does not replace arbitrary complete root
276
296
  configurations. The root is not a destination. `initialize` restarts it: it
277
297
  accepts fresh machine input, or `true` for a machine without input, and follows
@@ -387,9 +407,16 @@ const invocations = [
387
407
 
388
408
  Include each handler demanded by the concrete program's type. Use an explicit
389
409
  `id` for simultaneous instances of one source; effect, stream, and timer IDs
390
- default to `src`. Logic requires a lifecycle `id` and a typed `Machine.childAddress`.
391
- A child uses its `Machine.child` descriptor's identity and protocol. All
392
- invocations are owned by their state and cancelled when it exits.
410
+ default to `src`. Invocation IDs within one state must be distinct. Logic
411
+ requires a lifecycle `id` and a typed `Machine.childAddress`. A child uses its
412
+ `Machine.child` descriptor's identity and protocol. All invocations are owned by
413
+ their state and cancelled when it exits.
414
+
415
+ Effect, Stream, and timer invocations run under runtime-owned child IDs, so
416
+ they never fail with `ChildAlreadyExistsError`. Logic addresses and child
417
+ descriptor IDs are chosen by you: starting one while another active child uses
418
+ the same ID fails the owning machine with `ChildAlreadyExistsError`. A parent's
419
+ `onFailure` for an invoked child receives only the child's own typed failures.
393
420
 
394
421
  Effect services flow through the used sources and lifecycle effects into the
395
422
  machine's requirements. Unused registrations add no requirements. Supply them
@@ -560,7 +587,7 @@ Snapshots can be validated for storage or transport:
560
587
  ```ts
561
588
  const encoded = yield * Machine.encodeSnapshot(machine, snapshot)
562
589
  const decoded = yield * Machine.decodeSnapshot(machine, encoded)
563
- const ref = yield * Machine.resume(machine, decoded)
590
+ const ref = yield * Machine.resume(machine, decoded) // owned by the current Scope
564
591
  ```
565
592
 
566
593
  Decoded snapshots are local runtime values and may contain class instances or
package/dist/Machine.d.ts CHANGED
@@ -516,6 +516,19 @@ type StateDefinitionError<Message extends string, Path extends PropertyKey = nev
516
516
  readonly path: Path;
517
517
  readonly details: Details;
518
518
  };
519
+ type InvocationDefinitionError<Message extends string, Source extends string, Field extends PropertyKey> = {
520
+ readonly "~effect/Machine/InvocationDefinitionError": Message;
521
+ readonly source: Source;
522
+ readonly field: Field;
523
+ };
524
+ type TransitionDefinitionError<Message extends string, Choice extends string, Target extends string> = {
525
+ readonly "~effect/Machine/TransitionDefinitionError": Message;
526
+ readonly choice: Choice;
527
+ readonly target: Target;
528
+ };
529
+ type RootCompatibilityError<Message extends string> = {
530
+ readonly "~effect/Machine/RootCompatibilityError": Message;
531
+ };
519
532
  type ActiveStateKey<States extends Machine.StateSchemas> = Machine.ActiveStateKey<States>;
520
533
  type HistoryStateKey<States extends Machine.StateSchemas> = Machine.HistoryStateKey<States>;
521
534
  type ChoiceStateKey<States extends Machine.StateSchemas> = Machine.ChoiceStateKey<States>;
@@ -1112,7 +1125,8 @@ export type RuntimeOutcome<State, Error = never, Output = never> = {
1112
1125
  *
1113
1126
  * Subscribe to `emissions` before evaluating `start` when initial-entry
1114
1127
  * emissions must be observed. `start` is one-shot: concurrent and repeated
1115
- * evaluations share the same initialization and running reference.
1128
+ * evaluations share the same initialization and running reference, and the
1129
+ * `Scope` of the first evaluation owns the machine.
1116
1130
  *
1117
1131
  * @category models
1118
1132
  * @since 0.11.0
@@ -1133,7 +1147,7 @@ export interface Prepared<out State, in Event, out Error, out Output, out Emitte
1133
1147
  * observe initialization.
1134
1148
  */
1135
1149
  readonly inspection: Stream.Stream<Inspection.Event>;
1136
- /** Initializes this machine once and returns its running reference. */
1150
+ /** Initializes this machine once, owned by the first evaluating `Scope`, and returns its running reference. */
1137
1151
  readonly start: Effect.Effect<MachineRef<State, Event, Error, Output, Emitted>, StartError, StartRequirements>;
1138
1152
  }
1139
1153
  /**
@@ -1520,8 +1534,20 @@ export declare namespace Machine {
1520
1534
  type ParentEventsOf<Declaration extends Parent.Any | undefined> = Declaration extends Parent<infer Mode, infer Events> ? ParentEventSchemas<Mode, Events> : readonly [];
1521
1535
  /** Extracts the owning-machine declaration carried by a machine. */
1522
1536
  type ParentDeclarationOf<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends infer Mode ? Mode extends ParentMode ? Parent<Mode, Events> : undefined : never;
1523
- /** Constraint applied to APIs that create an independent root runtime. */
1524
- type RootCompatible<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends "required" ? never : unknown;
1537
+ /**
1538
+ * Constraint applied to APIs that create an independent root runtime.
1539
+ *
1540
+ * **Details**
1541
+ *
1542
+ * A machine without a parent protocol, or with an optional one, is
1543
+ * accepted. A machine that declares a required parent can only run as an
1544
+ * owned child, so the constraint resolves to a diagnostic that names the
1545
+ * reason instead of an unexplained `never`.
1546
+ *
1547
+ * @category utility types
1548
+ * @since 0.27.0
1549
+ */
1550
+ type RootCompatible<Events extends ReadonlyArray<TaggedSchema>> = ParentModeOf<Events> extends "required" ? RootCompatibilityError<"Machine declares a required parent and cannot run as a root; invoke or spawn it from an owning machine"> : unknown;
1525
1551
  /**
1526
1552
  * Any schema-first machine.
1527
1553
  *
@@ -3300,7 +3326,7 @@ export declare namespace Machine {
3300
3326
  * @category utility types
3301
3327
  * @since 0.4.0
3302
3328
  */
3303
- type HandlerResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>> | CombinedTarget<Target<States, StateIdentifier<States>> | Snapshot<States>, States, ValuedStateIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>>> | NoTarget;
3329
+ type HandlerResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>> | CombinedTarget<Target<States, StateIdentifier<States>> | Snapshot<States> | ChoiceTarget<States, ChoiceIdentifier<States>>, States, ValuedStateIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateUpdate<States, ValuedStateIdentifier<States>>> | NoTarget;
3304
3330
  /** A choice resolver must always select a typed target synchronously. */
3305
3331
  type ChoiceResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>> | StateConstruction<Snapshot<States> | Target<States, StateIdentifier<States>> | HistoryTarget<States, HistoryIdentifier<States>> | ChoiceTarget<States, ChoiceIdentifier<States>>>;
3306
3332
  /**
@@ -3480,13 +3506,27 @@ export declare namespace Machine {
3480
3506
  } ? EventTransitionReturn<NonNullable<Handler>> : never) : never;
3481
3507
  type InvokeOutcomeError<Invoke> = IsAny<InvokeOutcomeReturn<Invoke>> extends true ? never : Effect.Error<InvokeOutcomeReturn<Invoke>>;
3482
3508
  type InvokeOutcomeServices<Invoke> = IsAny<InvokeOutcomeReturn<Invoke>> extends true ? never : Effect.Services<InvokeOutcomeReturn<Invoke>>;
3509
+ type InvokeCollisionError<Invoke> = Invoke extends {
3510
+ readonly logic: unknown;
3511
+ } | {
3512
+ readonly child: unknown;
3513
+ } ? ChildAlreadyExistsError : never;
3483
3514
  /**
3484
3515
  * Extracts the parent transition error contribution from invoked children.
3485
3516
  *
3517
+ * **Details**
3518
+ *
3519
+ * The contribution contains the startup and lifecycle-handler failures of
3520
+ * every invocation. `ChildAlreadyExistsError` is included only for
3521
+ * invocations whose child id is chosen by the caller, namely logic
3522
+ * invocations with an `address` and child machine invocations, which fail to
3523
+ * start while another child with that id is active. Effect, Stream, and timer
3524
+ * invocations run under runtime-reserved ids and cannot collide.
3525
+ *
3486
3526
  * @category utility types
3487
3527
  * @since 0.4.0
3488
3528
  */
3489
- type InvokeError<Config> = [InvokeReturn<Config>] extends [never] ? never : ChildAlreadyExistsError | InvokeInitialError<InvokeReturn<Config>> | InvokeOutcomeError<InvokeReturn<Config>>;
3529
+ type InvokeError<Config> = [InvokeReturn<Config>] extends [never] ? never : InvokeCollisionError<InvokeReturn<Config>> | InvokeInitialError<InvokeReturn<Config>> | InvokeOutcomeError<InvokeReturn<Config>>;
3490
3530
  /**
3491
3531
  * Extracts the parent service requirement contribution from invoked children.
3492
3532
  *
@@ -3978,7 +4018,10 @@ export declare namespace Machine {
3978
4018
  } & ({
3979
4019
  /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
3980
4020
  readonly target: ReferenceUnion<S, DestinationPath<S>>;
3981
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4021
+ /**
4022
+ * Replaces the complete value of a retained ancestor of the source and target without replacing its active
4023
+ * children. A choice target resolves after the update, and every branch it can reach must stay below the owner.
4024
+ */
3982
4025
  readonly update?: ReferenceUnion<S, ValuedStateIdentifier<S>>;
3983
4026
  /** Enters a compound or parallel subtree through its declared initialization. */
3984
4027
  readonly initial?: never;
@@ -4118,7 +4161,9 @@ export declare namespace Machine {
4118
4161
  readonly update: infer Update;
4119
4162
  } ? RefPath<Update> extends infer Owner extends Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>> ? P extends StateIdentifier<S> ? TargetSelection<ConstructionCall<ConstructionObject<NodeByIdentifier<S, P>, Src extends `${P}.${infer Rest}` ? Rest : Src extends P ? "" : never> & {
4120
4163
  readonly update: ConstructionData<NodeByIdentifier<S, Owner>>;
4121
- }, CombinedTarget<Target<S, P>, S, Owner>>, P, "state", "branch"> : never : never : TargetSelection<ObjectSelection<S, Src, P, R>, P, P extends ChoiceIdentifier<S> ? "choice" : "state", "branch"> : never : D extends {
4164
+ }, CombinedTarget<Target<S, P>, S, Owner>>, P, "state", "branch"> : P extends ChoiceIdentifier<S> ? TargetSelection<(construction: {
4165
+ readonly update: ConstructionData<NodeByIdentifier<S, Owner>>;
4166
+ }) => CombinedTarget<ChoiceTarget<S, P>, S, Owner>, P, "choice", "branch"> : never : never : TargetSelection<ObjectSelection<S, Src, P, R>, P, P extends ChoiceIdentifier<S> ? "choice" : "state", "branch"> : never : D extends {
4122
4167
  readonly history: infer Ref;
4123
4168
  } ? RefPath<Ref> extends infer P extends HistoryIdentifier<S> ? TargetSelection<() => HistoryTarget<S, P>, P, "history", "full"> : never : D extends {
4124
4169
  readonly update: infer Ref;
@@ -4201,7 +4246,7 @@ export declare namespace Machine {
4201
4246
  readonly update: StateByIdentifier<S, Owner>;
4202
4247
  };
4203
4248
  readonly from?: never;
4204
- }) : never;
4249
+ }) : P extends ChoiceIdentifier<S> ? ObjectConstruction<C, StateUpdateBuilder<S, Owner>> : never;
4205
4250
  type InlineCombined<S extends StateSchemas, Src extends StateNodeIdentifier<S>, C> = Src extends ChoiceIdentifier<S> ? never : [
4206
4251
  Extract<ParentStateIdentifier<Src>, ValuedStateIdentifier<S>>
4207
4252
  ] extends [never] ? never : {
@@ -4209,7 +4254,11 @@ export declare namespace Machine {
4209
4254
  readonly [Owner in Extract<ParentStateIdentifier<Src>, ParentStateIdentifier<P> & ValuedStateIdentifier<S>>]: {
4210
4255
  /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4211
4256
  readonly target: ReferenceAt<S, P>;
4212
- /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4257
+ /**
4258
+ * Replaces the complete value of a retained ancestor of the source and target without replacing its active
4259
+ * children. A choice target resolves after the update, and every branch it can reach must stay below the
4260
+ * owner; `data` then constructs only the owner value.
4261
+ */
4213
4262
  readonly update: ReferenceAt<S, Owner>;
4214
4263
  /** Enters a compound or parallel subtree through its declared initialization. */
4215
4264
  readonly initial?: never;
@@ -4641,25 +4690,94 @@ export declare namespace Machine {
4641
4690
  readonly resolve: never;
4642
4691
  } : unknown);
4643
4692
  type AllowedInvokeChannels<R, K extends PropertyKey> = ([InvokeOutput<ResolvedInvoke<R, K>>] extends [never] ? never : "onDone") | ([RegisteredInvokeError<R, K>] extends [never] ? never : "onFailure") | (SourceKind<R, K> extends "streams" ? [Stream.Success<Extract<InvokeResolvedSource<SourceValue<R, K>>, Stream.Stream<any, any, any>>>] extends [never] ? never : "onElement" : never) | (SourceKind<R, K> extends "logic" | "children" ? "onSnapshot" : never);
4644
- type ValidateObjectInvoke<I, R> = I extends ReadonlyArray<unknown> ? {
4645
- readonly [K in keyof I]: ValidateObjectInvoke<I[K], R>;
4646
- } : I extends {
4693
+ type UnreachableInvokeChannelMessage<Channel extends string, Src extends string> = Channel extends "onDone" ? `Invocation '${Src}' never completes, so onDone is unreachable` : Channel extends "onFailure" ? `Invocation '${Src}' cannot fail, so onFailure is unreachable` : Channel extends "onElement" ? `Invocation '${Src}' emits no Stream elements, so onElement is unreachable` : `Invocation '${Src}' has no snapshots; onSnapshot applies only to logic and child invocations`;
4694
+ type InvokeFieldError<K, Src extends string> = K extends "onDone" | "onFailure" | "onElement" | "onSnapshot" ? InvocationDefinitionError<UnreachableInvokeChannelMessage<K, Src>, Src, K> : K extends string ? InvocationDefinitionError<`Invocation '${Src}' does not accept the field '${K}'`, Src, K> : never;
4695
+ type InvokeLifecycleIdOf<I, R> = I extends {
4696
+ readonly id: infer Id extends string;
4697
+ } ? Id : I extends {
4698
+ readonly src: infer Src extends PropertyKey;
4699
+ } ? SourceValue<R, Src> extends ChildMachine<infer Id, Any> ? Id : Extract<Src, string> : never;
4700
+ type LiteralInvokeIdAt<I extends ReadonlyArray<unknown>, K, R> = K extends keyof I ? InvokeLifecycleIdOf<I[K], R> extends infer Id extends string ? string extends Id ? never : Id : never : never;
4701
+ type DuplicateInvokeId<I extends ReadonlyArray<unknown>, K, R> = LiteralInvokeIdAt<I, K, R> extends infer Id ? [
4702
+ Id
4703
+ ] extends [never] ? never : Id extends LiteralInvokeIdAt<I, Exclude<Extract<keyof I, `${number}`>, K>, R> ? Id : never : never;
4704
+ type ValidateInvokeEntry<I, R, Duplicate extends string, Root> = I extends {
4647
4705
  /** Name of the source registered in make. */
4648
4706
  readonly src: infer Src extends PropertyKey;
4649
4707
  } ? {
4650
- readonly [K in keyof I]: K extends AllowedInvokeChannels<R, Src> ? ValidateObjectTransition<I[K]> : K extends "src" | "id" | "address" | "input" ? unknown : never;
4708
+ readonly [K in keyof I]: [Duplicate] extends [never] ? ValidateInvokeField<I, K, R, Extract<Src, string>, Root> : K extends ("id" extends keyof I ? "id" : "src") ? InvocationDefinitionError<`Invocation id '${Duplicate}' is declared more than once in this state`, Extract<Src, string>, K> : ValidateInvokeField<I, K, R, Extract<Src, string>, Root>;
4709
+ } : never;
4710
+ type ValidateInvokeField<I, K extends keyof I, R, Src extends string, Root> = K extends AllowedInvokeChannels<R, Src> ? ValidateObjectTransition<I[K]> & ValidateChoiceUpdate<I[K], R, Root> : K extends "src" | "id" | "address" | "input" ? unknown : InvokeFieldError<K, Src>;
4711
+ type ValidateObjectInvoke<I, R, Root> = I extends ReadonlyArray<unknown> ? number extends I["length"] ? {
4712
+ readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, never, Root>;
4713
+ } : {
4714
+ readonly [K in keyof I]: ValidateInvokeEntry<I[K], R, DuplicateInvokeId<I, K, R>, Root>;
4715
+ } : ValidateInvokeEntry<I, R, never, Root>;
4716
+ type HandlerConfigAt<Config, Path extends string> = Config extends {
4717
+ readonly states: infer Children;
4718
+ } ? Path extends `${infer Head}.${infer Rest}` ? Head extends keyof Children ? HandlerConfigAt<Children[Head], Rest> : never : Path extends keyof Children ? Children[Path] : never : never;
4719
+ type ChoiceConfigAt<Root, Path extends string> = HandlerConfigAt<Root, Path> extends {
4720
+ /** Implements this choice pseudo-state with one required synchronous transition. */
4721
+ readonly choice: infer Choice;
4722
+ } ? Choice : never;
4723
+ type ChoiceBranchDeclaration<Choice, R> = Choice extends {
4724
+ /** Named groups of inspectable destinations used by transition resolvers. */
4725
+ readonly branches: infer G extends keyof Registered<R, "branches">;
4726
+ } ? {
4727
+ readonly [K in Extract<keyof Registered<R, "branches">[G], string>]: {
4728
+ readonly label: `branch '${K}'`;
4729
+ readonly declaration: Registered<R, "branches">[G][K];
4730
+ };
4731
+ }[Extract<keyof Registered<R, "branches">[G], string>] : {
4732
+ readonly label: "transition";
4733
+ readonly declaration: Choice;
4734
+ };
4735
+ type IsBelowOwner<Path extends string, Owner extends string> = Owner extends "" ? Path extends "" ? false : true : Path extends `${Owner}.${string}` ? true : false;
4736
+ type ChoiceBranchEscape<Path extends string, Owner extends string, Choice extends string, Label extends string> = IsBelowOwner<Path, Owner> extends true ? never : TransitionDefinitionError<`Choice '${Choice}' ${Label} targets '${PathName<Path>}' outside the updated owner '${PathName<Owner>}'`, Choice, PathName<Path>>;
4737
+ type ChoiceUpdateEscape<Root, R, Choice extends string, Owner extends string, Visited extends string = never> = Choice extends Visited ? never : ChoiceBranchDeclaration<ChoiceConfigAt<Root, Choice>, R> extends infer Branch ? Branch extends {
4738
+ readonly label: infer Label extends string;
4739
+ readonly declaration: infer D;
4740
+ } ? D extends {
4741
+ /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4742
+ readonly target: infer Ref extends string;
4743
+ } ? [
4744
+ ChoiceConfigAt<Root, PathOf<Ref>>
4745
+ ] extends [never] ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label> : ChoiceUpdateEscape<Root, R, PathOf<Ref>, Owner, Visited | Choice> : D extends {
4746
+ /** Restores the declared history reference, using its fallback on first entry. */
4747
+ readonly history: infer Ref extends string;
4748
+ } ? ChoiceBranchEscape<PathOf<Ref>, Owner, Choice, Label> : D extends {
4749
+ /** Reconstructs root and its initial children from fresh machine input. */
4750
+ readonly initialize: unknown;
4751
+ } ? ChoiceBranchEscape<"", Owner, Choice, Label> : never : never : never;
4752
+ type ChoiceUpdateEscapeOf<D, R, Root> = D extends {
4753
+ /** Selects a declared descendant; its transition or bound branch constructor supplies required values. */
4754
+ readonly target: infer Ref extends string;
4755
+ /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4756
+ readonly update: infer Owner extends string;
4757
+ } ? [ChoiceConfigAt<Root, PathOf<Ref>>] extends [never] ? never : ChoiceUpdateEscape<Root, R, PathOf<Ref>, PathOf<Owner>> : never;
4758
+ type ValidateChoiceUpdate<T, R, Root> = T extends {
4759
+ /** Named groups of inspectable destinations used by transition resolvers. */
4760
+ readonly branches: infer G extends keyof Registered<R, "branches">;
4761
+ } ? {
4762
+ readonly [K in keyof Registered<R, "branches">[G]]: ChoiceUpdateEscapeOf<Registered<R, "branches">[G][K], R, Root>;
4763
+ }[keyof Registered<R, "branches">[G]] extends infer Escape ? [Escape] extends [never] ? unknown : {
4764
+ /** Named groups of inspectable destinations used by transition resolvers. */
4765
+ readonly branches: Escape;
4766
+ } : never : ChoiceUpdateEscapeOf<T, R, Root> extends infer Escape ? [Escape] extends [never] ? unknown : {
4767
+ /** Replaces the complete value of a retained source or ancestor without replacing its active children. */
4768
+ readonly update: Escape;
4651
4769
  } : never;
4652
4770
  type ObjectDeclarations<C> = Extract<keyof C, "on" | "always" | "onDone" | "choice" | "invoke"> | (C extends {
4653
4771
  readonly states: infer Children;
4654
4772
  } ? {
4655
4773
  readonly [K in keyof Children]: ObjectDeclarations<Children[K]>;
4656
4774
  }[keyof Children] : never);
4657
- type ValidateObjectConfig<C, R> = [ObjectDeclarations<C>] extends [never] ? unknown : {
4775
+ type ValidateObjectConfig<C, R, Root = C> = [ObjectDeclarations<C>] extends [never] ? unknown : {
4658
4776
  readonly [K in keyof C]: K extends "states" ? {
4659
- readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R>;
4777
+ readonly [P in keyof C[K]]: ValidateObjectConfig<C[K][P], R, Root>;
4660
4778
  } : K extends "on" ? {
4661
- readonly [P in keyof C[K]]: ValidateObjectTransition<C[K][P]>;
4662
- } : K extends "always" | "onDone" | "choice" ? ValidateObjectTransition<C[K]> : K extends "invoke" ? ValidateObjectInvoke<C[K], R> : unknown;
4779
+ readonly [P in keyof C[K]]: ValidateObjectTransition<C[K][P]> & ValidateChoiceUpdate<C[K][P], R, Root>;
4780
+ } : K extends "always" | "onDone" ? ValidateObjectTransition<C[K]> & ValidateChoiceUpdate<C[K], R, Root> : K extends "choice" ? ValidateObjectTransition<C[K]> : K extends "invoke" ? ValidateObjectInvoke<C[K], R, Root> : unknown;
4663
4781
  };
4664
4782
  type NormalizeObjectInvoke<I, R> = I extends ReadonlyArray<unknown> ? {
4665
4783
  readonly [K in keyof I]: NormalizeObjectInvoke<I[K], R>;
@@ -5699,6 +5817,9 @@ export declare const waitFor: {
5699
5817
  * `prepared.start`. Ordinary callers can continue to use {@link start}, which
5700
5818
  * starts directly and does not allocate the prepared lifecycle boundary.
5701
5819
  *
5820
+ * `prepared.start` is one-shot and scoped: the `Scope` that first evaluates it
5821
+ * owns the machine, and closing that `Scope` is equivalent to `ref.stop`.
5822
+ *
5702
5823
  * ```ts
5703
5824
  * const prepared = yield* Machine.prepare(machine)
5704
5825
  *
@@ -5713,9 +5834,9 @@ export declare const waitFor: {
5713
5834
  * @category constructors
5714
5835
  * @since 0.11.0
5715
5836
  */
5716
- export declare const prepare: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<Prepared<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>, InitialE | E | ActionError<InitialR | R> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, ExcludeCompatibleRuntime<ExecutionServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>>;
5837
+ export declare const prepare: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<Prepared<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>, InitialE | E | ActionError<InitialR | R> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Scope.Scope | ExcludeCompatibleRuntime<ExecutionServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>>;
5717
5838
  /**
5718
- * Starts a machine.
5839
+ * Starts a machine owned by the current `Scope`.
5719
5840
  *
5720
5841
  * **When to use**
5721
5842
  *
@@ -5729,6 +5850,13 @@ export declare const prepare: <const States extends Machine.StateSchemas, const
5729
5850
  * publishes the new state, delivers emitted events, and then starts invokes
5730
5851
  * for entered states.
5731
5852
  *
5853
+ * The machine is a scoped resource, like `Effect.forkScoped`. Closing the
5854
+ * `Scope` is equivalent to `ref.stop`: active invocations are interrupted,
5855
+ * owned children stop, the snapshot becomes `stopped`, and later sends fail
5856
+ * with `StoppedError`. An earlier `ref.stop` or terminal completion leaves the
5857
+ * finalizer with nothing to do. Own a `Scope` explicitly, for example with
5858
+ * `Scope.make` and `Scope.provide`, when the machine must outlive the caller.
5859
+ *
5732
5860
  * **Gotchas**
5733
5861
  *
5734
5862
  * The returned handle's `send` operation only enqueues events. Transition
@@ -5755,10 +5883,10 @@ export declare const prepare: <const States extends Machine.StateSchemas, const
5755
5883
  * Idle: {}
5756
5884
  * }
5757
5885
  * })
5758
- * const state = Effect.gen(function*() {
5886
+ * const state = Effect.scoped(Effect.gen(function*() {
5759
5887
  * const ref = yield* Machine.start(machine)
5760
5888
  * return yield* ref.state
5761
- * })
5889
+ * }))
5762
5890
  * ```
5763
5891
  *
5764
5892
  * @see {@link plan} for inspecting the same transition plan without executing it.
@@ -5766,12 +5894,16 @@ export declare const prepare: <const States extends Machine.StateSchemas, const
5766
5894
  * @category constructors
5767
5895
  * @since 0.4.0
5768
5896
  */
5769
- export declare const start: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<MachineRef<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>>, InitialE | E | ActionError<InitialR | R> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, ExcludeCompatibleRuntime<ExecutionServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>;
5897
+ export declare const start: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<MachineRef<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>>, InitialE | E | ActionError<InitialR | R> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Scope.Scope | ExcludeCompatibleRuntime<ExecutionServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>;
5770
5898
  /**
5771
- * Starts a fresh managed runtime from a decoded logical snapshot.
5899
+ * Starts a fresh managed runtime from a decoded logical snapshot, owned by the
5900
+ * current `Scope`.
5772
5901
  *
5773
5902
  * **Details**
5774
5903
  *
5904
+ * The resumed machine has the same scoped lifetime as {@link start}: closing
5905
+ * the `Scope` is equivalent to `ref.stop`.
5906
+ *
5775
5907
  * `resume` validates and normalizes the supplied snapshot before publishing it
5776
5908
  * as the first state. It does not call the machine's initial function, replay
5777
5909
  * entry or transition actions, re-deliver raised or emitted events, or
@@ -5810,12 +5942,12 @@ export declare const start: <const States extends Machine.StateSchemas, const Ev
5810
5942
  * Idle: {}
5811
5943
  * }
5812
5944
  * })
5813
- * const resumed = Effect.gen(function*() {
5945
+ * const resumed = Effect.scoped(Effect.gen(function*() {
5814
5946
  * const initial = yield* Machine.planInitial(machine)
5815
5947
  * const encoded = yield* Machine.encodeSnapshot(machine, initial.state)
5816
5948
  * const snapshot = yield* Machine.decodeSnapshot(machine, encoded)
5817
5949
  * return yield* Machine.resume(machine, snapshot)
5818
- * })
5950
+ * }))
5819
5951
  * ```
5820
5952
  *
5821
5953
  * @see {@link decodeSnapshot} for the schema and transport boundary.
@@ -5823,5 +5955,5 @@ export declare const start: <const States extends Machine.StateSchemas, const Ev
5823
5955
  * @category constructors
5824
5956
  * @since 0.4.0
5825
5957
  */
5826
- export declare const resume: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, snapshot: Machine.Snapshot<States>) => Effect.Effect<MachineRef<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>>, MachineSchemaDecodeError, ExcludeCompatibleRuntime<ExecutionServices<R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>;
5958
+ export declare const resume: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], const Input extends Schema.Top = typeof Schema.Void, UnhandledStates extends Machine.StateIdentifier<States> = Machine.StateIdentifier<States>, E = never, R = never, InitialE = never, InitialR = never, FinalStates extends Machine.StateIdentifier<States> = never, Output = never, OutputStates extends Machine.StateIdentifier<States> = never, InputEvents extends ReadonlyArray<Machine.TaggedSchema> = Events, ParentEvents extends ReadonlyArray<Machine.TaggedSchema> = readonly []>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates, InputEvents, ParentEvents> & EnsureExecutable<States, UnhandledStates, OutputStates> & Machine.RootCompatible<ParentEvents>, snapshot: Machine.Snapshot<States>) => Effect.Effect<MachineRef<Machine.Snapshot<States>, Machine.EventInputOf<InputEvents>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, Output, Machine.EmittedEventOf<Emits>>, MachineSchemaDecodeError, Scope.Scope | ExcludeCompatibleRuntime<ExecutionServices<R>, Machine.EventOf<Events>, Machine.EmittedEventOf<Emits>>>;
5827
5959
  //# sourceMappingURL=Machine.d.ts.map