effect-machine 0.17.1 → 0.19.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 (86) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +97 -54
  3. package/dist/actor.d.ts +8 -45
  4. package/dist/actor.js +157 -231
  5. package/dist/atom.d.ts +31 -0
  6. package/dist/atom.js +29 -0
  7. package/dist/cluster/adapters/in-memory.d.ts +0 -1
  8. package/dist/cluster/adapters/in-memory.js +10 -5
  9. package/dist/cluster/entity-actor-ref.d.ts +2 -3
  10. package/dist/cluster/entity-actor-ref.js +14 -17
  11. package/dist/cluster/entity-machine.d.ts +2 -8
  12. package/dist/cluster/entity-machine.js +57 -34
  13. package/dist/cluster/index.js +1 -1
  14. package/dist/cluster/persistence.d.ts +0 -1
  15. package/dist/cluster/to-entity.d.ts +19 -21
  16. package/dist/cluster/to-entity.js +18 -19
  17. package/dist/errors.d.ts +11 -37
  18. package/dist/errors.js +12 -30
  19. package/dist/index.d.ts +4 -5
  20. package/dist/index.js +4 -5
  21. package/dist/inspection.d.ts +0 -1
  22. package/dist/inspection.js +24 -13
  23. package/dist/internal/brands.d.ts +0 -1
  24. package/dist/internal/event-advancement.d.ts +50 -0
  25. package/dist/internal/event-advancement.js +79 -0
  26. package/dist/internal/inspection.d.ts +5 -9
  27. package/dist/internal/inspection.js +31 -10
  28. package/dist/internal/machine-definition.d.ts +16 -0
  29. package/dist/internal/runtime.d.ts +1 -161
  30. package/dist/internal/runtime.js +191 -150
  31. package/dist/internal/transition.d.ts +4 -135
  32. package/dist/internal/transition.js +82 -157
  33. package/dist/internal/utils.d.ts +3 -40
  34. package/dist/internal/utils.js +2 -2
  35. package/dist/machine.d.ts +47 -137
  36. package/dist/machine.js +147 -215
  37. package/dist/schema.d.ts +42 -21
  38. package/dist/schema.js +28 -18
  39. package/dist/supervision.d.ts +1 -24
  40. package/dist/supervision.js +2 -3
  41. package/dist/testing.d.ts +15 -29
  42. package/dist/testing.js +76 -95
  43. package/package.json +41 -35
  44. package/dist/slot.d.ts +0 -159
  45. package/dist/slot.js +0 -165
  46. package/v3/dist/_virtual/_rolldown/runtime.js +0 -13
  47. package/v3/dist/actor.d.ts +0 -250
  48. package/v3/dist/actor.js +0 -577
  49. package/v3/dist/cluster/adapters/in-memory.d.ts +0 -15
  50. package/v3/dist/cluster/adapters/in-memory.js +0 -62
  51. package/v3/dist/cluster/entity-actor-ref.d.ts +0 -49
  52. package/v3/dist/cluster/entity-actor-ref.js +0 -19
  53. package/v3/dist/cluster/entity-machine.d.ts +0 -74
  54. package/v3/dist/cluster/entity-machine.js +0 -166
  55. package/v3/dist/cluster/index.d.ts +0 -6
  56. package/v3/dist/cluster/index.js +0 -6
  57. package/v3/dist/cluster/persistence.d.ts +0 -48
  58. package/v3/dist/cluster/persistence.js +0 -14
  59. package/v3/dist/cluster/to-entity.d.ts +0 -69
  60. package/v3/dist/cluster/to-entity.js +0 -59
  61. package/v3/dist/errors.d.ts +0 -95
  62. package/v3/dist/errors.js +0 -54
  63. package/v3/dist/index.d.ts +0 -11
  64. package/v3/dist/index.js +0 -9
  65. package/v3/dist/inspection.d.ts +0 -151
  66. package/v3/dist/inspection.js +0 -128
  67. package/v3/dist/internal/brands.d.ts +0 -50
  68. package/v3/dist/internal/inspection.d.ts +0 -11
  69. package/v3/dist/internal/inspection.js +0 -20
  70. package/v3/dist/internal/runtime.d.ts +0 -161
  71. package/v3/dist/internal/runtime.js +0 -360
  72. package/v3/dist/internal/transition.d.ts +0 -190
  73. package/v3/dist/internal/transition.js +0 -278
  74. package/v3/dist/internal/utils.d.ts +0 -101
  75. package/v3/dist/internal/utils.js +0 -75
  76. package/v3/dist/machine.d.ts +0 -398
  77. package/v3/dist/machine.js +0 -487
  78. package/v3/dist/schema.d.ts +0 -174
  79. package/v3/dist/schema.js +0 -206
  80. package/v3/dist/slot.d.ts +0 -158
  81. package/v3/dist/slot.js +0 -165
  82. package/v3/dist/supervision.d.ts +0 -97
  83. package/v3/dist/supervision.js +0 -42
  84. package/v3/dist/testing.d.ts +0 -151
  85. package/v3/dist/testing.js +0 -189
  86. /package/{v3/dist/internal/brands.js → dist/internal/machine-definition.js} +0 -0
@@ -11,53 +11,35 @@ import { Cause, Effect, Exit, Scope } from "effect";
11
11
  *
12
12
  * @internal
13
13
  */
14
- /**
15
- * Run a transition handler and return the new state.
16
- * Shared logic for executing handlers with proper context.
17
- *
18
- * Used by:
19
- * - executeTransition (actor event loop, testing)
20
- * - Machine.replay (event sourcing restore)
21
- *
22
- * @internal
23
- */
24
- const runTransitionHandler = Effect.fn("effect-machine.runTransitionHandler")(function* (machine, transition, state, event, self, system, actorId) {
25
- const ctx = {
26
- actorId,
27
- state,
28
- event,
29
- self,
30
- system
31
- };
32
- const handlerCtx = {
33
- state,
34
- event,
35
- slots: machine._slots
36
- };
37
- const raw = transition.handler(handlerCtx);
38
- const resolved = isEffect(raw) ? yield* raw.pipe(Effect.provideService(machine.Context, ctx)) : raw;
14
+ const completeTransition = (transition, resolved) => {
39
15
  if (isReplyResult(resolved)) return {
40
16
  newState: resolved.state,
17
+ transitioned: true,
18
+ reenter: transition.reenter === true,
41
19
  hasReply: true,
42
20
  deferReply: false,
43
21
  reply: resolved.reply
44
22
  };
45
23
  if (isDeferReplyResult(resolved)) return {
46
24
  newState: resolved.state,
25
+ transitioned: true,
26
+ reenter: transition.reenter === true,
47
27
  hasReply: false,
48
28
  deferReply: true,
49
29
  reply: void 0
50
30
  };
51
31
  return {
52
32
  newState: resolved,
33
+ transitioned: true,
34
+ reenter: transition.reenter === true,
53
35
  hasReply: false,
54
36
  deferReply: false,
55
37
  reply: void 0
56
38
  };
57
- });
39
+ };
58
40
  /**
59
41
  * Execute a transition for a given state and event.
60
- * Handles transition resolution, handler invocation, and guard/effect slot creation.
42
+ * Handles transition resolution and handler invocation.
61
43
  *
62
44
  * Used by:
63
45
  * - processEvent in actor.ts (actual actor event loop)
@@ -66,7 +48,18 @@ const runTransitionHandler = Effect.fn("effect-machine.runTransitionHandler")(fu
66
48
  *
67
49
  * @internal
68
50
  */
69
- const executeTransition = Effect.fn("effect-machine.executeTransition")(function* (machine, currentState, event, self, system, actorId) {
51
+ const executeTransition = (machine, currentState, event) => Effect.suspend(() => {
52
+ const result = executeTransitionImmediate(machine, currentState, event);
53
+ if (isEffect(result)) return result;
54
+ return Effect.succeed(result);
55
+ });
56
+ /**
57
+ * Execute a transition without adding an Effect boundary for a synchronous handler.
58
+ * A throwing handler becomes a defect Effect.
59
+ *
60
+ * @internal
61
+ */
62
+ const executeTransitionImmediate = (machine, currentState, event) => {
70
63
  const transition = resolveTransition(machine, currentState, event);
71
64
  if (transition === void 0) return {
72
65
  newState: currentState,
@@ -76,24 +69,24 @@ const executeTransition = Effect.fn("effect-machine.executeTransition")(function
76
69
  deferReply: false,
77
70
  reply: void 0
78
71
  };
79
- const { newState, hasReply, deferReply, reply } = yield* runTransitionHandler(machine, transition, currentState, event, self, system, actorId);
80
- return {
81
- newState,
82
- transitioned: true,
83
- reenter: transition.reenter === true,
84
- hasReply,
85
- deferReply,
86
- reply
72
+ const handlerCtx = {
73
+ state: currentState,
74
+ event
87
75
  };
88
- });
76
+ let raw;
77
+ try {
78
+ raw = transition.handler(handlerCtx);
79
+ } catch (defect) {
80
+ return Effect.die(defect);
81
+ }
82
+ if (isEffect(raw)) return raw.pipe(Effect.map((resolved) => completeTransition(transition, resolved)));
83
+ return completeTransition(transition, raw);
84
+ };
89
85
  /**
90
86
  * Check if an event should be postponed in the current state.
91
87
  * @internal
92
88
  */
93
- const shouldPostpone = (machine, stateTag, eventTag) => {
94
- for (const rule of machine.postponeRules) if (rule.stateTag === stateTag && rule.eventTag === eventTag) return true;
95
- return false;
96
- };
89
+ const shouldPostpone = (machine, stateTag, eventTag) => machine._shouldPostpone(stateTag, eventTag);
97
90
  /**
98
91
  * Process a single event through the machine.
99
92
  *
@@ -106,18 +99,12 @@ const shouldPostpone = (machine, stateTag, eventTag) => {
106
99
  *
107
100
  * @internal
108
101
  */
109
- const processEventCore = Effect.fn("effect-machine.processEventCore")(function* (machine, currentState, event, self, stateScopeRef, system, actorId, hooks) {
110
- const result = yield* executeTransition(machine, currentState, event, self, system, actorId).pipe(Effect.catchCause((cause) => {
111
- if (Cause.hasInterruptsOnly(cause)) return Effect.interrupt;
112
- const onError = hooks?.onError;
113
- if (onError === void 0) return Effect.failCause(cause).pipe(Effect.orDie);
114
- return onError({
115
- phase: "transition",
116
- state: currentState,
117
- event,
118
- cause
119
- }).pipe(Effect.andThen(Effect.failCause(cause).pipe(Effect.orDie)));
120
- }));
102
+ const processEventCore = (machine, currentState, event, self, stateScopeRef, system, actorId, hooks) => Effect.suspend(() => {
103
+ const processed = processEventCoreImmediate(machine, currentState, event, self, stateScopeRef, system, actorId, hooks);
104
+ if (isEffect(processed)) return processed;
105
+ return Effect.succeed(processed);
106
+ });
107
+ const completeProcessedEvent = (machine, currentState, event, result, self, stateScopeRef, system, actorId, hooks) => {
121
108
  if (!result.transitioned) return {
122
109
  newState: currentState,
123
110
  previousState: currentState,
@@ -131,40 +118,55 @@ const processEventCore = Effect.fn("effect-machine.processEventCore")(function*
131
118
  };
132
119
  const newState = result.newState;
133
120
  const runLifecycle = newState._tag !== currentState._tag || result.reenter;
134
- if (runLifecycle) {
135
- yield* Scope.close(stateScopeRef.current, Exit.void);
136
- stateScopeRef.current = yield* Scope.make();
137
- if (hooks?.onTransition !== void 0) yield* hooks.onTransition(currentState, newState, event);
138
- if (hooks?.onSpawnEffect !== void 0) yield* hooks.onSpawnEffect(newState);
139
- yield* runSpawnEffects(machine, newState, { _tag: INTERNAL_ENTER_EVENT }, self, stateScopeRef.current, system, actorId, hooks?.onError, hooks?.onSpawnDefect);
140
- }
141
- return {
121
+ const processed = {
142
122
  newState,
143
123
  previousState: currentState,
144
124
  transitioned: true,
145
125
  lifecycleRan: runLifecycle,
146
- isFinal: machine.finalStates.has(newState._tag),
126
+ isFinal: machine._isFinal(newState._tag),
147
127
  hasReply: result.hasReply,
148
128
  deferReply: result.deferReply,
149
129
  reply: result.reply,
150
130
  postponed: false
151
131
  };
152
- });
132
+ if (!runLifecycle) return processed;
133
+ return Effect.gen(function* () {
134
+ yield* Scope.close(stateScopeRef.current, Exit.void);
135
+ stateScopeRef.current = yield* Scope.make();
136
+ if (hooks?.onTransition !== void 0) yield* hooks.onTransition(currentState, newState, event);
137
+ if (hooks?.onSpawnEffect !== void 0) yield* hooks.onSpawnEffect(newState);
138
+ yield* runSpawnEffects(machine, newState, { _tag: INTERNAL_ENTER_EVENT }, self, stateScopeRef.current, system, actorId, hooks?.onError, hooks?.onSpawnDefect);
139
+ return processed;
140
+ });
141
+ };
142
+ /** @internal */
143
+ const processEventCoreImmediate = (machine, currentState, event, self, stateScopeRef, system, actorId, hooks) => {
144
+ const execution = executeTransitionImmediate(machine, currentState, event);
145
+ const complete = (result) => completeProcessedEvent(machine, currentState, event, result, self, stateScopeRef, system, actorId, hooks);
146
+ if (!isEffect(execution)) return complete(execution);
147
+ return execution.pipe(Effect.catchCause((cause) => {
148
+ if (Cause.hasInterruptsOnly(cause)) return Effect.interrupt;
149
+ const onError = hooks?.onError;
150
+ if (onError === void 0) return Effect.failCause(cause).pipe(Effect.orDie);
151
+ return onError({
152
+ phase: "transition",
153
+ state: currentState,
154
+ event,
155
+ cause
156
+ }).pipe(Effect.andThen(Effect.failCause(cause).pipe(Effect.orDie)));
157
+ }), Effect.flatMap((result) => {
158
+ const processed = complete(result);
159
+ if (isEffect(processed)) return processed;
160
+ return Effect.succeed(processed);
161
+ }));
162
+ };
153
163
  /**
154
164
  * Run spawn effects for a state (forked into state scope, auto-cancelled on state exit).
155
165
  *
156
166
  * @internal
157
167
  */
158
168
  const runSpawnEffects = Effect.fn("effect-machine.runSpawnEffects")(function* (machine, state, event, self, stateScope, system, actorId, onError, onSpawnDefect) {
159
- const spawnEffects = findSpawnEffects(machine, state._tag);
160
- const ctx = {
161
- actorId,
162
- state,
163
- event,
164
- self,
165
- system
166
- };
167
- const slots = machine._slots;
169
+ const spawnEffects = machine._findSpawnEffects(state._tag);
168
170
  const reportError = onError;
169
171
  const defectSignal = onSpawnDefect;
170
172
  for (const spawnEffect of spawnEffects) {
@@ -173,17 +175,18 @@ const runSpawnEffects = Effect.fn("effect-machine.runSpawnEffects")(function* (m
173
175
  state,
174
176
  event,
175
177
  self,
176
- slots,
177
178
  system
178
- }).pipe(Effect.provideService(machine.Context, ctx), Effect.catchCause((cause) => {
179
+ }).pipe(Effect.catchCause((cause) => {
179
180
  if (Cause.hasInterruptsOnly(cause)) return Effect.interrupt;
180
- const report = reportError !== void 0 ? reportError({
181
+ let report = Effect.void;
182
+ if (reportError !== void 0) report = reportError({
181
183
  phase: "spawn",
182
184
  state,
183
185
  event,
184
186
  cause
185
- }) : Effect.void;
186
- const signal = defectSignal !== void 0 ? defectSignal(cause) : Effect.void;
187
+ });
188
+ let signal = Effect.void;
189
+ if (defectSignal !== void 0) signal = defectSignal(cause);
187
190
  return report.pipe(Effect.andThen(signal), Effect.andThen(Effect.failCause(cause).pipe(Effect.orDie)));
188
191
  }));
189
192
  yield* Effect.forkScoped(effect).pipe(Effect.provideService(Scope.Scope, stateScope));
@@ -194,85 +197,7 @@ const runSpawnEffects = Effect.fn("effect-machine.runSpawnEffects")(function* (m
194
197
  * Uses indexed O(1) lookup. First matching transition wins.
195
198
  */
196
199
  const resolveTransition = (machine, currentState, event) => {
197
- return findTransitions(machine, currentState._tag, event._tag)[0];
198
- };
199
- const indexCache = /* @__PURE__ */ new WeakMap();
200
- /**
201
- * Invalidate cached index for a machine (call after mutation).
202
- */
203
- const invalidateIndex = (machine) => {
204
- indexCache.delete(machine);
205
- };
206
- /**
207
- * Build transition index from machine definition.
208
- * O(n) where n = number of transitions.
209
- */
210
- const buildTransitionIndex = (transitions) => {
211
- const index = /* @__PURE__ */ new Map();
212
- for (const t of transitions) {
213
- let stateMap = index.get(t.stateTag);
214
- if (stateMap === void 0) {
215
- stateMap = /* @__PURE__ */ new Map();
216
- index.set(t.stateTag, stateMap);
217
- }
218
- let eventList = stateMap.get(t.eventTag);
219
- if (eventList === void 0) {
220
- eventList = [];
221
- stateMap.set(t.eventTag, eventList);
222
- }
223
- eventList.push(t);
224
- }
225
- return index;
226
- };
227
- /**
228
- * Build spawn index from machine definition.
229
- */
230
- const buildSpawnIndex = (effects) => {
231
- const index = /* @__PURE__ */ new Map();
232
- for (const e of effects) {
233
- let stateList = index.get(e.stateTag);
234
- if (stateList === void 0) {
235
- stateList = [];
236
- index.set(e.stateTag, stateList);
237
- }
238
- stateList.push(e);
239
- }
240
- return index;
241
- };
242
- /**
243
- * Get or build index for a machine.
244
- */
245
- const getIndex = (machine) => {
246
- let index = indexCache.get(machine);
247
- if (index === void 0) {
248
- index = {
249
- transitions: buildTransitionIndex(machine.transitions),
250
- spawn: buildSpawnIndex(machine.spawnEffects)
251
- };
252
- indexCache.set(machine, index);
253
- }
254
- return index;
255
- };
256
- /**
257
- * Find all transitions matching a state/event pair.
258
- * Returns empty array if no matches.
259
- *
260
- * O(1) lookup after first access (index is lazily built).
261
- */
262
- const findTransitions = (machine, stateTag, eventTag) => {
263
- const index = getIndex(machine);
264
- const specific = index.transitions.get(stateTag)?.get(eventTag) ?? [];
265
- if (specific.length > 0) return specific;
266
- return index.transitions.get("*")?.get(eventTag) ?? [];
267
- };
268
- /**
269
- * Find all spawn effects for a state.
270
- * Returns empty array if no matches.
271
- *
272
- * O(1) lookup after first access (index is lazily built).
273
- */
274
- const findSpawnEffects = (machine, stateTag) => {
275
- return getIndex(machine).spawn.get(stateTag) ?? [];
200
+ return machine._findTransitions(currentState._tag, event._tag)[0];
276
201
  };
277
202
  //#endregion
278
- export { executeTransition, findSpawnEffects, findTransitions, invalidateIndex, processEventCore, resolveTransition, runSpawnEffects, runTransitionHandler, shouldPostpone };
203
+ export { executeTransition, executeTransitionImmediate, processEventCore, processEventCoreImmediate, resolveTransition, runSpawnEffects, shouldPostpone };
@@ -1,28 +1,4 @@
1
- import { ActorSystemService } from "../actor.js";
2
- import { Effect } from "effect";
3
-
4
1
  //#region src/internal/utils.d.ts
5
- /**
6
- * Extracts _tag from a tagged union member
7
- */
8
- type TagOf<T> = T extends {
9
- readonly _tag: infer Tag;
10
- } ? Tag : never;
11
- /**
12
- * Extracts args type from a Data.taggedEnum constructor
13
- */
14
- type ArgsOf<C> = C extends ((args: infer A) => unknown) ? A : never;
15
- /**
16
- * Extracts return type from a Data.taggedEnum constructor
17
- * @internal
18
- */
19
- type InstanceOf<C> = C extends ((...args: unknown[]) => infer R) ? R : never;
20
- /**
21
- * A tagged union constructor (from Data.taggedEnum)
22
- */
23
- type TaggedConstructor<T extends {
24
- readonly _tag: string;
25
- }> = (args: Omit<T, "_tag">) => T;
26
2
  declare const ReplyResultSymbol: unique symbol;
27
3
  type ReplyResultSymbol = typeof ReplyResultSymbol;
28
4
  /**
@@ -68,19 +44,13 @@ declare const isDeferReplyResult: (value: unknown) => value is DeferReplyResult<
68
44
  * - When Reply is concrete: handler must return ReplyResult via Machine.reply()
69
45
  */
70
46
  type TransitionResult<State, R, Reply = never> = [Reply] extends [never] ? State | Effect.Effect<State, never, R> : ReplyResult<State, Reply> | DeferReplyResult<State> | Effect.Effect<ReplyResult<State, Reply> | DeferReplyResult<State>, never, R>;
71
- /**
72
- * Internal event tags used for lifecycle effect contexts.
73
- * Prefixed with $ to distinguish from user events.
74
- * @internal
75
- */
76
- declare const INTERNAL_INIT_EVENT: "$init";
77
47
  declare const INTERNAL_ENTER_EVENT: "$enter";
78
48
  /**
79
49
  * Extract _tag from a tagged value or constructor.
80
50
  *
81
51
  * Supports:
82
- * - Plain values with `_tag` (MachineSchema empty structs)
83
- * - Constructors with static `_tag` (MachineSchema non-empty structs)
52
+ * - Plain values with `_tag` (`State` and `Event` empty structs)
53
+ * - Constructors with static `_tag` (`State` and `Event` non-empty structs)
84
54
  * - Data.taggedEnum constructors (fallback via instantiation)
85
55
  */
86
56
  declare const getTag: (constructorOrValue: {
@@ -90,12 +60,5 @@ declare const getTag: (constructorOrValue: {
90
60
  })) => string;
91
61
  /** Check if a value is an Effect */
92
62
  declare const isEffect: (value: unknown) => value is Effect.Effect<unknown, unknown, unknown>;
93
- /**
94
- * Stub ActorSystemService that dies on any method call.
95
- * Used in contexts where spawning/system access isn't supported
96
- * (testing simulation, persistent actor replay).
97
- * @internal
98
- */
99
- declare const stubSystem: ActorSystemService;
100
63
  //#endregion
101
- export { ArgsOf, DeferReplyResult, DeferReplySymbol, INTERNAL_ENTER_EVENT, INTERNAL_INIT_EVENT, InstanceOf, ReplyResult, ReplyResultSymbol, TagOf, TaggedConstructor, TransitionResult, getTag, isDeferReplyResult, isEffect, isReplyResult, makeDeferReply, makeReply, stubSystem };
64
+ export { DeferReplyResult, DeferReplySymbol, INTERNAL_ENTER_EVENT, ReplyResult, ReplyResultSymbol, TransitionResult, getTag, isDeferReplyResult, isEffect, isReplyResult, makeDeferReply, makeReply };
@@ -41,8 +41,8 @@ const INTERNAL_ENTER_EVENT = "$enter";
41
41
  * Extract _tag from a tagged value or constructor.
42
42
  *
43
43
  * Supports:
44
- * - Plain values with `_tag` (MachineSchema empty structs)
45
- * - Constructors with static `_tag` (MachineSchema non-empty structs)
44
+ * - Plain values with `_tag` (`State` and `Event` empty structs)
45
+ * - Constructors with static `_tag` (`State` and `Event` non-empty structs)
46
46
  * - Data.taggedEnum constructors (fallback via instantiation)
47
47
  */
48
48
  const getTag = (constructorOrValue) => {