effect-machine 0.9.0 → 0.11.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 (73) hide show
  1. package/README.md +118 -55
  2. package/dist/actor.d.ts +77 -179
  3. package/dist/actor.js +161 -113
  4. package/dist/cluster/entity-machine.js +5 -3
  5. package/dist/errors.d.ts +12 -1
  6. package/dist/errors.js +8 -1
  7. package/dist/index.d.ts +4 -8
  8. package/dist/index.js +2 -7
  9. package/dist/internal/transition.d.ts +27 -3
  10. package/dist/internal/transition.js +38 -9
  11. package/dist/internal/utils.d.ts +7 -2
  12. package/dist/internal/utils.js +1 -5
  13. package/dist/machine.d.ts +94 -35
  14. package/dist/machine.js +128 -13
  15. package/dist/testing.js +57 -3
  16. package/package.json +10 -9
  17. package/v3/dist/actor.d.ts +210 -0
  18. package/{dist-v3 → v3/dist}/actor.js +198 -117
  19. package/{dist-v3 → v3/dist}/cluster/entity-machine.d.ts +1 -1
  20. package/{dist-v3 → v3/dist}/cluster/entity-machine.js +8 -6
  21. package/{dist-v3 → v3/dist}/cluster/to-entity.d.ts +1 -1
  22. package/{dist-v3 → v3/dist}/cluster/to-entity.js +1 -1
  23. package/v3/dist/errors.d.ts +76 -0
  24. package/{dist-v3 → v3/dist}/errors.js +9 -2
  25. package/v3/dist/index.d.ts +9 -0
  26. package/v3/dist/index.js +8 -0
  27. package/{dist-v3 → v3/dist}/inspection.d.ts +53 -8
  28. package/v3/dist/inspection.js +156 -0
  29. package/{dist-v3 → v3/dist}/internal/brands.d.ts +1 -1
  30. package/{dist-v3 → v3/dist}/internal/inspection.d.ts +1 -1
  31. package/v3/dist/internal/inspection.js +20 -0
  32. package/{dist-v3 → v3/dist}/internal/transition.d.ts +35 -11
  33. package/{dist-v3 → v3/dist}/internal/transition.js +47 -15
  34. package/{dist-v3 → v3/dist}/internal/utils.d.ts +9 -4
  35. package/{dist-v3 → v3/dist}/internal/utils.js +2 -6
  36. package/{dist-v3 → v3/dist}/machine.d.ts +113 -40
  37. package/{dist-v3 → v3/dist}/machine.js +191 -15
  38. package/{dist-v3 → v3/dist}/schema.d.ts +1 -1
  39. package/{dist-v3 → v3/dist}/schema.js +5 -2
  40. package/{dist-v3 → v3/dist}/slot.d.ts +4 -3
  41. package/{dist-v3 → v3/dist}/slot.js +1 -1
  42. package/{dist-v3 → v3/dist}/testing.d.ts +14 -8
  43. package/{dist-v3 → v3/dist}/testing.js +60 -6
  44. package/dist/persistence/adapter.d.ts +0 -135
  45. package/dist/persistence/adapter.js +0 -25
  46. package/dist/persistence/adapters/in-memory.d.ts +0 -32
  47. package/dist/persistence/adapters/in-memory.js +0 -174
  48. package/dist/persistence/index.d.ts +0 -5
  49. package/dist/persistence/index.js +0 -5
  50. package/dist/persistence/persistent-actor.d.ts +0 -50
  51. package/dist/persistence/persistent-actor.js +0 -368
  52. package/dist/persistence/persistent-machine.d.ts +0 -105
  53. package/dist/persistence/persistent-machine.js +0 -22
  54. package/dist-v3/actor.d.ts +0 -291
  55. package/dist-v3/errors.d.ts +0 -27
  56. package/dist-v3/index.d.ts +0 -12
  57. package/dist-v3/index.js +0 -13
  58. package/dist-v3/inspection.js +0 -48
  59. package/dist-v3/internal/inspection.js +0 -13
  60. package/dist-v3/persistence/adapter.d.ts +0 -125
  61. package/dist-v3/persistence/adapter.js +0 -25
  62. package/dist-v3/persistence/adapters/in-memory.d.ts +0 -32
  63. package/dist-v3/persistence/adapters/in-memory.js +0 -174
  64. package/dist-v3/persistence/index.d.ts +0 -5
  65. package/dist-v3/persistence/index.js +0 -5
  66. package/dist-v3/persistence/persistent-actor.d.ts +0 -49
  67. package/dist-v3/persistence/persistent-actor.js +0 -365
  68. package/dist-v3/persistence/persistent-machine.d.ts +0 -105
  69. package/dist-v3/persistence/persistent-machine.js +0 -22
  70. /package/{dist-v3 → v3/dist}/_virtual/_rolldown/runtime.js +0 -0
  71. /package/{dist-v3 → v3/dist}/cluster/index.d.ts +0 -0
  72. /package/{dist-v3 → v3/dist}/cluster/index.js +0 -0
  73. /package/{dist-v3 → v3/dist}/internal/brands.js +0 -0
@@ -1,291 +0,0 @@
1
- import { PersistentMachine } from "./persistence/persistent-machine.js";
2
- import { DuplicateActorError } from "./errors.js";
3
- import { EffectsDef, GuardsDef } from "./slot.js";
4
- import { ProcessEventError, ProcessEventHooks, ProcessEventResult, processEventCore, resolveTransition, runSpawnEffects } from "./internal/transition.js";
5
- import { PersistentActorRef } from "./persistence/persistent-actor.js";
6
- import { ActorMetadata, PersistenceAdapterTag, PersistenceError, RestoreResult, VersionConflictError } from "./persistence/adapter.js";
7
- import { BuiltMachine, Machine } from "./machine.js";
8
- import { Effect, Option, Queue, Ref, Stream, SubscriptionRef } from "effect";
9
-
10
- //#region src-v3/actor.d.ts
11
- /**
12
- * Reference to a running actor.
13
- */
14
- interface ActorRef<State extends {
15
- readonly _tag: string;
16
- }, Event> {
17
- /**
18
- * Unique identifier for this actor
19
- */
20
- readonly id: string;
21
- /**
22
- * Send an event to the actor
23
- */
24
- readonly send: (event: Event) => Effect.Effect<void>;
25
- /**
26
- * Observable state of the actor
27
- */
28
- readonly state: SubscriptionRef.SubscriptionRef<State>;
29
- /**
30
- * Stop the actor gracefully
31
- */
32
- readonly stop: Effect.Effect<void>;
33
- /**
34
- * Stop the actor (fire-and-forget).
35
- * Signals graceful shutdown without waiting for completion.
36
- * Use when stopping from sync contexts (e.g. framework cleanup hooks).
37
- */
38
- readonly stopSync: () => void;
39
- /**
40
- * Get current state snapshot (Effect)
41
- */
42
- readonly snapshot: Effect.Effect<State>;
43
- /**
44
- * Get current state snapshot (sync)
45
- */
46
- readonly snapshotSync: () => State;
47
- /**
48
- * Check if current state matches tag (Effect)
49
- */
50
- readonly matches: (tag: State["_tag"]) => Effect.Effect<boolean>;
51
- /**
52
- * Check if current state matches tag (sync)
53
- */
54
- readonly matchesSync: (tag: State["_tag"]) => boolean;
55
- /**
56
- * Check if event can be handled in current state (Effect)
57
- */
58
- readonly can: (event: Event) => Effect.Effect<boolean>;
59
- /**
60
- * Check if event can be handled in current state (sync)
61
- */
62
- readonly canSync: (event: Event) => boolean;
63
- /**
64
- * Stream of state changes
65
- */
66
- readonly changes: Stream.Stream<State>;
67
- /**
68
- * Wait for a state that matches predicate or state variant (includes current snapshot).
69
- * Accepts a predicate function or a state constructor/value (e.g. `State.Active`).
70
- */
71
- readonly waitFor: {
72
- (predicate: (state: State) => boolean): Effect.Effect<State>;
73
- (state: {
74
- readonly _tag: State["_tag"];
75
- }): Effect.Effect<State>;
76
- };
77
- /**
78
- * Wait for a final state (includes current snapshot)
79
- */
80
- readonly awaitFinal: Effect.Effect<State>;
81
- /**
82
- * Send event and wait for predicate, state variant, or final state.
83
- * Accepts a predicate function or a state constructor/value (e.g. `State.Active`).
84
- */
85
- readonly sendAndWait: {
86
- (event: Event, predicate: (state: State) => boolean): Effect.Effect<State>;
87
- (event: Event, state: {
88
- readonly _tag: State["_tag"];
89
- }): Effect.Effect<State>;
90
- (event: Event): Effect.Effect<State>;
91
- };
92
- /**
93
- * Send event synchronously (fire-and-forget).
94
- * No-op on stopped actors. Use when you need to send from sync contexts
95
- * (e.g. framework hooks, event handlers).
96
- */
97
- readonly sendSync: (event: Event) => void;
98
- /**
99
- * Subscribe to state changes (sync callback)
100
- * Returns unsubscribe function
101
- */
102
- readonly subscribe: (fn: (state: State) => void) => () => void;
103
- /**
104
- * The actor system this actor belongs to.
105
- * Every actor always has a system — either inherited from context or implicitly created.
106
- */
107
- readonly system: ActorSystem;
108
- /**
109
- * Child actors spawned via `self.spawn` in this actor's handlers.
110
- * State-scoped children are auto-removed on state exit.
111
- */
112
- readonly children: ReadonlyMap<string, ActorRef<AnyState, unknown>>;
113
- }
114
- /** Base type for stored actors (internal) */
115
- type AnyState = {
116
- readonly _tag: string;
117
- };
118
- /**
119
- * Events emitted by the ActorSystem when actors are spawned or stopped.
120
- */
121
- type SystemEvent = {
122
- readonly _tag: "ActorSpawned";
123
- readonly id: string;
124
- readonly actor: ActorRef<AnyState, unknown>;
125
- } | {
126
- readonly _tag: "ActorStopped";
127
- readonly id: string;
128
- readonly actor: ActorRef<AnyState, unknown>;
129
- };
130
- /**
131
- * Listener callback for system events.
132
- */
133
- type SystemEventListener = (event: SystemEvent) => void;
134
- /**
135
- * Actor system for managing actor lifecycles
136
- */
137
- interface ActorSystem {
138
- /**
139
- * Spawn a new actor with the given machine.
140
- *
141
- * For regular machines, returns ActorRef.
142
- * For persistent machines (created with Machine.persist), returns PersistentActorRef.
143
- *
144
- * All effect slots must be provided via `.build()` before spawning.
145
- *
146
- * @example
147
- * ```ts
148
- * // Regular machine (built)
149
- * const built = machine.build({ fetchData: ... })
150
- * const actor = yield* system.spawn("my-actor", built);
151
- *
152
- * // Persistent machine (auto-detected)
153
- * const persistentActor = yield* system.spawn("my-actor", persistentMachine);
154
- * persistentActor.persist; // available
155
- * persistentActor.version; // available
156
- * ```
157
- */
158
- readonly spawn: {
159
- <S extends {
160
- readonly _tag: string;
161
- }, E extends {
162
- readonly _tag: string;
163
- }, R>(id: string, machine: BuiltMachine<S, E, R>): Effect.Effect<ActorRef<S, E>, DuplicateActorError, R>;
164
- <S extends {
165
- readonly _tag: string;
166
- }, E extends {
167
- readonly _tag: string;
168
- }, R>(id: string, machine: PersistentMachine<S, E, R>): Effect.Effect<PersistentActorRef<S, E, R>, PersistenceError | VersionConflictError | DuplicateActorError, R | PersistenceAdapterTag>;
169
- };
170
- /**
171
- * Restore an actor from persistence.
172
- * Returns None if no persisted state exists for the given ID.
173
- *
174
- * @example
175
- * ```ts
176
- * const maybeActor = yield* system.restore("order-1", persistentMachine);
177
- * if (Option.isSome(maybeActor)) {
178
- * const actor = maybeActor.value;
179
- * const state = yield* actor.snapshot;
180
- * console.log(`Restored to state: ${state._tag}`);
181
- * }
182
- * ```
183
- */
184
- readonly restore: <S extends {
185
- readonly _tag: string;
186
- }, E extends {
187
- readonly _tag: string;
188
- }, R>(id: string, machine: PersistentMachine<S, E, R>) => Effect.Effect<Option.Option<PersistentActorRef<S, E, R>>, PersistenceError | DuplicateActorError, R | PersistenceAdapterTag>;
189
- /**
190
- * Get an existing actor by ID
191
- */
192
- readonly get: (id: string) => Effect.Effect<Option.Option<ActorRef<AnyState, unknown>>>;
193
- /**
194
- * Stop an actor by ID
195
- */
196
- readonly stop: (id: string) => Effect.Effect<boolean>;
197
- /**
198
- * Async stream of system events (actor spawned/stopped).
199
- * Each subscriber gets their own queue — late subscribers miss prior events.
200
- */
201
- readonly events: Stream.Stream<SystemEvent>;
202
- /**
203
- * Sync snapshot of all currently registered actors.
204
- * Returns a new Map on each access (not live).
205
- */
206
- readonly actors: ReadonlyMap<string, ActorRef<AnyState, unknown>>;
207
- /**
208
- * Subscribe to system events synchronously.
209
- * Returns an unsubscribe function.
210
- */
211
- readonly subscribe: (fn: SystemEventListener) => () => void;
212
- /**
213
- * List all persisted actor metadata.
214
- * Returns empty array if adapter doesn't support registry.
215
- *
216
- * @example
217
- * ```ts
218
- * const actors = yield* system.listPersisted();
219
- * for (const meta of actors) {
220
- * console.log(`${meta.id}: ${meta.stateTag} (v${meta.version})`);
221
- * }
222
- * ```
223
- */
224
- readonly listPersisted: () => Effect.Effect<ReadonlyArray<ActorMetadata>, PersistenceError, PersistenceAdapterTag>;
225
- /**
226
- * Restore multiple actors by ID.
227
- * Returns both successfully restored actors and failures.
228
- *
229
- * @example
230
- * ```ts
231
- * const result = yield* system.restoreMany(["order-1", "order-2"], orderMachine);
232
- * console.log(`Restored: ${result.restored.length}, Failed: ${result.failed.length}`);
233
- * ```
234
- */
235
- readonly restoreMany: <S extends {
236
- readonly _tag: string;
237
- }, E extends {
238
- readonly _tag: string;
239
- }, R>(ids: ReadonlyArray<string>, machine: PersistentMachine<S, E, R>) => Effect.Effect<RestoreResult<S, E, R>, never, R | PersistenceAdapterTag>;
240
- /**
241
- * Restore all persisted actors for a machine type.
242
- * Uses adapter registry if available, otherwise returns empty result.
243
- *
244
- * @example
245
- * ```ts
246
- * const result = yield* system.restoreAll(orderMachine, {
247
- * filter: (meta) => meta.stateTag !== "Done"
248
- * });
249
- * console.log(`Restored ${result.restored.length} active orders`);
250
- * ```
251
- */
252
- readonly restoreAll: <S extends {
253
- readonly _tag: string;
254
- }, E extends {
255
- readonly _tag: string;
256
- }, R>(machine: PersistentMachine<S, E, R>, options?: {
257
- filter?: (meta: ActorMetadata) => boolean;
258
- }) => Effect.Effect<RestoreResult<S, E, R>, PersistenceError, R | PersistenceAdapterTag>;
259
- }
260
- /**
261
- * ActorSystem service tag
262
- */
263
- declare const ActorSystem: any;
264
- /** Listener set for sync subscriptions */
265
- type Listeners<S> = Set<(state: S) => void>;
266
- /**
267
- * Notify all listeners of state change.
268
- */
269
- declare const notifyListeners: <S>(listeners: Listeners<S>, state: S) => void;
270
- /**
271
- * Build core ActorRef methods shared between regular and persistent actors.
272
- */
273
- declare const buildActorRefCore: <S extends {
274
- readonly _tag: string;
275
- }, E extends {
276
- readonly _tag: string;
277
- }, R, GD extends GuardsDef, EFD extends EffectsDef>(id: string, machine: Machine<S, E, R, any, any, GD, EFD>, stateRef: SubscriptionRef.SubscriptionRef<S>, eventQueue: Queue.Queue<E>, stoppedRef: Ref.Ref<boolean>, listeners: Listeners<S>, stop: Effect.Effect<void>, system: ActorSystem, childrenMap: ReadonlyMap<string, ActorRef<AnyState, unknown>>) => ActorRef<S, E>;
278
- /**
279
- * Create and start an actor for a machine
280
- */
281
- declare const createActor: <S extends {
282
- readonly _tag: string;
283
- }, E extends {
284
- readonly _tag: string;
285
- }, R, GD extends GuardsDef, EFD extends EffectsDef>(id: string, machine: Machine<S, E, R, Record<string, never>, Record<string, never>, GD, EFD>) => Effect.Effect<ActorRef<S, E>, unknown, unknown>;
286
- /**
287
- * Default ActorSystem layer
288
- */
289
- declare const Default: any;
290
- //#endregion
291
- export { ActorRef, ActorSystem, Default, Listeners, type ProcessEventError, type ProcessEventHooks, type ProcessEventResult, SystemEvent, SystemEventListener, buildActorRefCore, createActor, notifyListeners, processEventCore, resolveTransition, runSpawnEffects };
@@ -1,27 +0,0 @@
1
- //#region src-v3/errors.d.ts
2
- declare const DuplicateActorError_base: any;
3
- /** Attempted to spawn/restore actor with ID already in use */
4
- declare class DuplicateActorError extends DuplicateActorError_base {}
5
- declare const UnprovidedSlotsError_base: any;
6
- /** Machine has unprovided effect slots */
7
- declare class UnprovidedSlotsError extends UnprovidedSlotsError_base {}
8
- declare const MissingSchemaError_base: any;
9
- /** Operation requires schemas attached to machine */
10
- declare class MissingSchemaError extends MissingSchemaError_base {}
11
- declare const InvalidSchemaError_base: any;
12
- /** State/Event schema has no variants */
13
- declare class InvalidSchemaError extends InvalidSchemaError_base {}
14
- declare const MissingMatchHandlerError_base: any;
15
- /** $match called with missing handler for tag */
16
- declare class MissingMatchHandlerError extends MissingMatchHandlerError_base {}
17
- declare const SlotProvisionError_base: any;
18
- /** Slot handler not found at runtime (internal error) */
19
- declare class SlotProvisionError extends SlotProvisionError_base {}
20
- declare const ProvisionValidationError_base: any;
21
- /** Machine.build() validation failed - missing or extra handlers */
22
- declare class ProvisionValidationError extends ProvisionValidationError_base {}
23
- declare const AssertionError_base: any;
24
- /** Assertion failed in testing utilities */
25
- declare class AssertionError extends AssertionError_base {}
26
- //#endregion
27
- export { AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError };
@@ -1,12 +0,0 @@
1
- import { Event, MachineEventSchema, MachineStateSchema, State } from "./schema.js";
2
- import { PersistenceConfig, PersistentMachine, isPersistentMachine } from "./persistence/persistent-machine.js";
3
- import { AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError } from "./errors.js";
4
- import { EffectHandlers, EffectSlot, EffectSlots, EffectsDef, EffectsSchema, GuardHandlers, GuardSlot, GuardSlots, GuardsDef, GuardsSchema, MachineContext, Slot } from "./slot.js";
5
- import { PersistentActorRef, createPersistentActor, restorePersistentActor } from "./persistence/persistent-actor.js";
6
- import { ActorMetadata, PersistedEvent, PersistenceAdapter, PersistenceAdapterTag, PersistenceError, RestoreFailure, RestoreResult, Snapshot, VersionConflictError } from "./persistence/adapter.js";
7
- import { InMemoryPersistenceAdapter, makeInMemoryPersistenceAdapter } from "./persistence/adapters/in-memory.js";
8
- import { BackgroundEffect, BuiltMachine, HandlerContext, Machine, MachineRef, MakeConfig, PersistOptions, ProvideHandlers, SpawnEffect, StateHandlerContext, Transition, machine_d_exports } from "./machine.js";
9
- import { ActorRef, ActorSystem, Default, SystemEvent, SystemEventListener } from "./actor.js";
10
- import { SimulationResult, TestHarness, TestHarnessOptions, assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
11
- import { AnyInspectionEvent, EffectEvent, ErrorEvent, EventReceivedEvent, InspectionEvent, Inspector, SpawnEvent, StopEvent, TransitionEvent, collectingInspector, consoleInspector, makeInspector } from "./inspection.js";
12
- export { type ActorMetadata, type ActorRef, type ActorSystem, Default as ActorSystemDefault, ActorSystem as ActorSystemService, type AnyInspectionEvent, AssertionError, type BackgroundEffect, type BuiltMachine, DuplicateActorError, type EffectEvent, type EffectSlots, type EffectsDef, type EffectsSchema, type ErrorEvent, Event, type EventReceivedEvent, type GuardHandlers, type GuardSlot, type GuardSlots, type GuardsDef, type GuardsSchema, type HandlerContext, InMemoryPersistenceAdapter, type InspectionEvent, type Inspector, Inspector as InspectorService, InvalidSchemaError, machine_d_exports as Machine, type MachineContext, type MachineEventSchema, type MachineRef, type MachineStateSchema, type Machine as MachineType, type MakeConfig, MissingMatchHandlerError, MissingSchemaError, type PersistOptions, type PersistedEvent, type PersistenceAdapter, PersistenceAdapterTag, type PersistenceConfig, PersistenceError, type PersistentActorRef, type PersistentMachine, type ProvideHandlers, ProvisionValidationError, type RestoreFailure, type RestoreResult, type SimulationResult, Slot, type EffectHandlers as SlotEffectHandlers, type EffectSlot as SlotEffectSlot, SlotProvisionError, type Snapshot, type SpawnEffect, type SpawnEvent, State, type StateHandlerContext, type StopEvent, type SystemEvent, type SystemEventListener, type TestHarness, type TestHarnessOptions, type Transition, type TransitionEvent, UnprovidedSlotsError, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, consoleInspector, createPersistentActor, createTestHarness, isPersistentMachine, makeInMemoryPersistenceAdapter, makeInspector, restorePersistentActor, simulate };
package/dist-v3/index.js DELETED
@@ -1,13 +0,0 @@
1
- import { Inspector, collectingInspector, consoleInspector, makeInspector } from "./inspection.js";
2
- import { AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, ProvisionValidationError, SlotProvisionError, UnprovidedSlotsError } from "./errors.js";
3
- import { isPersistentMachine } from "./persistence/persistent-machine.js";
4
- import { Slot } from "./slot.js";
5
- import { machine_exports } from "./machine.js";
6
- import { PersistenceAdapterTag, PersistenceError, VersionConflictError } from "./persistence/adapter.js";
7
- import { createPersistentActor, restorePersistentActor } from "./persistence/persistent-actor.js";
8
- import { ActorSystem, Default } from "./actor.js";
9
- import { Event, State } from "./schema.js";
10
- import { assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
11
- import { InMemoryPersistenceAdapter, makeInMemoryPersistenceAdapter } from "./persistence/adapters/in-memory.js";
12
- import "./persistence/index.js";
13
- export { Default as ActorSystemDefault, ActorSystem as ActorSystemService, AssertionError, DuplicateActorError, Event, InMemoryPersistenceAdapter, Inspector as InspectorService, InvalidSchemaError, machine_exports as Machine, MissingMatchHandlerError, MissingSchemaError, PersistenceAdapterTag, PersistenceError, ProvisionValidationError, Slot, SlotProvisionError, State, UnprovidedSlotsError, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, consoleInspector, createPersistentActor, createTestHarness, isPersistentMachine, makeInMemoryPersistenceAdapter, makeInspector, restorePersistentActor, simulate };
@@ -1,48 +0,0 @@
1
- import { Context } from "effect";
2
- //#region src-v3/inspection.ts
3
- /**
4
- * Inspector service tag - optional service for machine introspection
5
- * Uses `any` types to allow variance flexibility when providing the service
6
- */
7
- const Inspector = Context.GenericTag("@effect/machine/Inspector");
8
- /**
9
- * Create an inspector from a callback function.
10
- *
11
- * Type params accept either raw tagged types or Schema constructors:
12
- * - `makeInspector(cb)` — defaults to `AnyInspectionEvent`
13
- * - `makeInspector<MyState, MyEvent>(cb)` — explicit tagged types
14
- * - `makeInspector<typeof MyState, typeof MyEvent>(cb)` — schema constructors (auto-extracts `.Type`)
15
- */
16
- const makeInspector = (onInspect) => ({ onInspect });
17
- /**
18
- * Console inspector that logs events in a readable format
19
- */
20
- const consoleInspector = () => makeInspector((event) => {
21
- const prefix = `[${event.actorId}]`;
22
- switch (event.type) {
23
- case "@machine.spawn":
24
- console.log(prefix, "spawned →", event.initialState._tag);
25
- break;
26
- case "@machine.event":
27
- console.log(prefix, "received", event.event._tag, "in", event.state._tag);
28
- break;
29
- case "@machine.transition":
30
- console.log(prefix, event.fromState._tag, "→", event.toState._tag);
31
- break;
32
- case "@machine.effect":
33
- console.log(prefix, event.effectType, "effect in", event.state._tag);
34
- break;
35
- case "@machine.error":
36
- console.log(prefix, "error in", event.phase, event.state._tag, "-", event.error);
37
- break;
38
- case "@machine.stop":
39
- console.log(prefix, "stopped in", event.finalState._tag);
40
- break;
41
- }
42
- });
43
- /**
44
- * Collecting inspector that stores events in an array for testing
45
- */
46
- const collectingInspector = (events) => ({ onInspect: (event) => events.push(event) });
47
- //#endregion
48
- export { Inspector, collectingInspector, consoleInspector, makeInspector };
@@ -1,13 +0,0 @@
1
- import { Clock, Effect } from "effect";
2
- //#region src-v3/internal/inspection.ts
3
- /**
4
- * Emit an inspection event with timestamp from Clock.
5
- * @internal
6
- */
7
- const emitWithTimestamp = Effect.fn("effect-machine.emitWithTimestamp")(function* (inspector, makeEvent) {
8
- if (inspector === void 0) return;
9
- const timestamp = yield* Clock.currentTimeMillis;
10
- yield* Effect.try(() => inspector.onInspect(makeEvent(timestamp))).pipe(Effect.ignore);
11
- });
12
- //#endregion
13
- export { emitWithTimestamp };
@@ -1,125 +0,0 @@
1
- import { DuplicateActorError } from "../errors.js";
2
- import { PersistentActorRef } from "./persistent-actor.js";
3
- import { Effect, Option, Schema } from "effect";
4
-
5
- //#region src-v3/persistence/adapter.d.ts
6
- /**
7
- * Metadata for a persisted actor.
8
- * Used for discovery and filtering during bulk restore.
9
- */
10
- interface ActorMetadata {
11
- readonly id: string;
12
- /** User-provided identifier for the machine type */
13
- readonly machineType: string;
14
- readonly createdAt: number;
15
- readonly lastActivityAt: number;
16
- readonly version: number;
17
- /** Current state _tag value */
18
- readonly stateTag: string;
19
- }
20
- /**
21
- * Result of a bulk restore operation.
22
- * Contains both successfully restored actors and failures.
23
- */
24
- interface RestoreResult<S extends {
25
- readonly _tag: string;
26
- }, E extends {
27
- readonly _tag: string;
28
- }, R = never> {
29
- readonly restored: ReadonlyArray<PersistentActorRef<S, E, R>>;
30
- readonly failed: ReadonlyArray<RestoreFailure>;
31
- }
32
- /**
33
- * A single restore failure with actor ID and error details.
34
- */
35
- interface RestoreFailure {
36
- readonly id: string;
37
- readonly error: PersistenceError | DuplicateActorError;
38
- }
39
- /**
40
- * Snapshot of actor state at a point in time
41
- */
42
- interface Snapshot<S> {
43
- readonly state: S;
44
- readonly version: number;
45
- readonly timestamp: number;
46
- }
47
- /**
48
- * Persisted event with metadata
49
- */
50
- interface PersistedEvent<E> {
51
- readonly event: E;
52
- readonly version: number;
53
- readonly timestamp: number;
54
- }
55
- /**
56
- * Adapter for persisting actor state and events.
57
- *
58
- * Implementations handle serialization and storage of snapshots and event journals.
59
- * Schema parameters ensure type-safe serialization/deserialization.
60
- * Schemas must have no context requirements (use Schema<S, SI, never>).
61
- */
62
- interface PersistenceAdapter {
63
- /**
64
- * Save a snapshot of actor state.
65
- * Implementations should use optimistic locking — fail if version mismatch.
66
- */
67
- readonly saveSnapshot: <S, SI>(id: string, snapshot: Snapshot<S>, schema: Schema.Schema<S, SI, never>) => Effect.Effect<void, PersistenceError | VersionConflictError>;
68
- /**
69
- * Load the latest snapshot for an actor.
70
- * Returns None if no snapshot exists.
71
- */
72
- readonly loadSnapshot: <S, SI>(id: string, schema: Schema.Schema<S, SI, never>) => Effect.Effect<Option.Option<Snapshot<S>>, PersistenceError>;
73
- /**
74
- * Append an event to the actor's event journal.
75
- */
76
- readonly appendEvent: <E, EI>(id: string, event: PersistedEvent<E>, schema: Schema.Schema<E, EI, never>) => Effect.Effect<void, PersistenceError>;
77
- /**
78
- * Load events from the journal, optionally after a specific version.
79
- */
80
- readonly loadEvents: <E, EI>(id: string, schema: Schema.Schema<E, EI, never>, afterVersion?: number) => Effect.Effect<ReadonlyArray<PersistedEvent<E>>, PersistenceError>;
81
- /**
82
- * Delete all persisted data for an actor (snapshot + events).
83
- */
84
- readonly deleteActor: (id: string) => Effect.Effect<void, PersistenceError>;
85
- /**
86
- * List all persisted actor metadata.
87
- * Optional — adapters without registry support can omit this.
88
- */
89
- readonly listActors?: () => Effect.Effect<ReadonlyArray<ActorMetadata>, PersistenceError>;
90
- /**
91
- * Save or update actor metadata.
92
- * Called on spawn and state transitions.
93
- * Optional — adapters without registry support can omit this.
94
- */
95
- readonly saveMetadata?: (metadata: ActorMetadata) => Effect.Effect<void, PersistenceError>;
96
- /**
97
- * Delete actor metadata.
98
- * Called when actor is deleted.
99
- * Optional — adapters without registry support can omit this.
100
- */
101
- readonly deleteMetadata?: (id: string) => Effect.Effect<void, PersistenceError>;
102
- /**
103
- * Load metadata for a specific actor by ID.
104
- * Returns None if no metadata exists.
105
- * Optional — adapters without registry support can omit this.
106
- */
107
- readonly loadMetadata?: (id: string) => Effect.Effect<Option.Option<ActorMetadata>, PersistenceError>;
108
- }
109
- declare const PersistenceError_base: any;
110
- /**
111
- * Error type for persistence operations
112
- */
113
- declare class PersistenceError extends PersistenceError_base {}
114
- declare const VersionConflictError_base: any;
115
- /**
116
- * Version conflict error — snapshot version doesn't match expected
117
- */
118
- declare class VersionConflictError extends VersionConflictError_base {}
119
- declare const PersistenceAdapterTag_base: any;
120
- /**
121
- * PersistenceAdapter service tag
122
- */
123
- declare class PersistenceAdapterTag extends PersistenceAdapterTag_base {}
124
- //#endregion
125
- export { ActorMetadata, PersistedEvent, PersistenceAdapter, PersistenceAdapterTag, PersistenceError, RestoreFailure, RestoreResult, Snapshot, VersionConflictError };
@@ -1,25 +0,0 @@
1
- import { Context, Schema } from "effect";
2
- //#region src-v3/persistence/adapter.ts
3
- /**
4
- * Error type for persistence operations
5
- */
6
- var PersistenceError = class extends Schema.TaggedError()("PersistenceError", {
7
- operation: Schema.String,
8
- actorId: Schema.String,
9
- cause: Schema.optional(Schema.Unknown),
10
- message: Schema.optional(Schema.String)
11
- }) {};
12
- /**
13
- * Version conflict error — snapshot version doesn't match expected
14
- */
15
- var VersionConflictError = class extends Schema.TaggedError()("VersionConflictError", {
16
- actorId: Schema.String,
17
- expectedVersion: Schema.Number,
18
- actualVersion: Schema.Number
19
- }) {};
20
- /**
21
- * PersistenceAdapter service tag
22
- */
23
- var PersistenceAdapterTag = class extends Context.Tag("effect-machine/src/persistence/adapter/PersistenceAdapterTag")() {};
24
- //#endregion
25
- export { PersistenceAdapterTag, PersistenceError, VersionConflictError };
@@ -1,32 +0,0 @@
1
- import { PersistenceAdapter, PersistenceAdapterTag } from "../adapter.js";
2
- import { Effect, Layer } from "effect";
3
-
4
- //#region src-v3/persistence/adapters/in-memory.d.ts
5
- /**
6
- * Create an in-memory persistence adapter effect.
7
- * Returns the adapter directly for custom layer composition.
8
- */
9
- declare const makeInMemoryPersistenceAdapter: Effect.Effect<PersistenceAdapter, never, never>;
10
- /**
11
- * In-memory persistence adapter layer.
12
- * Data is not persisted across process restarts.
13
- *
14
- * NOTE: Each `Effect.provide(InMemoryPersistenceAdapter)` creates a NEW adapter
15
- * with empty storage. For tests that need persistent storage across multiple
16
- * runPromise calls, use `makeInMemoryPersistenceAdapter` with a shared scope.
17
- *
18
- * @example
19
- * ```ts
20
- * const program = Effect.gen(function* () {
21
- * const system = yield* ActorSystemService;
22
- * const actor = yield* system.spawn("my-actor", persistentMachine);
23
- * // ...
24
- * }).pipe(
25
- * Effect.provide(InMemoryPersistenceAdapter),
26
- * Effect.provide(ActorSystemDefault),
27
- * );
28
- * ```
29
- */
30
- declare const InMemoryPersistenceAdapter: Layer.Layer<PersistenceAdapterTag>;
31
- //#endregion
32
- export { InMemoryPersistenceAdapter, makeInMemoryPersistenceAdapter };