@typeonce/effect-machine 0.1.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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE +5 -0
  3. package/README.md +117 -0
  4. package/dist/AtomMachine.d.ts +141 -0
  5. package/dist/AtomMachine.d.ts.map +1 -0
  6. package/dist/AtomMachine.js +191 -0
  7. package/dist/AtomMachine.js.map +1 -0
  8. package/dist/ClusterMachine.d.ts +250 -0
  9. package/dist/ClusterMachine.d.ts.map +1 -0
  10. package/dist/ClusterMachine.js +280 -0
  11. package/dist/ClusterMachine.js.map +1 -0
  12. package/dist/Machine.d.ts +2587 -0
  13. package/dist/Machine.d.ts.map +1 -0
  14. package/dist/Machine.js +923 -0
  15. package/dist/Machine.js.map +1 -0
  16. package/dist/cluster.d.ts +2 -0
  17. package/dist/cluster.d.ts.map +1 -0
  18. package/dist/cluster.js +2 -0
  19. package/dist/cluster.js.map +1 -0
  20. package/dist/index.d.ts +2 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +2 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/internal/machineErrors.d.ts +109 -0
  25. package/dist/internal/machineErrors.d.ts.map +1 -0
  26. package/dist/internal/machineErrors.js +65 -0
  27. package/dist/internal/machineErrors.js.map +1 -0
  28. package/dist/internal/machineModel.d.ts +88 -0
  29. package/dist/internal/machineModel.d.ts.map +1 -0
  30. package/dist/internal/machineModel.js +713 -0
  31. package/dist/internal/machineModel.js.map +1 -0
  32. package/dist/internal/machinePlanner.d.ts +64 -0
  33. package/dist/internal/machinePlanner.d.ts.map +1 -0
  34. package/dist/internal/machinePlanner.js +594 -0
  35. package/dist/internal/machinePlanner.js.map +1 -0
  36. package/dist/internal/machineProcess.d.ts +16 -0
  37. package/dist/internal/machineProcess.d.ts.map +1 -0
  38. package/dist/internal/machineProcess.js +170 -0
  39. package/dist/internal/machineProcess.js.map +1 -0
  40. package/dist/internal/machineRuntime.d.ts +119 -0
  41. package/dist/internal/machineRuntime.d.ts.map +1 -0
  42. package/dist/internal/machineRuntime.js +354 -0
  43. package/dist/internal/machineRuntime.js.map +1 -0
  44. package/dist/reactivity.d.ts +2 -0
  45. package/dist/reactivity.d.ts.map +1 -0
  46. package/dist/reactivity.js +2 -0
  47. package/dist/reactivity.js.map +1 -0
  48. package/package.json +76 -0
@@ -0,0 +1,2587 @@
1
+ /**
2
+ * Schema-first machine definitions.
3
+ *
4
+ * @since 4.0.0
5
+ */
6
+ import type * as Cause from "effect/Cause";
7
+ import * as Effect from "effect/Effect";
8
+ import * as Option from "effect/Option";
9
+ import { type Pipeable } from "effect/Pipeable";
10
+ import type * as Schema from "effect/Schema";
11
+ import type * as Scope from "effect/Scope";
12
+ import type * as Stream from "effect/Stream";
13
+ import type * as Types from "effect/Types";
14
+ import type { ChildAlreadyExistsError, InfiniteTransitionError, MachineSchemaDecodeError, MachineSchemaEncodeError, ProcessLocalError, StartupError, StoppedError } from "./internal/machineErrors.js";
15
+ import * as Model from "./internal/machineModel.js";
16
+ import * as internalPlanner from "./internal/machinePlanner.js";
17
+ import * as internalRuntime from "./internal/machineRuntime.js";
18
+ /**
19
+ * String literal type used as the runtime type identifier for `Machine`
20
+ * values.
21
+ *
22
+ * @category type IDs
23
+ * @since 4.0.0
24
+ */
25
+ export type TypeId = "~effect/Machine";
26
+ /**
27
+ * Runtime type identifier attached to `Machine` values.
28
+ *
29
+ * @category type IDs
30
+ * @since 4.0.0
31
+ */
32
+ export declare const TypeId: TypeId;
33
+ /**
34
+ * Type identifier used for the synthetic event passed to startup lifecycle
35
+ * actions.
36
+ *
37
+ * @category type IDs
38
+ * @since 4.0.0
39
+ */
40
+ export declare const InitialEventTypeId: typeof internalPlanner.InitialEventTypeId;
41
+ /**
42
+ * Synthetic event passed to entry, exit, always, invoke, and output callbacks
43
+ * that run while the machine is settling its initial state.
44
+ *
45
+ * @category models
46
+ * @since 4.0.0
47
+ */
48
+ export interface InitialEvent {
49
+ readonly _tag: typeof InitialEventTypeId;
50
+ }
51
+ /**
52
+ * Synthetic event value used while the machine settles its initial state.
53
+ *
54
+ * @category constructors
55
+ * @since 4.0.0
56
+ */
57
+ export declare const InitialEvent: InitialEvent;
58
+ /**
59
+ * Returns `true` if a value is the synthetic machine initial event.
60
+ *
61
+ * @category guards
62
+ * @since 4.0.0
63
+ */
64
+ export declare const isInitialEvent: (u: unknown) => u is InitialEvent;
65
+ type IsAny<A> = 0 extends (1 & A) ? true : false;
66
+ /**
67
+ * A schema-first machine definition.
68
+ *
69
+ * **Details**
70
+ *
71
+ * Machines support atomic, compound, parallel, and final states together with
72
+ * completion transitions, eventless transitions, raised events, actions,
73
+ * spawned children, and state-scoped invokes. Schemas validate machine
74
+ * boundaries while preserving decoded state, event, output, error, and service
75
+ * types throughout planning and execution.
76
+ *
77
+ * **Gotchas**
78
+ *
79
+ * History states, delayed transitions, and declarative first-class guards are
80
+ * not part of the current API. Conditional behavior can be expressed in typed
81
+ * handlers with ordinary TypeScript control flow.
82
+ *
83
+ * @category models
84
+ * @since 4.0.0
85
+ */
86
+ export interface Machine<States extends Machine.StateSchemas, Events extends ReadonlyArray<Machine.TaggedSchema>, 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, Emits extends ReadonlyArray<Machine.TaggedSchema> = readonly [], OutputStates extends Machine.StateIdentifier<States> = never> extends Pipeable {
87
+ readonly [TypeId]: TypeId;
88
+ readonly states: States;
89
+ readonly events: Events;
90
+ readonly emits: Emits;
91
+ readonly input: Input | undefined;
92
+ readonly id: string | undefined;
93
+ /** @internal */
94
+ readonly stateNodes: Machine.StateNodes;
95
+ /** @internal */
96
+ readonly makeTargetBuilder: <Source extends Machine.StateIdentifier<States>>(source: Source) => Machine.TargetBuilder<States, Source>;
97
+ readonly handlers: Machine.StateConfigs<States, Events, Emits, UnhandledStates, Machine.TagOf<Events[number]>, E, R>;
98
+ readonly handle: Machine.Handler<States, Events, Emits, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, OutputStates>;
99
+ /** @internal */
100
+ readonly initial: (...args: [...Machine.InputArgs<Input>]) => Machine.InitialResult<States, InitialE, InitialR>;
101
+ }
102
+ export {
103
+ /**
104
+ * Error returned by `spawn` when a child process with the same id already
105
+ * exists for the current machine.
106
+ *
107
+ * @category errors
108
+ * @since 4.0.0
109
+ */
110
+ ChildAlreadyExistsError,
111
+ /**
112
+ * Error returned when a machine does not stabilize within the maximum
113
+ * number of macrostep iterations.
114
+ *
115
+ * @category errors
116
+ * @since 4.0.0
117
+ */
118
+ InfiniteTransitionError,
119
+ /**
120
+ * Error returned when a machine contract value does not match the schema or
121
+ * structural configuration declared for a machine boundary.
122
+ *
123
+ * @category errors
124
+ * @since 4.0.0
125
+ */
126
+ MachineSchemaDecodeError,
127
+ /**
128
+ * Error returned when a decoded machine snapshot cannot be encoded through
129
+ * its declared state or output schemas.
130
+ *
131
+ * @category errors
132
+ * @since 4.0.0
133
+ */
134
+ MachineSchemaEncodeError,
135
+ /**
136
+ * Error returned when standalone action execution attempts an operation that
137
+ * requires a managed machine process.
138
+ *
139
+ * @category errors
140
+ * @since 4.0.0
141
+ */
142
+ ProcessLocalError,
143
+ /**
144
+ * Error returned when a machine fails while running startup lifecycle
145
+ * logic after the initial state has been computed.
146
+ *
147
+ * @category errors
148
+ * @since 4.0.0
149
+ */
150
+ StartupError,
151
+ /**
152
+ * Error returned by `join` when a running machine is stopped before
153
+ * producing an output.
154
+ *
155
+ * @category errors
156
+ * @since 4.0.0
157
+ */
158
+ StoppedError } from "./internal/machineErrors.js";
159
+ declare const RuntimeRequirementTypeId = "~effect/Machine/RuntimeRequirement";
160
+ declare const ActionRequirementTypeId = "~effect/Machine/ActionRequirement";
161
+ type MachineRuntimeRequirement = internalRuntime.MachineRuntime;
162
+ /**
163
+ * Opaque marker used to keep staged action errors and services separate from
164
+ * the Effect that plans a machine step.
165
+ *
166
+ * @category services
167
+ * @since 4.0.0
168
+ */
169
+ export interface ActionRequirement<Error, Requirements> {
170
+ readonly [ActionRequirementTypeId]: {
171
+ readonly error: Types.Covariant<Error>;
172
+ readonly requirements: Types.Covariant<Requirements>;
173
+ };
174
+ }
175
+ /**
176
+ * Extracts the typed error channel of staged machine actions.
177
+ *
178
+ * @category utility types
179
+ * @since 4.0.0
180
+ */
181
+ export type ActionError<Requirements> = Requirements extends ActionRequirement<infer Error, any> ? Error : never;
182
+ /**
183
+ * Extracts the service requirements of staged machine actions.
184
+ *
185
+ * @category utility types
186
+ * @since 4.0.0
187
+ */
188
+ export type ActionServices<Requirements> = Requirements extends ActionRequirement<any, infer Services> ? Services : never;
189
+ /**
190
+ * Removes staged action requirements from machine planning services.
191
+ *
192
+ * @category utility types
193
+ * @since 4.0.0
194
+ */
195
+ export type PlanningServices<Requirements> = Exclude<Requirements, ActionRequirement<any, any>>;
196
+ /**
197
+ * Resolves all services needed to execute a machine at runtime.
198
+ *
199
+ * @category utility types
200
+ * @since 4.0.0
201
+ */
202
+ export type ExecutionServices<Requirements> = Exclude<PlanningServices<Requirements>, MachineRuntimeRequirement> | Exclude<ActionServices<Requirements>, MachineRuntimeRequirement>;
203
+ /**
204
+ * Runtime capability available to machine actions.
205
+ *
206
+ * @category models
207
+ * @since 4.0.0
208
+ */
209
+ export interface Runtime<in Events, in Emits> {
210
+ readonly raise: (event: Events) => Effect.Effect<void, MachineSchemaDecodeError | StoppedError>;
211
+ readonly sendParent: (event: Emits) => Effect.Effect<void, MachineSchemaDecodeError | StoppedError>;
212
+ }
213
+ /**
214
+ * Namespace containing type-level members associated with `Runtime`.
215
+ *
216
+ * @since 4.0.0
217
+ */
218
+ export declare namespace Runtime {
219
+ /**
220
+ * Protocol annotation accepted by {@link runtime}.
221
+ *
222
+ * @category models
223
+ * @since 4.0.0
224
+ */
225
+ interface Protocol {
226
+ readonly events?: unknown;
227
+ readonly emits?: unknown;
228
+ }
229
+ /**
230
+ * Extracts the events required by a runtime protocol annotation.
231
+ *
232
+ * @category utility types
233
+ * @since 4.0.0
234
+ */
235
+ type Events<Protocol> = Protocol extends {
236
+ readonly events: infer Events;
237
+ } ? Events : never;
238
+ /**
239
+ * Extracts the emitted events required by a runtime protocol annotation.
240
+ *
241
+ * @category utility types
242
+ * @since 4.0.0
243
+ */
244
+ type Emits<Protocol> = Protocol extends {
245
+ readonly emits: infer Emits;
246
+ } ? Emits : never;
247
+ /**
248
+ * Opaque service requirement for a machine runtime capability.
249
+ *
250
+ * @category services
251
+ * @since 4.0.0
252
+ */
253
+ interface Requirement<Events, Emits> {
254
+ readonly [RuntimeRequirementTypeId]: {
255
+ readonly events: Events;
256
+ readonly emits: Emits;
257
+ };
258
+ }
259
+ }
260
+ type ExcludeCompatibleRuntime<Requirements, Events, Emits> = Requirements extends Runtime.Requirement<infer RequiredEvents, infer RequiredEmits> ? IsAny<Requirements> extends true ? Requirements : [RequiredEvents] extends [Events] ? [RequiredEmits] extends [Emits] ? never : Requirements : Requirements : Requirements;
261
+ type IncompatibleRuntime<Requirements, Events, Emits> = Requirements extends Runtime.Requirement<infer RequiredEvents, infer RequiredEmits> ? IsAny<Requirements> extends true ? never : [RequiredEvents] extends [Events] ? [RequiredEmits] extends [Emits] ? never : Requirements : Requirements : never;
262
+ declare const RuntimeCompatibilityErrorTypeId = "~effect/Machine/RuntimeCompatibilityError";
263
+ declare const InvokeTypeId: unique symbol;
264
+ type EnsureCompatibleRuntime<Requirements, Events, Emits> = [IncompatibleRuntime<Requirements, Events, Emits>] extends [
265
+ never
266
+ ] ? unknown : {
267
+ readonly [RuntimeCompatibilityErrorTypeId]: IncompatibleRuntime<Requirements, Events, Emits>;
268
+ };
269
+ type StateDefinitionError<Message extends string> = {
270
+ readonly "~effect/Machine/DefinitionError": Message;
271
+ };
272
+ type ValidateStateTree<States extends Machine.StateSchemas> = {
273
+ readonly [Key in keyof States]: ValidateStateNode<States[Key]>;
274
+ };
275
+ type ValidateStateNode<Node> = Node extends Machine.TaggedSchema ? unknown : Node extends {
276
+ readonly schema: Machine.TaggedSchema;
277
+ } ? ValidateStateNodeConfig<Node> : StateDefinitionError<"State nodes must be tagged schemas or state node configs">;
278
+ type ValidateStateNodeConfig<Node extends {
279
+ readonly schema: Machine.TaggedSchema;
280
+ }> = Node extends {
281
+ readonly states: infer Children;
282
+ } ? ValidateStateNodeWithChildren<Node, Children> : ValidateStateNodeWithoutChildren<Node>;
283
+ type ValidateOutputSchema<Node> = "output" extends keyof Node ? Node extends {
284
+ readonly output: Schema.Top;
285
+ } ? unknown : StateDefinitionError<"State output must be a schema"> : unknown;
286
+ type ValidateStateNodeWithChildren<Node extends {
287
+ readonly schema: Machine.TaggedSchema;
288
+ }, Children> = Children extends Machine.StateSchemas ? Node extends {
289
+ readonly type: "final";
290
+ } ? StateDefinitionError<"Final states cannot declare child states"> : Node extends {
291
+ readonly type: "parallel";
292
+ } ? "initial" extends keyof Node ? StateDefinitionError<"Parallel states cannot declare an initial child"> : {
293
+ readonly states: ValidateStateTree<Children>;
294
+ } & ValidateOutputSchema<Node> : "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output"> : ValidateCompoundStateNode<Node, Children> : StateDefinitionError<"Child states must be a state tree">;
295
+ type ValidateCompoundStateNode<Node extends {
296
+ readonly schema: Machine.TaggedSchema;
297
+ }, Children extends Machine.StateSchemas> = Node extends {
298
+ readonly initial: infer Initial;
299
+ } ? Initial extends Extract<keyof Children, string> ? {
300
+ readonly states: ValidateStateTree<Children>;
301
+ } : StateDefinitionError<"Compound initial must be one of its direct child keys"> : StateDefinitionError<"Compound states must declare an initial child">;
302
+ type ValidateStateNodeWithoutChildren<Node extends {
303
+ readonly schema: Machine.TaggedSchema;
304
+ }> = "initial" extends keyof Node ? StateDefinitionError<"Atomic states cannot declare an initial child"> : Node extends {
305
+ readonly type: infer Type;
306
+ } ? Type extends "final" ? ValidateOutputSchema<Node> : Type extends "active" | undefined ? "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output"> : unknown : StateDefinitionError<"State node type must be active, final, or parallel"> : "output" extends keyof Node ? StateDefinitionError<"Only final and parallel states can declare output"> : unknown;
307
+ type DefineStateTreeInput<States extends Machine.StateSchemas> = {
308
+ readonly [Key in keyof States]: DefineStateNodeInput<States[Key]>;
309
+ };
310
+ type DefineStateNodeInput<Node> = Node extends Machine.TaggedSchema ? Node : Node extends {
311
+ readonly type: "parallel";
312
+ readonly states: infer Children extends Machine.StateSchemas;
313
+ } ? Omit<Node, "states"> & {
314
+ readonly states: DefineStateTreeInput<Children>;
315
+ } : Node extends {
316
+ readonly states: infer Children extends Machine.StateSchemas;
317
+ } ? Omit<Node, "initial" | "states"> & {
318
+ readonly initial: Extract<keyof Children, string>;
319
+ readonly states: DefineStateTreeInput<Children>;
320
+ } : Node;
321
+ type ValidateDefinedStates<States extends Machine.StateSchemas> = [States] extends [
322
+ Machine.ValidateStateSchemas<States>
323
+ ] ? [] : [validation: Machine.ValidateStateSchemas<States>];
324
+ declare const SnapshotBuilderStateTypeId: unique symbol;
325
+ type SnapshotBuilderComplete<Regions> = {
326
+ readonly [SnapshotBuilderStateTypeId]: Regions;
327
+ };
328
+ type InitialSnapshotBuilderWithPrefix<States extends Machine.StateSchemas, Prefix extends string = ""> = {
329
+ readonly [Key in Extract<keyof States, string>]: InitialSnapshotMethod<States, Key, Prefix>;
330
+ };
331
+ type InitialSnapshotMethod<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string> = (...args: InitialSnapshotArguments<States, StateId, Prefix>) => InitialSnapshotResult<States, StateId, Prefix>;
332
+ type InitialSnapshotArguments<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
333
+ readonly type: "parallel";
334
+ readonly states: infer Children extends Machine.StateSchemas;
335
+ } ? [
336
+ value: Machine.NodeSchema<Node>["Type"],
337
+ states: (builder: InitialParallelBuilder<Children, Path>) => SnapshotBuilderComplete<InitialSnapshotRegionsWithPrefix<Children, Path>>
338
+ ] : Node extends {
339
+ readonly states: infer Children extends Machine.StateSchemas;
340
+ } ? Node extends {
341
+ readonly initial: infer Initial extends Extract<keyof Children, string>;
342
+ } ? [
343
+ value: Machine.NodeSchema<Node>["Type"],
344
+ state: (builder: Pick<InitialSnapshotBuilderWithPrefix<Children, Path>, Initial>) => InitialSnapshotResult<Children, Initial, Path>
345
+ ] : never : [value: Machine.NodeSchema<Node>["Type"]] : never;
346
+ type InitialSnapshotResult<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
347
+ readonly type: "parallel";
348
+ readonly states: infer Children extends Machine.StateSchemas;
349
+ } ? Machine.ParallelSnapshot<Path, Machine.NodeSchema<Node>["Type"], InitialSnapshotRegionsWithPrefix<Children, Path>> : Node extends {
350
+ readonly states: infer Children extends Machine.StateSchemas;
351
+ } ? Node extends {
352
+ readonly initial: infer Initial extends Extract<keyof Children, string>;
353
+ } ? Machine.CompoundSnapshot<Path, Machine.NodeSchema<Node>["Type"], InitialSnapshotResult<Children, Initial, Path>> : never : Machine.AtomicSnapshot<Path, Machine.NodeSchema<Node>["Type"]> : never;
354
+ type InitialSnapshotRegionsWithPrefix<States extends Machine.StateSchemas, Prefix extends string> = {
355
+ readonly [Key in Extract<keyof States, string>]: InitialSnapshotResult<States, Key, Prefix>;
356
+ };
357
+ type InitialParallelBuilder<States extends Machine.StateSchemas, Prefix extends string, Remaining extends Extract<keyof States, string> = Extract<keyof States, string>, Regions = {}> = SnapshotBuilderComplete<Regions> & {
358
+ readonly [Key in Remaining]: (...args: InitialSnapshotArguments<States, Key, Prefix>) => InitialParallelBuilder<States, Prefix, Exclude<Remaining, Key>, Regions & {
359
+ readonly [Region in Key]: InitialSnapshotResult<States, Key, Prefix>;
360
+ }>;
361
+ };
362
+ type FullSnapshotBuilderWithPrefix<States extends Machine.StateSchemas, Prefix extends string = ""> = {
363
+ readonly [Key in Extract<keyof States, string>]: FullSnapshotMethod<States, Key, Prefix>;
364
+ };
365
+ type FullSnapshotMethod<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string> = (...args: FullSnapshotArguments<States, StateId, Prefix>) => FullSnapshotResult<States, StateId, Prefix>;
366
+ type FullSnapshotArguments<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
367
+ readonly type: "parallel";
368
+ readonly states: infer Children extends Machine.StateSchemas;
369
+ } ? [
370
+ value: Machine.NodeSchema<Node>["Type"],
371
+ states: (builder: FullParallelBuilder<Children, Path>) => SnapshotBuilderComplete<Machine.SnapshotRegionsWithPrefix<Children, Path>>
372
+ ] : Node extends {
373
+ readonly states: infer Children extends Machine.StateSchemas;
374
+ } ? [
375
+ value: Machine.NodeSchema<Node>["Type"],
376
+ state: (builder: FullSnapshotBuilderWithPrefix<Children, Path>) => Machine.SnapshotWithPrefix<Children, Path>
377
+ ] : [value: Machine.NodeSchema<Node>["Type"]] : never;
378
+ type FullSnapshotResult<States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = Machine.SnapshotByIdentifierWithPath<States, StateId, Path>;
379
+ type FullParallelBuilder<States extends Machine.StateSchemas, Prefix extends string, Remaining extends Extract<keyof States, string> = Extract<keyof States, string>, Regions = {}> = SnapshotBuilderComplete<Regions> & {
380
+ readonly [Key in Remaining]: (...args: FullSnapshotArguments<States, Key, Prefix>) => FullParallelBuilder<States, Prefix, Exclude<Remaining, Key>, Regions & {
381
+ readonly [Region in Key]: FullSnapshotResult<States, Key, Prefix>;
382
+ }>;
383
+ };
384
+ type ParentPath<Path extends string> = Path extends `${infer Parent}.${infer Child}` ? Child extends `${string}.${string}` ? `${Parent}.${ParentPath<Child>}` : Parent : never;
385
+ type IsCompoundNode<Node> = Node extends {
386
+ readonly type: "parallel";
387
+ } ? false : Node extends {
388
+ readonly states: Machine.StateSchemas;
389
+ } ? true : false;
390
+ type NearestCompoundScope<States extends Machine.StateSchemas, Source extends Machine.StateIdentifier<States>> = IsCompoundNode<Machine.NodeByIdentifier<States, Source>> extends true ? Source : ParentPath<Source> extends infer Parent extends Machine.StateIdentifier<States> ? NearestCompoundScope<States, Parent> : never;
391
+ type ChildrenOf<States extends Machine.StateSchemas, Path extends Machine.StateIdentifier<States>> = Machine.NodeByIdentifier<States, Path> extends {
392
+ readonly states: infer Children extends Machine.StateSchemas;
393
+ } ? Children : never;
394
+ type StateIdentifierFromPath<States extends Machine.StateSchemas, Path extends string> = Extract<Path, Machine.StateIdentifier<States>>;
395
+ type LocalTargetResult<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends {
396
+ readonly states: infer Children extends Machine.StateSchemas;
397
+ } ? LocalTargetResultWithPrefix<AllStates, Children, Path> : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>;
398
+ type LocalTargetResultWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
399
+ readonly [Key in Extract<keyof States, string>]: LocalTargetResult<AllStates, States, Key, Prefix>;
400
+ }[Extract<keyof States, string>];
401
+ type LocalTargetBuilderWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
402
+ readonly [Key in Extract<keyof States, string>]: LocalTargetMethod<AllStates, States, Key, Prefix>;
403
+ };
404
+ type LocalTargetMethod<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
405
+ readonly states: infer Children extends Machine.StateSchemas;
406
+ } ? <Result extends LocalTargetResultWithPrefix<AllStates, Children, Path>>(value: Machine.NodeSchema<Node>["Type"], state: (builder: LocalTargetBuilderWithPrefix<AllStates, Children, Path>) => Result) => Result : (value: Machine.NodeSchema<Node>["Type"]) => Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>> : never;
407
+ type LocalTargetBuilderForScope<States extends Machine.StateSchemas, Scope extends Machine.StateIdentifier<States>> = ChildrenOf<States, Scope> extends infer Children extends Machine.StateSchemas ? LocalTargetBuilderWithPrefix<States, Children, Scope> & {
408
+ /**
409
+ * Updates the value of the state containing the local group and moves to
410
+ * one of the states inside it. Values in other active branches are kept.
411
+ *
412
+ * @since 4.0.0
413
+ */
414
+ readonly with: <Result extends LocalTargetResultWithPrefix<States, Children, Scope>>(value: Machine.StateByIdentifier<States, Scope>, state: (builder: LocalTargetBuilderWithPrefix<States, Children, Scope>) => Result) => Result;
415
+ } : {};
416
+ type BranchTargetResult<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends {
417
+ readonly states: infer Children extends Machine.StateSchemas;
418
+ } ? BranchTargetResultWithPrefix<AllStates, Children, Path> : Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>>;
419
+ type BranchTargetResultWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
420
+ readonly [Key in Extract<keyof States, string>]: BranchTargetResult<AllStates, States, Key, Prefix>;
421
+ }[Extract<keyof States, string>];
422
+ type BranchTargetBuilderWithPrefix<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, Prefix extends string> = {
423
+ readonly [Key in Extract<keyof States, string>]: BranchTargetMethod<AllStates, States, Key, Prefix>;
424
+ };
425
+ type BranchTargetMethod<AllStates extends Machine.StateSchemas, States extends Machine.StateSchemas, StateId extends Extract<keyof States, string>, Prefix extends string, Path extends string = Machine.JoinPath<Prefix, StateId>> = States[StateId] extends infer Node ? Node extends {
426
+ readonly states: infer Children extends Machine.StateSchemas;
427
+ } ? (<Result extends BranchTargetResultWithPrefix<AllStates, Children, Path>>(value: Machine.NodeSchema<Node>["Type"], state: (builder: BranchTargetBuilderWithPrefix<AllStates, Children, Path>) => Result) => Result) & BranchTargetBuilderWithPrefix<AllStates, Children, Path> : (value: Machine.NodeSchema<Node>["Type"]) => Machine.Target<AllStates, StateIdentifierFromPath<AllStates, Path>> : never;
428
+ type BranchTargetBuilderForRoot<States extends Machine.StateSchemas, Root extends Extract<keyof States, string>> = {
429
+ readonly [Key in Root]: BranchTargetMethod<States, States, Key, "">;
430
+ };
431
+ type SpawnRequirements<Requirements> = Exclude<Requirements, Scope.Scope>;
432
+ type SpawnIdError<Options extends SpawnOptions> = "id" extends keyof Options ? Options extends {
433
+ readonly id?: infer Id;
434
+ } ? [Id] extends [undefined] ? never : ChildAlreadyExistsError : ChildAlreadyExistsError : never;
435
+ type SpawnError<Options extends SpawnOptions> = SpawnIdError<Options>;
436
+ type SpawnResult<State, Event, Error, Requirements, Output, SpawnError, InitialError = never> = Effect.Effect<MachineRef<State, Event, Error | InitialError, Output>, SpawnError | InitialError, MachineRuntimeRequirement | SpawnRequirements<Requirements>>;
437
+ /**
438
+ * Represents the active or terminal lifecycle state of a running machine.
439
+ *
440
+ * **Details**
441
+ *
442
+ * Failures retain the last successfully published machine state and expose the
443
+ * complete `Cause`. Stopped machines are distinct from machines that complete
444
+ * with output or fail while processing an event.
445
+ *
446
+ * @category models
447
+ * @since 4.0.0
448
+ */
449
+ export type RuntimeSnapshot<State, Error = never, Output = never> = {
450
+ readonly status: "active";
451
+ readonly state: State;
452
+ } | {
453
+ readonly status: "done";
454
+ readonly state: State;
455
+ readonly output: Output;
456
+ } | {
457
+ readonly status: "error";
458
+ readonly state: State;
459
+ readonly cause: Cause.Cause<Error>;
460
+ } | {
461
+ readonly status: "stopped";
462
+ readonly state: State;
463
+ };
464
+ /**
465
+ * Represents a classified terminal outcome derived from a runtime snapshot.
466
+ *
467
+ * @category models
468
+ * @since 4.0.0
469
+ */
470
+ export type RuntimeOutcome<State, Error = never, Output = never> = {
471
+ readonly _tag: "Done";
472
+ readonly output: Output;
473
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
474
+ readonly status: "done";
475
+ }>;
476
+ } | {
477
+ readonly _tag: "Failure";
478
+ readonly error: Error;
479
+ readonly cause: Cause.Cause<Error>;
480
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
481
+ readonly status: "error";
482
+ }>;
483
+ } | {
484
+ readonly _tag: "Defect";
485
+ readonly defect: unknown;
486
+ readonly cause: Cause.Cause<Error>;
487
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
488
+ readonly status: "error";
489
+ }>;
490
+ } | {
491
+ readonly _tag: "Interrupted";
492
+ readonly cause: Cause.Cause<Error>;
493
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
494
+ readonly status: "error";
495
+ }>;
496
+ } | {
497
+ readonly _tag: "Cause";
498
+ readonly cause: Cause.Cause<Error>;
499
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
500
+ readonly status: "error";
501
+ }>;
502
+ } | {
503
+ readonly _tag: "Stopped";
504
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
505
+ readonly status: "stopped";
506
+ }>;
507
+ };
508
+ /**
509
+ * Provides access to a running machine's state, lifecycle, event input, and
510
+ * termination operations.
511
+ *
512
+ * **Gotchas**
513
+ *
514
+ * `send` reports whether an event was accepted for delivery. Errors that occur
515
+ * while asynchronously processing an accepted event are observed through
516
+ * `snapshot`, `changes`, or `join`. Sending after termination fails with
517
+ * `StoppedError`.
518
+ *
519
+ * @category models
520
+ * @since 4.0.0
521
+ */
522
+ export interface MachineRef<out State, in Event, out Error = never, out Output = never> {
523
+ readonly id: string;
524
+ readonly sessionId: string;
525
+ readonly state: Effect.Effect<State>;
526
+ readonly snapshot: Effect.Effect<RuntimeSnapshot<State, Error, Output>>;
527
+ readonly changes: Stream.Stream<RuntimeSnapshot<State, Error, Output>>;
528
+ readonly join: Effect.Effect<Output, Error | StoppedError>;
529
+ readonly stop: Effect.Effect<void>;
530
+ readonly send: (event: Event) => Effect.Effect<void, StoppedError>;
531
+ /** Returns the current directly owned child for a typed descriptor. */
532
+ readonly child: <Child extends ChildMachine.Any>(child: Child) => Effect.Effect<Option.Option<ChildMachine.Ref<Child>>>;
533
+ /** Streams activation, replacement, and removal of a directly owned child. */
534
+ readonly childChanges: <Child extends ChildMachine.Any>(child: Child) => Stream.Stream<Option.Option<ChildMachine.Ref<Child>>>;
535
+ }
536
+ /**
537
+ * Machine-specific process logic used by `spawn` and `invoke`.
538
+ *
539
+ * @category models
540
+ * @since 4.0.0
541
+ */
542
+ export interface Logic<State, Event, out Error = never, out Requirements = never, out Output = never, out InitialError = never> {
543
+ initial(scope: Logic.Scope<Event>): Effect.Effect<State, InitialError, Requirements>;
544
+ run(context: Logic.Context<State, Event>): Effect.Effect<Output, Error, Requirements>;
545
+ }
546
+ /**
547
+ * Public types used by advanced machine process logic.
548
+ *
549
+ * @since 4.0.0
550
+ */
551
+ export declare namespace Logic {
552
+ /**
553
+ * Machine-local endpoint that can receive events and be stopped.
554
+ *
555
+ * @category models
556
+ * @since 4.0.0
557
+ */
558
+ interface Address<in Event> {
559
+ readonly id: string;
560
+ readonly sessionId: string;
561
+ readonly stop: Effect.Effect<void>;
562
+ readonly send: (event: Event) => Effect.Effect<void, StoppedError>;
563
+ }
564
+ /**
565
+ * Starts child process logic owned by the current machine process.
566
+ *
567
+ * @category models
568
+ * @since 4.0.0
569
+ */
570
+ interface Spawn {
571
+ <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(logic: Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>): Effect.Effect<MachineRef<ChildState, ChildEvent, ChildError | ChildInitialError, ChildOutput>, ChildInitialError, Exclude<ChildRequirements, Scope.Scope>>;
572
+ <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(logic: Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>, options: {
573
+ readonly id: string;
574
+ }): Effect.Effect<MachineRef<ChildState, ChildEvent, ChildError | ChildInitialError, ChildOutput>, ChildAlreadyExistsError | ChildInitialError, Exclude<ChildRequirements, Scope.Scope>>;
575
+ }
576
+ /**
577
+ * Machine-local capabilities available while process logic initializes.
578
+ *
579
+ * **Gotchas**
580
+ *
581
+ * `sendParent` accepts `unknown` because process logic is independent from
582
+ * the parent that eventually owns it. Prefer typed process output or an
583
+ * invoke snapshot mapper when either can represent the communication.
584
+ *
585
+ * @category models
586
+ * @since 4.0.0
587
+ */
588
+ interface Scope<Event> {
589
+ readonly self: Address<Event>;
590
+ readonly parent: Address<unknown> | undefined;
591
+ readonly spawn: Spawn;
592
+ readonly sendParent: (event: unknown) => Effect.Effect<void, StoppedError>;
593
+ readonly sendTo: <Address extends string>(id: Address, event: ChildAddress.Event<Address>) => Effect.Effect<void, StoppedError>;
594
+ readonly stopChild: (id: string) => Effect.Effect<void>;
595
+ }
596
+ /**
597
+ * Machine-local capabilities available while stateful process logic runs.
598
+ *
599
+ * @category models
600
+ * @since 4.0.0
601
+ */
602
+ interface Context<State, Event> extends Scope<Event> {
603
+ readonly receive: Effect.Effect<Event>;
604
+ readonly state: Effect.Effect<State>;
605
+ readonly setState: (state: State) => Effect.Effect<void>;
606
+ readonly updateState: <E, R>(update: (state: State) => Effect.Effect<State, E, R>) => Effect.Effect<void, E, R>;
607
+ }
608
+ }
609
+ declare const ChildAddressTypeId = "~effect/Machine/ChildAddress";
610
+ declare const ChildAddressCompatibilityErrorTypeId = "~effect/Machine/ChildAddressCompatibilityError";
611
+ declare const ChildMachineTypeId = "~effect/Machine/ChildMachine";
612
+ /**
613
+ * Typed descriptor for a complete machine invoked as a child.
614
+ *
615
+ * **Details**
616
+ *
617
+ * The descriptor carries the child's address and complete machine type. Pass
618
+ * the same value to `invokeMachine`, `sendTo`, and child lookup APIs so state,
619
+ * event, error, and output types are inferred without separate annotations.
620
+ *
621
+ * @category models
622
+ * @since 4.0.0
623
+ */
624
+ export interface ChildMachine<Id extends string, M extends Machine.Any> {
625
+ readonly [ChildMachineTypeId]: typeof ChildMachineTypeId;
626
+ readonly id: Id;
627
+ readonly machine: M;
628
+ }
629
+ /**
630
+ * Namespace containing type-level members associated with `ChildMachine`.
631
+ *
632
+ * @since 4.0.0
633
+ */
634
+ export declare namespace ChildMachine {
635
+ /**
636
+ * Any typed child machine descriptor.
637
+ *
638
+ * @category models
639
+ * @since 4.0.0
640
+ */
641
+ type Any = ChildMachine<string, Machine.Any>;
642
+ /**
643
+ * Running machine reference selected by a child descriptor.
644
+ *
645
+ * @category utility types
646
+ * @since 4.0.0
647
+ */
648
+ type Ref<Child> = Child extends ChildMachine<string, infer M> ? M extends Machine<infer States, infer Events, any, any, infer E, infer R, infer InitialE, infer InitialR, any, infer Output, any, any> ? MachineRef<Machine.Snapshot<States>, Machine.EventOf<Events>, E | InitialE | ActionError<R | InitialR> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Output | undefined> : never : never;
649
+ /**
650
+ * Event accepted by the child selected by a descriptor.
651
+ *
652
+ * @category utility types
653
+ * @since 4.0.0
654
+ */
655
+ type Event<Child> = Ref<Child> extends MachineRef<any, infer Event, any, any> ? Event : never;
656
+ }
657
+ /**
658
+ * Parent-local address for a child process that can receive events.
659
+ *
660
+ * @category models
661
+ * @since 4.0.0
662
+ */
663
+ export type ChildAddress<Event> = string & ChildAddress.Variance<Event>;
664
+ /**
665
+ * Namespace containing type-level members associated with `ChildAddress`.
666
+ *
667
+ * @since 4.0.0
668
+ */
669
+ export declare namespace ChildAddress {
670
+ /**
671
+ * Variance marker carried by a typed child process address.
672
+ *
673
+ * @category models
674
+ * @since 4.0.0
675
+ */
676
+ interface Variance<in Event> {
677
+ readonly [ChildAddressTypeId]: {
678
+ readonly _Event: Types.Contravariant<Event>;
679
+ };
680
+ }
681
+ /**
682
+ * Extracts the event protocol accepted by a child address.
683
+ *
684
+ * @category utility types
685
+ * @since 4.0.0
686
+ */
687
+ type Event<Address> = Address extends ChildAddress<infer Event> ? Event : unknown;
688
+ /**
689
+ * Ensures a child address protocol is compatible with a child process event
690
+ * protocol.
691
+ *
692
+ * @category utility types
693
+ * @since 4.0.0
694
+ */
695
+ type Compatibility<Address, Event> = [Address] extends [ChildAddress<infer AddressEvent>] ? [
696
+ AddressEvent
697
+ ] extends [Event] ? unknown : {
698
+ readonly [ChildAddressCompatibilityErrorTypeId]: {
699
+ readonly address: AddressEvent;
700
+ readonly child: Event;
701
+ };
702
+ } : unknown;
703
+ /**
704
+ * Ensures spawn options with a typed child address are compatible with a
705
+ * child process event protocol.
706
+ *
707
+ * @category utility types
708
+ * @since 4.0.0
709
+ */
710
+ type OptionsCompatibility<Options, Event> = "id" extends keyof Options ? Options extends {
711
+ readonly id?: infer Address;
712
+ } ? Compatibility<Exclude<Address, undefined>, Event> : unknown : unknown;
713
+ }
714
+ /**
715
+ * Options for spawning child processes.
716
+ *
717
+ * @category models
718
+ * @since 4.0.0
719
+ */
720
+ export interface SpawnOptions {
721
+ readonly id?: string;
722
+ }
723
+ /**
724
+ * Options for spawning child processes with a parent-local id.
725
+ *
726
+ * @category models
727
+ * @since 4.0.0
728
+ */
729
+ export interface SpawnIdOptions extends SpawnOptions {
730
+ readonly id: string;
731
+ }
732
+ /**
733
+ * Namespace containing type-level members associated with `Machine`.
734
+ *
735
+ * @since 4.0.0
736
+ */
737
+ export declare namespace Machine {
738
+ /**
739
+ * Any schema-first machine.
740
+ *
741
+ * @category models
742
+ * @since 4.0.0
743
+ */
744
+ type Any = Machine<any, any, any, any, any, any, any, any, any, any, any, any>;
745
+ /**
746
+ * A schema whose decoded value contains a `_tag` discriminator.
747
+ *
748
+ * **Details**
749
+ *
750
+ * This mirrors the tagged-schema constraint used by `Schema.toTaggedUnion`.
751
+ *
752
+ * @category models
753
+ * @since 4.0.0
754
+ */
755
+ type TaggedSchema = Schema.Top & {
756
+ readonly Type: {
757
+ readonly _tag: PropertyKey;
758
+ };
759
+ };
760
+ /**
761
+ * Configuration accepted for an atomic object state node.
762
+ *
763
+ * @category models
764
+ * @since 4.0.0
765
+ */
766
+ type AtomicStateNodeConfig = {
767
+ readonly schema: TaggedSchema;
768
+ readonly type?: "active";
769
+ readonly output?: never;
770
+ } | {
771
+ readonly schema: TaggedSchema;
772
+ readonly type: "final";
773
+ readonly output?: Schema.Top;
774
+ };
775
+ /**
776
+ * Configuration accepted for a compound object state node.
777
+ *
778
+ * @category models
779
+ * @since 4.0.0
780
+ */
781
+ interface CompoundStateNodeConfig {
782
+ readonly schema: TaggedSchema;
783
+ readonly type?: "active";
784
+ readonly initial: string;
785
+ readonly states: StateTree;
786
+ }
787
+ /**
788
+ * Configuration accepted for a parallel object state node.
789
+ *
790
+ * @category models
791
+ * @since 4.0.0
792
+ */
793
+ interface ParallelStateNodeConfig {
794
+ readonly schema: TaggedSchema;
795
+ readonly type: "parallel";
796
+ readonly output?: Schema.Top;
797
+ readonly states: StateTree;
798
+ }
799
+ /**
800
+ * Configuration accepted for an object state node.
801
+ *
802
+ * @category models
803
+ * @since 4.0.0
804
+ */
805
+ type StateNodeConfig = AtomicStateNodeConfig | CompoundStateNodeConfig | ParallelStateNodeConfig;
806
+ /**
807
+ * Object state tree keyed by state path.
808
+ *
809
+ * @category models
810
+ * @since 4.0.0
811
+ */
812
+ type StateTree = Readonly<Record<string, TaggedSchema | StateNodeConfig>>;
813
+ /**
814
+ * State schema definitions accepted by `make`.
815
+ *
816
+ * @category models
817
+ * @since 4.0.0
818
+ */
819
+ type StateSchemas = StateTree;
820
+ /**
821
+ * Builder for initial state snapshots generated by `defineStates`.
822
+ *
823
+ * **When to use**
824
+ *
825
+ * Use when you need the type of the `initial` property returned by
826
+ * `defineStates` or want to expose an initial snapshot builder from a helper.
827
+ *
828
+ * **Details**
829
+ *
830
+ * Initial builders enforce the declared initial child for compound states and
831
+ * require every direct region for parallel states.
832
+ *
833
+ * @category utility types
834
+ * @since 4.0.0
835
+ */
836
+ type InitialBuilder<States extends StateSchemas> = InitialSnapshotBuilderWithPrefix<States>;
837
+ /**
838
+ * State definitions and snapshot builders returned by `defineStates`.
839
+ *
840
+ * **Details**
841
+ *
842
+ * The `states` property is the original state tree and can be passed directly
843
+ * to `make`. The `initial` property builds path-safe snapshots for the same
844
+ * state tree.
845
+ *
846
+ * @category models
847
+ * @since 4.0.0
848
+ */
849
+ interface DefinedStates<States extends StateSchemas> {
850
+ readonly states: States;
851
+ readonly initial: InitialBuilder<States>;
852
+ /**
853
+ * Returns the decoded value for an active state path.
854
+ *
855
+ * @since 4.0.0
856
+ */
857
+ readonly get: <Path extends StateIdentifier<States>>(snapshot: Snapshot<States>, path: Path) => Option.Option<StateByIdentifier<States, Path>>;
858
+ /**
859
+ * Returns the decoded value for an active state path together with all of
860
+ * its active parent values.
861
+ *
862
+ * **Details**
863
+ *
864
+ * Parent values are keyed by their full state paths.
865
+ *
866
+ * @since 4.0.0
867
+ */
868
+ readonly getWithParents: <Path extends StateIdentifier<States>>(snapshot: Snapshot<States>, path: Path) => Option.Option<StateWithParents<States, Path>>;
869
+ /**
870
+ * Returns the snapshot for an active state path.
871
+ *
872
+ * @since 4.0.0
873
+ */
874
+ readonly getSnapshot: <Path extends StateIdentifier<States>>(snapshot: Snapshot<States>, path: Path) => Option.Option<SnapshotByIdentifier<States, Path>>;
875
+ /**
876
+ * Returns whether a state path is active in the snapshot.
877
+ *
878
+ * @since 4.0.0
879
+ */
880
+ readonly matches: <Path extends StateIdentifier<States>>(snapshot: Snapshot<States>, path: Path) => boolean;
881
+ }
882
+ /**
883
+ * Validates the nested shape of state schema definitions.
884
+ *
885
+ * @category utility types
886
+ * @since 4.0.0
887
+ */
888
+ type ValidateStateSchemas<States extends StateSchemas> = ValidateStateTree<States>;
889
+ /**
890
+ * Runtime metadata for a compiled state node.
891
+ *
892
+ * @category models
893
+ * @since 4.0.0
894
+ */
895
+ interface StateNode {
896
+ readonly path: string;
897
+ readonly key: string;
898
+ readonly schema: TaggedSchema;
899
+ readonly output: Schema.Top | undefined;
900
+ readonly type: "atomic" | "compound" | "parallel" | "final";
901
+ readonly parent: string | undefined;
902
+ readonly children: ReadonlyArray<string>;
903
+ readonly initial: string | undefined;
904
+ readonly order: number;
905
+ }
906
+ /**
907
+ * Runtime lookup table for state nodes.
908
+ *
909
+ * @category models
910
+ * @since 4.0.0
911
+ */
912
+ interface StateNodes {
913
+ readonly byPath: ReadonlyMap<string, StateNode>;
914
+ readonly roots: ReadonlyArray<string>;
915
+ }
916
+ /**
917
+ * Constructor arguments for a machine initial state function.
918
+ *
919
+ * @category utility types
920
+ * @since 4.0.0
921
+ */
922
+ type InputArgs<Input extends Schema.Top> = Input extends typeof Schema.Void ? [] : [input: Input["Type"]];
923
+ /**
924
+ * Extracts the discriminator value represented by a tagged schema.
925
+ *
926
+ * @category utility types
927
+ * @since 4.0.0
928
+ */
929
+ type TagOf<S extends TaggedSchema> = S["Type"]["_tag"];
930
+ /**
931
+ * Extracts the schema from a state tree node definition.
932
+ *
933
+ * @category utility types
934
+ * @since 4.0.0
935
+ */
936
+ type NodeSchema<Node> = Node extends TaggedSchema ? Node : Node extends {
937
+ readonly schema: infer Schema extends TaggedSchema;
938
+ } ? Schema : never;
939
+ /**
940
+ * Prefixes a state path with its parent path.
941
+ *
942
+ * @category utility types
943
+ * @since 4.0.0
944
+ */
945
+ type JoinPath<Parent extends string, Child extends string> = Parent extends "" ? Child : `${Parent}.${Child}`;
946
+ /**
947
+ * Extracts the state path values represented by a state definition.
948
+ *
949
+ * @category utility types
950
+ * @since 4.0.0
951
+ */
952
+ type StateIdentifier<States extends StateSchemas> = StateIdentifierWithPrefix<States>;
953
+ /**
954
+ * Extracts the state path values represented by a state definition under a
955
+ * parent path prefix.
956
+ *
957
+ * @category utility types
958
+ * @since 4.0.0
959
+ */
960
+ type StateIdentifierWithPrefix<States extends StateSchemas, Prefix extends string = ""> = {
961
+ readonly [Key in Extract<keyof States, string>]: States[Key] extends {
962
+ readonly states: infer Children;
963
+ } ? Children extends StateSchemas ? JoinPath<Prefix, Key> | StateIdentifierWithPrefix<Children, JoinPath<Prefix, Key>> : JoinPath<Prefix, Key> : JoinPath<Prefix, Key>;
964
+ }[Extract<keyof States, string>];
965
+ /**
966
+ * Extracts a state-tree node by state path.
967
+ *
968
+ * @category utility types
969
+ * @since 4.0.0
970
+ */
971
+ type NodeByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends `${infer Head}.${infer Rest}` ? Head extends keyof States ? States[Head] extends {
972
+ readonly states: infer Children extends StateSchemas;
973
+ } ? Rest extends StateIdentifier<Children> ? NodeByIdentifier<Children, Rest> : never : never : never : StateId extends keyof States ? States[StateId] : never;
974
+ /**
975
+ * Extracts a schema from a state definition by state identifier.
976
+ *
977
+ * @category utility types
978
+ * @since 4.0.0
979
+ */
980
+ type SchemaByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeSchema<NodeByIdentifier<States, StateId>>;
981
+ /**
982
+ * Extracts the union of state values represented by a state definition.
983
+ *
984
+ * @category utility types
985
+ * @since 4.0.0
986
+ */
987
+ type StateOf<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? SchemaByIdentifier<States, StateId>["Type"] : never : never;
988
+ /**
989
+ * Extracts the union of event values represented by an event schema list.
990
+ *
991
+ * @category utility types
992
+ * @since 4.0.0
993
+ */
994
+ type EventOf<Events extends ReadonlyArray<TaggedSchema>> = Events[number]["Type"];
995
+ /**
996
+ * Extracts the union of emitted event values represented by an emitted event
997
+ * schema list.
998
+ *
999
+ * @category utility types
1000
+ * @since 4.0.0
1001
+ */
1002
+ type EmitOf<Emits extends ReadonlyArray<TaggedSchema>> = Emits[number]["Type"];
1003
+ /**
1004
+ * Event values received by lifecycle callbacks.
1005
+ *
1006
+ * @category utility types
1007
+ * @since 4.0.0
1008
+ */
1009
+ type LifecycleEvent<Events extends ReadonlyArray<TaggedSchema>> = EventOf<Events> | InitialEvent;
1010
+ /**
1011
+ * Runtime capability specialized to a machine's event protocols.
1012
+ *
1013
+ * @category utility types
1014
+ * @since 4.0.0
1015
+ */
1016
+ type RuntimeEffect<Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>> = Effect.Effect<Runtime<EventOf<Events>, EmitOf<Emits>>, never, Runtime.Requirement<EventOf<Events>, EmitOf<Emits>>>;
1017
+ /**
1018
+ * Extracts a state value from a state definition by identifier.
1019
+ *
1020
+ * @category utility types
1021
+ * @since 4.0.0
1022
+ */
1023
+ type StateByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = Extract<StateOf<States>, SchemaByIdentifier<States, StateId>["Type"]>;
1024
+ /**
1025
+ * Extracts every parent state path from a state identifier.
1026
+ *
1027
+ * @category utility types
1028
+ * @since 4.0.0
1029
+ */
1030
+ type ParentStateIdentifier<StateId extends string> = StateId extends `${infer Parent}.${infer Child}` ? Parent | (Child extends `${string}.${string}` ? `${Parent}.${ParentStateIdentifier<Child>}` : never) : never;
1031
+ /**
1032
+ * Maps every parent state path of a state identifier to its decoded value.
1033
+ *
1034
+ * @category utility types
1035
+ * @since 4.0.0
1036
+ */
1037
+ type ParentStateValues<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
1038
+ readonly [Parent in Extract<ParentStateIdentifier<StateId>, StateIdentifier<States>>]: StateByIdentifier<States, Parent>;
1039
+ } : never;
1040
+ /**
1041
+ * Represents a decoded state value together with all of its parent values.
1042
+ *
1043
+ * @category models
1044
+ * @since 4.0.0
1045
+ */
1046
+ type StateWithParents<States extends StateSchemas, StateId extends StateIdentifier<States>> = StateId extends StateIdentifier<States> ? {
1047
+ readonly value: StateByIdentifier<States, StateId>;
1048
+ readonly parents: ParentStateValues<States, StateId>;
1049
+ } : never;
1050
+ type UndefinedIfNever<A> = [A] extends [never] ? undefined : A;
1051
+ type NodeOutput<Node> = Node extends {
1052
+ readonly output: infer Output extends Schema.Top;
1053
+ } ? Schema.Schema.Type<Output> : undefined;
1054
+ /**
1055
+ * Extracts the declared output type for a state node.
1056
+ *
1057
+ * @category utility types
1058
+ * @since 4.0.0
1059
+ */
1060
+ type OutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeOutput<NodeByIdentifier<States, StateId>>;
1061
+ type DirectFinalCompletionOutput<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1062
+ readonly type: "final";
1063
+ } ? OutputByIdentifier<States, StateId> : never;
1064
+ type CompoundCompletionOutput<States extends StateSchemas, Children extends StateSchemas, Prefix extends StateIdentifier<States>> = UndefinedIfNever<{
1065
+ readonly [Key in Extract<keyof Children, string>]: DirectFinalCompletionOutput<States, Extract<JoinPath<Prefix, Key>, StateIdentifier<States>>>;
1066
+ }[Extract<keyof Children, string>]>;
1067
+ /**
1068
+ * Extracts the output passed when a state node completes.
1069
+ *
1070
+ * @category utility types
1071
+ * @since 4.0.0
1072
+ */
1073
+ type CompletionOutputByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
1074
+ readonly type: "parallel";
1075
+ } ? OutputByIdentifier<States, StateId> : Node extends {
1076
+ readonly states: infer Children extends StateSchemas;
1077
+ } ? CompoundCompletionOutput<States, Children, StateId> : Node extends {
1078
+ readonly type: "final";
1079
+ } ? OutputByIdentifier<States, StateId> : undefined : undefined;
1080
+ type OutputSchema<Node> = Node extends {
1081
+ readonly output: infer Output extends Schema.Top;
1082
+ } ? Output : never;
1083
+ type DecodingServices<Current> = Current extends Schema.Top ? Current["DecodingServices"] : never;
1084
+ type EncodingServices<Current> = Current extends Schema.Top ? Current["EncodingServices"] : never;
1085
+ /**
1086
+ * Services required to decode every state value and completion output in a
1087
+ * machine snapshot.
1088
+ *
1089
+ * @category utility types
1090
+ * @since 4.0.0
1091
+ */
1092
+ type SnapshotDecodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? DecodingServices<SchemaByIdentifier<States, StateId>> | DecodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
1093
+ /**
1094
+ * Services required to encode every state value and completion output in a
1095
+ * machine snapshot.
1096
+ *
1097
+ * @category utility types
1098
+ * @since 4.0.0
1099
+ */
1100
+ type SnapshotEncodingServices<States extends StateSchemas> = StateIdentifier<States> extends infer StateId ? StateId extends StateIdentifier<States> ? EncodingServices<SchemaByIdentifier<States, StateId>> | EncodingServices<OutputSchema<NodeByIdentifier<States, StateId>>> : never : never;
1101
+ /**
1102
+ * Encoded value for one active state path in a normalized machine snapshot.
1103
+ *
1104
+ * @category models
1105
+ * @since 4.0.0
1106
+ */
1107
+ interface EncodedSnapshotState {
1108
+ readonly path: string;
1109
+ readonly value: unknown;
1110
+ }
1111
+ /**
1112
+ * Encoded output for one completed state path in a normalized machine
1113
+ * snapshot. An omitted output represents `undefined`.
1114
+ *
1115
+ * @category models
1116
+ * @since 4.0.0
1117
+ */
1118
+ interface EncodedSnapshotCompletion {
1119
+ readonly path: string;
1120
+ readonly output?: unknown;
1121
+ }
1122
+ /**
1123
+ * Normalized data representation of a machine snapshot.
1124
+ *
1125
+ * **Details**
1126
+ *
1127
+ * Active state and completion values use the encoded representations of
1128
+ * their declared schemas. Runtime process state such as children, fibers,
1129
+ * scopes, queues, and subscriptions is not included.
1130
+ *
1131
+ * @category models
1132
+ * @since 4.0.0
1133
+ */
1134
+ interface EncodedSnapshot {
1135
+ readonly _tag: "MachineSnapshot";
1136
+ readonly active: ReadonlyArray<EncodedSnapshotState>;
1137
+ readonly completed?: ReadonlyArray<EncodedSnapshotCompletion>;
1138
+ }
1139
+ /**
1140
+ * Completed state path and its resolved output value.
1141
+ *
1142
+ * @category models
1143
+ * @since 4.0.0
1144
+ */
1145
+ interface SnapshotCompletion {
1146
+ readonly path: string;
1147
+ readonly output: unknown;
1148
+ }
1149
+ /**
1150
+ * Carries lifecycle metadata required to resume planning from a cloned
1151
+ * snapshot.
1152
+ *
1153
+ * **Gotchas**
1154
+ *
1155
+ * Snapshots contain decoded in-memory values. Their current object shape is
1156
+ * experimental and is not a stable JSON persistence or wire format. Copies
1157
+ * must preserve decoded values such as `Schema.Class` instances; JSON and
1158
+ * `structuredClone` may not preserve those runtime contracts.
1159
+ * Use {@link encodeSnapshot} and {@link decodeSnapshot} to cross a persistence
1160
+ * or transport boundary.
1161
+ *
1162
+ * @category models
1163
+ * @since 4.0.0
1164
+ */
1165
+ interface SnapshotMetadata {
1166
+ readonly completed?: ReadonlyArray<SnapshotCompletion>;
1167
+ }
1168
+ /**
1169
+ * Atomic statechart snapshot carrying path identity separately from the
1170
+ * decoded state value.
1171
+ *
1172
+ * @category models
1173
+ * @since 4.0.0
1174
+ */
1175
+ interface AtomicSnapshot<Path extends string, Value> extends SnapshotMetadata {
1176
+ readonly path: Path;
1177
+ readonly value: Value;
1178
+ }
1179
+ /**
1180
+ * Compound statechart snapshot carrying parent value plus the active child
1181
+ * snapshot.
1182
+ *
1183
+ * @category models
1184
+ * @since 4.0.0
1185
+ */
1186
+ interface CompoundSnapshot<Path extends string, Value, Child> extends SnapshotMetadata {
1187
+ readonly path: Path;
1188
+ readonly value: Value;
1189
+ readonly state: Child;
1190
+ }
1191
+ /**
1192
+ * Parallel statechart snapshot carrying parent value plus one active snapshot
1193
+ * per child region.
1194
+ *
1195
+ * @category models
1196
+ * @since 4.0.0
1197
+ */
1198
+ interface ParallelSnapshot<Path extends string, Value, Regions> extends SnapshotMetadata {
1199
+ readonly path: Path;
1200
+ readonly value: Value;
1201
+ readonly states: Regions;
1202
+ }
1203
+ /**
1204
+ * Extracts the snapshot value represented by a state definition by
1205
+ * identifier.
1206
+ *
1207
+ * @category utility types
1208
+ * @since 4.0.0
1209
+ */
1210
+ type SnapshotByIdentifier<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
1211
+ readonly type: "parallel";
1212
+ readonly states: infer Children;
1213
+ } ? Children extends StateSchemas ? ParallelSnapshot<StateId, StateByIdentifier<States, StateId>, SnapshotRegionsWithPrefix<Children, StateId>> : AtomicSnapshot<StateId, StateByIdentifier<States, StateId>> : Node extends {
1214
+ readonly states: infer Children;
1215
+ } ? Children extends StateSchemas ? CompoundSnapshot<StateId, StateByIdentifier<States, StateId>, SnapshotWithPrefix<Children, StateId>> : AtomicSnapshot<StateId, StateByIdentifier<States, StateId>> : AtomicSnapshot<StateId, StateByIdentifier<States, StateId>> : AtomicSnapshot<StateId, StateByIdentifier<States, StateId>>;
1216
+ /**
1217
+ * Extracts child snapshots under a parent path prefix.
1218
+ *
1219
+ * @category utility types
1220
+ * @since 4.0.0
1221
+ */
1222
+ type SnapshotWithPrefix<States extends StateSchemas, Prefix extends string> = {
1223
+ readonly [Key in Extract<keyof States, string>]: SnapshotByIdentifierWithPath<States, Key, JoinPath<Prefix, Key>>;
1224
+ }[Extract<keyof States, string>];
1225
+ /**
1226
+ * Extracts child snapshots under a parallel parent path prefix, keyed by
1227
+ * child region.
1228
+ *
1229
+ * @category utility types
1230
+ * @since 4.0.0
1231
+ */
1232
+ type SnapshotRegionsWithPrefix<States extends StateSchemas, Prefix extends string> = {
1233
+ readonly [Key in Extract<keyof States, string>]: SnapshotByIdentifierWithPath<States, Key, JoinPath<Prefix, Key>>;
1234
+ };
1235
+ /**
1236
+ * Extracts a snapshot for a state node while preserving its full path.
1237
+ *
1238
+ * @category utility types
1239
+ * @since 4.0.0
1240
+ */
1241
+ type SnapshotByIdentifierWithPath<States extends StateSchemas, StateId extends Extract<keyof States, string>, Path extends string> = States[StateId] extends {
1242
+ readonly type: "parallel";
1243
+ readonly states: infer Children;
1244
+ } ? Children extends StateSchemas ? ParallelSnapshot<Path, NodeSchema<States[StateId]>["Type"], SnapshotRegionsWithPrefix<Children, Path>> : AtomicSnapshot<Path, NodeSchema<States[StateId]>["Type"]> : States[StateId] extends {
1245
+ readonly states: infer Children;
1246
+ } ? Children extends StateSchemas ? CompoundSnapshot<Path, NodeSchema<States[StateId]>["Type"], SnapshotWithPrefix<Children, Path>> : AtomicSnapshot<Path, NodeSchema<States[StateId]>["Type"]> : AtomicSnapshot<Path, NodeSchema<States[StateId]>["Type"]>;
1247
+ /**
1248
+ * Extracts the union of statechart snapshots represented by a state
1249
+ * definition.
1250
+ *
1251
+ * @category models
1252
+ * @since 4.0.0
1253
+ */
1254
+ type Snapshot<States extends StateSchemas> = {
1255
+ readonly [StateId in Extract<keyof States, string>]: SnapshotByIdentifier<States, StateId & StateIdentifier<States>>;
1256
+ }[Extract<keyof States, string>];
1257
+ /**
1258
+ * Extracts the root state identifier from a state path.
1259
+ *
1260
+ * @category utility types
1261
+ * @since 4.0.0
1262
+ */
1263
+ type RootStateIdentifier<StateId extends string> = StateId extends `${infer Root}.${string}` ? Root : StateId;
1264
+ /**
1265
+ * Extracts the public snapshot shape that contains a final state path.
1266
+ *
1267
+ * @category utility types
1268
+ * @since 4.0.0
1269
+ */
1270
+ type SnapshotContainingFinal<States extends StateSchemas, FinalStates extends StateIdentifier<States>> = FinalStates extends StateIdentifier<States> ? RootStateIdentifier<FinalStates> extends infer Root extends StateIdentifier<States> ? SnapshotByIdentifier<States, Root> : never : never;
1271
+ /**
1272
+ * Extracts state identifiers whose state-tree definition marks them final.
1273
+ *
1274
+ * @category utility types
1275
+ * @since 4.0.0
1276
+ */
1277
+ type FinalStateFromDefinition<States extends StateSchemas> = {
1278
+ readonly [StateId in StateIdentifier<States>]: NodeByIdentifier<States, StateId> extends {
1279
+ readonly type: "final";
1280
+ } ? StateId : never;
1281
+ }[StateIdentifier<States>] & StateIdentifier<States>;
1282
+ /**
1283
+ * Extracts an event value from an event schema list by tag.
1284
+ *
1285
+ * @category utility types
1286
+ * @since 4.0.0
1287
+ */
1288
+ type EventByTag<Events extends ReadonlyArray<TaggedSchema>, Tag extends TagOf<Events[number]>> = Extract<EventOf<Events>, {
1289
+ readonly _tag: Tag;
1290
+ }>;
1291
+ /**
1292
+ * Machine-bound target instruction accepted from transition handlers.
1293
+ *
1294
+ * @category models
1295
+ * @since 4.0.0
1296
+ */
1297
+ interface Target<States extends StateSchemas, StateId extends StateIdentifier<States>> {
1298
+ readonly [Model.TargetTypeId]: typeof Model.TargetTypeId;
1299
+ readonly path: StateId;
1300
+ readonly value: StateByIdentifier<States, StateId>;
1301
+ readonly values?: Partial<{
1302
+ readonly [AncestorStateId in StateIdentifier<States>]: StateByIdentifier<States, AncestorStateId>;
1303
+ }>;
1304
+ }
1305
+ /**
1306
+ * Builder for complete transition snapshots.
1307
+ *
1308
+ * **When to use**
1309
+ *
1310
+ * Use when a transition enters an inactive root or otherwise needs to provide
1311
+ * every active child below the selected root.
1312
+ *
1313
+ * @category utility types
1314
+ * @since 4.0.0
1315
+ */
1316
+ type FullTargetBuilder<States extends StateSchemas> = FullSnapshotBuilderWithPrefix<States>;
1317
+ /**
1318
+ * Builder for source-local transition targets.
1319
+ *
1320
+ * **When to use**
1321
+ *
1322
+ * Use when a transition stays inside the nearest active compound ancestor of
1323
+ * the source state and should preserve active ancestor and sibling values.
1324
+ *
1325
+ * @category utility types
1326
+ * @since 4.0.0
1327
+ */
1328
+ type LocalTargetBuilder<States extends StateSchemas, Source extends StateIdentifier<States>> = NearestCompoundScope<States, Source> extends infer Scope ? [Scope] extends [never] ? {} : Scope extends StateIdentifier<States> ? LocalTargetBuilderForScope<States, Scope> : {} : {};
1329
+ /**
1330
+ * Builder for partial transition targets within the active source root.
1331
+ *
1332
+ * **When to use**
1333
+ *
1334
+ * Use when a transition should replace one descendant of the active source
1335
+ * root while preserving unmentioned active ancestors or parallel regions.
1336
+ *
1337
+ * @category utility types
1338
+ * @since 4.0.0
1339
+ */
1340
+ type BranchTargetBuilder<States extends StateSchemas, Source extends StateIdentifier<States>> = BranchTargetBuilderForRoot<States, Extract<RootStateIdentifier<Source>, Extract<keyof States, string>>>;
1341
+ /**
1342
+ * Machine-bound target builders available in transition contexts.
1343
+ *
1344
+ * **Details**
1345
+ *
1346
+ * `local` targets the nearest compound scope for the source state, `branch`
1347
+ * targets descendants of the source root, and `full` builds complete
1348
+ * snapshots for any root.
1349
+ *
1350
+ * @category models
1351
+ * @since 4.0.0
1352
+ */
1353
+ interface TargetBuilder<States extends StateSchemas, Source extends StateIdentifier<States>> {
1354
+ /**
1355
+ * Moves to another state in the same local group. The value of the state
1356
+ * containing that group, and values in other active branches, are kept.
1357
+ *
1358
+ * @since 4.0.0
1359
+ */
1360
+ readonly local: LocalTargetBuilder<States, Source>;
1361
+ /**
1362
+ * Moves to a state elsewhere under the current top-level state. Parent
1363
+ * values change only when their builder methods are explicitly called;
1364
+ * other active branches are kept.
1365
+ *
1366
+ * @since 4.0.0
1367
+ */
1368
+ readonly branch: BranchTargetBuilder<States, Source>;
1369
+ /**
1370
+ * Moves to any top-level state by building its complete active state
1371
+ * configuration.
1372
+ *
1373
+ * **Details**
1374
+ *
1375
+ * When the target contains nested states, an active child must be selected.
1376
+ * When it contains parallel states, an active state must be provided for
1377
+ * every region.
1378
+ *
1379
+ * @since 4.0.0
1380
+ */
1381
+ readonly full: FullTargetBuilder<States>;
1382
+ }
1383
+ /**
1384
+ * Stages an Effect to run after the current machine step is planned.
1385
+ *
1386
+ * @category models
1387
+ * @since 4.0.0
1388
+ */
1389
+ interface Action {
1390
+ <E, R>(effect: Effect.Effect<void, E, R>): Effect.Effect<void, never, ActionRequirement<E, R>>;
1391
+ }
1392
+ /**
1393
+ * Planning capabilities shared by transition and lifecycle callbacks.
1394
+ *
1395
+ * @category models
1396
+ * @since 4.0.0
1397
+ */
1398
+ interface PlanningCapabilities<Events, Emits> {
1399
+ readonly action: Action;
1400
+ readonly raise: (event: Events) => Effect.Effect<void, MachineSchemaDecodeError | StoppedError, Runtime.Requirement<Events, Emits>>;
1401
+ readonly emit: (event: Emits) => Effect.Effect<void, MachineSchemaDecodeError | StoppedError, Runtime.Requirement<Events, Emits>>;
1402
+ }
1403
+ /**
1404
+ * Context passed to a state/event handler.
1405
+ *
1406
+ * @category models
1407
+ * @since 4.0.0
1408
+ */
1409
+ interface HandlerContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> extends PlanningCapabilities<EventOf<Events>, EmitOf<Emits>> {
1410
+ readonly state: StateByIdentifier<States, StateId>;
1411
+ readonly parents: ParentStateValues<States, StateId>;
1412
+ readonly event: EventByTag<Events, EventTag>;
1413
+ readonly runtime: RuntimeEffect<Events, Emits>;
1414
+ /**
1415
+ * Provides typed builders for choosing the next active state from this
1416
+ * handler. Each builder documents which existing state values it keeps.
1417
+ *
1418
+ * @since 4.0.0
1419
+ */
1420
+ readonly target: TargetBuilder<States, StateId>;
1421
+ }
1422
+ /**
1423
+ * Context passed to an entry or exit state handler.
1424
+ *
1425
+ * @category models
1426
+ * @since 4.0.0
1427
+ */
1428
+ interface StateActionContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> extends PlanningCapabilities<EventOf<Events>, EmitOf<Emits>> {
1429
+ readonly state: StateByIdentifier<States, StateId>;
1430
+ readonly parents: ParentStateValues<States, StateId>;
1431
+ readonly event: LifecycleEvent<Events>;
1432
+ readonly runtime: RuntimeEffect<Events, Emits>;
1433
+ }
1434
+ /**
1435
+ * Context passed to an invoked child process source.
1436
+ *
1437
+ * @category models
1438
+ * @since 4.0.0
1439
+ */
1440
+ interface InvokeContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
1441
+ readonly state: StateByIdentifier<States, StateId>;
1442
+ readonly parents: ParentStateValues<States, StateId>;
1443
+ readonly event: LifecycleEvent<Events>;
1444
+ readonly runtime: RuntimeEffect<Events, Emits>;
1445
+ }
1446
+ /**
1447
+ * Context passed to an invoked child process active snapshot mapper.
1448
+ *
1449
+ * @category models
1450
+ * @since 4.0.0
1451
+ */
1452
+ interface InvokeSnapshotContext<State, Error, Output> {
1453
+ readonly id: string;
1454
+ readonly snapshot: Extract<RuntimeSnapshot<State, Error, Output>, {
1455
+ readonly status: "active";
1456
+ }>;
1457
+ }
1458
+ /**
1459
+ * Context passed to an invoked machine terminal output mapper.
1460
+ *
1461
+ * @category models
1462
+ * @since 4.0.0
1463
+ */
1464
+ interface InvokeDoneContext<Output> {
1465
+ readonly id: string;
1466
+ readonly output: Output;
1467
+ }
1468
+ /**
1469
+ * Context passed to an eventless transition handler.
1470
+ *
1471
+ * @category models
1472
+ * @since 4.0.0
1473
+ */
1474
+ interface AlwaysContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> extends PlanningCapabilities<EventOf<Events>, EmitOf<Emits>> {
1475
+ readonly state: StateByIdentifier<States, StateId>;
1476
+ readonly parents: ParentStateValues<States, StateId>;
1477
+ readonly event: LifecycleEvent<Events>;
1478
+ readonly runtime: RuntimeEffect<Events, Emits>;
1479
+ /**
1480
+ * Provides typed builders for choosing the next active state from this
1481
+ * eventless handler. Each builder documents which existing state values it
1482
+ * keeps.
1483
+ *
1484
+ * @since 4.0.0
1485
+ */
1486
+ readonly target: TargetBuilder<States, StateId>;
1487
+ }
1488
+ /**
1489
+ * Context passed to a state completion transition handler.
1490
+ *
1491
+ * @category models
1492
+ * @since 4.0.0
1493
+ */
1494
+ interface DoneContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> extends PlanningCapabilities<EventOf<Events>, EmitOf<Emits>> {
1495
+ readonly state: StateByIdentifier<States, StateId>;
1496
+ readonly parents: ParentStateValues<States, StateId>;
1497
+ readonly event: LifecycleEvent<Events>;
1498
+ readonly output: CompletionOutputByIdentifier<States, StateId>;
1499
+ readonly runtime: RuntimeEffect<Events, Emits>;
1500
+ /**
1501
+ * Provides typed builders for choosing the next active state after this
1502
+ * state completes. Each builder documents which existing state values it
1503
+ * keeps.
1504
+ *
1505
+ * @since 4.0.0
1506
+ */
1507
+ readonly target: TargetBuilder<States, StateId>;
1508
+ }
1509
+ /**
1510
+ * Context passed to a final state output function.
1511
+ *
1512
+ * @category models
1513
+ * @since 4.0.0
1514
+ */
1515
+ interface FinalOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
1516
+ readonly state: StateByIdentifier<States, StateId>;
1517
+ readonly parents: ParentStateValues<States, StateId>;
1518
+ readonly event: LifecycleEvent<Events>;
1519
+ }
1520
+ /**
1521
+ * Extracts region outputs for a completed parallel state.
1522
+ *
1523
+ * @category utility types
1524
+ * @since 4.0.0
1525
+ */
1526
+ type ParallelOutputRegions<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1527
+ readonly type: "parallel";
1528
+ readonly states: infer Children extends StateSchemas;
1529
+ } ? {
1530
+ readonly [Key in Extract<keyof Children, string>]: CompletionOutputByIdentifier<States, Extract<JoinPath<StateId, Key>, StateIdentifier<States>>>;
1531
+ } : never;
1532
+ /**
1533
+ * Context passed to a parallel state output function.
1534
+ *
1535
+ * @category models
1536
+ * @since 4.0.0
1537
+ */
1538
+ interface ParallelOutputContext<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> {
1539
+ readonly state: StateByIdentifier<States, StateId>;
1540
+ readonly parents: ParentStateValues<States, StateId>;
1541
+ readonly event: LifecycleEvent<Events>;
1542
+ readonly outputs: ParallelOutputRegions<States, StateId>;
1543
+ }
1544
+ /**
1545
+ * Return value accepted from entry and exit state actions.
1546
+ *
1547
+ * @category utility types
1548
+ * @since 4.0.0
1549
+ */
1550
+ type StateActionResult<E, R> = void | Effect.Effect<void, E, R>;
1551
+ /**
1552
+ * Return value accepted from a machine initial state function.
1553
+ *
1554
+ * @category utility types
1555
+ * @since 4.0.0
1556
+ */
1557
+ type InitialResult<States extends StateSchemas, E, R> = Snapshot<States> | Effect.Effect<Snapshot<States>, E, R>;
1558
+ /**
1559
+ * Return value accepted from transition handlers.
1560
+ *
1561
+ * **Details**
1562
+ *
1563
+ * Handlers return snapshots for complete state replacement or target builder
1564
+ * results for path-safe partial transitions. Raw decoded state values are not
1565
+ * accepted at transition boundaries.
1566
+ *
1567
+ * @category utility types
1568
+ * @since 4.0.0
1569
+ */
1570
+ type HandlerResult<States extends StateSchemas, E, R> = Snapshot<States> | Target<States, StateIdentifier<States>> | void | Effect.Effect<Snapshot<States> | Target<States, StateIdentifier<States>> | void, E, R>;
1571
+ /**
1572
+ * Extracts the union of handler return values from a handler map.
1573
+ *
1574
+ * @category utility types
1575
+ * @since 4.0.0
1576
+ */
1577
+ type HandlerEffect<Handlers> = Handlers[keyof Handlers];
1578
+ /**
1579
+ * Extracts the error type from a handler return value.
1580
+ *
1581
+ * @category utility types
1582
+ * @since 4.0.0
1583
+ */
1584
+ type HandlerError<Handlers> = Effect.Error<HandlerEffect<Handlers>>;
1585
+ /**
1586
+ * Extracts the service requirements from a handler return value.
1587
+ *
1588
+ * @category utility types
1589
+ * @since 4.0.0
1590
+ */
1591
+ type HandlerServices<Handlers> = Effect.Services<HandlerEffect<Handlers>>;
1592
+ /**
1593
+ * Extracts the return value from an initial state function.
1594
+ *
1595
+ * @category utility types
1596
+ * @since 4.0.0
1597
+ */
1598
+ type InitialReturn<Initial> = Initial extends (...args: any) => infer Ret ? Ret : never;
1599
+ /**
1600
+ * Extracts the return value from an entry or exit action.
1601
+ *
1602
+ * @category utility types
1603
+ * @since 4.0.0
1604
+ */
1605
+ type StateActionReturn<Config, Key extends "entry" | "exit"> = Key extends keyof Config ? NonNullable<Config[Key]> extends (...args: any) => infer Ret ? Ret : never : never;
1606
+ /**
1607
+ * Extracts the return value from an event transition config.
1608
+ *
1609
+ * @category utility types
1610
+ * @since 4.0.0
1611
+ */
1612
+ type EventTransitionReturn<Transition> = Transition extends (...args: any) => infer Ret ? Ret : Transition extends {
1613
+ readonly transition: (...args: any) => infer Ret;
1614
+ } ? Ret : never;
1615
+ /**
1616
+ * Extracts the return value from a state's event handlers.
1617
+ *
1618
+ * @category utility types
1619
+ * @since 4.0.0
1620
+ */
1621
+ type EventHandlerReturn<Config> = Config extends {
1622
+ readonly on?: infer On;
1623
+ } ? {
1624
+ readonly [EventTag in keyof On]: EventTransitionReturn<NonNullable<On[EventTag]>>;
1625
+ }[keyof On] : never;
1626
+ /**
1627
+ * Extracts the invoke config or configs from a state config.
1628
+ *
1629
+ * @category utility types
1630
+ * @since 4.0.0
1631
+ */
1632
+ type InvokeReturn<Config> = "invoke" extends keyof Config ? Config extends {
1633
+ readonly invoke?: infer Invoke;
1634
+ } ? NonNullable<Invoke> extends (...args: any) => infer Resolved ? NonNullable<Resolved> extends ReadonlyArray<infer One> ? One : NonNullable<Resolved> : NonNullable<Invoke> extends ReadonlyArray<infer One> ? One : NonNullable<Invoke> : never : never;
1635
+ /**
1636
+ * Extracts the child process logic returned by an invoke source.
1637
+ *
1638
+ * @category utility types
1639
+ * @since 4.0.0
1640
+ */
1641
+ type InvokeLogic<Invoke> = Invoke extends {
1642
+ readonly src: (...args: any) => infer Logic;
1643
+ } ? Logic : never;
1644
+ /**
1645
+ * Extracts the startup error from an invoke source child process logic.
1646
+ *
1647
+ * @category utility types
1648
+ * @since 4.0.0
1649
+ */
1650
+ type InvokeInitialError<Invoke> = Invoke extends {
1651
+ readonly [InvokeTypeId]: {
1652
+ readonly initialError: Types.Covariant<infer InitialError>;
1653
+ };
1654
+ } ? InitialError : InvokeLogic<Invoke> extends Logic<any, any, any, any, any, infer InitialError> ? InitialError : never;
1655
+ /**
1656
+ * Extracts the runtime error from an invoked child process.
1657
+ *
1658
+ * @category utility types
1659
+ * @since 4.0.0
1660
+ */
1661
+ type InvokeRuntimeError<Invoke> = Invoke extends {
1662
+ readonly [InvokeTypeId]: {
1663
+ readonly error: Types.Covariant<infer Error>;
1664
+ };
1665
+ } ? Error : InvokeLogic<Invoke> extends Logic<any, any, infer Error, any, any, any> ? Error : never;
1666
+ /**
1667
+ * Extracts the output from an invoked child process.
1668
+ *
1669
+ * @category utility types
1670
+ * @since 4.0.0
1671
+ */
1672
+ type InvokeOutput<Invoke> = Invoke extends {
1673
+ readonly [InvokeTypeId]: {
1674
+ readonly output: Types.Covariant<infer Output>;
1675
+ };
1676
+ } ? Output : InvokeLogic<Invoke> extends Logic<any, any, any, any, infer Output, any> ? Output : never;
1677
+ /**
1678
+ * Extracts the service requirements from an invoke source child process logic.
1679
+ *
1680
+ * @category utility types
1681
+ * @since 4.0.0
1682
+ */
1683
+ type InvokeServices<Invoke> = Invoke extends {
1684
+ readonly [InvokeTypeId]: {
1685
+ readonly requirements: Types.Covariant<infer Requirements>;
1686
+ };
1687
+ } ? Requirements : InvokeLogic<Invoke> extends Logic<any, any, any, infer Requirements, any, any> ? Requirements : never;
1688
+ /**
1689
+ * Extracts events emitted directly by an invoked child.
1690
+ *
1691
+ * @category utility types
1692
+ * @since 4.0.0
1693
+ */
1694
+ type InvokeEmits<Invoke> = Invoke extends {
1695
+ readonly [InvokeTypeId]: {
1696
+ readonly emits: Types.Covariant<infer Emits>;
1697
+ };
1698
+ } ? Emits : never;
1699
+ /**
1700
+ * Extracts events returned by an invoked child snapshot mapper.
1701
+ *
1702
+ * @category utility types
1703
+ * @since 4.0.0
1704
+ */
1705
+ type InvokeSnapshotEvent<Invoke> = Invoke extends {
1706
+ readonly [InvokeTypeId]: {
1707
+ readonly snapshotEvent: Types.Covariant<infer Event>;
1708
+ };
1709
+ } ? Event : never;
1710
+ /**
1711
+ * Extracts the parent transition error contribution from invoked children.
1712
+ *
1713
+ * @category utility types
1714
+ * @since 4.0.0
1715
+ */
1716
+ type InvokeError<Config> = [InvokeReturn<Config>] extends [never] ? never : ChildAlreadyExistsError | InvokeInitialError<InvokeReturn<Config>> | InvokeRuntimeError<InvokeReturn<Config>>;
1717
+ /**
1718
+ * Extracts the parent service requirement contribution from invoked children.
1719
+ *
1720
+ * @category utility types
1721
+ * @since 4.0.0
1722
+ */
1723
+ type InvokeRequirements<Config> = [InvokeReturn<Config>] extends [never] ? never : MachineRuntimeRequirement | InvokeServices<InvokeReturn<Config>>;
1724
+ /**
1725
+ * Extracts the return value from an eventless transition.
1726
+ *
1727
+ * @category utility types
1728
+ * @since 4.0.0
1729
+ */
1730
+ type AlwaysReturn<Config> = Config extends {
1731
+ readonly always?: infer Always;
1732
+ } ? NonNullable<Always> extends (...args: any) => infer Ret ? Ret : never : never;
1733
+ /**
1734
+ * Extracts the return value from a state completion transition.
1735
+ *
1736
+ * @category utility types
1737
+ * @since 4.0.0
1738
+ */
1739
+ type DoneReturn<Config> = Config extends {
1740
+ readonly onDone?: infer OnDone;
1741
+ } ? NonNullable<OnDone> extends (...args: any) => infer Ret ? Ret : never : never;
1742
+ /**
1743
+ * Extracts the return value from a final state output function.
1744
+ *
1745
+ * @category utility types
1746
+ * @since 4.0.0
1747
+ */
1748
+ type FinalOutputReturn<Config> = Config extends {
1749
+ readonly output?: infer Output;
1750
+ } ? NonNullable<Output> extends (...args: any) => infer Ret ? Ret : never : never;
1751
+ /**
1752
+ * Extracts all service requirements contributed by a state handler config.
1753
+ *
1754
+ * @category utility types
1755
+ * @since 4.0.0
1756
+ */
1757
+ type ConfigServices<Config> = Effect.Services<EventHandlerReturn<Config>> | Effect.Services<AlwaysReturn<Config>> | Effect.Services<DoneReturn<Config>> | Effect.Services<StateActionReturn<Config, "entry">> | Effect.Services<StateActionReturn<Config, "exit">> | InvokeRequirements<Config>;
1758
+ /**
1759
+ * Resolves the tag of a state config when it is final.
1760
+ *
1761
+ * @category utility types
1762
+ * @since 4.0.0
1763
+ */
1764
+ type FinalStateFromConfig<Config, StateTag extends PropertyKey> = Config extends {
1765
+ readonly type: "final";
1766
+ } ? StateTag : never;
1767
+ /**
1768
+ * Configuration for invoking a child process while a state is active.
1769
+ *
1770
+ * @category models
1771
+ * @since 4.0.0
1772
+ */
1773
+ interface InvokeConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Event, ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError, ChildEmits = never, DeliveredOutput = ChildOutput> {
1774
+ readonly [InvokeTypeId]: {
1775
+ readonly output: Types.Covariant<DeliveredOutput>;
1776
+ readonly emits: Types.Covariant<ChildEmits>;
1777
+ readonly snapshotEvent: Types.Covariant<Event>;
1778
+ readonly error: Types.Covariant<ChildError>;
1779
+ readonly requirements: Types.Covariant<ChildRequirements>;
1780
+ readonly initialError: Types.Covariant<ChildInitialError>;
1781
+ };
1782
+ readonly id: string;
1783
+ /** @internal */
1784
+ readonly addressable?: boolean;
1785
+ src(): Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>;
1786
+ snapshot?(context: InvokeSnapshotContext<ChildState, ChildError | ChildInitialError, ChildOutput>): Event | undefined;
1787
+ onDone?(context: InvokeDoneContext<ChildOutput>): DeliveredOutput | undefined;
1788
+ }
1789
+ /** @internal */
1790
+ interface AnyInvokeConfig<Output = unknown, Error = unknown, Requirements = unknown, InitialError = unknown, Emits = never, SnapshotEvent = never> {
1791
+ readonly [InvokeTypeId]: {
1792
+ readonly output: Types.Covariant<Output>;
1793
+ readonly emits: Types.Covariant<Emits>;
1794
+ readonly snapshotEvent: Types.Covariant<SnapshotEvent>;
1795
+ readonly error: Types.Covariant<Error>;
1796
+ readonly requirements: Types.Covariant<Requirements>;
1797
+ readonly initialError: Types.Covariant<InitialError>;
1798
+ };
1799
+ }
1800
+ /**
1801
+ * State-bound configuration for invoked child processes.
1802
+ *
1803
+ * **Details**
1804
+ *
1805
+ * A function form receives the owning state's typed value and lifecycle
1806
+ * event before constructing one or more invoke configurations.
1807
+ *
1808
+ * @category models
1809
+ * @since 4.0.0
1810
+ */
1811
+ type InvokeDefinition<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> = AnyInvokeConfig<any, any, any, any, any, any> | ReadonlyArray<AnyInvokeConfig<any, any, any, any, any, any>> | ((context: InvokeContext<States, Events, Emits, StateId>) => AnyInvokeConfig<any, any, any, any, any, any> | ReadonlyArray<AnyInvokeConfig<any, any, any, any, any, any>>);
1812
+ type OutputHandlerConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, Context> = NodeByIdentifier<States, StateId> extends {
1813
+ readonly output: Schema.Top;
1814
+ } ? {
1815
+ readonly output: (context: Context) => OutputByIdentifier<States, StateId>;
1816
+ } : {
1817
+ readonly output?: never;
1818
+ };
1819
+ type ActiveOutputHandlerConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1820
+ readonly type: "parallel";
1821
+ } ? OutputHandlerConfig<States, Events, StateId, ParallelOutputContext<States, Events, StateId>> : {
1822
+ readonly output?: never;
1823
+ };
1824
+ /**
1825
+ * Configuration accepted for a non-final state.
1826
+ *
1827
+ * @category models
1828
+ * @since 4.0.0
1829
+ */
1830
+ type ActiveStateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, E, R> = {
1831
+ readonly type?: "active";
1832
+ readonly entry?: (context: StateActionContext<States, Events, Emits, StateId>) => StateActionResult<any, any>;
1833
+ readonly exit?: (context: StateActionContext<States, Events, Emits, StateId>) => StateActionResult<any, any>;
1834
+ readonly invoke?: InvokeDefinition<States, Events, Emits, StateId>;
1835
+ readonly always?: (context: AlwaysContext<States, Events, Emits, StateId>) => HandlerResult<States, any, any>;
1836
+ readonly onDone?: (context: DoneContext<States, Events, Emits, StateId>) => HandlerResult<States, any, any>;
1837
+ readonly on?: {
1838
+ readonly [EventTag in TagOf<Events[number]>]?: ((context: HandlerContext<States, Events, Emits, StateId, EventTag, E, R>) => HandlerResult<States, any, any>) | {
1839
+ readonly reenter?: boolean;
1840
+ readonly transition: (context: HandlerContext<States, Events, Emits, StateId, EventTag, E, R>) => HandlerResult<States, any, any>;
1841
+ };
1842
+ };
1843
+ } & ActiveOutputHandlerConfig<States, Events, StateId>;
1844
+ /**
1845
+ * Configuration accepted for a final state.
1846
+ *
1847
+ * @category models
1848
+ * @since 4.0.0
1849
+ */
1850
+ type FinalStateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>> = {
1851
+ readonly type: "final";
1852
+ readonly entry?: (context: StateActionContext<States, Events, Emits, StateId>) => StateActionResult<any, any>;
1853
+ readonly exit?: never;
1854
+ readonly always?: never;
1855
+ readonly onDone?: never;
1856
+ readonly on?: never;
1857
+ } & OutputHandlerConfig<States, Events, StateId, FinalOutputContext<States, Events, StateId>>;
1858
+ /**
1859
+ * Configuration accepted by `handle` for a state tag.
1860
+ *
1861
+ * @category models
1862
+ * @since 4.0.0
1863
+ */
1864
+ type HandlerConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, E, R> = ActiveStateConfig<States, Events, Emits, StateId, E, R> | FinalStateConfig<States, Events, Emits, StateId>;
1865
+ type HandlerChildren<Node> = Node extends {
1866
+ readonly states: infer Children extends StateSchemas;
1867
+ } ? Children : never;
1868
+ type HandlerStateId<States extends StateSchemas, Path extends string> = StateIdentifierFromPath<States, Path>;
1869
+ type HandlerConfigPart<Config> = {
1870
+ readonly [Key in keyof Config as Key extends "states" ? never : Key]: Config[Key];
1871
+ };
1872
+ type HandlerNode<AllStates extends StateSchemas, Node, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, E, R, StateId extends StateIdentifier<AllStates>> = HandlerConfig<AllStates, Events, Emits, StateId, E, R> & (HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? {
1873
+ readonly states?: never;
1874
+ } : {
1875
+ readonly states?: HandlerTree<AllStates, Children, Events, Emits, E, R, StateId>;
1876
+ } : {
1877
+ readonly states?: never;
1878
+ });
1879
+ type HandlerTree<AllStates extends StateSchemas, States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, E, R, Prefix extends string> = {
1880
+ readonly [Key in Extract<keyof States, string>]?: HandlerNode<AllStates, States[Key], Events, Emits, E, R, HandlerStateId<AllStates, JoinPath<Prefix, Key>>>;
1881
+ };
1882
+ type HandlerNodeConfigKey = "always" | "entry" | "exit" | "invoke" | "on" | "onDone" | "output" | "states" | "type";
1883
+ type HandlerValidationError<Message extends string> = {
1884
+ readonly "~effect/Machine/HandlerError": Message;
1885
+ };
1886
+ type HandlerValidationErrors<Validation> = Validation extends HandlerValidationError<any> ? Validation : never;
1887
+ type NodeHasDeclaredOutput<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1888
+ readonly output: Schema.Top;
1889
+ } ? StateId : never;
1890
+ type DirectFinalOutputState<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1891
+ readonly type: "final";
1892
+ } ? NodeHasDeclaredOutput<States, StateId> : never;
1893
+ type CompoundCompletionOutputStates<States extends StateSchemas, Children extends StateSchemas, Prefix extends StateIdentifier<States>> = {
1894
+ readonly [Key in Extract<keyof Children, string>]: DirectFinalOutputState<States, Extract<JoinPath<Prefix, Key>, StateIdentifier<States>>>;
1895
+ }[Extract<keyof Children, string>];
1896
+ type RequiredCompletionOutputStates<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends infer Node ? Node extends {
1897
+ readonly type: "parallel";
1898
+ } ? NodeHasDeclaredOutput<States, StateId> : Node extends {
1899
+ readonly states: infer Children extends StateSchemas;
1900
+ } ? CompoundCompletionOutputStates<States, Children, StateId> : never : never;
1901
+ type RequiredParallelOutputStates<States extends StateSchemas, StateId extends StateIdentifier<States>> = NodeByIdentifier<States, StateId> extends {
1902
+ readonly type: "parallel";
1903
+ readonly states: infer Children extends StateSchemas;
1904
+ } ? {
1905
+ readonly [Key in Extract<keyof Children, string>]: RequiredCompletionOutputStates<States, Extract<JoinPath<StateId, Key>, StateIdentifier<States>>>;
1906
+ }[Extract<keyof Children, string>] : never;
1907
+ type HandlerOutputStates<AllStates extends StateSchemas, StateId extends StateIdentifier<AllStates>, Config> = "output" extends keyof Config ? StateId : never;
1908
+ type UnionToIntersection<Union> = (Union extends unknown ? (argument: Union) => void : never) extends (argument: infer Intersection) => void ? Intersection : never;
1909
+ type HandlerUnknownStateKeyValidation<States extends StateSchemas, Config> = [Exclude<Extract<keyof Config, string>, Extract<keyof States, string>>] extends [never] ? unknown : HandlerValidationError<"Handler tree contains a state key that does not exist">;
1910
+ type HandlerUnknownConfigKeyValidation<Config> = [
1911
+ Exclude<Extract<keyof Config, string>, HandlerNodeConfigKey>
1912
+ ] extends [never] ? unknown : HandlerValidationError<"Handler config contains an unknown key">;
1913
+ type HandlerOnKeyValidation<Events extends ReadonlyArray<TaggedSchema>, Config> = Config extends {
1914
+ readonly on?: infer On;
1915
+ } ? [
1916
+ Exclude<Extract<keyof NonNullable<On>, string>, TagOf<Events[number]>>
1917
+ ] extends [never] ? unknown : HandlerValidationError<"Handler config contains an event key that does not exist"> : unknown;
1918
+ type HandlerDepth = readonly [unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown];
1919
+ type HandlerNextDepth<Depth extends ReadonlyArray<unknown>> = Depth extends readonly [unknown, ...infer Rest extends ReadonlyArray<unknown>] ? Rest : readonly [];
1920
+ type HandlerChildrenValidation<AllStates extends StateSchemas, Node, Events extends ReadonlyArray<TaggedSchema>, Prefix extends string, Config, AvailableOutputStates extends StateIdentifier<AllStates>, Depth extends ReadonlyArray<unknown>> = "states" extends keyof Config ? Depth extends readonly [] ? HandlerValidationError<"Handler nesting exceeds the supported depth"> : Config extends {
1921
+ readonly states?: infer ChildrenConfig;
1922
+ } ? HandlerChildren<Node> extends infer Children extends StateSchemas ? [
1923
+ Children
1924
+ ] extends [never] ? HandlerValidationError<"Handler config contains child states for a state that has no children"> : HandlerTreeValidation<AllStates, Children, Events, Prefix, NonNullable<ChildrenConfig>, AvailableOutputStates, HandlerNextDepth<Depth>> : HandlerValidationError<"Handler config contains child states for a state that has no children"> : unknown : unknown;
1925
+ type HandlerOutputRequirementValidation<AllStates extends StateSchemas, StateId extends StateIdentifier<AllStates>, AvailableOutputStates extends StateIdentifier<AllStates>, Config> = ("onDone" extends keyof Config ? [
1926
+ Exclude<RequiredCompletionOutputStates<AllStates, StateId>, AvailableOutputStates>
1927
+ ] extends [never] ? unknown : HandlerValidationError<"Handler config is missing an output implementation required by onDone"> : unknown) & ("output" extends keyof Config ? NodeByIdentifier<AllStates, StateId> extends {
1928
+ readonly type: "parallel";
1929
+ } ? [
1930
+ Exclude<RequiredParallelOutputStates<AllStates, StateId>, AvailableOutputStates>
1931
+ ] extends [never] ? unknown : HandlerValidationError<"Handler config is missing a region output implementation required by parallel output"> : unknown : unknown);
1932
+ type HandlerNodeValidation<AllStates extends StateSchemas, Node, Events extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<AllStates>, Config, AvailableOutputStates extends StateIdentifier<AllStates>, Depth extends ReadonlyArray<unknown>> = HandlerUnknownConfigKeyValidation<Config> & HandlerOnKeyValidation<Events, Config> & HandlerInvokeOutputValidation<Events, Config> & HandlerInvokeEmitsValidation<Events, Config> & HandlerInvokeSnapshotValidation<Events, Config> & HandlerChildrenValidation<AllStates, Node, Events, StateId, Config, AvailableOutputStates, Depth> & HandlerOutputRequirementValidation<AllStates, StateId, AvailableOutputStates, Config>;
1933
+ type HandlerInvokeOutputValidation<Events extends ReadonlyArray<TaggedSchema>, Config> = [InvokeReturn<Config>] extends [never] ? unknown : [Exclude<InvokeOutput<InvokeReturn<Config>>, EventOf<Events> | void>] extends [never] ? unknown : HandlerValidationError<"Invoked child output must be a machine event or void">;
1934
+ type HandlerInvokeEmitsValidation<Events extends ReadonlyArray<TaggedSchema>, Config> = [InvokeReturn<Config>] extends [never] ? unknown : [Exclude<InvokeEmits<InvokeReturn<Config>>, EventOf<Events>>] extends [never] ? unknown : HandlerValidationError<"Invoked child emits events not accepted by the parent machine">;
1935
+ type HandlerInvokeSnapshotValidation<Events extends ReadonlyArray<TaggedSchema>, Config> = [InvokeReturn<Config>] extends [never] ? unknown : IsAny<InvokeSnapshotEvent<InvokeReturn<Config>>> extends true ? unknown : [Exclude<InvokeSnapshotEvent<InvokeReturn<Config>>, EventOf<Events> | undefined>] extends [never] ? unknown : HandlerValidationError<"Invoked child snapshot mapper must return a machine event or undefined">;
1936
+ type HandlerTreeNodeValidationErrors<AllStates extends StateSchemas, States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Prefix extends string, Config, AvailableOutputStates extends StateIdentifier<AllStates>, Depth extends ReadonlyArray<unknown>> = {
1937
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: HandlerValidationErrors<HandlerNodeValidation<AllStates, States[Key], Events, HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], AvailableOutputStates, Depth>>;
1938
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1939
+ type HandlerTreeNodeValidations<AllStates extends StateSchemas, States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Prefix extends string, Config, AvailableOutputStates extends StateIdentifier<AllStates>, Depth extends ReadonlyArray<unknown>> = HandlerTreeNodeValidationErrors<AllStates, States, Events, Prefix, Config, AvailableOutputStates, Depth> extends infer Errors ? [Errors] extends [never] ? unknown : UnionToIntersection<Errors> : never;
1940
+ type HandlerTreeValidation<AllStates extends StateSchemas, States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Prefix extends string, Config, AvailableOutputStates extends StateIdentifier<AllStates>, Depth extends ReadonlyArray<unknown> = HandlerDepth> = HandlerUnknownStateKeyValidation<States, Config> & HandlerTreeNodeValidations<AllStates, States, Events, Prefix, Config, AvailableOutputStates, Depth>;
1941
+ type HandlerNodeChildrenConfig<Config> = "states" extends keyof Config ? Config extends {
1942
+ readonly states?: infer Children;
1943
+ } ? NonNullable<Children> : never : never;
1944
+ type HandlerTreeStateIds<AllStates extends StateSchemas, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1945
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: HandlerStateId<AllStates, JoinPath<Prefix, Key>> | HandlerNodeChildStateIds<AllStates, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1946
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1947
+ type HandlerNodeChildStateIds<AllStates extends StateSchemas, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeStateIds<AllStates, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1948
+ type HandlerConfigError<Config> = Effect.Error<EventHandlerReturn<Config>> | Effect.Error<AlwaysReturn<Config>> | Effect.Error<DoneReturn<Config>> | Effect.Error<StateActionReturn<Config, "entry">> | Effect.Error<StateActionReturn<Config, "exit">> | InvokeError<Config>;
1949
+ type HandlerTreeError<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1950
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: HandlerConfigError<HandlerConfigPart<Config[Key]>> | HandlerNodeChildError<AllStates, Events, Emits, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1951
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1952
+ type HandlerNodeChildError<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeError<AllStates, Events, Emits, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1953
+ type HandlerTreeServices<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1954
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: ConfigServices<HandlerConfigPart<Config[Key]>> | HandlerNodeChildServices<AllStates, Events, Emits, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1955
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1956
+ type HandlerNodeChildServices<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeServices<AllStates, Events, Emits, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1957
+ type HandlerTreeFinalStates<AllStates extends StateSchemas, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1958
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: Extract<FinalStateFromConfig<HandlerConfigPart<Config[Key]>, HandlerStateId<AllStates, JoinPath<Prefix, Key>>>, StateIdentifier<AllStates>> | HandlerNodeChildFinalStates<AllStates, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1959
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1960
+ type HandlerNodeChildFinalStates<AllStates extends StateSchemas, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeFinalStates<AllStates, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1961
+ type HandlerTreeOutput<AllStates extends StateSchemas, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1962
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: ("output" extends keyof HandlerConfigPart<Config[Key]> ? OutputByIdentifier<AllStates, HandlerStateId<AllStates, JoinPath<Prefix, Key>>> : never) | HandlerNodeChildOutput<AllStates, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1963
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1964
+ type HandlerNodeChildOutput<AllStates extends StateSchemas, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeOutput<AllStates, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1965
+ type HandlerTreeOutputStates<AllStates extends StateSchemas, States extends StateSchemas, Prefix extends string, Config, Depth extends ReadonlyArray<unknown> = HandlerDepth> = {
1966
+ readonly [Key in Extract<Extract<keyof Config, string>, Extract<keyof States, string>>]: HandlerOutputStates<AllStates, HandlerStateId<AllStates, JoinPath<Prefix, Key>>, HandlerConfigPart<Config[Key]>> | HandlerNodeChildOutputStates<AllStates, States[Key], HandlerStateId<AllStates, JoinPath<Prefix, Key>>, Config[Key], Depth>;
1967
+ }[Extract<Extract<keyof Config, string>, Extract<keyof States, string>>];
1968
+ type HandlerNodeChildOutputStates<AllStates extends StateSchemas, Node, Prefix extends string, Config, Depth extends ReadonlyArray<unknown>> = Depth extends readonly [] ? never : HandlerChildren<Node> extends infer Children extends StateSchemas ? [Children] extends [never] ? never : HandlerTreeOutputStates<AllStates, Children, Prefix, HandlerNodeChildrenConfig<Config>, HandlerNextDepth<Depth>> : never;
1969
+ type HandleTreeResult<AllStates extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Input extends Schema.Top, UnhandledStates extends StateIdentifier<AllStates>, E, R, InitialE, InitialR, FinalStates extends StateIdentifier<AllStates>, Output, OutputStates extends StateIdentifier<AllStates>, Config> = Machine<AllStates, Events, Input, Exclude<UnhandledStates, HandlerTreeStateIds<AllStates, AllStates, "", Config>>, E | HandlerTreeError<AllStates, Events, Emits, AllStates, "", Config>, ExcludeCompatibleRuntime<R | HandlerTreeServices<AllStates, Events, Emits, AllStates, "", Config>, EventOf<Events>, EmitOf<Emits>>, InitialE, InitialR, FinalStates | Extract<HandlerTreeFinalStates<AllStates, AllStates, "", Config>, StateIdentifier<AllStates>>, Output | HandlerTreeOutput<AllStates, AllStates, "", Config>, Emits, OutputStates | Extract<HandlerTreeOutputStates<AllStates, AllStates, "", Config>, StateIdentifier<AllStates>>>;
1970
+ /**
1971
+ * Adds state handlers from a root state object.
1972
+ *
1973
+ * **Gotchas**
1974
+ *
1975
+ * Type inference traverses up to eight nested child-state objects. Deeper
1976
+ * handler trees are rejected explicitly instead of silently dropping their
1977
+ * error, service, final-state, or output channels.
1978
+ *
1979
+ * @category combinators
1980
+ * @since 4.0.0
1981
+ */
1982
+ interface Handler<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, Input extends Schema.Top, UnhandledStates extends StateIdentifier<States>, E, R, InitialE, InitialR, FinalStates extends StateIdentifier<States>, Output, OutputStates extends StateIdentifier<States>> {
1983
+ <const Config extends HandlerTree<States, States, Events, Emits, E, R, "">>(config: Config & HandlerTreeValidation<States, States, Events, "", Config, OutputStates | Extract<HandlerTreeOutputStates<States, States, "", Config>, StateIdentifier<States>>> & EnsureCompatibleRuntime<HandlerTreeServices<States, Events, Emits, States, "", Config>, EventOf<Events>, EmitOf<Emits>>): HandleTreeResult<States, Events, Emits, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, OutputStates, Config>;
1984
+ }
1985
+ /**
1986
+ * Any state config.
1987
+ *
1988
+ * @category utility types
1989
+ * @since 4.0.0
1990
+ */
1991
+ type AnyStateConfig = StateConfig<any, any, any, any, any, any, any>;
1992
+ /**
1993
+ * Runtime event-handler map stored for a single state tag.
1994
+ *
1995
+ * @category models
1996
+ * @since 4.0.0
1997
+ */
1998
+ type EventHandlerMap<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> = Readonly<Record<PropertyKey, ((context: HandlerContext<States, Events, Emits, StateId, EventTag, E, R>) => HandlerResult<States, E, R>) | {
1999
+ readonly reenter?: boolean;
2000
+ readonly transition: (context: HandlerContext<States, Events, Emits, StateId, EventTag, E, R>) => HandlerResult<States, E, R>;
2001
+ }>>;
2002
+ /**
2003
+ * Runtime state config stored for a single state tag.
2004
+ *
2005
+ * @category models
2006
+ * @since 4.0.0
2007
+ */
2008
+ interface StateConfig<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> {
2009
+ readonly type?: "final" | "active";
2010
+ readonly entry?: (context: StateActionContext<States, Events, Emits, StateId>) => StateActionResult<E, R>;
2011
+ readonly exit?: (context: StateActionContext<States, Events, Emits, StateId>) => StateActionResult<E, R>;
2012
+ readonly invoke?: InvokeDefinition<States, Events, Emits, StateId>;
2013
+ readonly always?: (context: AlwaysContext<States, Events, Emits, StateId>) => HandlerResult<States, E, R>;
2014
+ readonly onDone?: (context: DoneContext<States, Events, Emits, StateId>) => HandlerResult<States, E, R>;
2015
+ readonly output?: ((context: FinalOutputContext<States, Events, StateId>) => any) | ((context: ParallelOutputContext<States, Events, StateId>) => any);
2016
+ readonly on?: EventHandlerMap<States, Events, Emits, StateId, EventTag, E, R>;
2017
+ }
2018
+ /**
2019
+ * Runtime handler table stored on a machine.
2020
+ *
2021
+ * @category models
2022
+ * @since 4.0.0
2023
+ */
2024
+ type StateConfigs<States extends StateSchemas, Events extends ReadonlyArray<TaggedSchema>, Emits extends ReadonlyArray<TaggedSchema>, StateId extends StateIdentifier<States>, EventTag extends TagOf<Events[number]>, E, R> = Readonly<Record<PropertyKey, StateConfig<States, Events, Emits, StateId, EventTag, E, R>>>;
2025
+ }
2026
+ /**
2027
+ * Returns `true` if a value is a `Machine`.
2028
+ *
2029
+ * @category guards
2030
+ * @since 4.0.0
2031
+ */
2032
+ export declare const isMachine: (u: unknown) => u is Machine.Any;
2033
+ /**
2034
+ * Returns `true` if a state snapshot is final for a machine.
2035
+ *
2036
+ * @category guards
2037
+ * @since 4.0.0
2038
+ */
2039
+ export declare const isFinal: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema>, 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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates>, state: Machine.Snapshot<States>) => state is Machine.SnapshotContainingFinal<States, FinalStates>;
2040
+ /**
2041
+ * Defines a state tree while preserving literal state paths.
2042
+ *
2043
+ * **When to use**
2044
+ *
2045
+ * Use when you want to pass a state tree to `make` and also get typed
2046
+ * snapshot builders for initial states and tests.
2047
+ *
2048
+ * **Details**
2049
+ *
2050
+ * The returned `states` property is the same object passed to `defineStates`.
2051
+ * The returned `initial` builder creates snapshots without user-authored path
2052
+ * strings and enforces compound and parallel initial-state rules.
2053
+ *
2054
+ * **Example** (Atomic initial snapshot)
2055
+ *
2056
+ * ```ts
2057
+ * import { Schema } from "effect"
2058
+ * import { Machine } from "effect/unstable/machine"
2059
+ *
2060
+ * class Idle extends Schema.TaggedClass<Idle>("Idle")("Idle", {}) {}
2061
+ *
2062
+ * const States = Machine.defineStates({ idle: Idle })
2063
+ *
2064
+ * Machine.make({
2065
+ * states: States.states,
2066
+ * events: [],
2067
+ * initial: () => States.initial.idle(new Idle({}))
2068
+ * })
2069
+ * ```
2070
+ *
2071
+ * @category constructors
2072
+ * @since 4.0.0
2073
+ */
2074
+ export declare const defineStates: <const States extends Machine.StateSchemas>(states: States & DefineStateTreeInput<NoInfer<States>>, ..._validation: ValidateDefinedStates<NoInfer<States>>) => Machine.DefinedStates<States>;
2075
+ /**
2076
+ * Creates a schema-first machine definition.
2077
+ *
2078
+ * **Details**
2079
+ *
2080
+ * State and event schemas provide runtime boundary validation while their
2081
+ * decoded types drive handler, state, event, target, error, and service
2082
+ * inference. State-tree validation is applied whether `states` comes from
2083
+ * `defineStates` or is passed inline. Call `handle` on the returned definition
2084
+ * to implement state behavior with ordinary TypeScript control flow.
2085
+ *
2086
+ * **Example** (Typed counter machine)
2087
+ *
2088
+ * ```ts
2089
+ * import { Schema } from "effect"
2090
+ * import { Machine } from "effect/unstable/machine"
2091
+ *
2092
+ * class Count extends Schema.TaggedClass<Count>("Count")("Count", {
2093
+ * value: Schema.Number
2094
+ * }) {}
2095
+ *
2096
+ * class Increment extends Schema.TaggedClass<Increment>("Increment")("Increment", {
2097
+ * by: Schema.Number
2098
+ * }) {}
2099
+ *
2100
+ * const States = Machine.defineStates({ Count })
2101
+ *
2102
+ * const counter = Machine.make({
2103
+ * states: States.states,
2104
+ * events: [Increment],
2105
+ * initial: () => States.initial.Count(new Count({ value: 0 }))
2106
+ * }).handle({
2107
+ * Count: {
2108
+ * on: {
2109
+ * Increment: ({ event, state }) =>
2110
+ * States.initial.Count(new Count({ value: state.value + event.by }))
2111
+ * }
2112
+ * }
2113
+ * })
2114
+ * ```
2115
+ *
2116
+ * @see {@link defineStates} for typed initial snapshot builders.
2117
+ * @category constructors
2118
+ * @since 4.0.0
2119
+ */
2120
+ export declare const make: <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, InitialE = never, InitialR = never>(config: {
2121
+ readonly id?: string;
2122
+ readonly states: States & DefineStateTreeInput<NoInfer<States>>;
2123
+ readonly events: Events;
2124
+ readonly emits?: Emits;
2125
+ readonly input?: Input;
2126
+ readonly initial: (...args: [...Machine.InputArgs<Input>]) => Machine.InitialResult<States, InitialE, InitialR>;
2127
+ }, ..._validation: ValidateDefinedStates<NoInfer<States>>) => Machine<States, Events, Input, Machine.StateIdentifier<States>, never, never, InitialE, InitialR, Machine.FinalStateFromDefinition<States>, never, Emits>;
2128
+ /**
2129
+ * Encodes a decoded machine snapshot into a normalized data representation.
2130
+ *
2131
+ * **When to use**
2132
+ *
2133
+ * Use when you need to store or transport a statechart snapshot independently
2134
+ * of its local machine runtime.
2135
+ *
2136
+ * **Details**
2137
+ *
2138
+ * Each active state value and completed output is encoded with the schema
2139
+ * declared for its state path. The result contains no process-local runtime
2140
+ * state.
2141
+ *
2142
+ * **Gotchas**
2143
+ *
2144
+ * The encoded snapshot does not contain the machine definition, machine
2145
+ * version, running children, invoked process state, services, or subscriptions.
2146
+ * Store machine identity and migration metadata alongside the result when the
2147
+ * snapshot crosses deployment versions. Schema encoding does not by itself
2148
+ * guarantee JSON-compatible values; schemas used with JSON-backed storage must
2149
+ * have JSON-compatible encoded representations.
2150
+ *
2151
+ * @see {@link decodeSnapshot} for restoring an encoded snapshot.
2152
+ * @category encoding
2153
+ * @since 4.0.0
2154
+ */
2155
+ export declare const encodeSnapshot: <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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>, snapshot: Machine.Snapshot<States>) => Effect.Effect<Machine.EncodedSnapshot, MachineSchemaEncodeError, Machine.SnapshotEncodingServices<States>>;
2156
+ /**
2157
+ * Decodes a normalized data representation into a validated machine snapshot.
2158
+ *
2159
+ * **When to use**
2160
+ *
2161
+ * Use when you need to resume planning from a snapshot loaded from storage or
2162
+ * received over a transport boundary.
2163
+ *
2164
+ * **Details**
2165
+ *
2166
+ * Decoding resolves every path against the supplied machine, decodes values
2167
+ * with their state and output schemas, validates compound and parallel state
2168
+ * relationships, and rebuilds the recursive in-memory snapshot.
2169
+ *
2170
+ * **Gotchas**
2171
+ *
2172
+ * Decoding restores logical statechart data only. It does not restart invoked
2173
+ * processes, recreate spawned children, or restore a previous `MachineRef`.
2174
+ *
2175
+ * @see {@link encodeSnapshot} for creating the normalized representation.
2176
+ * @category decoding
2177
+ * @since 4.0.0
2178
+ */
2179
+ export declare const decodeSnapshot: <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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>, encoded: unknown) => Effect.Effect<Machine.Snapshot<States>, MachineSchemaDecodeError, Machine.SnapshotDecodingServices<States>>;
2180
+ /**
2181
+ * Creates an invoked child process configuration for an active state.
2182
+ *
2183
+ * **When to use**
2184
+ *
2185
+ * Use to run a child process while a machine remains in a state. Successful
2186
+ * outputs are sent directly to the parent machine as events; `void` sends
2187
+ * nothing. Unrecovered child failures fail the owning machine. Active
2188
+ * snapshots can optionally be mapped to progress events.
2189
+ *
2190
+ * **Gotchas**
2191
+ *
2192
+ * Invoked child processes run while their owning state is active and are
2193
+ * stopped before the state exits. An unrecovered child failure fails the owning
2194
+ * machine; recover inside the child Effect when failure should become an event.
2195
+ * The `src` callback is intentionally independent from its parent state. When
2196
+ * construction depends on the typed state, lifecycle event, or runtime, use
2197
+ * the state config factory form `invoke: (context) => Machine.invoke(...)` and
2198
+ * close over that context from `src`.
2199
+ *
2200
+ * **Example** (Effect output as a parent event)
2201
+ *
2202
+ * ```ts
2203
+ * import { Effect, Schema } from "effect"
2204
+ * import { Machine } from "effect/unstable/machine"
2205
+ *
2206
+ * class Loaded extends Schema.TaggedClass<Loaded>("Loaded")("Loaded", {
2207
+ * value: Schema.String
2208
+ * }) {}
2209
+ *
2210
+ * const load = Machine.invoke({
2211
+ * id: "load",
2212
+ * src: () => Machine.effect(Effect.succeed(new Loaded({ value: "ready" })))
2213
+ * })
2214
+ * ```
2215
+ *
2216
+ * @see {@link effect} for one-shot child effects.
2217
+ * @see {@link spawn} for children whose lifetime is controlled by actions.
2218
+ * @category constructors
2219
+ * @since 4.0.0
2220
+ */
2221
+ export declare const invoke: <ChildState, ChildEvent, ChildError = never, ChildRequirements = never, ChildOutput = never, ChildInitialError = never, Event = never, Id extends string = string>(config: {
2222
+ readonly id: Id;
2223
+ readonly src: () => Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>;
2224
+ readonly snapshot?: (context: Machine.InvokeSnapshotContext<ChildState, ChildError | ChildInitialError, ChildOutput>) => Event | undefined;
2225
+ } & ChildAddress.Compatibility<Id, ChildEvent>) => Machine.InvokeConfig<any, any, any, any, Event, ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>;
2226
+ type InvokeMachineInput<Input extends Schema.Top> = Input extends typeof Schema.Void ? {
2227
+ readonly input?: never;
2228
+ } : {
2229
+ readonly input: Input["Type"];
2230
+ };
2231
+ /**
2232
+ * Creates an invoked child process from a complete statechart machine.
2233
+ *
2234
+ * **When to use**
2235
+ *
2236
+ * Use when a state should own another statechart machine and communicate with
2237
+ * it through typed child events, emissions, snapshots, or terminal output.
2238
+ *
2239
+ * **Details**
2240
+ *
2241
+ * Child emissions are delivered directly to the parent as events. Active
2242
+ * snapshots and terminal output can be mapped to parent events. The owning
2243
+ * state controls the child lifetime.
2244
+ *
2245
+ * **Gotchas**
2246
+ *
2247
+ * Active invoked machines must have unique child addresses. A machine starts
2248
+ * after its owning state's entry actions, so those actions cannot send events
2249
+ * to a newly entered child. Unrecovered child failures fail the parent.
2250
+ *
2251
+ * @see {@link invoke} for invoking lower-level process logic.
2252
+ * @see {@link sendTo} for sending events to the invoked machine.
2253
+ * @category constructors
2254
+ * @since 4.0.0
2255
+ */
2256
+ export declare const invokeMachine: {
2257
+ <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, SnapshotEvent = never, DoneEvent = never, Id extends string = string>(config: {
2258
+ readonly child: ChildMachine<Id, Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>>;
2259
+ readonly snapshot?: (context: Machine.InvokeSnapshotContext<Machine.Snapshot<States>, E | InitialE | ActionError<R | InitialR> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Output | undefined>) => SnapshotEvent | undefined;
2260
+ readonly onDone: (context: Machine.InvokeDoneContext<Output | undefined>) => DoneEvent | undefined;
2261
+ } & InvokeMachineInput<Input>): Machine.InvokeConfig<any, any, any, any, SnapshotEvent, Machine.Snapshot<States>, Machine.EventOf<Events>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, ExcludeCompatibleRuntime<Exclude<ExecutionServices<InitialR | R>, internalRuntime.MachineRuntime>, Machine.EventOf<Events>, Machine.EmitOf<Emits>>, Output | undefined, InitialE | ActionError<InitialR | R> | MachineSchemaDecodeError | StartupError | StoppedError, Machine.EmitOf<Emits>, DoneEvent>;
2262
+ <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, SnapshotEvent = never, Id extends string = string>(config: {
2263
+ readonly child: ChildMachine<Id, Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>>;
2264
+ readonly snapshot?: (context: Machine.InvokeSnapshotContext<Machine.Snapshot<States>, E | InitialE | ActionError<R | InitialR> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Output | undefined>) => SnapshotEvent | undefined;
2265
+ readonly onDone?: never;
2266
+ } & InvokeMachineInput<Input>): Machine.InvokeConfig<any, any, any, any, SnapshotEvent, Machine.Snapshot<States>, Machine.EventOf<Events>, E | ActionError<R> | InfiniteTransitionError | MachineSchemaDecodeError | StoppedError, ExcludeCompatibleRuntime<Exclude<ExecutionServices<InitialR | R>, internalRuntime.MachineRuntime>, Machine.EventOf<Events>, Machine.EmitOf<Emits>>, Output | undefined, InitialE | ActionError<InitialR | R> | MachineSchemaDecodeError | StartupError | StoppedError, Machine.EmitOf<Emits>>;
2267
+ };
2268
+ /**
2269
+ * Plans the initial state for a machine without running deferred actions.
2270
+ *
2271
+ * **Details**
2272
+ *
2273
+ * The returned plan contains the settled initial snapshot, staged actions,
2274
+ * emitted events, and optional final output. Planning may evaluate transition
2275
+ * logic and follow completion, eventless, and raised-event steps, but it does
2276
+ * not execute effects passed to `action`.
2277
+ *
2278
+ * **Gotchas**
2279
+ *
2280
+ * Callers that execute a plan manually must run actions sequentially before
2281
+ * publishing its state or delivering its emitted events. `start` performs this
2282
+ * protocol automatically.
2283
+ *
2284
+ * @see {@link plan} for planning a received event.
2285
+ * @see {@link start} for the managed runtime protocol.
2286
+ * @category constructors
2287
+ * @since 4.0.0
2288
+ */
2289
+ export declare const planInitial: <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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<{
2290
+ readonly state: Machine.Snapshot<States>;
2291
+ readonly actions: ReadonlyArray<Effect.Effect<void, ActionError<InitialR | R>, ActionServices<InitialR | R>>>;
2292
+ readonly emittedEvents: ReadonlyArray<Machine.EmitOf<Emits>>;
2293
+ readonly output: Output | undefined;
2294
+ }, InitialE | MachineSchemaDecodeError | StartupError, ExcludeCompatibleRuntime<PlanningServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmitOf<Emits>>>;
2295
+ /**
2296
+ * Returns the event tags handled by the current state snapshot.
2297
+ *
2298
+ * @category getters
2299
+ * @since 4.0.0
2300
+ */
2301
+ export declare const enabled: <const States extends Machine.StateSchemas, const Events extends ReadonlyArray<Machine.TaggedSchema>, const Emits extends ReadonlyArray<Machine.TaggedSchema>, 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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits, OutputStates>, state: Machine.Snapshot<States>) => ReadonlyArray<Machine.TagOf<Events[number]>>;
2302
+ /**
2303
+ * Plans the next state snapshot without running deferred actions.
2304
+ *
2305
+ * **Details**
2306
+ *
2307
+ * Planning selects child transitions before conflicting ancestors, permits
2308
+ * non-conflicting transitions in parallel regions, processes completion and
2309
+ * eventless transitions, and drains raised events in FIFO order. Exit paths
2310
+ * are deepest-first and entry paths are parent-first.
2311
+ *
2312
+ * **Gotchas**
2313
+ *
2314
+ * `plan` returns data; it does not implement the runtime commit protocol. Run
2315
+ * actions sequentially, publish `next` only after they succeed, and then
2316
+ * deliver `emittedEvents`. A failed action must retain the previously
2317
+ * published state and suppress emissions. Events with no enabled transition
2318
+ * are ignored and produce an unchanged plan.
2319
+ *
2320
+ * @see {@link planInitial} for planning machine startup.
2321
+ * @see {@link start} for managed execution and lifecycle observation.
2322
+ * @category combinators
2323
+ * @since 4.0.0
2324
+ */
2325
+ export declare const plan: <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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>, state: Machine.Snapshot<States>, event: Machine.EventOf<Events>) => Effect.Effect<{
2326
+ readonly next: Machine.Snapshot<States>;
2327
+ readonly actions: ReadonlyArray<Effect.Effect<void, ActionError<R>, ActionServices<R>>>;
2328
+ readonly emittedEvents: ReadonlyArray<Machine.EmitOf<Emits>>;
2329
+ readonly microsteps: ReadonlyArray<{
2330
+ readonly next: Machine.Snapshot<States>;
2331
+ readonly event: Machine.EventOf<Events> | InitialEvent;
2332
+ readonly actions: ReadonlyArray<Effect.Effect<void, ActionError<R>, ActionServices<R>>>;
2333
+ readonly raisedEvents: ReadonlyArray<Machine.EventOf<Events>>;
2334
+ readonly emittedEvents: ReadonlyArray<Machine.EmitOf<Emits>>;
2335
+ readonly exitPaths: ReadonlyArray<string>;
2336
+ readonly entryPaths: ReadonlyArray<string>;
2337
+ readonly changed: boolean;
2338
+ }>;
2339
+ readonly output: Output | undefined;
2340
+ }, E | InfiniteTransitionError | MachineSchemaDecodeError, ExcludeCompatibleRuntime<PlanningServices<R>, Machine.EventOf<Events>, Machine.EmitOf<Emits>>>;
2341
+ /**
2342
+ * Defers an effectful action until the current machine step is planned.
2343
+ *
2344
+ * **Details**
2345
+ *
2346
+ * The action's error and service requirements are retained in the machine
2347
+ * type without becoming requirements of `plan` or `planInitial`. The managed
2348
+ * runtime executes staged actions sequentially before publishing the planned
2349
+ * state.
2350
+ *
2351
+ * **Example** (Typed staged action)
2352
+ *
2353
+ * ```ts
2354
+ * import { Context, Effect } from "effect"
2355
+ * import { Machine } from "effect/unstable/machine"
2356
+ *
2357
+ * class Audit extends Context.Service<Audit, {
2358
+ * readonly write: Effect.Effect<void, "AuditError">
2359
+ * }>()("example/Audit") {}
2360
+ *
2361
+ * const writeAudit = Machine.action(
2362
+ * Effect.flatMap(Audit, (audit) => audit.write)
2363
+ * )
2364
+ * ```
2365
+ *
2366
+ * @see {@link plan} for inspecting staged actions without executing them.
2367
+ * @category combinators
2368
+ * @since 4.0.0
2369
+ */
2370
+ export declare const action: <E, R>(effect: Effect.Effect<void, E, R>) => Effect.Effect<void, never, ActionRequirement<E, R>>;
2371
+ /**
2372
+ * Runs staged machine actions sequentially with the supplied runtime.
2373
+ *
2374
+ * **When to use**
2375
+ *
2376
+ * Use when you implement a commit protocol around `plan` or `planInitial` and
2377
+ * need to execute their staged actions before publishing the planned snapshot.
2378
+ *
2379
+ * **Gotchas**
2380
+ *
2381
+ * This function only runs actions. The caller remains responsible for
2382
+ * publishing the planned state and delivering planned emitted events after all
2383
+ * actions succeed. Process-local operations such as `spawn`, `sendTo`, and
2384
+ * `stopChild` fail with `ProcessLocalError` because no managed machine process
2385
+ * owns the actions.
2386
+ *
2387
+ * @see {@link plan} for creating a transition plan.
2388
+ * @see {@link planInitial} for creating an initial plan.
2389
+ * @category running
2390
+ * @since 4.0.0
2391
+ */
2392
+ export declare const runActions: <E, R, Events, Emits>(actions: Iterable<Effect.Effect<void, E, R>>, runtime: Runtime<Events, Emits>) => Effect.Effect<void, E | ProcessLocalError, Exclude<ExcludeCompatibleRuntime<R, Events, Emits>, MachineRuntimeRequirement>>;
2393
+ /**
2394
+ * Returns the typed runtime capability for the current machine.
2395
+ *
2396
+ * @category combinators
2397
+ * @since 4.0.0
2398
+ */
2399
+ export declare const runtime: <const Protocol extends Runtime.Protocol = {}>() => Effect.Effect<Runtime<Runtime.Events<Protocol>, Runtime.Emits<Protocol>>, never, Runtime.Requirement<Runtime.Events<Protocol>, Runtime.Emits<Protocol>>>;
2400
+ /**
2401
+ * Creates a one-shot child process from an Effect.
2402
+ *
2403
+ * **When to use**
2404
+ *
2405
+ * Use when you need side effects that produce one typed output or error.
2406
+ *
2407
+ * **Details**
2408
+ *
2409
+ * The Effect may run arbitrary side effects. Its success value is the process
2410
+ * output, its typed error is preserved, and its services are inferred. When
2411
+ * invoked, the output is sent to the owning machine as an event unless it is
2412
+ * `void`.
2413
+ *
2414
+ * **Gotchas**
2415
+ *
2416
+ * This process has no incoming event protocol. Its Effect runs once. Use
2417
+ * `transition` for a process that receives events over time and `logic` for
2418
+ * direct machine-local communication or intermediate snapshots.
2419
+ *
2420
+ * **Example** (Recover a child failure as output)
2421
+ *
2422
+ * ```ts
2423
+ * import { Effect, Schema } from "effect"
2424
+ * import { Machine } from "effect/unstable/machine"
2425
+ *
2426
+ * class LoadFailed extends Schema.TaggedClass<LoadFailed>("LoadFailed")("LoadFailed", {
2427
+ * reason: Schema.String
2428
+ * }) {}
2429
+ *
2430
+ * const load = Machine.effect(
2431
+ * Effect.fail("unavailable").pipe(
2432
+ * Effect.catch((reason) => Effect.succeed(new LoadFailed({ reason })))
2433
+ * )
2434
+ * )
2435
+ * ```
2436
+ *
2437
+ * @see {@link transition} for event-driven state.
2438
+ * @see {@link logic} for direct control over intermediate snapshots.
2439
+ * @category constructors
2440
+ * @since 4.0.0
2441
+ */
2442
+ export declare const effect: <Output, Error = never, Requirements = never>(effect: Effect.Effect<Output, Error, Requirements>) => Logic<void, never, Error, Requirements, Output>;
2443
+ /**
2444
+ * Creates advanced stateful process logic from explicit initialization and
2445
+ * execution methods.
2446
+ *
2447
+ * **When to use**
2448
+ *
2449
+ * Use when you need a machine-scoped process to publish intermediate snapshots
2450
+ * directly.
2451
+ *
2452
+ * **Details**
2453
+ *
2454
+ * Initialization produces the first state before `run` starts. The running
2455
+ * context receives events, reads or updates state, manages child processes,
2456
+ * and can communicate with its owning machine. Errors and service requirements
2457
+ * from both phases remain in the returned `Logic` type.
2458
+ *
2459
+ * **Gotchas**
2460
+ *
2461
+ * This is the low-level process constructor. Parent messages sent directly
2462
+ * through its scope are intentionally `unknown` because the logic does not know
2463
+ * which machine will eventually own it. Prefer typed output, typed child
2464
+ * addresses, or invoke snapshot mapping when possible.
2465
+ *
2466
+ * @see {@link effect} for one-shot work.
2467
+ * @see {@link transition} for event-driven state.
2468
+ * @category constructors
2469
+ * @since 4.0.0
2470
+ */
2471
+ export declare const logic: <State, Event = any, Output = void, Error = never, Requirements = never, InitialError = never, InitialRequirements = never>(options: {
2472
+ readonly initial: State | ((scope: Logic.Scope<Event>) => Effect.Effect<State, InitialError, InitialRequirements>);
2473
+ readonly run: (context: Logic.Context<State, Event>) => Effect.Effect<Output, Error, Requirements>;
2474
+ }) => Logic<State, Event, Error, Requirements | InitialRequirements, Output, InitialError>;
2475
+ /**
2476
+ * Creates child process logic from an initial state and a transition function.
2477
+ *
2478
+ * **When to use**
2479
+ *
2480
+ * Use when a child process only needs sequential event-driven state updates and
2481
+ * does not need direct control over intermediate snapshots or child ownership.
2482
+ *
2483
+ * **Details**
2484
+ *
2485
+ * Each received event runs the transition Effect against the latest state. The
2486
+ * resulting state is published before the next queued event is processed.
2487
+ *
2488
+ * @see {@link effect} for one-shot work.
2489
+ * @see {@link logic} for direct process lifecycle control.
2490
+ * @category constructors
2491
+ * @since 4.0.0
2492
+ */
2493
+ export declare const transition: <State, Event, Error = never, Requirements = never>(initial: State, transition: (state: State, event: Event) => Effect.Effect<State, Error, Requirements>) => Logic<State, Event, Error, Requirements, never>;
2494
+ /**
2495
+ * Creates a typed parent-local child address or complete machine descriptor.
2496
+ *
2497
+ * **When to use**
2498
+ *
2499
+ * Use with a complete machine to create the descriptor shared by
2500
+ * `invokeMachine`, `sendTo`, and child lookup APIs. The one-argument form
2501
+ * creates an event-only address for lower-level process logic.
2502
+ *
2503
+ * @category constructors
2504
+ * @since 4.0.0
2505
+ */
2506
+ export declare const child: {
2507
+ <const Id extends string, M extends Machine.Any>(id: Id, machine: M): ChildMachine<Id, M>;
2508
+ <Event>(id: string): ChildAddress<Event>;
2509
+ };
2510
+ /**
2511
+ * Spawns a child process owned by the currently running machine.
2512
+ *
2513
+ * **When to use**
2514
+ *
2515
+ * Use to create child processes from machine actions when the child
2516
+ * should be addressed or stopped by the owning machine instead of tied to a
2517
+ * single state's `invoke` lifecycle.
2518
+ *
2519
+ * **Gotchas**
2520
+ *
2521
+ * This effect requires the machine runtime, so it only runs from machine
2522
+ * actions. A named child id must be unique for the current parent machine until
2523
+ * that child stops.
2524
+ *
2525
+ * @see {@link invoke} for children that start and stop with a state.
2526
+ * @see {@link sendTo} for sending events to named children.
2527
+ * @category runtime
2528
+ * @since 4.0.0
2529
+ */
2530
+ export declare const spawn: {
2531
+ <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError = never>(logic: Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>): SpawnResult<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, never, ChildInitialError>;
2532
+ <ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, Options extends SpawnOptions, ChildInitialError = never>(logic: Logic<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, ChildInitialError>, options: Options & ChildAddress.OptionsCompatibility<Options, ChildEvent>): SpawnResult<ChildState, ChildEvent, ChildError, ChildRequirements, ChildOutput, SpawnError<Options>, ChildInitialError>;
2533
+ };
2534
+ /**
2535
+ * Sends an event to a named child process of the running machine.
2536
+ *
2537
+ * @category runtime
2538
+ * @since 4.0.0
2539
+ */
2540
+ export declare const sendTo: {
2541
+ <Child extends ChildMachine.Any>(child: Child, event: ChildMachine.Event<Child>): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>;
2542
+ <Address extends string>(id: Address, event: ChildAddress.Event<Address>): Effect.Effect<void, StoppedError, MachineRuntimeRequirement>;
2543
+ };
2544
+ /**
2545
+ * Stops a named child process of the running machine.
2546
+ *
2547
+ * @category runtime
2548
+ * @since 4.0.0
2549
+ */
2550
+ export declare const stopChild: (child: string | ChildMachine.Any) => Effect.Effect<void, never, MachineRuntimeRequirement>;
2551
+ /**
2552
+ * Returns a stream of terminal lifecycle outcomes for a running machine.
2553
+ *
2554
+ * @category combinators
2555
+ * @since 4.0.0
2556
+ */
2557
+ export declare const watch: <State, Event, Error = never, Output = never>(ref: MachineRef<State, Event, Error, Output>) => Stream.Stream<RuntimeOutcome<State, Error, Output>>;
2558
+ /**
2559
+ * Starts a machine.
2560
+ *
2561
+ * **When to use**
2562
+ *
2563
+ * Use when you want asynchronous event delivery, lifecycle snapshots, `join`,
2564
+ * and machine-owned spawned or invoked children.
2565
+ *
2566
+ * **Details**
2567
+ *
2568
+ * For each accepted event the runtime plans the complete macrostep, runs staged
2569
+ * actions sequentially, stops invokes for exited states, publishes the new
2570
+ * state, delivers emitted events, and then starts invokes for entered states.
2571
+ * If an action fails, the previous published state is retained and emissions
2572
+ * from that plan are suppressed.
2573
+ *
2574
+ * **Gotchas**
2575
+ *
2576
+ * The returned handle's `send` operation only enqueues events. Transition
2577
+ * failures are reported through the runtime snapshot, `changes`, and `join`
2578
+ * rather than being returned by `send`. Sending after the machine reaches any
2579
+ * terminal state fails immediately with `StoppedError`.
2580
+ *
2581
+ * @see {@link plan} for inspecting the same transition plan without executing it.
2582
+ * @see {@link watch} for classified terminal outcomes.
2583
+ * @category constructors
2584
+ * @since 4.0.0
2585
+ */
2586
+ 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>(machine: Machine<States, Events, Input, UnhandledStates, E, R, InitialE, InitialR, FinalStates, Output, Emits>, ...args: [...Machine.InputArgs<Input>]) => Effect.Effect<MachineRef<Machine.Snapshot<States>, Machine.EventOf<Events>, E | InitialE | ActionError<R | InitialR> | InfiniteTransitionError | MachineSchemaDecodeError | StartupError | StoppedError, Output | undefined>, InitialE | ActionError<InitialR | R> | MachineSchemaDecodeError | StartupError | StoppedError, ExcludeCompatibleRuntime<ExecutionServices<InitialR | R>, Machine.EventOf<Events>, Machine.EmitOf<Emits>>>;
2587
+ //# sourceMappingURL=Machine.d.ts.map