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
@@ -1,19 +0,0 @@
1
- //#region src/cluster/entity-actor-ref.ts
2
- /**
3
- * Create an EntityActorRef from a test client factory and entity ID.
4
- *
5
- * @example
6
- * ```ts
7
- * const makeClient = yield* Entity.makeTestClient(entity, entityLayer)
8
- * const ref = yield* makeEntityActorRef(makeClient, "order-123")
9
- * yield* ref.send(OrderEvent.Process)
10
- * ```
11
- */
12
- const makeEntityActorRef = (client, entityId) => ({
13
- entityId,
14
- send: (event) => client.Send({ event }),
15
- ask: ((event) => client.Ask({ event })),
16
- snapshot: client.GetState()
17
- });
18
- //#endregion
19
- export { makeEntityActorRef };
@@ -1,74 +0,0 @@
1
- import { ProcessEventHooks } from "../internal/transition.js";
2
- import { Machine } from "../machine.js";
3
- import { EntityPersistenceConfig } from "./persistence.js";
4
- import { Duration, Layer, Schedule } from "effect";
5
- import { Entity } from "@effect/cluster";
6
- import { Rpc } from "@effect/rpc";
7
-
8
- //#region src/cluster/entity-machine.d.ts
9
- /**
10
- * Options for EntityMachine.layer
11
- */
12
- interface EntityMachineOptions<S, E> {
13
- /**
14
- * Initialize state from entity ID.
15
- * Called once when entity is first activated.
16
- */
17
- readonly initializeState?: (entityId: string) => S;
18
- /**
19
- * Optional hooks for inspection/tracing.
20
- */
21
- readonly hooks?: ProcessEventHooks<S, E>;
22
- /**
23
- * Maximum idle time before entity deactivation.
24
- * Forwarded to Entity.toLayer.
25
- */
26
- readonly maxIdleTime?: Duration.DurationInput;
27
- /**
28
- * Concurrency for handler execution.
29
- * Forwarded to Entity.toLayer.
30
- */
31
- readonly concurrency?: number | "unbounded";
32
- /**
33
- * Mailbox capacity. Default: "unbounded".
34
- * Forwarded to Entity.toLayer.
35
- */
36
- readonly mailboxCapacity?: number | "unbounded";
37
- /**
38
- * Disable fatal defects (defects won't crash the entity activation).
39
- * Forwarded to Entity.toLayer.
40
- */
41
- readonly disableFatalDefects?: boolean;
42
- /**
43
- * Retry policy for defects (schedule for restarting after defect).
44
- * Forwarded to Entity.toLayer.
45
- */
46
- readonly defectRetryPolicy?: Schedule.Schedule<any>;
47
- /**
48
- * Persistence configuration. When set, requires PersistenceAdapter in R.
49
- */
50
- readonly persistence?: EntityPersistenceConfig;
51
- }
52
- /**
53
- * Create an Entity layer that wires a machine to handle RPC calls.
54
- *
55
- * v3: Uses `Entity.toLayer` with handler objects backed by the runtime kernel.
56
- *
57
- * @example
58
- * ```ts
59
- * const OrderEntity = toEntity(orderMachine, { type: "Order" })
60
- *
61
- * const OrderEntityLayer = EntityMachine.layer(OrderEntity, orderMachine, {
62
- * initializeState: (entityId) => OrderState.Pending({ orderId: entityId }),
63
- * })
64
- * ```
65
- */
66
- declare const EntityMachine: {
67
- layer: <S extends {
68
- readonly _tag: string;
69
- }, E extends {
70
- readonly _tag: string;
71
- }, R, EntityType extends string, Rpcs extends Rpc.Any>(entity: Entity.Entity<EntityType, Rpcs>, machine: Machine<S, E, R, any, any, any>, options?: EntityMachineOptions<S, E>) => Layer.Layer<never, never, R>;
72
- };
73
- //#endregion
74
- export { EntityMachine, EntityMachineOptions };
@@ -1,166 +0,0 @@
1
- import { stubSystem } from "../internal/utils.js";
2
- import { replay } from "../machine.js";
3
- import { createRuntime } from "../internal/runtime.js";
4
- import { ActorSystem } from "../actor.js";
5
- import { PersistenceAdapter } from "./persistence.js";
6
- import { Clock, Effect, Option, Ref } from "effect";
7
- import { Entity } from "@effect/cluster";
8
- //#region src/cluster/entity-machine.ts
9
- /**
10
- * EntityMachine adapter - wires a machine to a cluster Entity layer.
11
- *
12
- * Uses the runtime kernel for a single serialized event loop per entity.
13
- * All events (external RPCs + internal self.send) go through the
14
- * runtime kernel's single queue — no split-mailbox race.
15
- *
16
- * v3 uses `entity.toLayer` with handler objects (no `toLayerQueue`/`toLayerMailbox`).
17
- * Supports opt-in persistence (snapshot or journal strategy).
18
- *
19
- * @module
20
- */
21
- /**
22
- * Create an Entity layer that wires a machine to handle RPC calls.
23
- *
24
- * v3: Uses `Entity.toLayer` with handler objects backed by the runtime kernel.
25
- *
26
- * @example
27
- * ```ts
28
- * const OrderEntity = toEntity(orderMachine, { type: "Order" })
29
- *
30
- * const OrderEntityLayer = EntityMachine.layer(OrderEntity, orderMachine, {
31
- * initializeState: (entityId) => OrderState.Pending({ orderId: entityId }),
32
- * })
33
- * ```
34
- */
35
- const EntityMachine = { layer: (entity, machine, options) => {
36
- const persistence = options?.persistence;
37
- const build = Effect.gen(function* () {
38
- const entityId = yield* Effect.serviceOption(Entity.CurrentAddress).pipe(Effect.map((opt) => opt._tag === "Some" ? opt.value.entityId : ""));
39
- const existingSystem = yield* Effect.serviceOption(ActorSystem);
40
- const system = Option.isSome(existingSystem) ? existingSystem.value : stubSystem;
41
- const persistCtx = yield* hydratePersistence(persistence, entity, entityId, machine, options?.initializeState);
42
- const initialState = persistCtx.hydratedState ?? (options?.initializeState !== void 0 ? options.initializeState(entityId) : void 0);
43
- const machineWithState = initialState !== void 0 ? Object.create(machine, { initial: {
44
- value: initialState,
45
- enumerable: true
46
- } }) : machine;
47
- const versionRef = yield* Ref.make(persistCtx.initialVersion);
48
- const runtime = yield* createRuntime(machineWithState, system, {
49
- actorId: entityId,
50
- hooks: options?.hooks,
51
- childIdPrefix: `${entityId}/`
52
- });
53
- yield* runtime.start;
54
- if (persistCtx.adapter !== void 0) {
55
- const { adapter: pAdapter, key } = persistCtx;
56
- yield* Effect.addFinalizer(() => Effect.gen(function* () {
57
- const state = yield* runtime.getState;
58
- const version = yield* Ref.get(versionRef);
59
- const now = yield* Clock.currentTimeMillis;
60
- yield* pAdapter.saveSnapshot(key, {
61
- state,
62
- version,
63
- timestamp: now
64
- });
65
- }).pipe(Effect.catchAll(() => Effect.void)));
66
- }
67
- const hasPersistence = persistCtx.adapter !== void 0;
68
- const journalCtx = hasPersistence && (persistence?.strategy ?? "snapshot") === "journal" ? {
69
- adapter: persistCtx.adapter,
70
- key: persistCtx.key
71
- } : void 0;
72
- return entity.of({
73
- Send: (envelope) => Effect.gen(function* () {
74
- yield* runtime.sendWait(envelope.payload.event);
75
- if (journalCtx !== void 0) yield* persistEvent(journalCtx.adapter, journalCtx.key, versionRef, envelope.payload.event);
76
- else if (hasPersistence) yield* Ref.update(versionRef, (v) => v + 1);
77
- return yield* runtime.getState;
78
- }),
79
- Ask: (envelope) => Effect.gen(function* () {
80
- const reply = yield* runtime.ask(envelope.payload.event);
81
- if (journalCtx !== void 0) yield* persistEvent(journalCtx.adapter, journalCtx.key, versionRef, envelope.payload.event);
82
- else if (hasPersistence) yield* Ref.update(versionRef, (v) => v + 1);
83
- return reply;
84
- }),
85
- GetState: () => runtime.getState
86
- });
87
- });
88
- const clusterOptions = {};
89
- if (options?.maxIdleTime !== void 0) clusterOptions.maxIdleTime = options.maxIdleTime;
90
- if (options?.concurrency !== void 0) clusterOptions.concurrency = options.concurrency;
91
- if (options?.mailboxCapacity !== void 0) clusterOptions.mailboxCapacity = options.mailboxCapacity;
92
- if (options?.disableFatalDefects !== void 0) clusterOptions.disableFatalDefects = options.disableFatalDefects;
93
- if (options?.defectRetryPolicy !== void 0) clusterOptions.defectRetryPolicy = options.defectRetryPolicy;
94
- return entity.toLayer(build.pipe(Effect.orDie), Object.keys(clusterOptions).length > 0 ? clusterOptions : void 0);
95
- } };
96
- const noPersistence = {
97
- adapter: void 0,
98
- key: void 0,
99
- hydratedState: void 0,
100
- initialVersion: 0
101
- };
102
- /** Load snapshot/journal and compute hydrated state. */
103
- const hydratePersistence = (persistence, entityDef, entityId, machine, initializeState) => Effect.gen(function* () {
104
- if (persistence === void 0) return noPersistence;
105
- const adapter = yield* PersistenceAdapter;
106
- const key = {
107
- entityType: persistence.machineType ?? entityDef.type,
108
- entityId
109
- };
110
- const maybeSnapshot = yield* adapter.loadSnapshot(key);
111
- if ((persistence.strategy ?? "snapshot") === "journal") {
112
- const baseState = Option.isSome(maybeSnapshot) ? maybeSnapshot.value.state : initializeState !== void 0 ? initializeState(entityId) : machine.initial;
113
- const snapshotVersion = Option.isSome(maybeSnapshot) ? maybeSnapshot.value.version : 0;
114
- const events = yield* adapter.loadEvents(key, snapshotVersion);
115
- if (events.length > 0) {
116
- const hydratedState = yield* replay(machine, events.map((e) => e.event), { from: baseState });
117
- const lastEvent = events[events.length - 1];
118
- return {
119
- adapter,
120
- key,
121
- hydratedState,
122
- initialVersion: lastEvent !== void 0 ? lastEvent.version : snapshotVersion
123
- };
124
- }
125
- return {
126
- adapter,
127
- key,
128
- hydratedState: Option.isSome(maybeSnapshot) ? maybeSnapshot.value.state : void 0,
129
- initialVersion: snapshotVersion
130
- };
131
- }
132
- if (Option.isSome(maybeSnapshot)) return {
133
- adapter,
134
- key,
135
- hydratedState: maybeSnapshot.value.state,
136
- initialVersion: maybeSnapshot.value.version
137
- };
138
- return {
139
- adapter,
140
- key,
141
- hydratedState: void 0,
142
- initialVersion: 0
143
- };
144
- });
145
- /**
146
- * Append a single event to the journal, incrementing version.
147
- *
148
- * On failure: defects the entity activation. The cluster's defectRetryPolicy
149
- * restarts the entity from the last consistent snapshot.
150
- */
151
- const persistEvent = (adapter, key, versionRef, event) => Effect.gen(function* () {
152
- const expectedVersion = yield* Ref.get(versionRef);
153
- const newVersion = expectedVersion + 1;
154
- const persisted = {
155
- event,
156
- version: newVersion,
157
- timestamp: yield* Clock.currentTimeMillis
158
- };
159
- yield* adapter.appendEvents(key, [persisted], expectedVersion);
160
- yield* Ref.set(versionRef, newVersion);
161
- }).pipe(Effect.tapError((error) => Effect.logWarning("Journal append failed, defecting entity", {
162
- key,
163
- error
164
- })), Effect.orDie);
165
- //#endregion
166
- export { EntityMachine };
@@ -1,6 +0,0 @@
1
- import { EntityPersistenceConfig, PersistedEvent, PersistenceAdapter, PersistenceKey, Snapshot } from "./persistence.js";
2
- import { makeInMemoryPersistenceAdapter } from "./adapters/in-memory.js";
3
- import { EntityActorRef, makeEntityActorRef } from "./entity-actor-ref.js";
4
- import { EntityMachine, EntityMachineOptions } from "./entity-machine.js";
5
- import { EntityRpcs, ToEntityOptions, toEntity } from "./to-entity.js";
6
- export { type EntityActorRef, EntityMachine, type EntityMachineOptions, type EntityPersistenceConfig, type EntityRpcs, type PersistedEvent, PersistenceAdapter, type PersistenceAdapter as PersistenceAdapterInterface, type PersistenceKey, type Snapshot, type ToEntityOptions, makeEntityActorRef, makeInMemoryPersistenceAdapter, toEntity };
@@ -1,6 +0,0 @@
1
- import { PersistenceAdapter } from "./persistence.js";
2
- import { toEntity } from "./to-entity.js";
3
- import { EntityMachine } from "./entity-machine.js";
4
- import { makeEntityActorRef } from "./entity-actor-ref.js";
5
- import { makeInMemoryPersistenceAdapter } from "./adapters/in-memory.js";
6
- export { EntityMachine, PersistenceAdapter, makeEntityActorRef, makeInMemoryPersistenceAdapter, toEntity };
@@ -1,48 +0,0 @@
1
- import { PersistenceError, VersionConflictError } from "../errors.js";
2
- import { Context, Effect, Option, Schedule } from "effect";
3
-
4
- //#region src/cluster/persistence.d.ts
5
- /** Namespaced key preventing cross-type collisions (e.g. Order/123 vs User/123). */
6
- interface PersistenceKey {
7
- readonly entityType: string;
8
- readonly entityId: string;
9
- }
10
- /** Stored state snapshot with version and timestamp. */
11
- interface Snapshot<S> {
12
- readonly state: S;
13
- readonly version: number;
14
- readonly timestamp: number;
15
- }
16
- /** Stored event with version and timestamp. */
17
- interface PersistedEvent<E> {
18
- readonly event: E;
19
- readonly version: number;
20
- readonly timestamp: number;
21
- }
22
- /** Persistence configuration for EntityMachineOptions. */
23
- interface EntityPersistenceConfig {
24
- /** Persistence strategy. Default: "snapshot". */
25
- readonly strategy?: "snapshot" | "journal";
26
- /**
27
- * Schedule controlling snapshot frequency.
28
- * Default: save on every state change.
29
- */
30
- readonly snapshotSchedule?: Schedule.Schedule<any, any>;
31
- /** Override entityType in the persistence key (defaults to Entity.type). */
32
- readonly machineType?: string;
33
- }
34
- /** Storage backend for entity state persistence. */
35
- interface PersistenceAdapter {
36
- /** Save a state snapshot. Fails with VersionConflictError if version is stale. */
37
- readonly saveSnapshot: (key: PersistenceKey, snapshot: Snapshot<unknown>) => Effect.Effect<void, PersistenceError | VersionConflictError>;
38
- /** Load the latest snapshot, or None if no snapshot exists. */
39
- readonly loadSnapshot: (key: PersistenceKey) => Effect.Effect<Option.Option<Snapshot<unknown>>, PersistenceError>;
40
- /** Append events to the journal. Fails with VersionConflictError if expectedVersion doesn't match. */
41
- readonly appendEvents: (key: PersistenceKey, events: ReadonlyArray<PersistedEvent<unknown>>, expectedVersion: number) => Effect.Effect<void, PersistenceError | VersionConflictError>;
42
- /** Load events from the journal, optionally after a given version. */
43
- readonly loadEvents: (key: PersistenceKey, afterVersion?: number) => Effect.Effect<ReadonlyArray<PersistedEvent<unknown>>, PersistenceError>;
44
- }
45
- /** Service tag for PersistenceAdapter — resolve from context for shared infra. */
46
- declare const PersistenceAdapter: Context.Tag<PersistenceAdapter, PersistenceAdapter>;
47
- //#endregion
48
- export { EntityPersistenceConfig, PersistedEvent, PersistenceAdapter, PersistenceKey, Snapshot };
@@ -1,14 +0,0 @@
1
- import { Context } from "effect";
2
- //#region src/cluster/persistence.ts
3
- /**
4
- * Entity persistence types and adapter interface (v3).
5
- *
6
- * Provides snapshot and event journal persistence for entity-machine
7
- * state across deactivation/reactivation cycles.
8
- *
9
- * @module
10
- */
11
- /** Service tag for PersistenceAdapter — resolve from context for shared infra. */
12
- const PersistenceAdapter = Context.GenericTag("@effect-machine/cluster/PersistenceAdapter");
13
- //#endregion
14
- export { PersistenceAdapter };
@@ -1,69 +0,0 @@
1
- import { Machine } from "../machine.js";
2
- import { Schema } from "effect";
3
- import { Entity } from "@effect/cluster";
4
- import { Rpc } from "@effect/rpc";
5
-
6
- //#region src/cluster/to-entity.d.ts
7
- /**
8
- * Options for toEntity.
9
- */
10
- interface ToEntityOptions {
11
- /**
12
- * Entity type name (e.g., "Order", "User")
13
- */
14
- readonly type: string;
15
- }
16
- /**
17
- * Default RPC protocol for entity machines.
18
- *
19
- * - `Send` - Send event to machine (fire-and-forget), returns new state
20
- * - `Ask` - Send event and get domain reply (typed via Event.reply() schemas)
21
- * - `GetState` - Get current state
22
- */
23
- type EntityRpcs<StateSchema extends Schema.Schema.Any, EventSchema extends Schema.Schema.Any> = readonly [Rpc.Rpc<"Send", Schema.Struct<{
24
- readonly event: EventSchema;
25
- }>, StateSchema, typeof Schema.Never>, Rpc.Rpc<"Ask", Schema.Struct<{
26
- readonly event: EventSchema;
27
- }>, typeof Schema.Unknown, typeof Schema.Never>, Rpc.Rpc<"GetState", typeof Schema.Void, StateSchema, typeof Schema.Never>];
28
- /**
29
- * Generate an Entity definition from a machine.
30
- *
31
- * Creates an Entity with a standard RPC protocol:
32
- * - `Send(event)` - Process event through machine, returns new state
33
- * - `GetState()` - Returns current state
34
- *
35
- * Schemas are read from the machine - must use `Machine.make({ state, event, initial })`.
36
- *
37
- * @example
38
- * ```ts
39
- * const OrderState = State({
40
- * Pending: { orderId: Schema.String },
41
- * Shipped: { trackingId: Schema.String },
42
- * })
43
- *
44
- * const OrderEvent = Event({
45
- * Ship: { trackingId: Schema.String },
46
- * })
47
- *
48
- * const orderMachine = Machine.make({
49
- * state: OrderState,
50
- * event: OrderEvent,
51
- * initial: OrderState.Pending({ orderId: "" }),
52
- * }).pipe(
53
- * Machine.on(OrderState.Pending, OrderEvent.Ship, ...),
54
- * )
55
- *
56
- * const OrderEntity = toEntity(orderMachine, { type: "Order" })
57
- * ```
58
- */
59
- declare const toEntity: <S extends {
60
- readonly _tag: string;
61
- }, E extends {
62
- readonly _tag: string;
63
- }, R>(machine: Machine<S, E, R, any, any, any>, options: ToEntityOptions) => Entity.Entity<string, Rpc.Rpc<"Send", Schema.Struct<{
64
- event: Schema.Schema<E, E, never>;
65
- }>, Schema.Schema<S, S, never>, typeof Schema.Never, never> | Rpc.Rpc<"Ask", Schema.Struct<{
66
- event: Schema.Schema<E, E, never>;
67
- }>, typeof Schema.Unknown, typeof Schema.Never, never> | Rpc.Rpc<"GetState", typeof Schema.Void, Schema.Schema<S, S, never>, typeof Schema.Never, never>>;
68
- //#endregion
69
- export { EntityRpcs, ToEntityOptions, toEntity };
@@ -1,59 +0,0 @@
1
- import { MissingSchemaError } from "../errors.js";
2
- import { Schema } from "effect";
3
- import { Entity } from "@effect/cluster";
4
- import { Rpc } from "@effect/rpc";
5
- //#region src/cluster/to-entity.ts
6
- /**
7
- * Generate Entity definition from a machine.
8
- *
9
- * @module
10
- */
11
- /**
12
- * Generate an Entity definition from a machine.
13
- *
14
- * Creates an Entity with a standard RPC protocol:
15
- * - `Send(event)` - Process event through machine, returns new state
16
- * - `GetState()` - Returns current state
17
- *
18
- * Schemas are read from the machine - must use `Machine.make({ state, event, initial })`.
19
- *
20
- * @example
21
- * ```ts
22
- * const OrderState = State({
23
- * Pending: { orderId: Schema.String },
24
- * Shipped: { trackingId: Schema.String },
25
- * })
26
- *
27
- * const OrderEvent = Event({
28
- * Ship: { trackingId: Schema.String },
29
- * })
30
- *
31
- * const orderMachine = Machine.make({
32
- * state: OrderState,
33
- * event: OrderEvent,
34
- * initial: OrderState.Pending({ orderId: "" }),
35
- * }).pipe(
36
- * Machine.on(OrderState.Pending, OrderEvent.Ship, ...),
37
- * )
38
- *
39
- * const OrderEntity = toEntity(orderMachine, { type: "Order" })
40
- * ```
41
- */
42
- const toEntity = (machine, options) => {
43
- const stateSchema = machine.stateSchema;
44
- const eventSchema = machine.eventSchema;
45
- if (stateSchema === void 0 || eventSchema === void 0) throw new MissingSchemaError({ operation: "toEntity" });
46
- return Entity.make(options.type, [
47
- Rpc.make("Send", {
48
- payload: { event: eventSchema },
49
- success: stateSchema
50
- }),
51
- Rpc.make("Ask", {
52
- payload: { event: eventSchema },
53
- success: Schema.Unknown
54
- }),
55
- Rpc.make("GetState", { success: stateSchema })
56
- ]);
57
- };
58
- //#endregion
59
- export { toEntity };
@@ -1,95 +0,0 @@
1
- import { Schema } from "effect";
2
-
3
- //#region src/errors.d.ts
4
- declare const DuplicateActorError_base: Schema.TaggedErrorClass<DuplicateActorError, "DuplicateActorError", {
5
- readonly _tag: Schema.tag<"DuplicateActorError">;
6
- } & {
7
- actorId: typeof Schema.String;
8
- }>;
9
- /** Attempted to spawn/restore actor with ID already in use */
10
- declare class DuplicateActorError extends DuplicateActorError_base {}
11
- declare const MissingSchemaError_base: Schema.TaggedErrorClass<MissingSchemaError, "MissingSchemaError", {
12
- readonly _tag: Schema.tag<"MissingSchemaError">;
13
- } & {
14
- operation: typeof Schema.String;
15
- }>;
16
- /** Operation requires schemas attached to machine */
17
- declare class MissingSchemaError extends MissingSchemaError_base {}
18
- declare const InvalidSchemaError_base: Schema.TaggedErrorClass<InvalidSchemaError, "InvalidSchemaError", {
19
- readonly _tag: Schema.tag<"InvalidSchemaError">;
20
- } & {
21
- message: typeof Schema.String;
22
- }>;
23
- /** State/Event schema has no variants */
24
- declare class InvalidSchemaError extends InvalidSchemaError_base {}
25
- declare const MissingMatchHandlerError_base: Schema.TaggedErrorClass<MissingMatchHandlerError, "MissingMatchHandlerError", {
26
- readonly _tag: Schema.tag<"MissingMatchHandlerError">;
27
- } & {
28
- tag: typeof Schema.String;
29
- }>;
30
- /** $match called with missing handler for tag */
31
- declare class MissingMatchHandlerError extends MissingMatchHandlerError_base {}
32
- declare const SlotProvisionError_base: Schema.TaggedErrorClass<SlotProvisionError, "SlotProvisionError", {
33
- readonly _tag: Schema.tag<"SlotProvisionError">;
34
- } & {
35
- slotName: typeof Schema.String;
36
- slotType: Schema.Literal<["slot"]>;
37
- }>;
38
- /** Slot handler not found at runtime (internal error) */
39
- declare class SlotProvisionError extends SlotProvisionError_base {}
40
- declare const ProvisionValidationError_base: Schema.TaggedErrorClass<ProvisionValidationError, "ProvisionValidationError", {
41
- readonly _tag: Schema.tag<"ProvisionValidationError">;
42
- } & {
43
- missing: Schema.Array$<typeof Schema.String>;
44
- extra: Schema.Array$<typeof Schema.String>;
45
- }>;
46
- /** Slot provision validation failed — missing or extra handlers */
47
- declare class ProvisionValidationError extends ProvisionValidationError_base {}
48
- declare const AssertionError_base: Schema.TaggedErrorClass<AssertionError, "AssertionError", {
49
- readonly _tag: Schema.tag<"AssertionError">;
50
- } & {
51
- message: typeof Schema.String;
52
- }>;
53
- /** Assertion failed in testing utilities */
54
- declare class AssertionError extends AssertionError_base {}
55
- declare const ActorStoppedError_base: Schema.TaggedErrorClass<ActorStoppedError, "ActorStoppedError", {
56
- readonly _tag: Schema.tag<"ActorStoppedError">;
57
- } & {
58
- actorId: typeof Schema.String;
59
- }>;
60
- /** Actor was stopped while a call/ask was pending */
61
- declare class ActorStoppedError extends ActorStoppedError_base {}
62
- declare const NoReplyError_base: Schema.TaggedErrorClass<NoReplyError, "NoReplyError", {
63
- readonly _tag: Schema.tag<"NoReplyError">;
64
- } & {
65
- actorId: typeof Schema.String;
66
- eventTag: typeof Schema.String;
67
- }>;
68
- /** ask() was used but the transition handler did not call reply */
69
- declare class NoReplyError extends NoReplyError_base {}
70
- declare const PersistenceError_base: Schema.TaggedErrorClass<PersistenceError, "PersistenceError", {
71
- readonly _tag: Schema.tag<"PersistenceError">;
72
- } & {
73
- message: typeof Schema.String;
74
- }>;
75
- /** Persistence adapter operation failed */
76
- declare class PersistenceError extends PersistenceError_base {}
77
- declare const SlotCodecError_base: Schema.TaggedErrorClass<SlotCodecError, "SlotCodecError", {
78
- readonly _tag: Schema.tag<"SlotCodecError">;
79
- } & {
80
- slotName: typeof Schema.String;
81
- phase: Schema.Literal<["input", "output"]>;
82
- message: typeof Schema.String;
83
- }>;
84
- /** Slot input/output schema validation failed */
85
- declare class SlotCodecError extends SlotCodecError_base {}
86
- declare const VersionConflictError_base: Schema.TaggedErrorClass<VersionConflictError, "VersionConflictError", {
87
- readonly _tag: Schema.tag<"VersionConflictError">;
88
- } & {
89
- expected: typeof Schema.Number;
90
- actual: typeof Schema.Number;
91
- }>;
92
- /** Optimistic locking failure — stored version doesn't match expected */
93
- declare class VersionConflictError extends VersionConflictError_base {}
94
- //#endregion
95
- export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError };
package/v3/dist/errors.js DELETED
@@ -1,54 +0,0 @@
1
- import { Schema } from "effect";
2
- //#region src/errors.ts
3
- /**
4
- * Typed error classes for effect-machine.
5
- *
6
- * All errors extend Schema.TaggedErrorClass for:
7
- * - Type-safe catching via Effect.catchTag
8
- * - Serialization support
9
- * - Composable error handling
10
- *
11
- * @module
12
- */
13
- /** Attempted to spawn/restore actor with ID already in use */
14
- var DuplicateActorError = class extends Schema.TaggedError()("DuplicateActorError", { actorId: Schema.String }) {};
15
- /** Operation requires schemas attached to machine */
16
- var MissingSchemaError = class extends Schema.TaggedError()("MissingSchemaError", { operation: Schema.String }) {};
17
- /** State/Event schema has no variants */
18
- var InvalidSchemaError = class extends Schema.TaggedError()("InvalidSchemaError", { message: Schema.String }) {};
19
- /** $match called with missing handler for tag */
20
- var MissingMatchHandlerError = class extends Schema.TaggedError()("MissingMatchHandlerError", { tag: Schema.String }) {};
21
- /** Slot handler not found at runtime (internal error) */
22
- var SlotProvisionError = class extends Schema.TaggedError()("SlotProvisionError", {
23
- slotName: Schema.String,
24
- slotType: Schema.Literal("slot")
25
- }) {};
26
- /** Slot provision validation failed — missing or extra handlers */
27
- var ProvisionValidationError = class extends Schema.TaggedError()("ProvisionValidationError", {
28
- missing: Schema.Array(Schema.String),
29
- extra: Schema.Array(Schema.String)
30
- }) {};
31
- /** Assertion failed in testing utilities */
32
- var AssertionError = class extends Schema.TaggedError()("AssertionError", { message: Schema.String }) {};
33
- /** Actor was stopped while a call/ask was pending */
34
- var ActorStoppedError = class extends Schema.TaggedError()("ActorStoppedError", { actorId: Schema.String }) {};
35
- /** ask() was used but the transition handler did not call reply */
36
- var NoReplyError = class extends Schema.TaggedError()("NoReplyError", {
37
- actorId: Schema.String,
38
- eventTag: Schema.String
39
- }) {};
40
- /** Persistence adapter operation failed */
41
- var PersistenceError = class extends Schema.TaggedError()("PersistenceError", { message: Schema.String }) {};
42
- /** Slot input/output schema validation failed */
43
- var SlotCodecError = class extends Schema.TaggedError()("SlotCodecError", {
44
- slotName: Schema.String,
45
- phase: Schema.Literal("input", "output"),
46
- message: Schema.String
47
- }) {};
48
- /** Optimistic locking failure — stored version doesn't match expected */
49
- var VersionConflictError = class extends Schema.TaggedError()("VersionConflictError", {
50
- expected: Schema.Number,
51
- actual: Schema.Number
52
- }) {};
53
- //#endregion
54
- export { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError };
@@ -1,11 +0,0 @@
1
- import { DeferReplyResult, ReplyResult } from "./internal/utils.js";
2
- import { Event, MachineEventSchema, MachineStateSchema, ReplyFields, State } from "./schema.js";
3
- import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError } from "./errors.js";
4
- import { HasSlotKeys, MachineContext, ProvideSlots, Slot, SlotCall, SlotCalls, SlotFnDef, SlotHandler, SlotInvocation, SlotRequest, SlotResult, SlotsDef, SlotsSchema } from "./slot.js";
5
- import { ActorExit, CellPhase, DefectPhase, Supervision } from "./supervision.js";
6
- import { ProcessEventResult } from "./internal/transition.js";
7
- import { BackgroundEffect, Durability, DurabilityCommit, HandlerContext, Lifecycle, Machine, MachineRef, MakeConfig, Recovery, RecoveryContext, SpawnEffect, StateHandlerContext, TaskOptions, TimeoutConfig, Transition, machine_d_exports } from "./machine.js";
8
- import { ActorRef, ActorRefSync, ActorScope, ActorSystem, Default, SystemEvent, SystemEventListener, TransitionInfo } from "./actor.js";
9
- import { SimulationResult, TestHarness, TestHarnessOptions, assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
10
- import { AnyInspectionEvent, EffectEvent, ErrorEvent, EventReceivedEvent, InspectionEvent, Inspector, InspectorHandler, SpawnEvent, StopEvent, TaskEvent, TracingInspectorOptions, TransitionEvent, collectingInspector, combineInspectors, consoleInspector, makeInspector, makeInspectorEffect, tracingInspector } from "./inspection.js";
11
- export { ActorExit, type ActorRef, type ActorRefSync, ActorScope, ActorStoppedError, type ActorSystem, Default as ActorSystemDefault, ActorSystem as ActorSystemService, type AnyInspectionEvent, AssertionError, type BackgroundEffect, type CellPhase, type DefectPhase, type DeferReplyResult, DuplicateActorError, type Durability, type DurabilityCommit, type EffectEvent, type ErrorEvent, Event, type EventReceivedEvent, type HandlerContext, type HasSlotKeys, type InspectionEvent, type Inspector, type InspectorHandler, Inspector as InspectorService, InvalidSchemaError, type Lifecycle, machine_d_exports as Machine, type MachineContext, type MachineEventSchema, type MachineRef, type MachineStateSchema, type Machine as MachineType, type MakeConfig, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, type ProcessEventResult, type ProvideSlots, ProvisionValidationError, type Recovery, type RecoveryContext, type ReplyFields, type ReplyResult, type SimulationResult, Slot, type SlotCall, type SlotCalls, SlotCodecError, type SlotFnDef, type SlotHandler, type SlotInvocation, SlotProvisionError, type SlotRequest, type SlotResult, type SlotsDef, type SlotsSchema, type SpawnEffect, type SpawnEvent, State, type StateHandlerContext, type StopEvent, Supervision, type SystemEvent, type SystemEventListener, type TaskEvent, type TaskOptions, type TestHarness, type TestHarnessOptions, type TimeoutConfig, type TracingInspectorOptions, type Transition, type TransitionEvent, type TransitionInfo, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };
package/v3/dist/index.js DELETED
@@ -1,9 +0,0 @@
1
- import { ActorStoppedError, AssertionError, DuplicateActorError, InvalidSchemaError, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, SlotCodecError, SlotProvisionError, VersionConflictError } from "./errors.js";
2
- import { Inspector, collectingInspector, combineInspectors, consoleInspector, makeInspector, makeInspectorEffect, tracingInspector } from "./inspection.js";
3
- import { Slot } from "./slot.js";
4
- import { machine_exports } from "./machine.js";
5
- import { ActorExit, Supervision } from "./supervision.js";
6
- import { ActorScope, ActorSystem, Default } from "./actor.js";
7
- import { assertNeverReaches, assertPath, assertReaches, createTestHarness, simulate } from "./testing.js";
8
- import { Event, State } from "./schema.js";
9
- export { ActorExit, ActorScope, ActorStoppedError, Default as ActorSystemDefault, ActorSystem as ActorSystemService, AssertionError, DuplicateActorError, Event, Inspector as InspectorService, InvalidSchemaError, machine_exports as Machine, MissingMatchHandlerError, MissingSchemaError, NoReplyError, PersistenceError, ProvisionValidationError, Slot, SlotCodecError, SlotProvisionError, State, Supervision, VersionConflictError, assertNeverReaches, assertPath, assertReaches, collectingInspector, combineInspectors, consoleInspector, createTestHarness, makeInspector, makeInspectorEffect, simulate, tracingInspector };