@entifix/transactions 0.12.1 → 0.14.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 (41) hide show
  1. package/dist/contracts/command.d.ts +3 -3
  2. package/dist/contracts/command.d.ts.map +1 -1
  3. package/dist/contracts/command.js +3 -3
  4. package/dist/contracts/command.js.map +1 -1
  5. package/dist/contracts/event.d.ts.map +1 -1
  6. package/dist/contracts/event.js +2 -1
  7. package/dist/contracts/event.js.map +1 -1
  8. package/dist/contracts/flow-messages.d.ts +16 -0
  9. package/dist/contracts/flow-messages.d.ts.map +1 -1
  10. package/dist/contracts/flow-messages.js +20 -0
  11. package/dist/contracts/flow-messages.js.map +1 -1
  12. package/dist/contracts/record.d.ts +7 -7
  13. package/dist/contracts/record.d.ts.map +1 -1
  14. package/dist/contracts/record.js.map +1 -1
  15. package/dist/contracts/saga-definition.d.ts.map +1 -1
  16. package/dist/contracts/saga-definition.js +11 -5
  17. package/dist/contracts/saga-definition.js.map +1 -1
  18. package/dist/engine/local-saga-dispatcher.d.ts +3 -3
  19. package/dist/engine/local-saga-dispatcher.d.ts.map +1 -1
  20. package/dist/engine/local-saga-dispatcher.js +1 -5
  21. package/dist/engine/local-saga-dispatcher.js.map +1 -1
  22. package/dist/engine/resolve-template.d.ts.map +1 -1
  23. package/dist/engine/resolve-template.js +3 -13
  24. package/dist/engine/resolve-template.js.map +1 -1
  25. package/dist/engine/run-saga.d.ts +3 -3
  26. package/dist/engine/run-saga.d.ts.map +1 -1
  27. package/dist/engine/run-saga.js.map +1 -1
  28. package/dist/engine/run-transaction.d.ts +1 -1
  29. package/dist/engine/run-transaction.d.ts.map +1 -1
  30. package/dist/ports/event-bus.d.ts +2 -2
  31. package/dist/ports/event-bus.d.ts.map +1 -1
  32. package/dist/ports/event-bus.js.map +1 -1
  33. package/dist/ports/saga-dispatcher.d.ts +3 -3
  34. package/dist/ports/saga-dispatcher.d.ts.map +1 -1
  35. package/dist/ports/saga-dispatcher.js.map +1 -1
  36. package/dist/ports/transaction-handler.d.ts +4 -4
  37. package/dist/ports/transaction-handler.d.ts.map +1 -1
  38. package/dist/ports/transaction-handler.js.map +1 -1
  39. package/dist/use-case/facade.uc.d.ts +3 -3
  40. package/dist/use-case/facade.uc.d.ts.map +1 -1
  41. package/package.json +5 -5
@@ -1,5 +1,5 @@
1
1
  import './messages.js';
2
- import { EntifixBuildError, type EntifixEnvelope, type InvalidEnvelope, type SerializedEntity } from '@entifix/core';
2
+ import { type EntifixEnvelope, InvalidEnvelope, type SerializedEntity } from '@entifix/core';
3
3
  import { Effect } from 'effect';
4
4
  /**
5
5
  * A write intent in CQRS terms. A client no longer mutates directly — it issues
@@ -32,7 +32,7 @@ export interface TransactionCommand<TPayload = SerializedEntity> {
32
32
  * {@link readCommandEnvelope} drops whatever a caller sent under this name, so
33
33
  * a client cannot name another tenant by writing one into the body. It is the
34
34
  * same rule the id already follows (`entity.id = params.id`), and the same
35
- * rule `requireOrganization` states: the organization comes from the token and
35
+ * rule the organization guard states: the organization comes from the token and
36
36
  * nowhere else.
37
37
  *
38
38
  * Optional because the parser produces a command without it and the route
@@ -55,5 +55,5 @@ export declare const isTransactionId: (value: unknown) => value is string;
55
55
  * idempotency key, and a caller who omits it silently loses retry safety while
56
56
  * appearing to succeed.
57
57
  */
58
- export declare function readCommandEnvelope<TPayload = SerializedEntity>(body: unknown): Effect.Effect<TransactionCommand<TPayload>, EntifixBuildError | InvalidEnvelope>;
58
+ export declare function readCommandEnvelope<TPayload = SerializedEntity>(body: unknown): Effect.Effect<TransactionCommand<TPayload>, InvalidEnvelope>;
59
59
  //# sourceMappingURL=command.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"command.d.ts","sourceRoot":"","sources":["../../src/contracts/command.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,CAAC;AAEvB,OAAO,EAEL,iBAAiB,EACjB,KAAK,eAAe,EACpB,KAAK,eAAe,EAEpB,KAAK,gBAAgB,EACt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,gBAAgB;IAC7D;;;;;;;;OAQG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB,6CAA6C;IAC7C,IAAI,EAAE,QAAQ,CAAC;IACf,4EAA4E;IAC5E,MAAM,EAAE,MAAM,CAAC;IACf,uCAAuC;IACvC,OAAO,EAAE,QAAQ,CAAC;IAClB;;;;;;;;;;;;;;OAcG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED,MAAM,MAAM,eAAe,CAAC,QAAQ,GAAG,gBAAgB,IAAI,eAAe,CACxE,kBAAkB,CAAC,QAAQ,CAAC,CAC7B,CAAC;AAEF,+DAA+D;AAC/D,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,gBAAgB,EAC7D,OAAO,EAAE,kBAAkB,CAAC,QAAQ,CAAC,GACpC,eAAe,CAAC,QAAQ,CAAC,CAE3B;AAaD,kDAAkD;AAClD,eAAO,MAAM,eAAe,GAAI,OAAO,OAAO,KAAG,KAAK,IAAI,MACX,CAAC;AAEhD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,GAAG,gBAAgB,EAC7D,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,kBAAkB,CAAC,QAAQ,CAAC,EAAE,eAAe,CAAC,CAmB9D"}
@@ -1,7 +1,7 @@
1
1
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
2
  // Evaluated for its registrations: this reader decodes against them.
3
3
  import './messages.js';
4
- import { decodeRequestEnvelope, EntifixBuildError, makeEnvelope } from '@entifix/core';
4
+ import { decodeRequestEnvelope, InvalidEnvelope, makeEnvelope } from '@entifix/core';
5
5
  import { Effect } from 'effect';
6
6
  /** Frames a command as a transport-free `command` envelope. */ export function makeCommandEnvelope(command) {
7
7
  return makeEnvelope('command', command.entity, command);
@@ -29,8 +29,8 @@ import { Effect } from 'effect';
29
29
  // The registered schema already proved the frame; what it cannot say is
30
30
  // that the id is a UUID, which is what makes it safe as a primary key.
31
31
  if (!isTransactionId(command.transactionId)) {
32
- return yield* Effect.fail(new EntifixBuildError('command envelope carried no valid command', undefined, {
33
- body
32
+ return yield* Effect.fail(new InvalidEnvelope({
33
+ reason: 'command envelope carried no valid command'
34
34
  }));
35
35
  }
36
36
  // `organizationId` is deliberately **not** carried over from the parsed
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/command.ts"],"sourcesContent":["// Evaluated for its registrations: this reader decodes against them.\nimport './messages.js';\n\nimport {\n decodeRequestEnvelope,\n EntifixBuildError,\n type EntifixEnvelope,\n type InvalidEnvelope,\n makeEnvelope,\n type SerializedEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A write intent in CQRS terms. A client no longer mutates directly — it issues\n * a command, the service runs the transaction facade over it, and answers with a\n * transaction id. `payload` is a serialized entity (the same wire shape the\n * entity envelopes carry), so a command round-trips through the existing\n * (de)serializer.\n */\nexport interface TransactionCommand<TPayload = SerializedEntity> {\n /**\n * Correlates every event and record for this run, and **the client mints it**.\n *\n * It is also the stored entity's id and the idempotency key: re-sending a\n * command with the same id returns the first one's answer instead of writing\n * twice. That makes it untrusted input which becomes a primary key, so\n * {@link readCommandEnvelope} constrains it to a UUID rather than accepting\n * any string.\n */\n transactionId: string;\n /** What to do — only `create` in phase 1. */\n type: 'create';\n /** The target entity's `key` (e.g. `product`), the routing/lock subject. */\n entity: string;\n /** The serialized entity to act on. */\n payload: TPayload;\n /**\n * Whose organization this command acts in — **stamped by the route from the\n * verified token, never read from the wire**.\n *\n * {@link readCommandEnvelope} drops whatever a caller sent under this name, so\n * a client cannot name another tenant by writing one into the body. It is the\n * same rule the id already follows (`entity.id = params.id`), and the same\n * rule `requireOrganization` states: the organization comes from the token and\n * nowhere else.\n *\n * Optional because the parser produces a command without it and the route\n * fills it in a moment later. A command that reaches the engine still carrying\n * `undefined` emits events that no tenant-scoped stream connection receives —\n * which is the intended direction to fail.\n */\n organizationId?: string;\n}\n\nexport type CommandEnvelope<TPayload = SerializedEntity> = EntifixEnvelope<\n TransactionCommand<TPayload>\n>;\n\n/** Frames a command as a transport-free `command` envelope. */\nexport function makeCommandEnvelope<TPayload = SerializedEntity>(\n command: TransactionCommand<TPayload>,\n): CommandEnvelope<TPayload> {\n return makeEnvelope('command', command.entity, command);\n}\n\n/**\n * A canonical RFC 9562 UUID — any version, standard variant.\n *\n * The transaction id arrives from the client and becomes a primary key, so the\n * key space it may address has to be fixed rather than \"whatever string was\n * sent\". Accepting every version keeps v4 (random) and v7 (time-ordered) both\n * usable without the wire format becoming a second decision.\n */\nconst UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Whether a value is a usable transaction id. */\nexport const isTransactionId = (value: unknown): value is string =>\n typeof value === 'string' && UUID.test(value);\n\n/**\n * Parses a `command` envelope, failing on a wrong shape/type.\n *\n * A command carrying no valid transaction id is rejected outright — there is no\n * server-side fallback that mints one. That is deliberate: the id is the\n * idempotency key, and a caller who omits it silently loses retry safety while\n * appearing to succeed.\n */\nexport function readCommandEnvelope<TPayload = SerializedEntity>(\n body: unknown,\n): Effect.Effect<\n TransactionCommand<TPayload>,\n EntifixBuildError | InvalidEnvelope\n> {\n return Effect.gen(function* () {\n const envelope = yield* decodeRequestEnvelope(body, 'command', 'command');\n const command = envelope.data as TransactionCommand<TPayload>;\n // The registered schema already proved the frame; what it cannot say is\n // that the id is a UUID, which is what makes it safe as a primary key.\n if (!isTransactionId(command.transactionId)) {\n return yield* Effect.fail(\n new EntifixBuildError(\n 'command envelope carried no valid command',\n undefined,\n {\n body,\n },\n ),\n );\n }\n // `organizationId` is deliberately **not** carried over from the parsed\n // body. Spreading the caller's object here would let a request name another\n // tenant, which is precisely the scoping the stream depends on.\n const { organizationId: _ignored, ...trusted } = command;\n return trusted as TransactionCommand<TPayload>;\n });\n}\n"],"names":["decodeRequestEnvelope","EntifixBuildError","makeEnvelope","Effect","makeCommandEnvelope","command","entity","UUID","isTransactionId","value","test","readCommandEnvelope","body","gen","envelope","data","transactionId","fail","undefined","organizationId","_ignored","trusted"],"mappings":";AAAA,qEAAqE;AACrE,OAAO,gBAAgB;AAEvB,SACEA,qBAAqB,EACrBC,iBAAiB,EAGjBC,YAAY,QAEP,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAgDhC,6DAA6D,GAC7D,OAAO,SAASC,oBACdC,OAAqC;IAErC,OAAOH,aAAa,WAAWG,QAAQC,MAAM,EAAED;AACjD;AAEA;;;;;;;CAOC,GACD,MAAME,OACJ;AAEF,gDAAgD,GAChD,OAAO,MAAMC,kBAAkB,CAACC,QAC9B,OAAOA,UAAU,YAAYF,KAAKG,IAAI,CAACD,OAAO;AAEhD;;;;;;;CAOC,GACD,OAAO,SAASE,oBACdC,IAAa;IAKb,OAAOT,OAAOU,GAAG,CAAC;QAChB,MAAMC,WAAW,OAAOd,sBAAsBY,MAAM,WAAW;QAC/D,MAAMP,UAAUS,SAASC,IAAI;QAC7B,wEAAwE;QACxE,uEAAuE;QACvE,IAAI,CAACP,gBAAgBH,QAAQW,aAAa,GAAG;YAC3C,OAAO,OAAOb,OAAOc,IAAI,CACvB,IAAIhB,kBACF,6CACAiB,WACA;gBACEN;YACF;QAGN;QACA,wEAAwE;QACxE,4EAA4E;QAC5E,gEAAgE;QAChE,MAAM,EAAEO,gBAAgBC,QAAQ,EAAc,GAAGf,SAAZgB,2CAAYhB;;;QACjD,OAAOgB;IACT;AACF"}
1
+ {"version":3,"sources":["../../src/contracts/command.ts"],"sourcesContent":["// Evaluated for its registrations: this reader decodes against them.\nimport './messages.js';\n\nimport {\n decodeRequestEnvelope,\n type EntifixEnvelope,\n InvalidEnvelope,\n makeEnvelope,\n type SerializedEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A write intent in CQRS terms. A client no longer mutates directly — it issues\n * a command, the service runs the transaction facade over it, and answers with a\n * transaction id. `payload` is a serialized entity (the same wire shape the\n * entity envelopes carry), so a command round-trips through the existing\n * (de)serializer.\n */\nexport interface TransactionCommand<TPayload = SerializedEntity> {\n /**\n * Correlates every event and record for this run, and **the client mints it**.\n *\n * It is also the stored entity's id and the idempotency key: re-sending a\n * command with the same id returns the first one's answer instead of writing\n * twice. That makes it untrusted input which becomes a primary key, so\n * {@link readCommandEnvelope} constrains it to a UUID rather than accepting\n * any string.\n */\n transactionId: string;\n /** What to do — only `create` in phase 1. */\n type: 'create';\n /** The target entity's `key` (e.g. `product`), the routing/lock subject. */\n entity: string;\n /** The serialized entity to act on. */\n payload: TPayload;\n /**\n * Whose organization this command acts in — **stamped by the route from the\n * verified token, never read from the wire**.\n *\n * {@link readCommandEnvelope} drops whatever a caller sent under this name, so\n * a client cannot name another tenant by writing one into the body. It is the\n * same rule the id already follows (`entity.id = params.id`), and the same\n * rule the organization guard states: the organization comes from the token and\n * nowhere else.\n *\n * Optional because the parser produces a command without it and the route\n * fills it in a moment later. A command that reaches the engine still carrying\n * `undefined` emits events that no tenant-scoped stream connection receives —\n * which is the intended direction to fail.\n */\n organizationId?: string;\n}\n\nexport type CommandEnvelope<TPayload = SerializedEntity> = EntifixEnvelope<\n TransactionCommand<TPayload>\n>;\n\n/** Frames a command as a transport-free `command` envelope. */\nexport function makeCommandEnvelope<TPayload = SerializedEntity>(\n command: TransactionCommand<TPayload>,\n): CommandEnvelope<TPayload> {\n return makeEnvelope('command', command.entity, command);\n}\n\n/**\n * A canonical RFC 9562 UUID — any version, standard variant.\n *\n * The transaction id arrives from the client and becomes a primary key, so the\n * key space it may address has to be fixed rather than \"whatever string was\n * sent\". Accepting every version keeps v4 (random) and v7 (time-ordered) both\n * usable without the wire format becoming a second decision.\n */\nconst UUID =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n/** Whether a value is a usable transaction id. */\nexport const isTransactionId = (value: unknown): value is string =>\n typeof value === 'string' && UUID.test(value);\n\n/**\n * Parses a `command` envelope, failing on a wrong shape/type.\n *\n * A command carrying no valid transaction id is rejected outright — there is no\n * server-side fallback that mints one. That is deliberate: the id is the\n * idempotency key, and a caller who omits it silently loses retry safety while\n * appearing to succeed.\n */\nexport function readCommandEnvelope<TPayload = SerializedEntity>(\n body: unknown,\n): Effect.Effect<TransactionCommand<TPayload>, InvalidEnvelope> {\n return Effect.gen(function* () {\n const envelope = yield* decodeRequestEnvelope(body, 'command', 'command');\n const command = envelope.data as TransactionCommand<TPayload>;\n // The registered schema already proved the frame; what it cannot say is\n // that the id is a UUID, which is what makes it safe as a primary key.\n if (!isTransactionId(command.transactionId)) {\n return yield* Effect.fail(\n new InvalidEnvelope({\n reason: 'command envelope carried no valid command',\n }),\n );\n }\n // `organizationId` is deliberately **not** carried over from the parsed\n // body. Spreading the caller's object here would let a request name another\n // tenant, which is precisely the scoping the stream depends on.\n const { organizationId: _ignored, ...trusted } = command;\n return trusted as TransactionCommand<TPayload>;\n });\n}\n"],"names":["decodeRequestEnvelope","InvalidEnvelope","makeEnvelope","Effect","makeCommandEnvelope","command","entity","UUID","isTransactionId","value","test","readCommandEnvelope","body","gen","envelope","data","transactionId","fail","reason","organizationId","_ignored","trusted"],"mappings":";AAAA,qEAAqE;AACrE,OAAO,gBAAgB;AAEvB,SACEA,qBAAqB,EAErBC,eAAe,EACfC,YAAY,QAEP,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAgDhC,6DAA6D,GAC7D,OAAO,SAASC,oBACdC,OAAqC;IAErC,OAAOH,aAAa,WAAWG,QAAQC,MAAM,EAAED;AACjD;AAEA;;;;;;;CAOC,GACD,MAAME,OACJ;AAEF,gDAAgD,GAChD,OAAO,MAAMC,kBAAkB,CAACC,QAC9B,OAAOA,UAAU,YAAYF,KAAKG,IAAI,CAACD,OAAO;AAEhD;;;;;;;CAOC,GACD,OAAO,SAASE,oBACdC,IAAa;IAEb,OAAOT,OAAOU,GAAG,CAAC;QAChB,MAAMC,W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transaction record settles into.
3
4
  *
@@ -72,7 +73,7 @@ export const failedEvent = (command, error, source)=>message(source, {
72
73
  entity: command.entity,
73
74
  state: 'FAILED',
74
75
  step: 'failed',
75
- error: error instanceof Error ? error.message : String(error),
76
+ error: messageOf(error),
76
77
  at: now(),
77
78
  organizationId: command.organizationId
78
79
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/event.ts"],"sourcesContent":["import {\n type DomainEvent,\n type EntifixEnvelope,\n type EntityId,\n} from '@entifix/core';\n\nimport type { TransactionOutcome } from '../ports/transaction-handler.js';\nimport type { TransactionCommand } from './command.js';\nimport type { OutboxEvent } from './outbox.js';\n\n/**\n * The lifecycle states a transaction record settles into.\n *\n * A const array rather than a bare union because something has to **enumerate**\n * them: a by-state gauge must report every state including the ones at zero, and\n * a series that simply stops being reported reads on most dashboards as \"no\n * data\" rather than as \"none\" — so `STALE` falling to zero would look exactly\n * like the metric having broken.\n *\n * Note there are four states but only three {@link TransactionStep}s: `STALE` is\n * applied by the recovery sweep and has no event of its own.\n */\nexport const TRANSACTION_STATES = [\n 'PENDING',\n 'COMPLETED',\n 'FAILED',\n 'STALE',\n] as const;\n\n/** The lifecycle state a transaction record settles into. */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number];\n\n/** The facade step a given event reports. */\nexport type TransactionStep = 'accepted' | 'completed' | 'failed';\n\n/**\n * What a service reports as its transaction progresses — the **payload** of a\n * {@link DomainEvent}, not the message itself. The saga tracker is a passive\n * consumer of these: for a single-step write it dispatches nothing and only\n * records what the events tell it, which is what keeps such a write\n * choreographed. A flow spanning slices is orchestrated instead, from a\n * declarative definition, and its coordinator both reads these and\n * issues the next step — but that engine is not built, and single-step writes\n * stay exactly as described here when it is.\n *\n * `transactionId` and `at` are also reachable as the message's `correlationId`\n * and `at`. That duplication is deliberate and standard (CloudEvents' `subject`\n * does the same): metadata is what the *transport* routes and deduplicates on,\n * and the payload has to stand on its own for a consumer that has already\n * unwrapped it.\n */\nexport interface TransactionEvent {\n transactionId: string;\n /** The target entity's `key`. */\n entity: string;\n state: TransactionState;\n step: TransactionStep;\n /** The assigned code once executed (`product-001`). */\n code?: string;\n /** The stored entity id once executed. */\n entityId?: EntityId;\n /** Failure detail when `step === 'failed'`. */\n error?: string;\n /** ISO-8601 emission time. */\n at: string;\n /**\n * Whose organization this happened in — the per-connection scoping key for\n * the reactive stream.\n *\n * In `data` rather than in `meta`, under the envelope's rule: `meta` describes the\n * message, `data` describes the occurrence, and which vendor's catalog a\n * record was written in is a fact about what happened.\n *\n * **Optional, and absence is not a wildcard.** An event carrying no\n * organization is delivered to no tenant-scoped connection. Defaulting the\n * other way would make every event emitted before this member existed a\n * cross-tenant delivery, and it fails silently in the direction that matters.\n */\n organizationId?: string;\n}\n\nconst now = (): string => new Date().toISOString();\n\n/** The register's name for a transaction message: `transaction.completed`. */\nexport const transactionEventName = (step: TransactionStep): string =>\n `transaction.${step}`;\n\n/**\n * The message id for one step of one transaction — and therefore the\n * deduplication key.\n *\n * It is the transaction id **and** the step, never the transaction id alone.\n * One transaction emits up to three messages, so a consumer keying on the\n * transaction id would treat `completed` as a redelivery of `accepted` and drop\n * the outcome. The outbox's unique index is on exactly this value, which is what\n * keeps the idempotency claim and the dedup key the same fact rather than two\n * that can drift.\n */\nexport const transactionEventId = (\n transactionId: string,\n step: TransactionStep,\n): string => `${transactionId}:${step}`;\n\n/** Each step's version of its transaction: `accepted` first, then its end. */\nconst STEP_VERSION: Record<TransactionStep, number> = {\n accepted: 0,\n completed: 1,\n failed: 1,\n};\n\n/**\n * Wraps a payload as a routable message from `source`. The transaction is the\n * aggregate, so the outbox keeps `accepted` ahead of the step that ends it.\n */\nconst message = (\n source: string,\n data: TransactionEvent,\n): OutboxEvent<TransactionEvent> => ({\n name: transactionEventName(data.step),\n id: transactionEventId(data.transactionId, data.step),\n source,\n at: data.at,\n correlationId: data.transactionId,\n aggregate: { type: 'transaction', id: data.transactionId },\n version: STEP_VERSION[data.step],\n data,\n});\n\nexport const acceptedEvent = (\n command: TransactionCommand,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'PENDING',\n step: 'accepted',\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const completedEvent = (\n command: TransactionCommand,\n outcome: TransactionOutcome,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'COMPLETED',\n step: 'completed',\n code: outcome.code,\n entityId: outcome.entityId,\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const failedEvent = (\n command: TransactionCommand,\n error: unknown,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'FAILED',\n step: 'failed',\n error: error instanceof Error ? error.message : String(error),\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport type TransactionEventEnvelope = EntifixEnvelope<TransactionEvent>;\n"],"names":["TRANSACTION_STATES","now","Date","toISOString","transactionEventName","step","transactionEventId","transactionId","STEP_VERSION","accepted","completed","failed","message","source","data","name","id","at","correlationId","aggregate","type","version","acceptedEvent","command","entity","state","organizationId","completedEvent","outcome","code","entityId","failedEvent","error","Error","String"],"mappings":"AAUA;;;;;;;;;;;CAWC,GACD,OAAO,MAAMA,qBAAqB;IAChC;IACA;IACA;IACA;CACD,CAAU;AAsDX,MAAMC,MAAM,IAAc,IAAIC,OAAOC,WAAW;AAEhD,4EAA4E,GAC5E,OAAO,MAAMC,uBAAuB,CAACC,OACnC,CAAC,YAAY,EAAEA,MAAM,CAAC;AAExB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,eACAF,OACW,GAAGE,cAAc,CAAC,EAAEF,MAAM,CAAC;AAExC,4EAA4E,GAC5E,MAAMG,eAAgD;IACpDC,UAAU;IACVC,WAAW;IACXC,QAAQ;AACV;AAEA;;;CAGC,GACD,MAAMC,UAAU,CACdC,QACAC,OACmC,CAAA;QACnCC,MAAMX,qBAAqBU,KAAKT,IAAI;QACpCW,IAAIV,mBAAmBQ,KAAKP,aAAa,EAAEO,KAAKT,IAAI;QACpDQ;QACAI,IAAIH,KAAKG,EAAE;QACXC,eAAeJ,KAAKP,aAAa;QACjCY,WAAW;YAAEC,MAAM;YAAeJ,IAAIF,KAAKP,aAAa;QAAC;QACzDc,SAASb,YAAY,CAACM,KAAKT,IAAI,CAAC;QAChCS;IACF,CAAA;AAEA,OAAO,MAAMQ,gBAAgB,CAC3BC,SACAV,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACNY,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMC,iBAAiB,CAC5BJ,SACAK,SACAf,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACNwB,MAAMD,QAAQC,IAAI;QAClBC,UAAUF,QAAQE,QAAQ;QAC1Bb,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMK,cAAc,CACzBR,SACAS,OACAnB,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACN2B,OAAOA,iBAAiBC,QAAQD,MAAMpB,OAAO,GAAGsB,OAAOF;QACvDf,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG"}
1
+ {"version":3,"sources":["../../src/contracts/event.ts"],"sourcesContent":["import {\n type DomainEvent,\n type EntifixEnvelope,\n type EntityId,\n messageOf,\n} from '@entifix/core';\n\nimport type { TransactionOutcome } from '../ports/transaction-handler.js';\nimport type { TransactionCommand } from './command.js';\nimport type { OutboxEvent } from './outbox.js';\n\n/**\n * The lifecycle states a transaction record settles into.\n *\n * A const array rather than a bare union because something has to **enumerate**\n * them: a by-state gauge must report every state including the ones at zero, and\n * a series that simply stops being reported reads on most dashboards as \"no\n * data\" rather than as \"none\" — so `STALE` falling to zero would look exactly\n * like the metric having broken.\n *\n * Note there are four states but only three {@link TransactionStep}s: `STALE` is\n * applied by the recovery sweep and has no event of its own.\n */\nexport const TRANSACTION_STATES = [\n 'PENDING',\n 'COMPLETED',\n 'FAILED',\n 'STALE',\n] as const;\n\n/** The lifecycle state a transaction record settles into. */\nexport type TransactionState = (typeof TRANSACTION_STATES)[number];\n\n/** The facade step a given event reports. */\nexport type TransactionStep = 'accepted' | 'completed' | 'failed';\n\n/**\n * What a service reports as its transaction progresses — the **payload** of a\n * {@link DomainEvent}, not the message itself. The saga tracker is a passive\n * consumer of these: for a single-step write it dispatches nothing and only\n * records what the events tell it, which is what keeps such a write\n * choreographed. A flow spanning slices is orchestrated instead, from a\n * declarative definition, and its coordinator both reads these and\n * issues the next step — but that engine is not built, and single-step writes\n * stay exactly as described here when it is.\n *\n * `transactionId` and `at` are also reachable as the message's `correlationId`\n * and `at`. That duplication is deliberate and standard (CloudEvents' `subject`\n * does the same): metadata is what the *transport* routes and deduplicates on,\n * and the payload has to stand on its own for a consumer that has already\n * unwrapped it.\n */\nexport interface TransactionEvent {\n transactionId: string;\n /** The target entity's `key`. */\n entity: string;\n state: TransactionState;\n step: TransactionStep;\n /** The assigned code once executed (`product-001`). */\n code?: string;\n /** The stored entity id once executed. */\n entityId?: EntityId;\n /** Failure detail when `step === 'failed'`. */\n error?: string;\n /** ISO-8601 emission time. */\n at: string;\n /**\n * Whose organization this happened in — the per-connection scoping key for\n * the reactive stream.\n *\n * In `data` rather than in `meta`, under the envelope's rule: `meta` describes the\n * message, `data` describes the occurrence, and which vendor's catalog a\n * record was written in is a fact about what happened.\n *\n * **Optional, and absence is not a wildcard.** An event carrying no\n * organization is delivered to no tenant-scoped connection. Defaulting the\n * other way would make every event emitted before this member existed a\n * cross-tenant delivery, and it fails silently in the direction that matters.\n */\n organizationId?: string;\n}\n\nconst now = (): string => new Date().toISOString();\n\n/** The register's name for a transaction message: `transaction.completed`. */\nexport const transactionEventName = (step: TransactionStep): string =>\n `transaction.${step}`;\n\n/**\n * The message id for one step of one transaction — and therefore the\n * deduplication key.\n *\n * It is the transaction id **and** the step, never the transaction id alone.\n * One transaction emits up to three messages, so a consumer keying on the\n * transaction id would treat `completed` as a redelivery of `accepted` and drop\n * the outcome. The outbox's unique index is on exactly this value, which is what\n * keeps the idempotency claim and the dedup key the same fact rather than two\n * that can drift.\n */\nexport const transactionEventId = (\n transactionId: string,\n step: TransactionStep,\n): string => `${transactionId}:${step}`;\n\n/** Each step's version of its transaction: `accepted` first, then its end. */\nconst STEP_VERSION: Record<TransactionStep, number> = {\n accepted: 0,\n completed: 1,\n failed: 1,\n};\n\n/**\n * Wraps a payload as a routable message from `source`. The transaction is the\n * aggregate, so the outbox keeps `accepted` ahead of the step that ends it.\n */\nconst message = (\n source: string,\n data: TransactionEvent,\n): OutboxEvent<TransactionEvent> => ({\n name: transactionEventName(data.step),\n id: transactionEventId(data.transactionId, data.step),\n source,\n at: data.at,\n correlationId: data.transactionId,\n aggregate: { type: 'transaction', id: data.transactionId },\n version: STEP_VERSION[data.step],\n data,\n});\n\nexport const acceptedEvent = (\n command: TransactionCommand,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'PENDING',\n step: 'accepted',\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const completedEvent = (\n command: TransactionCommand,\n outcome: TransactionOutcome,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'COMPLETED',\n step: 'completed',\n code: outcome.code,\n entityId: outcome.entityId,\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport const failedEvent = (\n command: TransactionCommand,\n error: unknown,\n source: string,\n): OutboxEvent<TransactionEvent> =>\n message(source, {\n transactionId: command.transactionId,\n entity: command.entity,\n state: 'FAILED',\n step: 'failed',\n error: messageOf(error),\n at: now(),\n organizationId: command.organizationId,\n });\n\nexport type TransactionEventEnvelope = EntifixEnvelope<TransactionEvent>;\n"],"names":["messageOf","TRANSACTION_STATES","now","Date","toISOString","transactionEventName","step","transactionEventId","transactionId","STEP_VERSION","accepted","completed","failed","message","source","data","name","id","at","correlationId","aggregate","type","version","acceptedEvent","command","entity","state","organizationId","completedEvent","outcome","code","entityId","failedEvent","error"],"mappings":"AAAA,SAIEA,SAAS,QACJ,gBAAgB;AAMvB;;;;;;;;;;;CAWC,GACD,OAAO,MAAMC,qBAAqB;IAChC;IACA;IACA;IACA;CACD,CAAU;AAsDX,MAAMC,MAAM,IAAc,IAAIC,OAAOC,WAAW;AAEhD,4EAA4E,GAC5E,OAAO,MAAMC,uBAAuB,CAACC,OACnC,CAAC,YAAY,EAAEA,MAAM,CAAC;AAExB;;;;;;;;;;CAUC,GACD,OAAO,MAAMC,qBAAqB,CAChCC,eACAF,OACW,GAAGE,cAAc,CAAC,EAAEF,MAAM,CAAC;AAExC,4EAA4E,GAC5E,MAAMG,eAAgD;IACpDC,UAAU;IACVC,WAAW;IACXC,QAAQ;AACV;AAEA;;;CAGC,GACD,MAAMC,UAAU,CACdC,QACAC,OACmC,CAAA;QACnCC,MAAMX,qBAAqBU,KAAKT,IAAI;QACpCW,IAAIV,mBAAmBQ,KAAKP,aAAa,EAAEO,KAAKT,IAAI;QACpDQ;QACAI,IAAIH,KAAKG,EAAE;QACXC,eAAeJ,KAAKP,aAAa;QACjCY,WAAW;YAAEC,MAAM;YAAeJ,IAAIF,KAAKP,aAAa;QAAC;QACzDc,SAASb,YAAY,CAACM,KAAKT,IAAI,CAAC;QAChCS;IACF,CAAA;AAEA,OAAO,MAAMQ,gBAAgB,CAC3BC,SACAV,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACNY,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMC,iBAAiB,CAC5BJ,SACAK,SACAf,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACNwB,MAAMD,QAAQC,IAAI;QAClBC,UAAUF,QAAQE,QAAQ;QAC1Bb,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG;AAEL,OAAO,MAAMK,cAAc,CACzBR,SACAS,OACAnB,SAEAD,QAAQC,QAAQ;QACdN,eAAegB,QAAQhB,aAAa;QACpCiB,QAAQD,QAAQC,MAAM;QACtBC,OAAO;QACPpB,MAAM;QACN2B,OAAOjC,UAAUiC;QACjBf,IAAIhB;QACJyB,gBAAgBH,QAAQG,cAAc;IACxC,GAAG"}
@@ -33,6 +33,22 @@ export declare const FlowAccepted: Schema.Struct<{
33
33
  }>>;
34
34
  }>;
35
35
  export type FlowAccepted = typeof FlowAccepted.Type;
36
+ /**
37
+ * The body a flow's `status` link answers: where the flow stands, and why it
38
+ * failed when it did. A browser reads it to settle a write whose outcome it
39
+ * did not hear pushed; a `404` from that link means the flow is not projected
40
+ * yet, never that it failed.
41
+ */
42
+ export declare const FlowStatusBody: Schema.Struct<{
43
+ readonly flowId: Schema.String;
44
+ readonly state: Schema.Literals<readonly ["running", "waiting", "suspended", "completed", "compensated", "failed", "interrupted"]>;
45
+ readonly step: Schema.optionalKey<Schema.String>;
46
+ readonly failure: Schema.optionalKey<Schema.StructWithRest<Schema.Struct<{
47
+ code: Schema.NonEmptyString;
48
+ category: Schema.NonEmptyString;
49
+ }>, readonly [Schema.$Record<Schema.String, Schema.Unknown>]>>;
50
+ }>;
51
+ export type FlowStatusBody = typeof FlowStatusBody.Type;
36
52
  export interface FlowEventInput {
37
53
  readonly name: FlowEventName;
38
54
  readonly source: string;
@@ -1 +1 @@
1
- {"version":3,"file":"flow-messages.d.ts","sourceRoot":"","sources":["../../src/contracts/flow-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAInB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,qDAAqD;AACrD,eAAO,MAAM,WAAW,8EAKd,CAAC;AACX,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAQzD;;;;GAIG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;EAOxB,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,aAAa,CAAC,IAAI,CAAC;AAYtD;;;GAGG;AACH,eAAO,MAAM,YAAY;;;;;;EAQvB,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,YAAY,CAAC,IAAI,CAAC;AAIpD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;CAC9B;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GACpB,OAAO,cAAc,KACpB,WAAW,CAAC,aAAa,CAU1B,CAAC"}
1
+ {"version":3,"file":"flow-messages.d.ts","sourceRoot":"","sources":["../../src/contracts/flow-messages.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,aAAa,EAInB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAE/C,qDAAqD;AACrD,eAAO,MAAM,WAAW,8EAKd,CAAC;AACX,MAAM,MAAM,aAAa,GAAG,CAAC,OAAO,WAAW,CAAC,CAAC,MAAM,CAAC,CAAC;AAQzD;;;;GAIG;AACH,eAAO,MAAM,aAAa;;;;;;;;;;EAOxB,CAAC;AACH,MAAM,MAAM,aAAa,GAAG,OAAO,aAAa,CAAC,IAAI,CAAC;AAYtD;;;GAGG;AACH,eAAO,MAAM,YAAY;;;;;;EAQvB,CAAC;AACH,MAAM,MAAM,YAAY,GAAG,OAAO,YAAY,CAAC,IAAI,CAAC;AAIpD;;;;;GAKG;AACH,eAAO,MAAM,cAAc;;;;;;;;EAazB,CAAC;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,cAAc,CAAC,IAAI,CAAC;AAIxD,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,2EAA2E;IAC3E,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,QAAQ,EAAE,SAAS,aAAa,EAAE,CAAC;IAC5C,QAAQ,CAAC,IAAI,EAAE,aAAa,CAAC;CAC9B;AAED;;;;GAIG;AACH,eAAO,MAAM,SAAS,GACpB,OAAO,cAAc,KACpB,WAAW,CAAC,aAAa,CAU1B,CAAC"}
@@ -43,6 +43,26 @@ for (const name of FLOW_EVENTS)registerEvent(name, name === 'flow.failed' ? Flow
43
43
  }))
44
44
  });
45
45
  registerMessage('flowAccepted', FlowAccepted);
46
+ /**
47
+ * The body a flow's `status` link answers: where the flow stands, and why it
48
+ * failed when it did. A browser reads it to settle a write whose outcome it
49
+ * did not hear pushed; a `404` from that link means the flow is not projected
50
+ * yet, never that it failed.
51
+ */ export const FlowStatusBody = Schema.Struct({
52
+ flowId: Schema.String,
53
+ state: Schema.Literals([
54
+ 'running',
55
+ 'waiting',
56
+ 'suspended',
57
+ 'completed',
58
+ 'compensated',
59
+ 'failed',
60
+ 'interrupted'
61
+ ]),
62
+ step: Schema.optionalKey(Schema.String),
63
+ failure: Schema.optionalKey(FlowFailure)
64
+ });
65
+ registerMessage('flowStatus', FlowStatusBody);
46
66
  /**
47
67
  * Builds a `flow.*` event: id `<flowId>:<step>` so a redelivered announce is
48
68
  * the same message, `correlationId` the flow, the step ordinal as version, and
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/flow-messages.ts"],"sourcesContent":["import {\n type AudienceEntry,\n openStruct,\n registerEvent,\n registerMessage,\n} from '@entifix/core';\nimport { Schema } from 'effect';\n\nimport type { OutboxEvent } from './outbox.js';\n\n/** The four things a flow announces about itself. */\nexport const FLOW_EVENTS = [\n 'flow.started',\n 'flow.completed',\n 'flow.failed',\n 'flow.suspended',\n] as const;\nexport type FlowEventName = (typeof FLOW_EVENTS)[number];\n\n/** A failure inside an asynchronous message: the problem's code and category. */\nconst FlowFailure = openStruct({\n code: Schema.NonEmptyString,\n category: Schema.NonEmptyString,\n});\n\n/**\n * What a `flow.*` event carries. A `flow.failed` without a failure, or with a\n * failure missing its `code` or `category`, does not decode: a client settling\n * a write must be able to translate why it failed.\n */\nexport const FlowEventData = Schema.Struct({\n flowId: Schema.String,\n definition: Schema.String,\n slipVersion: Schema.Number,\n step: Schema.optionalKey(Schema.String),\n outcome: Schema.optionalKey(Schema.Unknown),\n failure: Schema.optionalKey(FlowFailure),\n});\nexport type FlowEventData = typeof FlowEventData.Type;\n\nconst FlowFailedData = Schema.Struct({\n ...FlowEventData.fields,\n failure: FlowFailure,\n});\n\nfor (const name of FLOW_EVENTS)\n registerEvent(name, name === 'flow.failed' ? FlowFailedData : FlowEventData, {\n versioned: true,\n });\n\n/**\n * The `202` body a flow start answers: the flow's id, and where to watch it —\n * its status read and its stream.\n */\nexport const FlowAccepted = Schema.Struct({\n flowId: Schema.String,\n links: Schema.Array(\n Schema.Struct({\n rel: Schema.Literals(['status', 'stream']),\n href: Schema.String,\n }),\n ),\n});\nexport type FlowAccepted = typeof FlowAccepted.Type;\n\nregisterMessage('flowAccepted', FlowAccepted);\n\nexport interface FlowEventInput {\n readonly name: FlowEventName;\n readonly source: string;\n readonly at: string;\n /** The step this event is about, and its ordinal — the event's version. */\n readonly step: string;\n readonly ordinal: number;\n readonly audience: readonly AudienceEntry[];\n readonly data: FlowEventData;\n}\n\n/**\n * Builds a `flow.*` event: id `<flowId>:<step>` so a redelivered announce is\n * the same message, `correlationId` the flow, the step ordinal as version, and\n * an audience that must not be empty.\n */\nexport const flowEvent = (\n input: FlowEventInput,\n): OutboxEvent<FlowEventData> => ({\n name: input.name,\n id: `${input.data.flowId}:${input.step}`,\n source: input.source,\n at: input.at,\n correlationId: input.data.flowId,\n aggregate: { type: 'flow', id: input.data.flowId },\n version: input.ordinal,\n audience: input.audience,\n data: input.data,\n});\n"],"names":["openStruct","registerEvent","registerMessage","Schema","FLOW_EVENTS","FlowFailure","code","NonEmptyString","category","FlowEventData","Struct","flowId","String","definition","slipVersion","Number","step","optionalKey","outcome","Unknown","failure","FlowFailedData","fields","name","versioned","FlowAccepted","links","Array","rel","Literals","href","flowEvent","input","id","data","source","at","correlationId","aggregate","type","version","ordinal","audience"],"mappings":";AAAA,SAEEA,UAAU,EACVC,aAAa,EACbC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAIhC,mDAAmD,GACnD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;CACD,CAAU;AAGX,+EAA+E,GAC/E,MAAMC,cAAcL,WAAW;IAC7BM,MAAMH,OAAOI,cAAc;IAC3BC,UAAUL,OAAOI,cAAc;AACjC;AAEA;;;;CAIC,GACD,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Entry,\n openStruct,\n registerEvent,\n registerMessage,\n} from '@entifix/core';\nimport { Schema } from 'effect';\n\nimport type { OutboxEvent } from './outbox.js';\n\n/** The four things a flow announces about itself. */\nexport const FLOW_EVENTS = [\n 'flow.started',\n 'flow.completed',\n 'flow.failed',\n 'flow.suspended',\n] as const;\nexport type FlowEventName = (typeof FLOW_EVENTS)[number];\n\n/** A failure inside an asynchronous message: the problem's code and category. */\nconst FlowFailure = openStruct({\n code: Schema.NonEmptyString,\n category: Schema.NonEmptyString,\n});\n\n/**\n * What a `flow.*` event carries. A `flow.failed` without a failure, or with a\n * failure missing its `code` or `category`, does not decode: a client settling\n * a write must be able to translate why it failed.\n */\nexport const FlowEventData = Schema.Struct({\n flowId: Schema.String,\n definition: Schema.String,\n slipVersion: Schema.Number,\n step: Schema.optionalKey(Schema.String),\n outcome: Schema.optionalKey(Schema.Unknown),\n failure: Schema.optionalKey(FlowFailure),\n});\nexport type FlowEventData = typeof FlowEventData.Type;\n\nconst FlowFailedData = Schema.Struct({\n ...FlowEventData.fields,\n failure: FlowFailure,\n});\n\nfor (const name of FLOW_EVENTS)\n registerEvent(name, name === 'flow.failed' ? FlowFailedData : FlowEventData, {\n versioned: true,\n });\n\n/**\n * The `202` body a flow start answers: the flow's id, and where to watch it —\n * its status read and its stream.\n */\nexport const FlowAccepted = Schema.Struct({\n flowId: Schema.String,\n links: Schema.Array(\n Schema.Struct({\n rel: Schema.Literals(['status', 'stream']),\n href: Schema.String,\n }),\n ),\n});\nexport type FlowAccepted = typeof FlowAccepted.Type;\n\nregisterMessage('flowAccepted', FlowAccepted);\n\n/**\n * The body a flow's `status` link answers: where the flow stands, and why it\n * failed when it did. A browser reads it to settle a write whose outcome it\n * did not hear pushed; a `404` from that link means the flow is not projected\n * yet, never that it failed.\n */\nexport const FlowStatusBody = Schema.Struct({\n flowId: Schema.String,\n state: Schema.Literals([\n 'running',\n 'waiting',\n 'suspended',\n 'completed',\n 'compensated',\n 'failed',\n 'interrupted',\n ]),\n step: Schema.optionalKey(Schema.String),\n failure: Schema.optionalKey(FlowFailure),\n});\nexport type FlowStatusBody = typeof FlowStatusBody.Type;\n\nregisterMessage('flowStatus', FlowStatusBody);\n\nexport interface FlowEventInput {\n readonly name: FlowEventName;\n readonly source: string;\n readonly at: string;\n /** The step this event is about, and its ordinal — the event's version. */\n readonly step: string;\n readonly ordinal: number;\n readonly audience: readonly AudienceEntry[];\n readonly data: FlowEventData;\n}\n\n/**\n * Builds a `flow.*` event: id `<flowId>:<step>` so a redelivered announce is\n * the same message, `correlationId` the flow, the step ordinal as version, and\n * an audience that must not be empty.\n */\nexport const flowEvent = (\n input: FlowEventInput,\n): OutboxEvent<FlowEventData> => ({\n name: input.name,\n id: `${input.data.flowId}:${input.step}`,\n source: input.source,\n at: input.at,\n correlationId: input.data.flowId,\n aggregate: { type: 'flow', id: input.data.flowId },\n version: input.ordinal,\n audience: input.audience,\n data: input.data,\n});\n"],"names":["openStruct","registerEvent","registerMessage","Schema","FLOW_EVENTS","FlowFailure","code","NonEmptyString","category","FlowEventData","Struct","flowId","String","definition","slipVersion","Number","step","optionalKey","outcome","Unknown","failure","FlowFailedData","fields","name","versioned","FlowAccepted","links","Array","rel","Literals","href","FlowStatusBody","state","flowEvent","input","id","data","source","at","correlationId","aggregate","type","version","ordinal","audience"],"mappings":";AAAA,SAEEA,UAAU,EACVC,aAAa,EACbC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAIhC,mDAAmD,GACnD,OAAO,MAAMC,cAAc;IACzB;IACA;IACA;IACA;CACD,CAAU;AAGX,+EAA+E,GAC/E,MAAMC,cAAcL,WAAW;IAC7BM,MAAMH,OAAOI,cAAc;IAC3BC,UAAUL,OAAOI,cAAc;AACjC;AAEA;;;;CAIC,GACD,OAAO,MAAME,gBAAgBN,OAAOO,MAAM,CAAC;IACzCC,QAAQR,OAAOS,MAAM;IACrBC,YAAYV,OAAOS,MAAM;IACzBE,aAAaX,OAAOY,MAAM;I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C;QACjD+B,SAASR,MAAMS,OAAO;QACtBC,UAAUV,MAAMU,QAAQ;QACxBR,MAAMF,MAAME,IAAI;IAClB,CAAA,EAAG"}
@@ -1,5 +1,5 @@
1
1
  import './messages.js';
2
- import { type EntifixConnError, type EntityId, type ProtocolFailure, type TransitionalFailure } from '@entifix/core';
2
+ import { type EntifixFailure, type EntityId, type ProtocolFailure, type StoreFault } from '@entifix/core';
3
3
  import { Context, Effect } from 'effect';
4
4
  import type { TransactionEvent, TransactionState } from './event.js';
5
5
  /**
@@ -31,11 +31,11 @@ export interface TransactionRecord {
31
31
  */
32
32
  export interface TransactionStore {
33
33
  /** Folds an event into the record, creating it on first sight. */
34
- upsertFromEvent(event: TransactionEvent): Effect.Effect<TransactionRecord, EntifixConnError>;
35
- get(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;
34
+ upsertFromEvent(event: TransactionEvent): Effect.Effect<TransactionRecord, StoreFault>;
35
+ get(transactionId: string): Effect.Effect<TransactionRecord | undefined, StoreFault>;
36
36
  /** Non-terminal records not updated within `olderThanMs` — recovery input. */
37
- findStale(olderThanMs: number): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;
38
- markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;
37
+ findStale(olderThanMs: number): Effect.Effect<readonly TransactionRecord[], StoreFault>;
38
+ markStale(transactionId: string): Effect.Effect<void, StoreFault>;
39
39
  /**
40
40
  * How many records sit in each state — the recovery sweep samples it.
41
41
  *
@@ -50,7 +50,7 @@ export interface TransactionStore {
50
50
  * poll discovers — which is what the recovery sweep, whose only action is to
51
51
  * apply that label, otherwise leaves entirely unobservable.
52
52
  */
53
- countByState(): Effect.Effect<Record<TransactionState, number>, EntifixConnError>;
53
+ countByState(): Effect.Effect<Record<TransactionState, number>, StoreFault>;
54
54
  }
55
55
  declare const TransactionStoreTag_base: Context.ServiceClass<TransactionStoreTag, "TransactionStoreTag", TransactionStore>;
56
56
  export declare class TransactionStoreTag extends TransactionStoreTag_base {
@@ -97,7 +97,7 @@ export declare function readTransactionRecordEnvelope(body: unknown): Effect.Eff
97
97
  * `STALE` are terminal.
98
98
  */
99
99
  export interface TransactionStatusReader {
100
- read(transactionId: string): Effect.Effect<TransactionRecord | undefined, TransitionalFailure>;
100
+ read(transactionId: string): Effect.Effect<TransactionRecord | undefined, EntifixFailure>;
101
101
  }
102
102
  declare const TransactionStatusReaderTag_base: Context.ServiceClass<TransactionStatusReaderTag, "TransactionStatusReaderTag", TransactionStatusReader>;
103
103
  export declare class TransactionStatusReaderTag extends TransactionStatusReaderTag_base {
@@ -1 +1 @@
1
- {"version":3,"file":"record.d.ts","sourceRoot":"","sources":["../../src/contracts/record.ts"],"names":[],"mappings":"AACA,OAAO,eAAe,CAAC;AAEvB,OAAO,EAEL,KAAK,gBAAgB,EACrB,KAAK,QAAQ,EACb,KAAK,eAAe,EACpB,KAAK,mBAAmB,EACzB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEzC,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAErE;;;GAGG;AACH,MAAM,WAAW,iBAAiB;IAChC,aAAa,EAAE,MAAM,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,gBAAgB,CAAC;IACxB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,QAAQ,CAAC,EAAE,QAAQ,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;;OAOG;IACH,cAAc,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;;GAGG;AACH,MAAM,WAAW,gBAAgB;IAC/B,kEAAkE;IAClE,eAAe,CACb,KAAK,EAAE,gBAAgB,GACtB,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,gBAAgB,CAAC,CAAC;I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AE7B;;;;;;;;;;GAUG;AACH,MAAM,WAAW,mBAAmB;IAClC,aAAa,EAAE,MAAM,CAAC;IACtB,KAAK,EAAE,gBAAgB,CAAC;CACzB;AAED;;;;;GAKG;AACH,wBAAgB,+BAA+B,CAC7C,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,mBAAmB,EAAE,eAAe,CAAC,CAKrD;AAED;;;;;;GAMG;AACH,wBAAgB,6BAA6B,CAC3C,IAAI,EAAE,OAAO,GACZ,MAAM,CAAC,MAAM,CAAC,iBAAiB,EAAE,eAAe,CAAC,CAKnD;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,uBAAuB;IACtC,IAAI,CACF,aAAa,EAAE,MAAM,GACpB,MAAM,CAAC,MAAM,CAAC,iBAAiB,GAAG,SAAS,EAAE,cAAc,CAAC,CAAC;CACjE;;AAED,qBAAa,0BAA2B,SAAQ,+BAGf;CAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["// Evaluated for its registrations: this reader decodes against them.\nimport './messages.js';\n\nimport {\n decodeEnvelope,\n type EntifixConnError,\n type EntityId,\n type ProtocolFailure,\n type TransitionalFailure,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, EntifixConnError>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixConnError>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], EntifixConnError>;\n markStale(transactionId: string): Effect.Effect<void, EntifixConnError>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<\n Record<TransactionState, number>,\n EntifixConnError\n >;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionAccepted'),\n envelope => envelope.data as TransactionAccepted,\n );\n}\n\n/**\n * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.\n *\n * The body is decoded against `transactionRecord`'s registered schema, so a\n * different message wearing the name — an event, which has a `step` and no\n * `createdAt` — is refused rather than handed back typed and wrong.\n */\nexport function readTransactionRecordEnvelope(\n body: unknown,\n): Effect.Effect<TransactionRecord, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionRecord'),\n envelope => envelope.data as TransactionRecord,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal.\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, TransitionalFailure>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Service<\n TransactionStatusReaderTag,\n TransactionStatusReader\n>()('TransactionStatusReaderTag') {}\n"],"names":["decodeEnvelope","Context","Effect","TransactionStoreTag","Service","readTransactionAcceptedEnvelope","body","map","envelope","data","readTransactionRecordEnvelope","TransactionStatusReaderTag"],"mappings":"AAAA,qEAAqE;AACrE,OAAO,gBAAgB;AAEvB,SACEA,cAAc,QAKT,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAsEzC,OAAO,MAAMC,4BAA4BF,QAAQG,OAAO,GAGpD;AAAwB;AAkB5B;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,wBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,sBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,OAAO,GAG3D;AAA+B"}
1
+ {"version":3,"sources":["../../src/contracts/record.ts"],"sourcesContent":["// Evaluated for its registrations: this reader decodes against them.\nimport './messages.js';\n\nimport {\n decodeEnvelope,\n type EntifixFailure,\n type EntityId,\n type ProtocolFailure,\n type StoreFault,\n} from '@entifix/core';\nimport { Context, Effect } from 'effect';\n\nimport type { TransactionEvent, TransactionState } from './event.js';\n\n/**\n * The the saga tracker's persisted view of a transaction, folded from the\n * events it observes. It is the source of truth a client polls.\n */\nexport interface TransactionRecord {\n transactionId: string;\n entity: string;\n state: TransactionState;\n code?: string;\n entityId?: EntityId;\n error?: string;\n createdAt: string;\n updatedAt: string;\n /**\n * Whose organization this transaction happened in, folded from the event.\n *\n * The `saga` store is control-plane and single-partition — it holds every\n * organization's records by design — so isolation on the read routes has to be\n * this filter. A record written before the member existed carries none and is\n * therefore readable by nobody, which is the direction to fail.\n */\n organizationId?: string;\n}\n\n/**\n * Port the manager tracks transactions through. Implemented over Mongo in the\n * service; framework-free here so the engine/manager stay environment-agnostic.\n */\nexport interface TransactionStore {\n /** Folds an event into the record, creating it on first sight. */\n upsertFromEvent(\n event: TransactionEvent,\n ): Effect.Effect<TransactionRecord, StoreFault>;\n get(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, StoreFault>;\n // There is deliberately no `list`. The `saga` store is control-plane and\n // single-partition, so an unfiltered index is every organization's\n // transactions — which is why there is no `GET /api/transaction` list.\n // Anything that needs a set of records asks for one narrow enough to scope,\n // the way `findStale` does.\n /** Non-terminal records not updated within `olderThanMs` — recovery input. */\n findStale(\n olderThanMs: number,\n ): Effect.Effect<readonly TransactionRecord[], StoreFault>;\n markStale(transactionId: string): Effect.Effect<void, StoreFault>;\n /**\n * How many records sit in each state — the recovery sweep samples it.\n *\n * ⚠️ **This is a count, and is not the `list` above.** It returns no record,\n * no id and no organization, so it does not reopen the list surface removed\n * `GET /api/transaction` for: an unfiltered *listing* of this store is every\n * organization's transactions, while a total of how many are `STALE` is a\n * fleet health number that names nobody. The distinction is the whole reason\n * one is here and the other is refused.\n *\n * It exists so `STALE` is something a dashboard shows rather than something a\n * poll discovers — which is what the recovery sweep, whose only action is to\n * apply that label, otherwise leaves entirely unobservable.\n */\n countByState(): Effect.Effect<Record<TransactionState, number>, StoreFault>;\n}\n\nexport class TransactionStoreTag extends Context.Service<\n TransactionStoreTag,\n TransactionStore\n>()('TransactionStoreTag') {}\n\n/**\n * What a service answers a `202` with: the id to poll, and the state it starts\n * in.\n *\n * ⚠️ **Not a {@link TransactionRecord}, which is why it has its own\n * discriminant.** Nothing has been folded yet — there is no `createdAt`, no\n * entity id, and no code, because the write has not run. Framing it as a record\n * meant the browser's accept-shape assertion was checking a name that the\n * by-id route and the bus payload also answered to, so it asserted nothing it\n * claimed to.\n */\nexport interface TransactionAccepted {\n transactionId: string;\n state: TransactionState;\n}\n\n/**\n * Parses a `202` accept body, for a browser about to start polling.\n *\n * Read for its **shape**, not its contents: it asserts the service really\n * accepted a transaction rather than answering something else with a `2xx`.\n */\nexport function readTransactionAcceptedEnvelope(\n body: unknown,\n): Effect.Effect<TransactionAccepted, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionAccepted'),\n envelope => envelope.data as TransactionAccepted,\n );\n}\n\n/**\n * Parses the tracker's by-id response, which frames a {@link TransactionRecord}.\n *\n * The body is decoded against `transactionRecord`'s registered schema, so a\n * different message wearing the name — an event, which has a `step` and no\n * `createdAt` — is refused rather than handed back typed and wrong.\n */\nexport function readTransactionRecordEnvelope(\n body: unknown,\n): Effect.Effect<TransactionRecord, ProtocolFailure> {\n return Effect.map(\n decodeEnvelope(body, 'transactionRecord'),\n envelope => envelope.data as TransactionRecord,\n );\n}\n\n/**\n * Reads one transaction's record, for a browser reconciling a write it started.\n *\n * ⚠️ **`undefined` means _not tracked yet_, not _failed_.** `accepted` reaches\n * the tracker over the bus, so with the broker down the entity write commits —\n * the outbox is in the same Mongo transaction — while no event is ever\n * published and this answers `404`. That is a write in perfect health, and a\n * caller that rolls back on it un-renders a record that is about to appear, at\n * exactly the moment nobody can tell a UI bug from an outage. Only `FAILED` and\n * `STALE` are terminal.\n */\nexport interface TransactionStatusReader {\n read(\n transactionId: string,\n ): Effect.Effect<TransactionRecord | undefined, EntifixFailure>;\n}\n\nexport class TransactionStatusReaderTag extends Context.Service<\n TransactionStatusReaderTag,\n TransactionStatusReader\n>()('TransactionStatusReaderTag') {}\n"],"names":["decodeEnvelope","Context","Effect","TransactionStoreTag","Service","readTransactionAcceptedEnvelope","body","map","envelope","data","readTransactionRecordEnvelope","TransactionStatusReaderTag"],"mappings":"AAAA,qEAAqE;AACrE,OAAO,gBAAgB;AAEvB,SACEA,cAAc,QAKT,gBAAgB;AACvB,SAASC,OAAO,EAAEC,MAAM,QAAQ,SAAS;AAmEzC,OAAO,MAAMC,4BAA4BF,QAAQG,OAAO,GAGpD;AAAwB;AAkB5B;;;;;CAKC,GACD,OAAO,SAASC,gCACdC,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,wBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAEA;;;;;;CAMC,GACD,OAAO,SAASC,8BACdJ,IAAa;IAEb,OAAOJ,OAAOK,GAAG,CACfP,eAAeM,MAAM,sBACrBE,CAAAA,WAAYA,SAASC,IAAI;AAE7B;AAmBA,OAAO,MAAME,mCAAmCV,QAAQG,OAAO,GAG3D;AAA+B"}
@@ -1 +1 @@
1
- {"version":3,"file":"saga-definition.d.ts","sourceRoot":"","sources":["../../src/contracts/saga-definition.ts"],"names":[],"mappings":"AAEA;;;;;;;;;GASG;AACH,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;AAE5E,mDAAmD;AACnD,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,KAAK,EAAE,SAAS,eAAe,EAAE,CAAC;IAC3C;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;IACxB;;;;;;OAMG;IACH,QAAQ,CAAC,WAAW,CAAC,EAAE,OAAO,CAAC;CAChC;AAMD;;;;;;;;GAQG;AACH,wBAAgB,UAAU,CAAC,UAAU,EAAE,cAAc,GAAG,cAAc,CAoGrE;AAED;;;;;;;GAOG;AACH,eAAO,MAAM,aAAa,GACxB,QAAQ,MAAM,EACd,QAAQ,MAAM,EACd,QAAQ,MAAM,KACb,MAGyC,CAAC"}
@@ -1,8 +1,14 @@
1
- import { EntifixLogicError } from '@entifix/core';
2
- const fail = (definition, detail)=>{
3
- throw new EntifixLogicError(`saga definition '${definition}' is invalid: ${detail}`, undefined, {
4
- definition
5
- });
1
+ /**
2
+ * Richardson's classification, and adopting the vocabulary is most of the answer
3
+ * to "which steps are compensable at all".
4
+ *
5
+ * - `compensatable` — before the point of no return; a failure downstream
6
+ * reverses it.
7
+ * - `pivot` — the point of no return. Once it commits, the saga goes forward.
8
+ * - `retriable` — after the pivot; no compensation exists, so the only path is
9
+ * to retry until it succeeds.
10
+ */ const fail = (definition, detail)=>{
11
+ throw new Error(`saga definition '${definition}' is invalid: ${detail}`);
6
12
  };
7
13
  /**
8
14
  * Validate a definition and return it, or throw.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\".\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and one domain package may not import another — which is exactly the\n * import that has no legal home and the reason a definition is **data** in the\n * first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could.\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and the whole construction collapses back into the class\n * that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * a definition-as-data exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header.\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** The explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type.\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal.\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new EntifixLogicError(\n `saga definition '${definition}' is invalid: ${detail}`,\n undefined,\n { definition },\n );\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning that makes an unrenderable action\n * cell throw at render. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud.\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n //. A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not.\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so the `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["EntifixLogicError","fail","definition","detail","undefined","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AA4KlD,MAAMC,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIH,kBACR,CAAC,iBAAiB,EAAEE,WAAW,cAAc,EAAEC,QAAQ,EACvDC,WACA;QAAEF;IAAW;AAEjB;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASG,WAAWH,UAA0B;IACnD,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAExB,IAAIK,MAAMC,MAAM,KAAK,GAAG;QACtBP,KAAKK,MAAM;IACb;IAEA,MAAMG,OAAO,IAAIC;IACjB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAIE,KAAKG,GAAG,CAACD,KAAKE,EAAE,GAAG;YACrB,wEAAwE;YACxE,iEAAiE;YACjE,gDAAgD;YAChDZ,KAAKK,MAAM,CAAC,wBAAwB,EAAEK,KAAKE,EAAE,CAAC,CAAC,CAAC;QAClD;QACAJ,KAAKK,GAAG,CAACH,KAAKE,EAAE;IAClB;IAEA,8EAA8E;IAC9E,6EAA6E;IAC7E,8EAA8E;IAC9E,4DAA4D;IAC5D,MAAME,SAAS,IAAIL;IACnB,KAAK,MAAMC,QAAQJ,MAAO;QACxB,IAAII,KAAKK,UAAU,KAAKZ,aAAa,CAACW,OAAOH,GAAG,CAACD,KAAKK,UAAU,GAAG;YACjEf,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iBAAiB,EAAEF,KAAKK,UAAU,CA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AC,KAAK,EAAEF,KAAKQ,IAAI,CAAC,8BAA8B,CAAC,GAC/D;oBAEN;oBACA,IAAIR,KAAKQ,IAAI,KAAK,eAAe,CAACO,WAAWC,QAAQ;wBACnD1B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iDAAiD,CAAC,GACjE,mEACA;oBAEN;oBACA;gBACF;QACF;IACF;IAEA,OAAOX;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAM4B,gBAAgB,CAC3BC,QACAC,QACAL,QAEAA,UAAUvB,YACN,GAAG2B,OAAO,CAAC,EAAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
1
+ {"version":3,"sources":["../../src/contracts/saga-definition.ts"],"sourcesContent":["/**\n * Richardson's classification, and adopting the vocabulary is most of the answer\n * to \"which steps are compensable at all\".\n *\n * - `compensatable` — before the point of no return; a failure downstream\n * reverses it.\n * - `pivot` — the point of no return. Once it commits, the saga goes forward.\n * - `retriable` — after the pivot; no compensation exists, so the only path is\n * to retry until it succeeds.\n */\nexport type SagaStepKind = 'compensatable' | 'pivot' | 'retriable';\n\n/** The HTTP verbs a step may be dispatched with. */\nexport type SagaMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\n\n/**\n * One call a step makes, as a template rather than a closure.\n *\n * `path` may carry `{…}` placeholders resolved by field path against the step's\n * recorded outcome — `/api/reservation/{outcome.data.id}`.\n *\n * ⚠️ **A template rather than a callback, and that is the constraint that\n * shaped the whole type.** A callback would have to name the participant's\n * types, and one domain package may not import another — which is exactly the\n * import that has no legal home and the reason a definition is **data** in the\n * first place.\n */\nexport interface SagaCall {\n readonly method: SagaMethod;\n readonly path: string;\n}\n\n/** One step of a flow. */\nexport interface SagaStep {\n /** Unique within the definition; half of the command id `<sagaId>:<stepId>`. */\n readonly id: string;\n /**\n * Which service answers it, as a **configuration key** — never a URI.\n *\n * A URI in a definition is a deployment fact written into a business\n * artifact, and it is what makes a definition untestable and un-relocatable.\n * The same lookup yields the crossing token for that participant, so a\n * definition carries no secret and never could.\n */\n readonly participant: string;\n readonly command: SagaCall;\n /** Required on a `compensatable` step, forbidden on every other kind. */\n readonly compensation?: SagaCall;\n readonly kind: SagaStepKind;\n /**\n * Dispatch one call per element of this step's input, rather than one call.\n *\n * ⚠️ **Cardinality is data, because it has to be.** Checkout reserves once per\n * vendor and how many vendors is known only from the cart, so writing that as\n * N steps would mean generating a definition per request — at which point it\n * is no longer data, and the whole construction collapses back into the class\n * that has no legal home.\n *\n * The consequence carried by {@link SagaStepOutcome}: **the unit of\n * compensation is the call, not the step.** Five lines with three holds taken\n * and the fourth refused must release exactly three.\n */\n readonly fanOut?: boolean;\n /**\n * Fan out over an **earlier step's successful calls** instead of over an\n * input the caller supplied.\n *\n * ⚠️ **Without this a later step cannot address what an earlier one created**,\n * and checkout is the case that proves it. `convert-reservation` needs one\n * call per hold, addressed by the reservation id — which stock-service mints,\n * so the caller cannot know it when it starts the flow. Supplying the ids as\n * input is impossible, and generating a definition per request is the thing\n * a definition-as-data exists to avoid.\n *\n * Each element inherits that call's `organizationId`, so a tenant-plane\n * participant reaches the same tenant it did the first time, and the `path`\n * template resolves against `{outcome.…}` — the same scope a compensation\n * gets, for the same reason: the id being addressed is in the response body.\n *\n * Implies {@link fanOut}. It names a step that must appear **before** this one,\n * and `defineSaga` refuses a forward or self reference at module load.\n */\n readonly fanOutFrom?: string;\n}\n\n/** A flow, as the data a generic engine walks. */\nexport interface SagaDefinition {\n readonly name: string;\n /**\n * What a caller must hold to run this flow, as a `<domain>:<entity>:<action>`\n * string.\n *\n * ⚠️ **On the definition rather than on the route**, so the route that runs a\n * flow stays generic. The alternative was one permission for every saga, which\n * would make \"may run a flow\" a single capability regardless of what the flow\n * does — and checkout writes an order.\n *\n * It is a plain string here rather than authz's `Permission`: this package is\n * T2, and `@entifix/authz` sits above it at T4. The service that\n * mounts the route resolves the string against\n * `SERVICE_CROSSING_PERMISSIONS`, which is where the closed list belongs.\n */\n readonly permission: string;\n readonly steps: readonly SagaStep[];\n}\n\n/** What one dispatched call returned, kept so its compensation can read it. */\nexport interface SagaCallOutcome {\n /** The fan-out element this call was made for; `0` on a single-call step. */\n readonly index: number;\n readonly status: number;\n readonly body: unknown;\n /**\n * The organization this call acted for, carried so its compensation acts on\n * the same one.\n *\n * ⚠️ **Not derivable from the outcome, and its absence is silent.** A\n * tenant-plane participant resolves its storage handle from\n * `x-organization-id`, so a compensation dispatched without it is refused\n * `400` — and the saga strands with every hold still in place while the\n * engine reports it tried. Measured on the live lab: two holds taken, a third\n * line refused, and both releases rejected for a missing header.\n */\n readonly organizationId?: string;\n}\n\n/**\n * What one step is given to work with — one element per call on a `fanOut` step,\n * exactly one otherwise.\n */\nexport interface SagaStepInput {\n /** The body to send. */\n readonly body?: unknown;\n /** The explicit organization, for a tenant-plane participant. */\n readonly organizationId?: string;\n}\n\n/**\n * The inputs each step needs, keyed by step id, supplied by the caller.\n *\n * ⚠️ **Here rather than in the engine**, because the durable instance carries\n * it: a resumed walk is a different process reading this off the store, so the\n * port that persists it may not reach up into the engine to name its type.\n */\nexport type SagaInputs = Readonly<Record<string, readonly SagaStepInput[]>>;\n\n/** Every call one step made, in dispatch order. */\nexport interface SagaStepOutcome {\n readonly stepId: string;\n readonly calls: readonly SagaCallOutcome[];\n /**\n * Why this step stopped, when it did — absent on a step that succeeded.\n *\n * ⚠️ **Without it a resumed walk cannot tell a finished step from a refused\n * one.** `calls` holds what succeeded either way, so the two are\n * indistinguishable on the stored document, and the distinction is what\n * decides whether the pivot committed. Guessing it either compensates behind\n * a capture or walks past a refusal.\n */\n readonly error?: string;\n /**\n * Whether this step's calls have already been given back.\n *\n * ⚠️ **What keeps a resumed unwind from compensating twice.** A second\n * `DELETE` of an order already deleted answers `404`, which the dispatcher\n * classifies as a refusal, which strands a flow that was in fact reversed.\n */\n readonly compensated?: boolean;\n}\n\nconst fail = (definition: string, detail: string): never => {\n throw new Error(`saga definition '${definition}' is invalid: ${detail}`);\n};\n\n/**\n * Validate a definition and return it, or throw.\n *\n * ⚠️ **At load, not at the step.** A fault that only appears on the unlucky path\n * is a fault that ships — the same reasoning that makes an unrenderable action\n * cell throw at render. Every definition is therefore constructed through this\n * function at module scope, and loaded in a spec: a definition that never loads\n * is a definition that never fails.\n */\nexport function defineSaga(definition: SagaDefinition): SagaDefinition {\n const { name, steps } = definition;\n\n if (steps.length === 0) {\n fail(name, 'it declares no steps');\n }\n\n const seen = new Set<string>();\n for (const step of steps) {\n if (seen.has(step.id)) {\n // The command id is `<sagaId>:<stepId>`, so a duplicate id is two steps\n // sharing one idempotency key — the second would be dropped as a\n // redelivery of the first and never run at all.\n fail(name, `two steps share the id '${step.id}'`);\n }\n seen.add(step.id);\n }\n\n // `fanOutFrom` must name a step that has already run, or the outcomes it fans\n // out over do not exist yet. A forward reference would silently produce zero\n // calls — a step that looks like it ran and did nothing, which is exactly how\n // a conversion gets skipped while a saga reports COMPLETED.\n const before = new Set<string>();\n for (const step of steps) {\n if (step.fanOutFrom !== undefined && !before.has(step.fanOutFrom)) {\n fail(\n name,\n `step '${step.id}' fans out from '${step.fanOutFrom}', which is not a ` +\n 'step before it',\n );\n }\n before.add(step.id);\n }\n\n const pivots = steps.filter(step => step.kind === 'pivot');\n if (pivots.length > 1) {\n // A flow with two points of no return is a flow that has not been designed\n // yet, and the engine says so out loud.\n fail(\n name,\n `it declares ${String(pivots.length)} pivots (${pivots\n .map(step => step.id)\n .join(', ')}); a flow has at most one point of no return`,\n );\n }\n\n // ⚠️ **Zero pivots is legal**, and checkout is the case that forced saying so.\n // Payment capture is M4; until it lands every step of checkout reverses. A\n // validator demanding exactly one would push the order write into a role it\n // would have to be removed from later — a wrong answer that passes\n //. A definition with no pivot means the whole saga can be unwound,\n // which is a stronger property than a pivot rather than a missing one.\n const pivot = pivots[0];\n const pivotAt = pivot ? steps.indexOf(pivot) : -1;\n const afterPivot = (index: number) => pivot !== undefined && index > pivotAt;\n\n for (const [index, step] of steps.entries()) {\n switch (step.kind) {\n case 'compensatable': {\n if (afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is compensatable but sits after the pivot ` +\n `'${String(pivot?.id)}', where nothing can be reversed`,\n );\n }\n if (!step.compensation) {\n fail(\n name,\n `step '${step.id}' is compensatable but declares no compensation`,\n );\n }\n break;\n }\n case 'pivot':\n case 'retriable': {\n if (step.compensation) {\n // Not dead code — a *false assurance*. Such a compensation could\n // never run, so writing one says the step is reversible when it is\n // not.\n fail(\n name,\n `step '${step.id}' is ${step.kind} and declares a compensation, ` +\n 'which could never run',\n );\n }\n if (step.kind === 'retriable' && !afterPivot(index)) {\n fail(\n name,\n `step '${step.id}' is retriable but sits before the pivot; a step ` +\n 'that cannot be reversed must not run while the saga can still ' +\n 'be unwound',\n );\n }\n break;\n }\n }\n }\n\n return definition;\n}\n\n/**\n * The command id one call is dispatched under.\n *\n * `<sagaId>:<stepId>` — the shape `transactionEventId` already uses for events,\n * so the `TransactionInbox` serves saga steps with no second dedup store and\n * no second key. A fan-out step appends the element index, because its calls are\n * separate side effects that must each be claimed on their own.\n */\nexport const sagaCommandId = (\n sagaId: string,\n stepId: string,\n index?: number,\n): string =>\n index === undefined\n ? `${sagaId}:${stepId}`\n : `${sagaId}:${stepId}:${String(index)}`;\n"],"names":["fail","definition","detail","Error","defineSaga","name","steps","length","seen","Set","step","has","id","add","before","fanOutFrom","undefined","pivots","filter","kind","String","map","join","pivot","pivotAt","indexOf","afterPivot","index","entries","compensation","sagaCommandId","sagaId","stepId"],"mappings":"AAAA;;;;;;;;;CASC,GAiKD,MAAMA,OAAO,CAACC,YAAoBC;IAChC,MAAM,IAAIC,MAAM,CAAC,iBAAiB,EAAEF,WAAW,cAAc,EAAEC,QAAQ;AACzE;AAEA;;;;;;;;CAQC,GACD,OAAO,SAASE,WAAWH,UAA0B;IACnD,MAAM,EAAEI,IAAI,EAAEC,KAAK,EAAE,GAAGL;IAExB,IAAIK,M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J,UAAUP,aAAaW,QAAQH;IAErE,KAAK,MAAM,CAACG,OAAOjB,KAAK,IAAIJ,MAAMsB,OAAO,GAAI;QAC3C,OAAQlB,KAAKS,IAAI;YACf,KAAK;gBAAiB;oBACpB,IAAIO,WAAWC,QAAQ;wBACrB3B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,4CAA4C,CAAC,GAC5D,CAAC,CAAC,EAAEQ,OAAOG,yBAAAA,MAAOX,EAAE,EAAE,gCAAgC,CAAC;oBAE7D;oBACA,IAAI,CAACF,KAAKmB,YAAY,EAAE;wBACtB7B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,+CAA+C,CAAC;oBAErE;oBACA;gBACF;YACA,KAAK;YACL,KAAK;gBAAa;oBAChB,IAAIF,KAAKmB,YAAY,EAAE;wBACrB,iEAAiE;wBACjE,mEAAmE;wBACnE,OAAO;wBACP7B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,KAAK,EAAEF,KAAKS,IAAI,CAAC,8BAA8B,CAAC,GAC/D;oBAEN;oBACA,IAAIT,KAAKS,IAAI,KAAK,eAAe,CAACO,WAAWC,QAAQ;wBACnD3B,KACEK,MACA,CAAC,MAAM,EAAEK,KAAKE,EAAE,CAAC,iDAAiD,CAAC,GACjE,mEACA;oBAEN;oBACA;gBACF;QACF;IACF;IAEA,OAAOX;AACT;AAEA;;;;;;;CAOC,GACD,OAAO,MAAM6B,gBAAgB,CAC3BC,QACAC,QACAL,QAEAA,UAAUX,YACN,GAAGe,OAAO,CAAC,EAAEC,QAAQ,GACrB,GAAGD,OAAO,CAAC,EAAEC,OAAO,CAAC,EAAEZ,OAAOO,QAAQ,CAAC"}
@@ -1,4 +1,4 @@
1
- import { type EntifixConnError } from '@entifix/core';
1
+ import type { Unavailable } from '@entifix/core';
2
2
  import { Effect, Layer } from 'effect';
3
3
  import type { SagaCall } from '../contracts/saga-definition.js';
4
4
  import { type SagaDispatch, type SagaDispatcher, SagaDispatcherTag, type SagaResponse } from '../ports/saga-dispatcher.js';
@@ -9,11 +9,11 @@ export type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;
9
9
  *
10
10
  * The same contract an HTTP participant keeps: a business refusal is a response
11
11
  * with `ok: false` — the engine compensates on it — and only a failure to reach
12
- * the participant at all is an {@link EntifixConnError}. Key the side effect on
12
+ * the participant at all is an {@link Unavailable}. Key the side effect on
13
13
  * `commandId` (an inbox), because a resumed flow dispatches the same command
14
14
  * again.
15
15
  */
16
- export type LocalSagaParticipant = (request: LocalSagaRequest) => Effect.Effect<SagaResponse, EntifixConnError>;
16
+ export type LocalSagaParticipant = (request: LocalSagaRequest) => Effect.Effect<SagaResponse, Unavailable>;
17
17
  /**
18
18
  * A {@link SagaDispatcher} that calls participants in this process.
19
19
  *
@@ -1 +1 @@
1
- {"version":3,"file":"local-saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/engine/local-saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,gBAAgB,EAAqB,MAAM,eAAe,CAAC;AACzE,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,QAAQ,CAAC;AAEvC,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAChE,OAAO,EACL,KAAK,YAAY,EACjB,KAAK,cAAc,EACnB,iBAAiB,EACjB,KAAK,YAAY,EAClB,MAAM,6BAA6B,CAAC;AAErC,8EAA8E;AAC9E,MAAM,MAAM,gBAAgB,GAAG,IAAI,CAAC,YAAY,EAAE,aAAa,CAAC,CAAC;AAEjE;;;;;;;;GAQG;AACH,MAAM,MAAM,oBAAoB,GAAG,CACjC,OAAO,EAAE,gBAAgB,KACtB,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,gBAAgB,CAAC,CAAC;AAEnD;;;;;;;;;;;;GAYG;AACH,eAAO,MAAM,uBAAuB,GAClC,cAAc,QAAQ,CAAC,MAAM,CAAC,MAAM,EAA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AO,MAAM,UAAU,GACrB,SAAS,gBAAgB,EACzB,MAAM,QAAQ,KACb,OACqE,CAAC"}
@@ -1,5 +1,4 @@
1
1
  import { _ as _object_without_properties_loose } from "@swc/helpers/_/_object_without_properties_loose";
2
- import { EntifixLogicError } from '@entifix/core';
3
2
  import { Effect, Layer } from 'effect';
4
3
  import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
5
4
  /**
@@ -20,10 +19,7 @@ import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
20
19
  "participant"
21
20
  ]);
22
21
  const handle = participants[participant];
23
- return handle === undefined ? Effect.die(new EntifixLogicError(`The saga dispatched to participant "${participant}", which this service registered no local handler for.`, undefined, {
24
- participant,
25
- call: request.call
26
- })) : handle(request);
22
+ return handle === undefined ? Effect.die(new Error(`The saga dispatched to participant "${participant}", which this service registered no local handler for.`)) : handle(request);
27
23
  }
28
24
  });
29
25
  /** Provides {@link SagaDispatcherTag} from local participants. */ export const LocalSagaDispatcherLayer = (participants)=>Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/local-saga-dispatcher.ts"],"sourcesContent":["import { type EntifixConnError, EntifixLogicError } from '@entifix/core';\nimport { Effect, Layer } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\nimport {\n type SagaDispatch,\n type SagaDispatcher,\n SagaDispatcherTag,\n type SagaResponse,\n} from '../ports/saga-dispatcher.js';\n\n/** What a local participant is handed: the dispatch, minus whom it is for. */\nexport type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;\n\n/**\n * One participant answered in-process.\n *\n * The same contract an HTTP participant keeps: a business refusal is a response\n * with `ok: false` — the engine compensates on it — and only a failure to reach\n * the participant at all is an {@link EntifixConnError}. Key the side effect on\n * `commandId` (an inbox), because a resumed flow dispatches the same command\n * again.\n */\nexport type LocalSagaParticipant = (\n request: LocalSagaRequest,\n) => Effect.Effect<SagaResponse, EntifixConnError>;\n\n/**\n * A {@link SagaDispatcher} that calls participants in this process.\n *\n * The saga engine never does HTTP itself: a step is a `{ method, path }` handed\n * to the dispatcher port. So a flow whose every step belongs to one service needs\n * no transport, no crossing token and no second process — only this, with each\n * participant name mapped to the Effect that performs its commands. A handler\n * that serves several commands routes on `request.call`.\n *\n * ⚠️ A participant the definition names and this map lacks is a **defect**, not\n * a failed step: it is a wiring mistake the flow cannot recover from, and\n * reporting it as a refusal would compensate a flow for a bug.\n */\nexport const makeLocalSagaDispatcher = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): SagaDispatcher => ({\n dispatch: ({ participant, ...request }) => {\n const handle = participants[participant];\n return handle === undefined\n ? Effect.die(\n new EntifixLogicError(\n `The saga dispatched to participant \"${participant}\", which this service registered no local handler for.`,\n undefined,\n { participant, call: request.call },\n ),\n )\n : handle(request);\n },\n});\n\n/** Provides {@link SagaDispatcherTag} from local participants. */\nexport const LocalSagaDispatcherLayer = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): Layer.Layer<SagaDispatcherTag> =>\n Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));\n\n/** True when a request is the given command, for a participant routing on it. */\nexport const isSagaCall = (\n request: LocalSagaRequest,\n call: SagaCall,\n): boolean =>\n request.call.method === call.method && request.call.path === call.path;\n"],"names":["EntifixLogicError","Effect","Layer","SagaDispatcherTag","makeLocalSagaDispatcher","participants","dispatch","participant","request","handle","undefined","die","call","LocalSagaDispatcherLayer","succeed","isSagaCall","method","path"],"mappings":";AAAA,SAAgCA,iBAAiB,QAAQ,gBAAgB;AACzE,SAASC,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGvC,SAGEC,iBAAiB,QAEZ,8BAA8B;AAkBrC;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,eACoB,CAAA;QACpBC,UAAU;gBAAC,EAAEC,WAAW,EAAc,OAATC;;;YAC3B,MAAMC,SAASJ,YAAY,CAACE,YAAY;YACxC,OAAOE,WAAWC,YACdT,OAAOU,GAAG,CACR,IAAIX,kBACF,CAAC,oCAAoC,EAAEO,YAAY,sDAAsD,CAAC,EAC1GG,WACA;gBAAEH;gBAAaK,MAAMJ,QAAQI,IAAI;YAAC,MAGtCH,OAAOD;QACb;IACF,CAAA,EAAG;AAEH,gEAAgE,GAChE,OAAO,MAAMK,2BAA2B,CACtCR,eAEAH,MAAMY,OAAO,CAACX,mBAAmBC,wBAAwBC,eAAe;AAE1E,+EAA+E,GAC/E,OAAO,MAAMU,aAAa,CACxBP,SACAI,OAEAJ,QAAQI,IAAI,CAACI,MAAM,KAAKJ,KAAKI,MAAM,IAAIR,QAAQI,IAAI,CAACK,IAAI,KAAKL,KAAKK,IAAI,CAAC"}
1
+ {"version":3,"sources":["../../src/engine/local-saga-dispatcher.ts"],"sourcesContent":["import type { Unavailable } from '@entifix/core';\nimport { Effect, Layer } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\nimport {\n type SagaDispatch,\n type SagaDispatcher,\n SagaDispatcherTag,\n type SagaResponse,\n} from '../ports/saga-dispatcher.js';\n\n/** What a local participant is handed: the dispatch, minus whom it is for. */\nexport type LocalSagaRequest = Omit<SagaDispatch, 'participant'>;\n\n/**\n * One participant answered in-process.\n *\n * The same contract an HTTP participant keeps: a business refusal is a response\n * with `ok: false` — the engine compensates on it — and only a failure to reach\n * the participant at all is an {@link Unavailable}. Key the side effect on\n * `commandId` (an inbox), because a resumed flow dispatches the same command\n * again.\n */\nexport type LocalSagaParticipant = (\n request: LocalSagaRequest,\n) => Effect.Effect<SagaResponse, Unavailable>;\n\n/**\n * A {@link SagaDispatcher} that calls participants in this process.\n *\n * The saga engine never does HTTP itself: a step is a `{ method, path }` handed\n * to the dispatcher port. So a flow whose every step belongs to one service needs\n * no transport, no crossing token and no second process — only this, with each\n * participant name mapped to the Effect that performs its commands. A handler\n * that serves several commands routes on `request.call`.\n *\n * ⚠️ A participant the definition names and this map lacks is a **defect**, not\n * a failed step: it is a wiring mistake the flow cannot recover from, and\n * reporting it as a refusal would compensate a flow for a bug.\n */\nexport const makeLocalSagaDispatcher = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): SagaDispatcher => ({\n dispatch: ({ participant, ...request }) => {\n const handle = participants[participant];\n return handle === undefined\n ? Effect.die(\n new Error(\n `The saga dispatched to participant \"${participant}\", which this service registered no local handler for.`,\n ),\n )\n : handle(request);\n },\n});\n\n/** Provides {@link SagaDispatcherTag} from local participants. */\nexport const LocalSagaDispatcherLayer = (\n participants: Readonly<Record<string, LocalSagaParticipant>>,\n): Layer.Layer<SagaDispatcherTag> =>\n Layer.succeed(SagaDispatcherTag, makeLocalSagaDispatcher(participants));\n\n/** True when a request is the given command, for a participant routing on it. */\nexport const isSagaCall = (\n request: LocalSagaRequest,\n call: SagaCall,\n): boolean =>\n request.call.method === call.method && request.call.path === call.path;\n"],"names":["Effect","Layer","SagaDispatcherTag","makeLocalSagaDispatcher","participants","dispatch","participant","request","handle","undefined","die","Error","LocalSagaDispatcherLayer","succeed","isSagaCall","call","method","path"],"mappings":";AACA,SAASA,MAAM,EAAEC,KAAK,QAAQ,SAAS;AAGvC,SAGEC,iBAAiB,QAEZ,8BAA8B;AAkBrC;;;;;;;;;;;;CAYC,GACD,OAAO,MAAMC,0BAA0B,CACrCC,eACoB,CAAA;QACpBC,UAAU;gBAAC,EAAEC,WAAW,EAAc,OAATC;;;YAC3B,MAAMC,SAASJ,YAAY,CAACE,YAAY;YACxC,OAAOE,WAAWC,YACdT,OAAOU,GAAG,CACR,IAAIC,MACF,CAAC,oCAAoC,EAAEL,YAAY,sDAAsD,CAAC,KAG9GE,OAAOD;QACb;IACF,CAAA,EAAG;AAEH,gEAAgE,GAChE,OAAO,MAAMK,2BAA2B,CACtCR,eAEAH,MAAMY,OAAO,CAACX,mBAAmBC,wBAAwBC,eAAe;AAE1E,+EAA+E,GAC/E,OAAO,MAAMU,aAAa,CACxBP,SACAQ,OAEAR,QAAQQ,IAAI,CAACC,MAAM,KAAKD,KAAKC,MAAM,IAAIT,QAAQQ,IAAI,CAACE,IAAI,KAAKF,KAAKE,IAAI,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"resolve-template.d.ts","sourceRoot":"","sources":["../../src/engine/resolve-template.ts"],"names":[],"mappings":"AAgBA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,MAAM,CAYR;AAKD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,OAAO,CAyCT"}
1
+ {"version":3,"file":"resolve-template.d.ts","sourceRoot":"","sources":["../../src/engine/resolve-template.ts"],"names":[],"mappings":"AAcA;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,MAAM,EAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,MAAM,CAUR;AAKD;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAgB,mBAAmB,CACjC,KAAK,EAAE,OAAO,EACd,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAC7B,OAAO,CAqCT"}
@@ -1,4 +1,3 @@
1
- import { EntifixLogicError } from '@entifix/core';
2
1
  /** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */ const PLACEHOLDER = /\{([^{}]+)\}/g;
3
2
  const readPath = (root, path)=>{
4
3
  let value = root;
@@ -29,10 +28,7 @@ const readPath = (root, path)=>{
29
28
  return template.replaceAll(PLACEHOLDER, (_match, path)=>{
30
29
  const value = readPath(scope, path);
31
30
  if (value === undefined || value === null) {
32
- throw new EntifixLogicError(`saga path template '${template}' has no value for '{${path}}'`, undefined, {
33
- template,
34
- path
35
- });
31
+ throw new Error(`saga path template '${template}' has no value for '{${path}}'`);
36
32
  }
37
33
  return encodeURIComponent(String(value));
38
34
  });
@@ -72,20 +68,14 @@ const readPath = (root, path)=>{
72
68
  if ((whole == null ? void 0 : whole[1]) !== undefined) {
73
69
  const resolved = readPath(scope, whole[1]);
74
70
  if (resolved === undefined || resolved === null) {
75
- throw new EntifixLogicError(`saga body template '${value}' has no value for '{${whole[1]}}'`, undefined, {
76
- template: value,
77
- path: whole[1]
78
- });
71
+ throw new Error(`saga body template '${value}' has no value for '{${whole[1]}}'`);
79
72
  }
80
73
  return resolved;
81
74
  }
82
75
  return value.replaceAll(PLACEHOLDER, (_match, path)=>{
83
76
  const resolved = readPath(scope, path);
84
77
  if (resolved === undefined || resolved === null) {
85
- throw new EntifixLogicError(`saga body template '${value}' has no value for '{${path}}'`, undefined, {
86
- template: value,
87
- path
88
- });
78
+ throw new Error(`saga body template '${value}' has no value for '{${path}}'`);
89
79
  }
90
80
  return String(resolved);
91
81
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/resolve-template.ts"],"sourcesContent":["import { EntifixLogicError } from '@entifix/core';\n\n/** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */\nconst PLACEHOLDER = /\\{([^{}]+)\\}/g;\n\nconst readPath = (root: unknown, path: string): unknown => {\n let value = root;\n for (const segment of path.split('.')) {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n};\n\n/**\n * Resolve a path template against a scope.\n *\n * `/api/reservation/{outcome.data.id}` with\n * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.\n *\n * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**\n * The failure this prevents is specific and silent: a compensation whose\n * template no longer matches its participant's response shape would otherwise\n * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a\n * compensation that ran — leaving the hold in place and the saga reporting that\n * it was reversed. That is the \"failed and stranded\" state nobody plans for, arrived at by string interpolation.\n *\n * Values are URI-encoded: a participant's id is data, and a path segment is not\n * the place to discover it contained a slash.\n */\nexport function resolveTemplate(\n template: string,\n scope: Record<string, unknown>,\n): string {\n return template.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const value = readPath(scope, path);\n if (value === undefined || value === null) {\n throw new EntifixLogicError(\n `saga path template '${template}' has no value for '{${path}}'`,\n undefined,\n { template, path },\n );\n }\n return encodeURIComponent(String(value));\n });\n}\n\n/** A string that is nothing but one placeholder, so its type can be preserved. */\nconst WHOLE_PLACEHOLDER = /^\\{([^{}]+)\\}$/;\n\n/**\n * Resolve the placeholders inside a **request body**, recursively.\n *\n * ⚠️ **Why a body needs this at all.** A step's payload can depend on what an\n * earlier step created: checkout's capture has to name the order that was just\n * written, and the order id is minted by order-service — so a caller cannot put\n * it in the body it sends when it starts the flow. Without this, the capture\n * carries a placeholder string and the order it names never advances, which is\n * precisely the defect measured on the live lab: a saga reporting `COMPLETED`\n * with a payment attached to nothing.\n *\n * ⚠️ **The template lives in the caller's `inputs`, never in the definition.**\n * That is a constraint, not an accident: a definition that carried\n * domain payloads would be importing the shape of another domain's entity, which\n * is the class of thing that has no legal home. The definition stays a list of\n * verbs and addresses; what to send is the caller's, and this only lets the\n * caller point at a value it could not have known yet.\n *\n * Two behaviours, and the difference is load-bearing:\n *\n * - A string that is **exactly** one placeholder resolves to the raw value, so\n * a number stays a number and an object stays an object. `\"{steps.x.data.qty}\"`\n * becoming the string `\"3\"` would reach a validator expecting a number.\n * - A string that merely **contains** placeholders is interpolated textually,\n * and — unlike {@link resolveTemplate} — **not** URI-encoded. A body is JSON,\n * not a path segment; encoding here would put `%20` in a customer's name.\n *\n * An unresolved placeholder throws, for the same reason it does in a path.\n */\nexport function resolveBodyTemplate(\n value: unknown,\n scope: Record<string, unknown>,\n): unknown {\n if (typeof value === 'string') {\n const whole = WHOLE_PLACEHOLDER.exec(value);\n if (whole?.[1] !== undefined) {\n const resolved = readPath(scope, whole[1]);\n if (resolved === undefined || resolved === null) {\n throw new EntifixLogicError(\n `saga body template '${value}' has no value for '{${whole[1]}}'`,\n undefined,\n { template: value, path: whole[1] },\n );\n }\n return resolved;\n }\n return value.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const resolved = readPath(scope, path);\n if (resolved === undefined || resolved === null) {\n throw new EntifixLogicError(\n `saga body template '${value}' has no value for '{${path}}'`,\n undefined,\n { template: value, path },\n );\n }\n return String(resolved);\n });\n }\n\n if (Array.isArray(value)) {\n return value.map(element => resolveBodyTemplate(element, scope));\n }\n\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n resolveBodyTemplate(entry, scope),\n ]),\n );\n }\n\n return value;\n}\n"],"names":["EntifixLogicError","PLACEHOLDER","readPath","root","path","value","segment","split","undefined","resolveTemplate","template","scope","replaceAll","_match","encodeURIComponent","String","WHOLE_PLACEHOLDER","resolveBodyTemplate","whole","exec","resolved","Array","isArray","map","element","Object","fromEntries","entries","key","entry"],"mappings":"AAAA,SAASA,iBAAiB,QAAQ,gBAAgB;AAElD,oEAAoE,GACpE,MAAMC,cAAc;AAEpB,MAAMC,WAAW,CAACC,MAAeC;IAC/B,IAAIC,QAAQF;IACZ,KAAK,MAAMG,WAAWF,KAAKG,KAAK,CAAC,KAAM;QACrC,IAAIF,UAAU,QAAQ,OAAOA,UAAU,UAAU;YAC/C,OAAOG;QACT;QACAH,QAAQ,AAACA,KAAiC,CAACC,QAAQ;IACrD;IACA,OAAOD;AACT;AAEA;;;;;;;;;;;;;;;CAeC,GACD,OAAO,SAASI,gBACdC,QAAgB,EAChBC,KAA8B;IAE9B,OAAOD,SAASE,UAAU,CAACX,aAAa,CAACY,QAAQT;QAC/C,MAAMC,QAAQH,SAASS,OAAOP;QAC9B,IAAIC,UAAUG,aAAaH,UAAU,MAAM;YACzC,MAAM,IAAIL,kBACR,CAAC,oBAAoB,EAAEU,SAAS,qB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,GAAK;gBACrED;gBACAX,oBAAoBY,OAAOlB;aAC5B;IAEL;IAEA,OAAON;AACT"}
1
+ {"version":3,"sources":["../../src/engine/resolve-template.ts"],"sourcesContent":["/** The `{a.b.c}` placeholders a {@link SagaCall}'s path may carry. */\nconst PLACEHOLDER = /\\{([^{}]+)\\}/g;\n\nconst readPath = (root: unknown, path: string): unknown => {\n let value = root;\n for (const segment of path.split('.')) {\n if (value === null || typeof value !== 'object') {\n return undefined;\n }\n value = (value as Record<string, unknown>)[segment];\n }\n return value;\n};\n\n/**\n * Resolve a path template against a scope.\n *\n * `/api/reservation/{outcome.data.id}` with\n * `{ outcome: { data: { id: 'r-1' } } }` becomes `/api/reservation/r-1`.\n *\n * ⚠️ **An unresolved placeholder throws rather than interpolating `undefined`.**\n * The failure this prevents is specific and silent: a compensation whose\n * template no longer matches its participant's response shape would otherwise\n * `DELETE /api/reservation/undefined`, get a `404`, and be recorded as a\n * compensation that ran — leaving the hold in place and the saga reporting that\n * it was reversed. That is the \"failed and stranded\" state nobody plans for, arrived at by string interpolation.\n *\n * Values are URI-encoded: a participant's id is data, and a path segment is not\n * the place to discover it contained a slash.\n */\nexport function resolveTemplate(\n template: string,\n scope: Record<string, unknown>,\n): string {\n return template.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const value = readPath(scope, path);\n if (value === undefined || value === null) {\n throw new Error(\n `saga path template '${template}' has no value for '{${path}}'`,\n );\n }\n return encodeURIComponent(String(value));\n });\n}\n\n/** A string that is nothing but one placeholder, so its type can be preserved. */\nconst WHOLE_PLACEHOLDER = /^\\{([^{}]+)\\}$/;\n\n/**\n * Resolve the placeholders inside a **request body**, recursively.\n *\n * ⚠️ **Why a body needs this at all.** A step's payload can depend on what an\n * earlier step created: checkout's capture has to name the order that was just\n * written, and the order id is minted by order-service — so a caller cannot put\n * it in the body it sends when it starts the flow. Without this, the capture\n * carries a placeholder string and the order it names never advances, which is\n * precisely the defect measured on the live lab: a saga reporting `COMPLETED`\n * with a payment attached to nothing.\n *\n * ⚠️ **The template lives in the caller's `inputs`, never in the definition.**\n * That is a constraint, not an accident: a definition that carried\n * domain payloads would be importing the shape of another domain's entity, which\n * is the class of thing that has no legal home. The definition stays a list of\n * verbs and addresses; what to send is the caller's, and this only lets the\n * caller point at a value it could not have known yet.\n *\n * Two behaviours, and the difference is load-bearing:\n *\n * - A string that is **exactly** one placeholder resolves to the raw value, so\n * a number stays a number and an object stays an object. `\"{steps.x.data.qty}\"`\n * becoming the string `\"3\"` would reach a validator expecting a number.\n * - A string that merely **contains** placeholders is interpolated textually,\n * and — unlike {@link resolveTemplate} — **not** URI-encoded. A body is JSON,\n * not a path segment; encoding here would put `%20` in a customer's name.\n *\n * An unresolved placeholder throws, for the same reason it does in a path.\n */\nexport function resolveBodyTemplate(\n value: unknown,\n scope: Record<string, unknown>,\n): unknown {\n if (typeof value === 'string') {\n const whole = WHOLE_PLACEHOLDER.exec(value);\n if (whole?.[1] !== undefined) {\n const resolved = readPath(scope, whole[1]);\n if (resolved === undefined || resolved === null) {\n throw new Error(\n `saga body template '${value}' has no value for '{${whole[1]}}'`,\n );\n }\n return resolved;\n }\n return value.replaceAll(PLACEHOLDER, (_match, path: string) => {\n const resolved = readPath(scope, path);\n if (resolved === undefined || resolved === null) {\n throw new Error(\n `saga body template '${value}' has no value for '{${path}}'`,\n );\n }\n return String(resolved);\n });\n }\n\n if (Array.isArray(value)) {\n return value.map(element => resolveBodyTemplate(element, scope));\n }\n\n if (value !== null && typeof value === 'object') {\n return Object.fromEntries(\n Object.entries(value as Record<string, unknown>).map(([key, entry]) => [\n key,\n resolveBodyTemplate(entry, scope),\n ]),\n );\n }\n\n return value;\n}\n"],"names":["PLACEHOLDER","readPath","root","path","value","segment","split","undefined","resolveTemplate","template","scope","replaceAll","_match","Error","encodeURIComponent","String","WHOLE_PLACEHOLDER","resolveBodyTemplate","whole","exec","resolved","Array","isArray","map","element","Object","fromEntries","entries","key","entry"],"mappings":"AAAA,oEAAoE,GACpE,MAAMA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AAET,MAAM,qBAAqB,EAAED,KAAK,EAAE,CAAC;YAEhE;YACA,OAAOY,OAAOK;QAChB;IACF;IAEA,IAAIC,MAAMC,OAAO,CAAClB,QAAQ;QACxB,OAAOA,MAAMmB,GAAG,CAACC,CAAAA,UAAWP,oBAAoBO,SAASd;IAC3D;IAEA,IAAIN,UAAU,QAAQ,OAAOA,UAAU,UAAU;QAC/C,OAAOqB,OAAOC,WAAW,CACvBD,OAAOE,OAAO,CAACvB,OAAkCmB,GAAG,CAAC,CAAC,CAACK,KAAKC,MAAM,GAAK;gBACrED;gBACAX,oBAAoBY,OAAOnB;aAC5B;IAEL;IAEA,OAAON;AACT"}
@@ -1,4 +1,4 @@
1
- import type { EntifixConnError, StoreFailure } from '@entifix/core';
1
+ import type { StoreFailure } from '@entifix/core';
2
2
  import { Effect } from 'effect';
3
3
  import { type SagaDefinition, type SagaInputs, type SagaStepInput, type SagaStepOutcome } from '../contracts/saga-definition.js';
4
4
  import { SagaDispatcherTag } from '../ports/saga-dispatcher.js';
@@ -23,7 +23,7 @@ export interface SagaResult {
23
23
  * is durability *behind* that answer: if this process dies mid-walk, the record
24
24
  * it has been writing all along is enough for another one to finish the flow.
25
25
  */
26
- export declare const runSaga: (options: RunSagaOptions) => Effect.Effect<SagaResult, StoreFailure | EntifixConnError, SagaDispatcherTag | SagaStoreTag>;
26
+ export declare const runSaga: (options: RunSagaOptions) => Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag | SagaStoreTag>;
27
27
  export interface ResumeSagaOptions {
28
28
  readonly instance: SagaInstance;
29
29
  readonly definition: SagaDefinition;
@@ -50,5 +50,5 @@ export interface ResumeSagaOptions {
50
50
  * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the
51
51
  * unwind**, skipping steps already marked `compensated`.
52
52
  */
53
- export declare const resumeSaga: (options: ResumeSagaOptions) => Effect.Effect<SagaResult, StoreFailure | EntifixConnError, SagaDispatcherTag | SagaStoreTag>;
53
+ export declare const resumeSaga: (options: ResumeSagaOptions) => Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag | SagaStoreTag>;
54
54
  //# sourceMappingURL=run-saga.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"run-saga.d.ts","sourceRoot":"","sources":["../../src/engine/run-saga.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,YAAY,EAAE,MAAM,eAAe,CAAC;AACpE,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EAIL,KAAK,cAAc,EACnB,KAAK,UAAU,EAEf,KAAK,aAAa,EAClB,KAAK,eAAe,EACrB,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,6BAA6B,CAAC;AAChE,OAAO,EACL,KAAK,YAAY,EAEjB,YAAY,EACb,MAAM,wBAAwB,CAAC;AAGhC,YAAY,EAAE,UAAU,EAAE,aAAa,EAAE,CAAC;AAa1C,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,UAAU,CAAC;CAC7B;AAED,uBAAuB;AACvB,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,KAAK,EAAE,WAAW,GAAG,aAAa,GAAG,UAAU,CAAC;IACzD,QAAQ,CAAC,QAAQ,EAAE,SAAS,eAAe,EAAE,CAAC;IAC9C,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAC;CACzB;AA8eD;;;;;;;GAOG;AACH,eAAO,MAAM,OAAO,GAClB,SAAS,cAAc,KACtB,MAAM,CAAC,MAAM,CACd,UAAU,EACV,YAAY,GAAG,gBAAgB,EAC/B,iBAAiB,GAAG,YAAY,CAoB9B,CAAC;AAEL,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE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AG,YAAY,CAmBvE,CAAC;AAEL,MAAM,WAAW,iBAAiB;IAChC,QAAQ,CAAC,QAAQ,EAAE,YAAY,CAAC;IAChC,QAAQ,CAAC,UAAU,EAAE,cAAc,CAAC;IACpC,0EAA0E;IAC1E,QAAQ,CAAC,iBAAiB,EAAE,MAAM,CAAC;CACpC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,eAAO,MAAM,UAAU,GACrB,SAAS,iBAAiB,KACzB,MAAM,CAAC,MAAM,CAAC,UAAU,EAAE,YAAY,EAAE,iBAAiB,GAAG,YAAY,CA6FvE,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { EntifixConnError, StoreFailure } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken.\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly — the same failure a conversion route that refuses a\n // redelivery has, from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: the alternative makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. That is a requirement on every participant a saga may\n * retry; this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // it is the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted — the outbox's rule, extended\n * from events to commands.\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length.\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated.\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<\n SagaResult,\n StoreFailure | EntifixConnError,\n SagaDispatcherTag | SagaStoreTag\n> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"mappings":";AACA,SAASA,MAAM,QAAQ,SAAS;AAEhC,SAGEC,aAAa,QAMR,kCAAkC;AACzC,SAASC,iBAAiB,QAAQ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,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS;YAChC;QACF;QAEA,IAAIU,SAAS9F,OAAO,CAACgC,KAAK,KAAKxB,WAAW;YACxC,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS,GAAG;YACnC;QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
1
+ {"version":3,"sources":["../../src/engine/run-saga.ts"],"sourcesContent":["import type { StoreFailure, Unavailable } from '@entifix/core';\nimport { Effect } from 'effect';\n\nimport {\n type SagaCall,\n type SagaCallOutcome,\n sagaCommandId,\n type SagaDefinition,\n type SagaInputs,\n type SagaStep,\n type SagaStepInput,\n type SagaStepOutcome,\n} from '../contracts/saga-definition.js';\nimport { SagaDispatcherTag } from '../ports/saga-dispatcher.js';\nimport {\n type SagaInstance,\n type SagaStore,\n SagaStoreTag,\n} from '../ports/saga-store.js';\nimport { resolveBodyTemplate, resolveTemplate } from './resolve-template.js';\n\nexport type { SagaInputs, SagaStepInput };\n\n/**\n * The steps that have run, kept with their outcomes.\n *\n * Paired rather than looked back up by id, because a lookup introduces a\n * not-found branch that cannot happen — and an unreachable branch is a line\n * nothing can ever prove correct. A resumed walk rebuilds this from the stored\n * outcomes, which is the one place the lookup does happen and can genuinely\n * fail.\n */\ntype Taken = Array<{ step: SagaStep; outcome: SagaStepOutcome }>;\n\nexport interface RunSagaOptions {\n readonly sagaId: string;\n readonly definition: SagaDefinition;\n readonly inputs: SagaInputs;\n}\n\n/** How a run ended. */\nexport interface SagaResult {\n readonly state: 'COMPLETED' | 'COMPENSATED' | 'STRANDED';\n readonly outcomes: readonly SagaStepOutcome[];\n readonly error?: string;\n}\n\n/**\n * What one element of a `fanOutFrom` step is dispatched with.\n *\n * The earlier call's body travels as `outcome` rather than `input`, which is the\n * same scope a compensation resolves against and for the same reason: the id\n * being addressed was minted by the participant and is in its response.\n */\ninterface DerivedElement {\n readonly input: SagaStepInput;\n readonly scope: Record<string, unknown>;\n}\n\nconst inputsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n): readonly SagaStepInput[] => {\n const declared = inputs[step.id] ?? [];\n // A non-fan-out step makes exactly one call whether or not it was given an\n // input, so an absent entry is an empty body rather than a skipped step.\n return step.fanOut ? declared : [declared[0] ?? {}];\n};\n\n/**\n * The elements a step actually dispatches: derived from an earlier step's\n * successful calls when it declares `fanOutFrom`, and from the caller's input\n * otherwise.\n *\n * ⚠️ **A `fanOutFrom` step ignores whatever the caller supplied for it.** The\n * cardinality is the earlier step's, and taking the caller's would let a\n * checkout convert a hold it never took — or, more likely, silently convert\n * none, which is how a saga reports COMPLETED with the goods still held.\n */\n/**\n * What every step can point at: the **first successful call** of each step that\n * has already run, by step id.\n *\n * First rather than all, because a template naming a fan-out step is ambiguous\n * by construction — \"the order id\" is one value and \"the reservation ids\" are\n * many, and the many case is what `fanOutFrom` exists for. Keeping this to the\n * unambiguous case is what stops `{steps.reserve.data.id}` quietly meaning\n * \"whichever hold happened to be first\".\n */\nconst stepsScope = (\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): Record<string, unknown> =>\n Object.fromEntries(\n taken\n .filter(entry => entry.outcome.calls.length > 0)\n .map(entry => [entry.step.id, entry.outcome.calls[0]?.body]),\n );\n\nconst elementsFor = (\n step: SagaStep,\n inputs: SagaInputs,\n taken: ReadonlyArray<{ step: SagaStep; outcome: SagaStepOutcome }>,\n): readonly DerivedElement[] => {\n const steps = stepsScope(taken);\n\n if (step.fanOutFrom === undefined) {\n return inputsFor(step, inputs).map(input => ({\n input,\n scope: { input: input.body, steps },\n }));\n }\n\n const source = taken.find(entry => entry.step.id === step.fanOutFrom);\n const body = inputs[step.id]?.[0]?.body;\n\n return (source?.outcome.calls ?? []).map(call => ({\n // ⚠️ The organization the *earlier call* acted for, never the caller's.\n // A tenant-plane participant resolves its handle from the header, so a\n // conversion dispatched without it is refused `400` and the hold expires\n // under a buyer who has already been charged.\n input: { body, organizationId: call.organizationId },\n scope: { outcome: call.body, input: body, steps },\n }));\n};\n\nconst dispatchCall = (\n step: SagaStep,\n call: SagaCall,\n sagaId: string,\n index: number,\n input: SagaStepInput,\n scope: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n const dispatcher = yield* SagaDispatcherTag;\n return yield* dispatcher.dispatch({\n participant: step.participant,\n call: { method: call.method, path: resolveTemplate(call.path, scope) },\n commandId: sagaCommandId(\n sagaId,\n step.id,\n step.fanOut ? index : undefined,\n ),\n organizationId: input.organizationId,\n body:\n call.method === 'GET' || call.method === 'DELETE'\n ? undefined\n : resolveBodyTemplate(input.body, scope),\n });\n });\n\n/**\n * Run one step: every call it makes, in order, stopping at the first refusal.\n *\n * Returns the calls that **succeeded** alongside the failure, because those are\n * exactly the calls a compensation has to undo — see {@link compensateStep}.\n */\nconst runStep = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n Unavailable,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n const calls: SagaCallOutcome[] = [];\n\n for (const [index, element] of elements.entries()) {\n const { input } = element;\n const response = yield* dispatchCall(\n step,\n step.command,\n sagaId,\n index,\n input,\n element.scope,\n );\n\n if (!response.ok) {\n // A business refusal. The saga fails *forward* into compensation, and\n // the calls already recorded are the ones that have to come back.\n return {\n calls,\n error: `step '${step.id}' call ${String(index)} refused with ${String(\n response.status,\n )}`,\n };\n }\n\n calls.push({\n index,\n status: response.status,\n body: response.body,\n // Carried so the compensation reaches the same tenant. Without it a\n // release is refused `400` and the saga strands holding stock.\n organizationId: input.organizationId,\n });\n }\n\n return { calls };\n });\n\n/**\n * Undo one step — **one compensation per successful call**, never one per step.\n *\n * ⚠️ This is the whole reason an outcome is kept per fan-out element. Five lines\n * with three holds taken and the fourth refused must release exactly three:\n * compensating the step as a unit would either release nothing or attempt to\n * release two holds that were never taken.\n *\n * Never fails: a compensation's own failure is reported by the caller and must\n * not stop the compensations after it, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst compensateStep = (\n step: SagaStep,\n sagaId: string,\n outcome: SagaStepOutcome,\n): Effect.Effect<readonly string[], never, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const compensation = step.compensation;\n if (!compensation) {\n return [];\n }\n\n const failures: string[] = [];\n // Reverse order: the last thing done is the first thing undone, which is\n // what a reader expects of a stack of effects and what keeps a future\n // ordering dependency from being an accident.\n for (const call of [...outcome.calls].reverse()) {\n const result = yield* dispatchCall(\n step,\n compensation,\n sagaId,\n call.index,\n // ⚠️ The organization the *call* acted for, not an empty input. A\n // tenant-plane participant resolves its handle from the header, so a\n // compensation without it is refused before it reaches the hold.\n { organizationId: call.organizationId },\n { outcome: call.body },\n ).pipe(\n Effect.catch(error =>\n Effect.succeed({ ok: false, status: 0, body: error }),\n ),\n // A template that no longer matches the participant's response shape\n // throws rather than interpolating `undefined`; that is a defect, and\n // it is reported as a stranded compensation rather than crashing the\n // walk and leaving every later hold in place.\n Effect.catchDefect(defect =>\n Effect.succeed({ ok: false, status: 0, body: defect }),\n ),\n );\n\n // ⚠️ **A `404` is a compensation that has nothing left to undo**, and it\n // counts as success. Compensation is at-least-once the moment a resumed\n // coordinator can retry it, and a participant answering \"no such record\"\n // on the second delivery is describing a flow that *was* reversed. Left\n // as a refusal it strands exactly the sagas that were cleaned up\n // correctly — the same failure a conversion route that refuses a\n // redelivery has, from the other side.\n if (!result.ok && result.status !== 404) {\n failures.push(\n `compensation for '${step.id}' call ${String(call.index)} failed: ${String(\n result.body,\n )}`,\n );\n }\n }\n\n return failures;\n });\n\n/**\n * How many extra times a step is dispatched once the pivot has committed.\n *\n * Small and immediate on purpose. This is the in-process half of \"roll forward\",\n * and it exists to ride out the blip — a participant restarting, a connection\n * reset — not to be a retry policy. A step that is still refusing after these\n * strands the saga, loudly, because the alternative is a coordinator spinning on\n * a permanent failure while a customer's money sits captured.\n *\n * Durable retry across a coordinator restart is a different mechanism and is not\n * built: the alternative makes a step dispatch an outbox entry whose relay\n * performs the POST.\n */\nconst POST_PIVOT_RETRIES = 3;\n\n/**\n * Dispatch a step, retrying it `retries` more times while it refuses.\n *\n * ⚠️ **A retry re-dispatches the calls that already succeeded**, and that is\n * safe for exactly one reason: `sagaCommandId(sagaId, step.id, index)` is stable\n * across attempts, so a participant that is idempotent on the command id\n * recognises the replay. That is a requirement on every participant a saga may\n * retry; this is the code that depends on it.\n */\nconst runStepWithRetries = (\n step: SagaStep,\n sagaId: string,\n elements: readonly DerivedElement[],\n retries: number,\n): Effect.Effect<\n { readonly calls: readonly SagaCallOutcome[]; readonly error?: string },\n Unavailable,\n SagaDispatcherTag\n> =>\n Effect.gen(function* () {\n let result = yield* runStep(step, sagaId, elements);\n\n for (\n let attempt = 1;\n attempt <= retries && result.error !== undefined;\n attempt += 1\n ) {\n yield* Effect.logWarning('retrying a saga step after the pivot').pipe(\n Effect.annotateLogs({\n sagaId,\n stepId: step.id,\n attempt,\n error: result.error,\n }),\n );\n result = yield* runStep(step, sagaId, elements);\n }\n\n return result;\n });\n\n/** Pair each recorded outcome with the step that produced it. */\nconst rebuildTaken = (\n definition: SagaDefinition,\n outcomes: readonly SagaStepOutcome[],\n): Taken | { readonly unknownStep: string } => {\n const taken: Taken = [];\n for (const outcome of outcomes) {\n const step = definition.steps.find(\n candidate => candidate.id === outcome.stepId,\n );\n // ⚠️ Not skipped. An outcome naming a step the definition no longer has\n // means the definition changed under a live instance, so the flow this\n // record describes and the flow the engine would walk are different flows.\n // Carrying on would compensate the wrong steps in the wrong order.\n if (!step) {\n return { unknownStep: outcome.stepId };\n }\n taken.push({ step, outcome });\n }\n return taken;\n};\n\n/** Whether the point of no return is behind us, read off what actually ran. */\nconst pivotCommittedIn = (taken: Taken): boolean =>\n taken.some(\n entry => entry.step.kind === 'pivot' && entry.outcome.error === undefined,\n );\n\n/**\n * Settle a saga that cannot go forward and cannot be reversed, loudly.\n *\n * ⚠️ The message is a parameter because these are **different operational\n * events** and each is grepped for on its own: money is captured behind a\n * pivot, a release was refused and stock is still held, a definition changed\n * under a live instance. Collapsing them into one string would make the log\n * line say only that something is wrong.\n */\nconst strand = (\n store: SagaStore,\n sagaId: string,\n outcomes: readonly SagaStepOutcome[],\n error: string,\n message: string,\n log: Record<string, unknown>,\n) =>\n Effect.gen(function* () {\n yield* Effect.logError(message).pipe(\n Effect.annotateLogs({ sagaId, error, ...log }),\n );\n yield* store.settle(sagaId, 'STRANDED', error);\n return { state: 'STRANDED', outcomes, error } as const;\n });\n\n/**\n * Unwind every compensatable step already taken, newest first.\n *\n * Shared by the in-process walk and by a resumed one, which is the whole reason\n * it is a function: a coordinator that died *while* compensating comes back\n * into exactly this loop, and the steps it already gave back carry\n * `compensated` so they are not given back twice.\n */\nconst unwind = (\n store: SagaStore,\n sagaId: string,\n definition: SagaDefinition,\n taken: Taken,\n error: string,\n): Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const outcomes = taken.map(entry => entry.outcome);\n const failures: string[] = [];\n\n for (const done of [...taken].reverse()) {\n if (done.outcome.compensated === true) {\n continue;\n }\n const stepFailures = yield* compensateStep(\n done.step,\n sagaId,\n done.outcome,\n );\n failures.push(...stepFailures);\n // Marked only when the step came back whole. A partial failure stays\n // unmarked so a later resume retries it — safe because a compensation\n // with nothing left to undo answers `404`, which is a success above.\n if (stepFailures.length === 0) {\n yield* store.markCompensated(sagaId, done.step.id);\n }\n }\n\n if (failures.length > 0) {\n // ⚠️ Surfaced, never swallowed. This is the state that leaves a\n // reservation held and — once payment lands — a customer charged, and\n // it is the failure class nobody plans for.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga compensation failed',\n { definition: definition.name, failures: failures.join('; ') },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATED', error);\n return { state: 'COMPENSATED', outcomes, error };\n });\n\n/**\n * Dispatch the definition's steps from `startIndex` on, and unwind on a refusal.\n *\n * The state transition is persisted **before** each dispatch, so a crash leaves\n * a record that says what was actually attempted — the outbox's rule, extended\n * from events to commands.\n *\n * ⚠️ **Once the pivot has committed, nothing is unwound.** That is what a pivot\n * means, and the walk has to know it rather than the definition merely declaring\n * it: `compensateStep` no-ops on a step that declares no compensation, so an\n * unconditional unwind after a successful capture would skip the pivot in\n * silence and then delete the order behind it and release the holds behind that\n * — money taken, goods back on sale, every probe green. The step is retried\n * instead, and a saga that still cannot go forward is settled `STRANDED` and\n * logged, because a stranded saga nobody is told about is the same as a lost one.\n */\nconst walk = (\n store: SagaStore,\n options: RunSagaOptions,\n from: { readonly taken: Taken; readonly startIndex: number },\n): Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag> =>\n Effect.gen(function* () {\n const { sagaId, definition, inputs } = options;\n // Step and outcome are kept **together**: looking the step back up by id\n // would introduce a not-found branch that cannot happen, and an unreachable\n // branch is a line nothing can ever prove correct.\n const taken = from.taken;\n const outcomes = () => taken.map(entry => entry.outcome);\n\n // The point of no return, once it is behind us. Tracked rather than read off\n // the definition because what matters is not that a pivot exists but that it\n // *committed* — a pivot that refuses is still fully reversible, and is the\n // ordinary compensation case below.\n let pivotCommitted = pivotCommittedIn(taken);\n\n for (\n let index = from.startIndex;\n index < definition.steps.length;\n index++\n ) {\n const step = definition.steps[index];\n /* v8 ignore next 3 -- the loop bound makes this unreachable; it exists\n because `noUncheckedIndexedAccess` cannot see that. */\n if (!step) {\n continue;\n }\n\n yield* store.beginStep(sagaId, index);\n const { calls, error } = yield* runStepWithRetries(\n step,\n sagaId,\n elementsFor(step, inputs, taken),\n pivotCommitted ? POST_PIVOT_RETRIES : 0,\n );\n\n const outcome: SagaStepOutcome = {\n stepId: step.id,\n calls,\n ...(error === undefined ? {} : { error }),\n };\n taken.push({ step, outcome });\n yield* store.recordOutcome(sagaId, outcome);\n\n if (error === undefined) {\n if (step.kind === 'pivot') {\n pivotCommitted = true;\n }\n continue;\n }\n\n if (pivotCommitted) {\n // ⚠️ Forward or nowhere. Compensating from here would undo steps whose\n // effects the pivot has already been paid for.\n return yield* strand(\n store,\n sagaId,\n outcomes(),\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n // Unwind. The failing step's own successful calls are compensated too —\n // a fan-out step that took three holds before its fourth was refused has\n // three to give back.\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, taken, error);\n }\n\n yield* store.settle(sagaId, 'COMPLETED');\n return { state: 'COMPLETED', outcomes: outcomes() };\n });\n\n/**\n * Start a flow and walk it to a terminal state.\n *\n * ⚠️ **Synchronous, and that is the buyer's requirement.** A checkout needs a\n * yes/no now, so this answers the settled result. What {@link resumeSaga} adds\n * is durability *behind* that answer: if this process dies mid-walk, the record\n * it has been writing all along is enough for another one to finish the flow.\n */\nexport const runSaga = (\n options: RunSagaOptions,\n): Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag | SagaStoreTag> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { sagaId, definition, inputs } = options;\n\n yield* store.start({\n sagaId,\n definition: definition.name,\n state: 'RUNNING',\n stepIndex: 0,\n outcomes: [],\n // ⚠️ Persisted, because a resume has nothing to dispatch without it: a\n // fan-out step's cardinality *is* its input's length.\n inputs,\n resumeAttempts: 0,\n createdAt: new Date().toISOString(),\n });\n\n return yield* walk(store, options, { taken: [], startIndex: 0 });\n });\n\nexport interface ResumeSagaOptions {\n readonly instance: SagaInstance;\n readonly definition: SagaDefinition;\n /** Past this many sweeps, the instance is surfaced instead of retried. */\n readonly maxResumeAttempts: number;\n}\n\n/**\n * Finish a flow another coordinator abandoned.\n *\n * ⚠️ **Where to re-enter is derived, never stored.** A resume point written\n * beside the outcomes would be a second record of the same fact, free to\n * disagree with them; the outcomes already say what happened, and\n * `beginStep`-before-dispatch means `stepIndex` says what was attempted. The\n * four cases are exhaustive:\n *\n * - the step at `stepIndex` recorded no outcome — the process died during the\n * dispatch, so **re-dispatch it**. Safe because `sagaCommandId` is stable\n * across attempts and every participant claims it in its own command inbox,\n * so calls that did land are recognised as replays rather than repeated.\n * - it recorded a successful outcome — the process died between\n * `recordOutcome` and the next `beginStep`, so **start at the one after**.\n * - it recorded a refusal — the process died deciding what to do about it, so\n * **re-enter that decision**: unwind, or strand if the pivot had committed.\n * - the instance is `COMPENSATING` — it died mid-unwind, so **continue the\n * unwind**, skipping steps already marked `compensated`.\n */\nexport const resumeSaga = (\n options: ResumeSagaOptions,\n): Effect.Effect<SagaResult, StoreFailure, SagaDispatcherTag | SagaStoreTag> =>\n Effect.gen(function* () {\n const store = yield* SagaStoreTag;\n const { instance, definition, maxResumeAttempts } = options;\n const { sagaId, outcomes } = instance;\n\n if (instance.resumeAttempts > maxResumeAttempts) {\n // Surfaced rather than retried forever. A coordinator spinning on a\n // permanent failure is how money stays captured with nobody told.\n return yield* strand(\n store,\n sagaId,\n outcomes,\n instance.error ??\n `resumed ${String(instance.resumeAttempts - 1)} times without settling`,\n 'saga abandoned after too many resumes',\n {\n definition: definition.name,\n resumeAttempts: instance.resumeAttempts,\n },\n );\n }\n\n const rebuilt = rebuildTaken(definition, outcomes);\n if ('unknownStep' in rebuilt) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `recorded step '${rebuilt.unknownStep}' is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const resumeOptions: RunSagaOptions = {\n sagaId,\n definition,\n inputs: instance.inputs,\n };\n\n if (instance.state === 'COMPENSATING') {\n return yield* unwind(\n store,\n sagaId,\n definition,\n rebuilt,\n instance.error ?? 'compensation resumed',\n );\n }\n\n const step = definition.steps[instance.stepIndex];\n if (!step) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n `step ${String(instance.stepIndex)} is not in definition '${definition.name}'`,\n 'saga instance does not match its definition',\n { definition: definition.name },\n );\n }\n\n const recorded = rebuilt.find(entry => entry.step.id === step.id);\n\n if (recorded === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex,\n });\n }\n\n if (recorded.outcome.error === undefined) {\n return yield* walk(store, resumeOptions, {\n taken: rebuilt,\n startIndex: instance.stepIndex + 1,\n });\n }\n\n const error = recorded.outcome.error;\n if (pivotCommittedIn(rebuilt)) {\n return yield* strand(\n store,\n sagaId,\n outcomes,\n error,\n 'saga stranded after the pivot',\n { definition: definition.name, stepId: step.id },\n );\n }\n\n yield* store.settle(sagaId, 'COMPENSATING', error);\n return yield* unwind(store, sagaId, definition, rebuilt, error);\n });\n"],"names":["Effect","sagaCommandId","SagaDispatcherTag","SagaStoreTag","resolveBodyTemplate","resolveTemplate","inputsFor","step","inputs","declared","id","fanOut","stepsScope","taken","Object","fromEntries","filter","entry","outcome","calls","length","map","body","elementsFor","steps","fanOutFrom","undefined","input","scope","source","find","call","organizationId","dispatchCall","sagaId","index","gen","dispatcher","dispatch","participant","method","path","commandId","runStep","elements","element","entries","response","command","ok","error","String","status","push","compensateStep","compensation","failures","reverse","result","pipe","catch","succeed","catchDefect","defect","POST_PIVOT_RETRIES","runStepWithRetries","retries","attempt","logWarning","annotateLogs","stepId","rebuildTaken","definition","outcomes","candidate","unknownStep","pivotCommittedIn","some","kind","strand","store","message","log","logError","settle","state","unwind","done","compensated","stepFailures","markCompensated","name","join","walk","options","from","pivotCommitted","startIndex","beginStep","recordOutcome","runSaga","start","stepIndex","resumeAttempts","createdAt","Date","toISOString","resumeSaga","instance","maxResumeAttempts","rebuilt","resumeOptions","recorded"],"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AACG,EAAE,KAAKH,KAAKG,EAAE;QAEhE,IAAIsG,aAAatF,WAAW;YAC1B,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS;YAChC;QACF;QAEA,IAAIU,SAAS9F,OAAO,CAACgC,KAAK,KAAKxB,WAAW;YACxC,OAAO,OAAOmE,KAAKb,OAAO+B,eAAe;gBACvClG,OAAOiG;gBACPb,YAAYW,SAASN,SAAS,GAAG;YACnC;QACF;QAEA,MAAMpD,QAAQ8D,SAAS9F,OAAO,CAACgC,KAAK;QACpC,IAAI0B,iBAAiBkC,UAAU;YAC7B,OAAO,OAAO/B,OACZC,OACA9C,QACAuC,UACAvB,OACA,iCACA;gBAAEsB,YAAYA,WAAWmB,IAAI;gBAAErB,QAAQ/D,KAAKG,EAAE;YAAC;QAEnD;QAEA,OAAOsE,MAAMI,MAAM,CAAClD,QAAQ,gBAAgBgB;QAC5C,OAAO,OAAOoC,OAAON,OAAO9C,QAAQsC,YAAYsC,SAAS5D;IAC3D,GAAG"}
@@ -35,7 +35,7 @@ export declare function acceptTransaction(): Effect.Effect<{
35
35
  } | {
36
36
  readonly status: "accepted";
37
37
  readonly handles: readonly LockHandle[];
38
- }, import("@entifix/core").EntifixError | import("@entifix/core").StoreFailure, import("../index.js").TransactionHandlerTag | OutboxTag | import("../index.js").LockServiceTag | CommandTag | EventSourceTag>;
38
+ }, import("@entifix/core").EntifixFailure<string, string, import("@entifix/core").FailureCategory>, import("../index.js").TransactionHandlerTag | OutboxTag | import("../index.js").LockServiceTag | CommandTag | EventSourceTag>;
39
39
  /** What {@link acceptTransaction} decided — a fresh command, or a replay. */
40
40
  export type AcceptOutcome = Effect.Success<ReturnType<typeof acceptTransaction>>;
41
41
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;8MAgBhC;AAED,6EAA6E;AAC7E,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CACxC,UAAU,CAAC,OAAO,iBAAiB,CAAC,CACrC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,4JA2DjE"}
1
+ {"version":3,"file":"run-transaction.d.ts","sourceRoot":"","sources":["../../src/engine/run-transaction.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,OAAO,EAAE,SAAS,EAAE,MAAM,wBAAwB,CAAC;AACnD,OAAO,EACL,UAAU,EAGX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC1D,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,0BAA0B,CAAC;AAS3D;;;;;;;;;;;;;;;GAeG;AAEH;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB;;;;;;kOAgBhC;AAED,6EAA6E;AAC7E,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,CACxC,UAAU,CAAC,OAAO,iBAAiB,CAAC,CACrC,CAAC;AAEF;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,SAAS,UAAU,EAAE,4JA2DjE"}
@@ -1,4 +1,4 @@
1
- import type { DomainEvent, StoreFailure, TransitionalFailure } from '@entifix/core';
1
+ import type { DomainEvent, EntifixFailure, StoreFailure } from '@entifix/core';
2
2
  import { Context, type Effect } from 'effect';
3
3
  /**
4
4
  * How a subscriber's queue is shaped, which is a property of the *workload*
@@ -98,7 +98,7 @@ export interface EventBus {
98
98
  * behind it. A *business* failure is neither: that message was processed
99
99
  * successfully and already produced its own event.
100
100
  */
101
- subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void, TransitionalFailure>): Effect.Effect<void, StoreFailure>;
101
+ subscribe(subscription: Subscription, handler: (event: DomainEvent) => Effect.Effect<void, EntifixFailure>): Effect.Effect<void, StoreFailure>;
102
102
  }
103
103
  declare const EventBusTag_base: Context.ServiceClass<EventBusTag, "EventBusTag", EventBus>;
104
104
  export declare class EventBusTag extends EventBusTag_base {
@@ -1 +1 @@
1
- {"version":3,"file":"event-bus.d.ts","sourceRoot":"","sources":["../../src/ports/event-bus.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,mBAAmB,EACpB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,WAAW,CAAC;AAEpD;;;;;;;GAOG;AACH,MAAM,WAAW,YAAY;IAC3B;;;;;;;;OAQG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;;;;;OAMG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,IAAI,EAAE,gBAAgB,CAAC;IAChC;;;;;;;OAOG;IACH,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IAC7B;;;;;;;;OAQG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED;;;;;;;;;;;;GAYG;AACH,MAAM,WAAW,QAAQ;IACvB,OAAO,CAAC,KAAK,EAAE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AAO,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,GACnE,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC;CACtC;;AAED,qBAAa,WAAY,SAAQ,gBAEhC;CAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type {\n DomainEvent,\n StoreFailure,\n TransitionalFailure,\n} from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport.\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * The bus first built the exclusive queue for every subscriber, with a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment may host several slices, so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n /**\n * The breaker keys whose dependency this consumer cannot work without\n * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)).\n * While any of them is open — or forced open — the adapter stops consuming,\n * and it resumes once all are closed or half-open, so an outage leaves the\n * messages waiting on the queue rather than spending their attempts into\n * quarantine. A delivery refused mid-flight by an open breaker goes back\n * without counting as an attempt.\n */\n readonly pauseWhileOpen?: readonly string[];\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for a publication event to\n * travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, StoreFailure>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event.\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, TransitionalFailure>,\n ): Effect.Effect<void, StoreFailure>;\n}\n\nexport class EventBusTag extends Context.Service<EventBusTag, EventBus>()(\n 'EventBusTag',\n) {}\n"],"names":["Context","EventBusTag","Service"],"mappings":"AAKA,SAASA,OAAO,QAAqB,SAAS;AA4G9C,OAAO,MAAMC,oBAAoBD,QAAQE,OAAO,GAC9C;AACC"}
1
+ {"version":3,"sources":["../../src/ports/event-bus.ts"],"sourcesContent":["import type { DomainEvent, EntifixFailure, StoreFailure } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\n/**\n * How a subscriber's queue is shaped, which is a property of the *workload*\n * rather than of the transport.\n *\n * - `work` — a named, durable queue that survives the consumer's restart and\n * accumulates while it is gone. Replicas share it, so each message reaches\n * exactly one of them. A projection writer, a fold and a settlement consumer\n * all want this.\n * - `broadcast` — a connection-scoped exclusive queue, so every replica\n * receives every message and nothing is retained across a restart. Correct\n * only when the replicas differ from one another — a socket push holding\n * different clients per process.\n *\n * The bus first built the exclusive queue for every subscriber, with a stated\n * reason: a shared queue delivers each event to one replica, \"which reads as\n * flakiness rather than as a design\". That reasoning is right for `broadcast`\n * and wrong for `work`; it picked broadcast semantics for a workload that is\n * work, at a time when the only subscriber made the difference invisible.\n */\nexport type SubscriptionMode = 'work' | 'broadcast';\n\n/**\n * A subscriber's declared interest, together with the delivery policy the\n * broker enforces for it.\n *\n * The shape mirrors `subscriptions` in `tools/slices/*.slice.ts`, so \"how does\n * this fail\" is answered where it can be checked rather than in a review\n * comment.\n */\nexport interface Subscription {\n /**\n * The **subscribing** slice — the `tools/slices/` key, and half of the queue\n * name.\n *\n * Deliberately not `EventSourceTag`, which is the *emitting* slice: one\n * deployment may host several slices, so a process-wide \"my slice\" would attribute a\n * consumer's queue to whichever slice happened to publish from the same\n * process.\n */\n readonly slice: string;\n /**\n * The event name pattern, used verbatim as the broker's binding —\n * `transaction.*`, `catalog.published`. Filtering in the handler instead is\n * what this exists to prevent: it makes every consumer pay for every\n * publisher's traffic, and it puts the routing rule where no register can\n * check it.\n */\n readonly pattern: string;\n readonly mode: SubscriptionMode;\n /**\n * How many times the broker may deliver a message before dead-lettering it.\n *\n * Enforced by the queue itself rather than by logic each consumer\n * reimplements, so it applies to a redelivery after a crash as well as to one\n * after a nack. `broadcast` queues have no dead-letter path, so the value is\n * carried but unenforced there.\n */\n readonly maxAttempts: number;\n /**\n * The breaker keys whose dependency this consumer cannot work without\n * ([ADR 0017](../../../../../docs/adr/0017-circuit-breaker-and-bulkhead-ports.md)).\n * While any of them is open — or forced open — the adapter stops consuming,\n * and it resumes once all are closed or half-open, so an outage leaves the\n * messages waiting on the queue rather than spending their attempts into\n * quarantine. A delivery refused mid-flight by an open breaker goes back\n * without counting as an attempt.\n */\n readonly pauseWhileOpen?: readonly string[];\n}\n\n/**\n * The domain event bus (RabbitMQ in `@entifix/amqp`). Services publish\n * what happened; interested slices subscribe to the names they declared.\n *\n * Typed on {@link DomainEvent} rather than on any one publisher's payload: a bus\n * that only knew `TransactionEvent` had nothing for a publication event to\n * travel in, which would have meant a second framing and a second\n * transport for the same job.\n *\n * The port stays event-typed rather than envelope-typed — the adapter owns the\n * wire framing — so a handler receives the message and its metadata without\n * ever seeing the envelope that carried them.\n */\nexport interface EventBus {\n publish(event: DomainEvent): Effect.Effect<void, StoreFailure>;\n /**\n * Register a consumer for the events matching `subscription.pattern`.\n *\n * The returned Effect completes once the subscription is established; the\n * handler then runs per delivered event. Delivery is at-least-once, so a\n * handler that is not idempotent must deduplicate on `event.id`.\n *\n * A handler failure is **transient**: the adapter requeues it and the broker\n * counts the redelivery against `maxAttempts`, dead-lettering at the limit. A\n * payload the adapter cannot read is **poison** and is quarantined with zero\n * retries — a message that cannot be deserialized never becomes\n * deserializable, and retrying it only spends the budget of the messages\n * behind it. A *business* failure is neither: that message was processed\n * successfully and already produced its own event.\n */\n subscribe(\n subscription: Subscription,\n handler: (event: DomainEvent) => Effect.Effect<void, EntifixFailure>,\n ): Effect.Effect<void, StoreFailure>;\n}\n\nexport class EventBusTag extends Context.Service<EventBusTag, EventBus>()(\n 'EventBusTag',\n) {}\n"],"names":["Context","EventBusTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA4G9C,OAAO,MAAMC,oBAAoBD,QAAQE,OAAO,GAC9C;AACC"}
@@ -1,4 +1,4 @@
1
- import type { EntifixConnError } from '@entifix/core';
1
+ import type { Unavailable } from '@entifix/core';
2
2
  import { Context, type Effect } from 'effect';
3
3
  import type { SagaCall } from '../contracts/saga-definition.js';
4
4
  /** One call the engine wants made, fully resolved. */
@@ -29,7 +29,7 @@ export interface SagaDispatch {
29
29
  * forever or permanently fails a checkout because a pod was restarting.
30
30
  *
31
31
  * So a `refused` response is a **success** of this port carrying `ok: false`,
32
- * and only a transport or `5xx` failure is an `EntifixConnError`.
32
+ * and only a transport or `5xx` failure is an `Unavailable`.
33
33
  */
34
34
  export interface SagaResponse {
35
35
  readonly ok: boolean;
@@ -37,7 +37,7 @@ export interface SagaResponse {
37
37
  readonly body: unknown;
38
38
  }
39
39
  export interface SagaDispatcher {
40
- dispatch(dispatch: SagaDispatch): Effect.Effect<SagaResponse, EntifixConnError>;
40
+ dispatch(dispatch: SagaDispatch): Effect.Effect<SagaResponse, Unavailable>;
41
41
  }
42
42
  declare const SagaDispatcherTag_base: Context.ServiceClass<SagaDispatcherTag, "SagaDispatcherTag", SagaDispatcher>;
43
43
  export declare class SagaDispatcherTag extends SagaDispatcherTag_base {
@@ -1 +1 @@
1
- {"version":3,"file":"saga-dispatcher.d.ts","sourceRoot":"","sources":["../../src/ports/saga-dispatcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,OAAO,EAAE,KAAK,MAAM,EAAE,MAAM,QAAQ,CAAC;AAE9C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,iCAAiC,CAAC;AAEhE,sDAAsD;AACtD,MAAM,WAAW,YAAY;IAC3B,iFAAiF;IACjF,QAAQ,CAAC,WAAW,EAAE,MAAM,CAA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,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,OAAO,CAAC;CACxB;AAED,MAAM,WAAW,cAAc;IAC7B,QAAQ,CAAC,QAAQ,EAAE,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,WAAW,CAAC,CAAC;CAC5E;;AAED,qBAAa,iBAAkB,SAAQ,sBAGf;CAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { EntifixConnError } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes the\n * `x-organization-id` header — and it is safe only because the crossing token is\n * checked first, so the input the caller controls is never the input that\n * authorizes.\n */\n readonly organizationId?: string;\n readonly body?: unknown;\n}\n\n/**\n * What a dispatched call answered.\n *\n * ⚠️ **A refusal is not a failure, and the split is the dispatcher's job.** A\n * `409` from reserve is the business answer \"not enough stock\" and must fail the\n * saga *forward* into compensation; a `503` is a participant that is down and\n * the entry is retried. Collapsing the two either retries an out-of-stock line\n * forever or permanently fails a checkout because a pod was restarting.\n *\n * So a `refused` response is a **success** of this port carrying `ok: false`,\n * and only a transport or `5xx` failure is an `EntifixConnError`.\n */\nexport interface SagaResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly body: unknown;\n}\n\nexport interface SagaDispatcher {\n dispatch(\n dispatch: SagaDispatch,\n ): Effect.Effect<SagaResponse, EntifixConnError>;\n}\n\nexport class SagaDispatcherTag extends Context.Service<\n SagaDispatcherTag,\n SagaDispatcher\n>()('SagaDispatcherTag') {}\n"],"names":["Context","SagaDispatcherTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA+C9C,OAAO,MAAMC,0BAA0BD,QAAQE,OAAO,GAGlD;AAAsB"}
1
+ {"version":3,"sources":["../../src/ports/saga-dispatcher.ts"],"sourcesContent":["import type { Unavailable } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { SagaCall } from '../contracts/saga-definition.js';\n\n/** One call the engine wants made, fully resolved. */\nexport interface SagaDispatch {\n /** The participant's configuration key — the dispatcher resolves the address. */\n readonly participant: string;\n readonly call: SagaCall;\n /** `<sagaId>:<stepId>[:<index>]`, which the participant claims. */\n readonly commandId: string;\n /**\n * The organization this call acts for, when the participant is tenant-plane.\n *\n * Absent for a platform-plane participant. Present, it becomes the\n * `x-organization-id` header — and it is safe only because the crossing token is\n * checked first, so the input the caller controls is never the input that\n * authorizes.\n */\n readonly organizationId?: string;\n readonly body?: unknown;\n}\n\n/**\n * What a dispatched call answered.\n *\n * ⚠️ **A refusal is not a failure, and the split is the dispatcher's job.** A\n * `409` from reserve is the business answer \"not enough stock\" and must fail the\n * saga *forward* into compensation; a `503` is a participant that is down and\n * the entry is retried. Collapsing the two either retries an out-of-stock line\n * forever or permanently fails a checkout because a pod was restarting.\n *\n * So a `refused` response is a **success** of this port carrying `ok: false`,\n * and only a transport or `5xx` failure is an `Unavailable`.\n */\nexport interface SagaResponse {\n readonly ok: boolean;\n readonly status: number;\n readonly body: unknown;\n}\n\nexport interface SagaDispatcher {\n dispatch(dispatch: SagaDispatch): Effect.Effect<SagaResponse, Unavailable>;\n}\n\nexport class SagaDispatcherTag extends Context.Service<\n SagaDispatcherTag,\n SagaDispatcher\n>()('SagaDispatcherTag') {}\n"],"names":["Context","SagaDispatcherTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AA6C9C,OAAO,MAAMC,0BAA0BD,QAAQE,OAAO,GAGlD;AAAsB"}
@@ -1,4 +1,4 @@
1
- import type { EntifixError, EntityId } from '@entifix/core';
1
+ import type { EntifixFailure, EntityId } from '@entifix/core';
2
2
  import { Context, type Effect } from 'effect';
3
3
  import type { TransactionCommand } from '../contracts/command.js';
4
4
  /** What a successful `execute` produced — echoed into the completed event. */
@@ -18,7 +18,7 @@ export interface TransactionOutcome {
18
18
  */
19
19
  export interface TransactionHandler {
20
20
  /** Reject a malformed/illegal command (surfaced as `400`). */
21
- validate(command: TransactionCommand): Effect.Effect<void, EntifixError>;
21
+ validate(command: TransactionCommand): Effect.Effect<void, EntifixFailure>;
22
22
  /** The resource keys to lock for this command (e.g. the code sequence). */
23
23
  lockKeys(command: TransactionCommand): readonly string[];
24
24
  /**
@@ -41,7 +41,7 @@ export interface TransactionHandler {
41
41
  * code from the Redis sequence, say — **outside** that retried callback, or a
42
42
  * retry consumes a second value and skips a code.
43
43
  */
44
- execute(command: TransactionCommand): Effect.Effect<TransactionOutcome, EntifixError>;
44
+ execute(command: TransactionCommand): Effect.Effect<TransactionOutcome, EntifixFailure>;
45
45
  /**
46
46
  * Undo a failed execution. Must be idempotent (e.g. delete-if-exists), since
47
47
  * the recovery sweep may reach a transaction whose rollback already ran.
@@ -57,7 +57,7 @@ export interface TransactionHandler {
57
57
  * reservation's id and a delete-if-exists does not. A single-step handler is
58
58
  * untouched by that: the contract grows a second shape and keeps the first.
59
59
  */
60
- rollback(command: TransactionCommand, outcome: TransactionOutcome | undefined): Effect.Effect<void, EntifixError>;
60
+ rollback(command: TransactionCommand, outcome: TransactionOutcome | undefined): Effect.Effect<void, EntifixFailure>;
61
61
  }
62
62
  declare const TransactionHandlerTag_base: Context.ServiceClass<TransactionHandlerTag, "TransactionHandlerTag", TransactionHandler>;
63
63
  export declare class TransactionHandlerTag extends TransactionHandlerTag_base {
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-handler.d.ts","sourceRoot":"","sources":["../../src/ports/transaction-handler.ts"],"names":[],"mappings":"AAAA,OAAO,KAA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AC;IACb,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,kBAAkB;IACjC,8DAA8D;IAC9D,QAAQ,CAAC,OAAO,EAAE,kBAAkB,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;IAC3E,2EAA2E;IAC3E,QAAQ,CAAC,OAAO,EAAE,kBAAkB,GAAG,SAAS,MAAM,EAAE,CAAC;IACzD;;;;;;;;;;;;;;;;;;;OAmBG;IACH,OAAO,CACL,OAAO,EAAE,kBAAkB,GAC1B,MAAM,CAAC,MAAM,CAAC,kBAAkB,EAAE,cAAc,CAAC,CAAC;IACrD;;;;;;;;;;;;;;OAcG;IACH,QAAQ,CACN,OAAO,EAAE,kBAAkB,EAC3B,OAAO,EAAE,kBAAkB,GAAG,SAAS,GACtC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,cAAc,CAAC,CAAC;CACxC;;AAED,qBAAa,qBAAsB,SAAQ,0BAGf;CAAG"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/ports/transaction-handler.ts"],"sourcesContent":["import type { EntifixError, EntityId } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\n\n/** What a successful `execute` produced — echoed into the completed event. */\nexport interface TransactionOutcome {\n code: string;\n entityId: EntityId;\n}\n\n/**\n * The domain-specific half of the facade. `validate`/`lock`/`execute`/`free`/\n * `rollback` are standardised by the engine, but *what* a command validates to,\n * *which* resources it locks, and *how* it executes/rolls back are the service's\n * concern — injected as this handler.\n *\n * Methods return `R = never`: the service closes over its own dependencies (db,\n * sequence, repository) when constructing the handler, exactly as\n * `makeMongoRepository` closes over its `Db`.\n */\nexport interface TransactionHandler {\n /** Reject a malformed/illegal command (surfaced as `400`). */\n validate(command: TransactionCommand): Effect.Effect<void, EntifixError>;\n /** The resource keys to lock for this command (e.g. the code sequence). */\n lockKeys(command: TransactionCommand): readonly string[];\n /**\n * Assign the code and persist — the actual write.\n *\n * **The implementation must write the `completed` outbox entry in the same\n * storage transaction as its state change**, as a full `OutboxEntry` whose\n * `event` is the `DomainEvent` `completedEvent` builds and whose `eventId` is\n * that event's `id`. The engine deliberately records\n * nothing on the success path, because only an implementation holds the\n * driver session that can make those two writes one fact; an engine-level\n * record would be a second dual write, announcing a state change that may\n * still roll back.\n *\n * Two rules that only a replica set will teach you, and only in production:\n * drive the transaction with the driver's retrying helper (Mongo's\n * `session.withTransaction`), because an election aborts in-flight\n * transactions with a `TransientTransactionError` the *application* is\n * expected to retry; and keep any non-transactional side effect — drawing a\n * code from the Redis sequence, say — **outside** that retried callback, or a\n * retry consumes a second value and skips a code.\n */\n execute(\n command: TransactionCommand,\n ): Effect.Effect<TransactionOutcome, EntifixError>;\n /**\n * Undo a failed execution. Must be idempotent (e.g. delete-if-exists), since\n * the recovery sweep may reach a transaction whose rollback already ran.\n *\n * **`outcome` is always `undefined` on the single-step path, and cannot be\n * anything else there.** `rollback` runs on exactly one arm — the one where\n * `execute` failed — so there is no outcome to hand it.\n *\n * That is a property of this path rather than an unfinished signature, and it\n * stays true now that the multi-step engine exists beside it. A saga's\n * compensation is dispatched by `runSaga` with **its own call's** recorded\n * outcome (`SagaStepOutcome`), because reversing a reservation needs the\n * reservation's id and a delete-if-exists does not. A single-step handler is\n * untouched by that: the contract grows a second shape and keeps the first.\n */\n rollback(\n command: TransactionCommand,\n outcome: TransactionOutcome | undefined,\n ): Effect.Effect<void, EntifixError>;\n}\n\nexport class TransactionHandlerTag extends Context.Service<\n TransactionHandlerTag,\n TransactionHandler\n>()('TransactionHandlerTag') {}\n"],"names":["Context","TransactionHandlerTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAqE9C,OAAO,MAAMC,8BAA8BD,QAAQE,OAAO,GAGtD;AAA0B"}
1
+ {"version":3,"sources":["../../src/ports/transaction-handler.ts"],"sourcesContent":["import type { EntifixFailure, EntityId } from '@entifix/core';\nimport { Context, type Effect } from 'effect';\n\nimport type { TransactionCommand } from '../contracts/command.js';\n\n/** What a successful `execute` produced — echoed into the completed event. */\nexport interface TransactionOutcome {\n code: string;\n entityId: EntityId;\n}\n\n/**\n * The domain-specific half of the facade. `validate`/`lock`/`execute`/`free`/\n * `rollback` are standardised by the engine, but *what* a command validates to,\n * *which* resources it locks, and *how* it executes/rolls back are the service's\n * concern — injected as this handler.\n *\n * Methods return `R = never`: the service closes over its own dependencies (db,\n * sequence, repository) when constructing the handler, exactly as\n * `makeMongoRepository` closes over its `Db`.\n */\nexport interface TransactionHandler {\n /** Reject a malformed/illegal command (surfaced as `400`). */\n validate(command: TransactionCommand): Effect.Effect<void, EntifixFailure>;\n /** The resource keys to lock for this command (e.g. the code sequence). */\n lockKeys(command: TransactionCommand): readonly string[];\n /**\n * Assign the code and persist — the actual write.\n *\n * **The implementation must write the `completed` outbox entry in the same\n * storage transaction as its state change**, as a full `OutboxEntry` whose\n * `event` is the `DomainEvent` `completedEvent` builds and whose `eventId` is\n * that event's `id`. The engine deliberately records\n * nothing on the success path, because only an implementation holds the\n * driver session that can make those two writes one fact; an engine-level\n * record would be a second dual write, announcing a state change that may\n * still roll back.\n *\n * Two rules that only a replica set will teach you, and only in production:\n * drive the transaction with the driver's retrying helper (Mongo's\n * `session.withTransaction`), because an election aborts in-flight\n * transactions with a `TransientTransactionError` the *application* is\n * expected to retry; and keep any non-transactional side effect — drawing a\n * code from the Redis sequence, say — **outside** that retried callback, or a\n * retry consumes a second value and skips a code.\n */\n execute(\n command: TransactionCommand,\n ): Effect.Effect<TransactionOutcome, EntifixFailure>;\n /**\n * Undo a failed execution. Must be idempotent (e.g. delete-if-exists), since\n * the recovery sweep may reach a transaction whose rollback already ran.\n *\n * **`outcome` is always `undefined` on the single-step path, and cannot be\n * anything else there.** `rollback` runs on exactly one arm — the one where\n * `execute` failed — so there is no outcome to hand it.\n *\n * That is a property of this path rather than an unfinished signature, and it\n * stays true now that the multi-step engine exists beside it. A saga's\n * compensation is dispatched by `runSaga` with **its own call's** recorded\n * outcome (`SagaStepOutcome`), because reversing a reservation needs the\n * reservation's id and a delete-if-exists does not. A single-step handler is\n * untouched by that: the contract grows a second shape and keeps the first.\n */\n rollback(\n command: TransactionCommand,\n outcome: TransactionOutcome | undefined,\n ): Effect.Effect<void, EntifixFailure>;\n}\n\nexport class TransactionHandlerTag extends Context.Service<\n TransactionHandlerTag,\n TransactionHandler\n>()('TransactionHandlerTag') {}\n"],"names":["Context","TransactionHandlerTag","Service"],"mappings":"AACA,SAASA,OAAO,QAAqB,SAAS;AAqE9C,OAAO,MAAMC,8BAA8BD,QAAQE,OAAO,GAGtD;AAA0B"}
@@ -10,13 +10,13 @@ import { TransactionHandlerTag } from '../ports/transaction-handler.js';
10
10
  * sequences them.
11
11
  */
12
12
  /** 1. Validate — delegates to the injected domain handler. */
13
- export declare function validateUCFactory(): Effect.Effect<void, import("@entifix/core").EntifixError, TransactionHandlerTag | CommandTag>;
13
+ export declare function validateUCFactory(): Effect.Effect<void, import("@entifix/core").EntifixFailure<string, string, import("@entifix/core").FailureCategory>, TransactionHandlerTag | CommandTag>;
14
14
  /** 2. Lock — acquire every resource key the handler declares for the command. */
15
15
  export declare function lockUCFactory(): Effect.Effect<readonly LockHandle[], import("@entifix/core").StoreFailure, TransactionHandlerTag | LockServiceTag | CommandTag>;
16
16
  /** 3. Execute — the write; returns the assigned code + stored id. */
17
- export declare function executeUCFactory(): Effect.Effect<import("../index.js").TransactionOutcome, import("@entifix/core").EntifixError, TransactionHandlerTag | CommandTag>;
17
+ export declare function executeUCFactory(): Effect.Effect<import("../index.js").TransactionOutcome, import("@entifix/core").EntifixFailure<string, string, import("@entifix/core").FailureCategory>, TransactionHandlerTag | CommandTag>;
18
18
  /** 4. Rollback — undo a failed execution (idempotent). */
19
- export declare function rollbackUCFactory(): Effect.Effect<void, import("@entifix/core").EntifixError, TransactionHandlerTag | CommandTag | OutcomeTag>;
19
+ export declare function rollbackUCFactory(): Effect.Effect<void, import("@entifix/core").EntifixFailure<string, string, import("@entifix/core").FailureCategory>, TransactionHandlerTag | CommandTag | OutcomeTag>;
20
20
  /** 5. Free — release every held lock, best-effort per handle. */
21
21
  export declare function freeUCFactory(): Effect.Effect<void, import("@entifix/core").StoreFailure, LockServiceTag | LockHandlesTag>;
22
22
  //# sourceMappingURL=facade.uc.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"facade.uc.d.ts","sourceRoot":"","sources":["../../src/use-case/facade.uc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EACL,UAAU,EACV,cAAc,EACd,UAAU,EACX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,KAAK,UAAU,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE;;;;;;GAMG;AAEH,8DAA8D;AAC9D,wBAAgB,iBAAiB,kGAMhC;AAED,iFAAiF;AACjF,wBAAgB,aAAa,oIAY5B;AAED,qEAAqE;AACrE,wBAAgB,gBAAgB,sIAM/B;AAED,0DAA0D;AAC1D,wBAAgB,iBAAiB,+GAOhC;AAED,iEAAiE;AACjE,wBAAgB,aAAa,+FAQ5B"}
1
+ {"version":3,"file":"facade.uc.d.ts","sourceRoot":"","sources":["../../src/use-case/facade.uc.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,OAAO,EACL,UAAU,EACV,cAAc,EACd,UAAU,EACX,MAAM,iCAAiC,CAAC;AACzC,OAAO,EAAE,KAAK,UAAU,EAAE,cAAc,EAAE,MAAM,0BAA0B,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAExE;;;;;;GAMG;AAEH,8DAA8D;AAC9D,wBAAgB,iBAAiB,6JAMhC;AAED,iFAAiF;AACjF,wBAAgB,aAAa,oIAY5B;AAED,qEAAqE;AACrE,wBAAgB,gBAAgB,iMAM/B;AAED,0DAA0D;AAC1D,wBAAgB,iBAAiB,0KAOhC;AAED,iEAAiE;AACjE,wBAAgB,aAAa,+FAQ5B"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/transactions",
3
- "version": "0.12.1",
3
+ "version": "0.14.0",
4
4
  "description": "Commands, transactions and sagas: inbox and outbox ports, an event bus, locks, and a declarative saga runner.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -56,13 +56,13 @@
56
56
  },
57
57
  "dependencies": {
58
58
  "@swc/helpers": "0.5.23",
59
- "@entifix/business": "0.12.1",
60
- "@entifix/core": "0.12.1"
59
+ "@entifix/core": "0.14.0",
60
+ "@entifix/business": "0.14.0"
61
61
  },
62
62
  "peerDependencies": {
63
- "effect": "^4.0.6"
63
+ "effect": "^4.0.7"
64
64
  },
65
65
  "devDependencies": {
66
- "effect": "4.0.6"
66
+ "effect": "4.0.7"
67
67
  }
68
68
  }