@entifix/testing-unit 0.10.2 → 0.12.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 (65) hide show
  1. package/dist/contracts/breaker.contract.d.ts +25 -0
  2. package/dist/contracts/breaker.contract.d.ts.map +1 -0
  3. package/dist/contracts/breaker.contract.js +159 -0
  4. package/dist/contracts/breaker.contract.js.map +1 -0
  5. package/dist/contracts/flow-engine.contract.d.ts +16 -0
  6. package/dist/contracts/flow-engine.contract.d.ts.map +1 -0
  7. package/dist/contracts/flow-engine.contract.js +199 -0
  8. package/dist/contracts/flow-engine.contract.js.map +1 -0
  9. package/dist/contracts/idempotency-store.contract.d.ts +17 -0
  10. package/dist/contracts/idempotency-store.contract.d.ts.map +1 -0
  11. package/dist/contracts/idempotency-store.contract.js +94 -0
  12. package/dist/contracts/idempotency-store.contract.js.map +1 -0
  13. package/dist/contracts/index.d.ts +5 -0
  14. package/dist/contracts/index.d.ts.map +1 -1
  15. package/dist/contracts/index.js +5 -0
  16. package/dist/contracts/index.js.map +1 -1
  17. package/dist/contracts/outbox.contract.d.ts +18 -0
  18. package/dist/contracts/outbox.contract.d.ts.map +1 -0
  19. package/dist/contracts/outbox.contract.js +117 -0
  20. package/dist/contracts/outbox.contract.js.map +1 -0
  21. package/dist/contracts/transaction-ports.contract.d.ts +1 -1
  22. package/dist/contracts/transaction-ports.contract.d.ts.map +1 -1
  23. package/dist/contracts/transaction-ports.contract.js +10 -1
  24. package/dist/contracts/transaction-ports.contract.js.map +1 -1
  25. package/dist/contracts/unit-of-work.contract.d.ts.map +1 -1
  26. package/dist/contracts/unit-of-work.contract.js +5 -0
  27. package/dist/contracts/unit-of-work.contract.js.map +1 -1
  28. package/dist/contracts/variants.contract.d.ts +15 -0
  29. package/dist/contracts/variants.contract.d.ts.map +1 -0
  30. package/dist/contracts/variants.contract.js +39 -0
  31. package/dist/contracts/variants.contract.js.map +1 -0
  32. package/dist/doubles/entity-repository.d.ts +3 -3
  33. package/dist/doubles/entity-repository.d.ts.map +1 -1
  34. package/dist/doubles/entity-repository.js +2 -4
  35. package/dist/doubles/entity-repository.js.map +1 -1
  36. package/dist/doubles/flow-engine.d.ts +22 -0
  37. package/dist/doubles/flow-engine.d.ts.map +1 -0
  38. package/dist/doubles/flow-engine.js +148 -0
  39. package/dist/doubles/flow-engine.js.map +1 -0
  40. package/dist/doubles/idempotency-store.d.ts +12 -0
  41. package/dist/doubles/idempotency-store.d.ts.map +1 -0
  42. package/dist/doubles/idempotency-store.js +40 -0
  43. package/dist/doubles/idempotency-store.js.map +1 -0
  44. package/dist/doubles/link-resolver.d.ts.map +1 -1
  45. package/dist/doubles/link-resolver.js +3 -4
  46. package/dist/doubles/link-resolver.js.map +1 -1
  47. package/dist/doubles/outbox.d.ts +15 -0
  48. package/dist/doubles/outbox.d.ts.map +1 -0
  49. package/dist/doubles/outbox.js +70 -0
  50. package/dist/doubles/outbox.js.map +1 -0
  51. package/dist/doubles/unit-of-work.d.ts +2 -3
  52. package/dist/doubles/unit-of-work.d.ts.map +1 -1
  53. package/dist/doubles/unit-of-work.js.map +1 -1
  54. package/dist/drivers/fake-amqp.d.ts +2 -0
  55. package/dist/drivers/fake-amqp.d.ts.map +1 -1
  56. package/dist/drivers/fake-amqp.js +8 -0
  57. package/dist/drivers/fake-amqp.js.map +1 -1
  58. package/dist/drivers/fake-sql.d.ts.map +1 -1
  59. package/dist/drivers/fake-sql.js +16 -1
  60. package/dist/drivers/fake-sql.js.map +1 -1
  61. package/dist/index.d.ts +3 -0
  62. package/dist/index.d.ts.map +1 -1
  63. package/dist/index.js +3 -0
  64. package/dist/index.js.map +1 -1
  65. package/package.json +5 -5
@@ -1,8 +1,13 @@
1
+ export * from './breaker.contract.js';
1
2
  export * from './entity-facet-counter.contract.js';
2
3
  export * from './entity-repository.contract.js';
3
4
  export * from './failure.contract.js';
5
+ export * from './flow-engine.contract.js';
6
+ export * from './idempotency-store.contract.js';
7
+ export * from './outbox.contract.js';
4
8
  export * from './saga-store.contract.js';
5
9
  export * from './transaction-ports.contract.js';
6
10
  export * from './unit-of-work.contract.js';
11
+ export * from './variants.contract.js';
7
12
 
8
13
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,2BAA2B;AACzC,cAAc,kCAAkC;AAChD,cAAc,6BAA6B"}
1
+ {"version":3,"sources":["../../src/contracts/index.ts"],"sourcesContent":["export * from './breaker.contract.js';\nexport * from './entity-facet-counter.contract.js';\nexport * from './entity-repository.contract.js';\nexport * from './failure.contract.js';\nexport * from './flow-engine.contract.js';\nexport * from './idempotency-store.contract.js';\nexport * from './outbox.contract.js';\nexport * from './saga-store.contract.js';\nexport * from './transaction-ports.contract.js';\nexport * from './unit-of-work.contract.js';\nexport * from './variants.contract.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB;AACtC,cAAc,qCAAqC;AACnD,cAAc,kCAAkC;AAChD,cAAc,wBAAwB;AACtC,cAAc,4BAA4B;AAC1C,cAAc,kCAAkC;AAChD,cAAc,uBAAuB;AACrC,cAAc,2BAA2B;AACzC,cAAc,kCAAkC;AAChD,cAAc,6BAA6B;AAC3C,cAAc,yBAAyB"}
@@ -0,0 +1,18 @@
1
+ import { type EventBus, type Outbox } from '@entifix/transactions';
2
+ import { Effect } from 'effect';
3
+ /** What a case needs from an outbox implementation: the port, and its relay's drain. */
4
+ export interface OutboxUnderTest {
5
+ readonly outbox: Outbox;
6
+ /** One relay pass over `outbox`, publishing through `bus`. */
7
+ readonly drain: (bus: EventBus, maxAttempts: number) => Effect.Effect<number, unknown>;
8
+ }
9
+ /**
10
+ * What every {@link Outbox} and its relay must guarantee
11
+ * ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):
12
+ * a duplicate enqueue is recognised, each aggregate publishes in version
13
+ * order, a failing aggregate holds back only itself, a poisoned one is
14
+ * quarantined without blocking another, and a consumer discards a stale
15
+ * version.
16
+ */
17
+ export declare const describeOutboxContract: (name: string, make: () => Effect.Effect<OutboxUnderTest, unknown>) => void;
18
+ //# sourceMappingURL=outbox.contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"outbox.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/outbox.contract.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,QAAQ,EACb,KAAK,MAAM,EAEZ,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAGhC,wFAAwF;AACxF,MAAM,WAAW,eAAe;IAC9B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,8DAA8D;IAC9D,QAAQ,CAAC,KAAK,EAAE,CACd,GAAG,EAAE,QAAQ,EACb,WAAW,EAAE,MAAM,KAChB,MAAM,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CACrC;AAgCD;;;;;;;GAOG;AACH,eAAO,MAAM,sBAAsB,GACjC,MAAM,MAAM,EACZ,MAAM,MAAM,MAAM,CAAC,MAAM,CAAC,eAAe,EAAE,OAAO,CAAC,KAClD,IAsEF,CAAC"}
@@ -0,0 +1,117 @@
1
+ import { Unavailable } from '@entifix/core';
2
+ import { discardIfStale } from '@entifix/transactions';
3
+ import { Effect } from 'effect';
4
+ import { describe, expect, it } from 'vitest';
5
+ let clock = 0;
6
+ const event = (aggregate, version)=>{
7
+ clock += 1;
8
+ return {
9
+ name: 'contract.changed',
10
+ id: `${aggregate}:${String(version)}`,
11
+ source: 'contract',
12
+ at: new Date(Date.UTC(2026, 0, 1, 0, 0, clock)).toISOString(),
13
+ aggregate: {
14
+ type: 'contract',
15
+ id: aggregate
16
+ },
17
+ version,
18
+ data: {}
19
+ };
20
+ };
21
+ /** A bus that records what it published and refuses the ids it is told to. */ const recordingBus = (refuse = new Set())=>{
22
+ const published = [];
23
+ const bus = {
24
+ publish: (published_)=>refuse.has(published_.id) ? Effect.fail(new Unavailable({
25
+ dependency: 'contract-bus'
26
+ })) : Effect.sync(()=>{
27
+ published.push(published_);
28
+ }),
29
+ /* v8 ignore next -- the relay only publishes; the bus port asks for both. */ subscribe: ()=>Effect.void
30
+ };
31
+ return {
32
+ bus,
33
+ published
34
+ };
35
+ };
36
+ /**
37
+ * What every {@link Outbox} and its relay must guarantee
38
+ * ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):
39
+ * a duplicate enqueue is recognised, each aggregate publishes in version
40
+ * order, a failing aggregate holds back only itself, a poisoned one is
41
+ * quarantined without blocking another, and a consumer discards a stale
42
+ * version.
43
+ */ export const describeOutboxContract = (name, make)=>{
44
+ const run = (effect)=>Effect.runPromise(effect);
45
+ describe(`Outbox contract: ${name}`, ()=>{
46
+ it('recognises a duplicate enqueue by event id', async ()=>{
47
+ const { outbox } = await run(make());
48
+ const first = event('a', 1);
49
+ expect(await run(outbox.enqueue(first))).toBe('enqueued');
50
+ expect(await run(outbox.enqueue(first))).toBe('duplicate');
51
+ });
52
+ it('publishes each aggregate in version order', async ()=>{
53
+ const { outbox, drain } = await run(make());
54
+ for (const entry of [
55
+ event('a', 1),
56
+ event('b', 1),
57
+ event('a', 2)
58
+ ])await run(outbox.enqueue(entry));
59
+ const { bus, published } = recordingBus();
60
+ expect(await run(drain(bus, 3))).toBe(3);
61
+ expect(published.filter((e)=>{
62
+ var _e_aggregate;
63
+ return ((_e_aggregate = e.aggregate) == null ? void 0 : _e_aggregate.id) === 'a';
64
+ }).map((e)=>e.version)).toEqual([
65
+ 1,
66
+ 2
67
+ ]);
68
+ expect((await run(outbox.stats())).pending).toBe(0);
69
+ });
70
+ // The record's point: a failing head holds back its own aggregate only.
71
+ it('holds back only the aggregate whose head failed', async ()=>{
72
+ const { outbox, drain } = await run(make());
73
+ for (const entry of [
74
+ event('a', 1),
75
+ event('a', 2),
76
+ event('b', 1)
77
+ ])await run(outbox.enqueue(entry));
78
+ const { bus, published } = recordingBus(new Set([
79
+ 'a:1'
80
+ ]));
81
+ await run(drain(bus, 3));
82
+ expect(published.map((e)=>e.id)).toEqual([
83
+ 'b:1'
84
+ ]);
85
+ expect((await run(outbox.stats())).pending).toBe(2);
86
+ });
87
+ it('quarantines a poisoned aggregate without blocking another', async ()=>{
88
+ const { outbox, drain } = await run(make());
89
+ for (const entry of [
90
+ event('a', 1),
91
+ event('b', 1),
92
+ event('a', 2)
93
+ ])await run(outbox.enqueue(entry));
94
+ const { bus, published } = recordingBus(new Set([
95
+ 'a:1'
96
+ ]));
97
+ await run(drain(bus, 1));
98
+ expect(published.map((e)=>e.id)).toEqual([
99
+ 'b:1',
100
+ 'a:2'
101
+ ]);
102
+ expect(await run(outbox.stats())).toMatchObject({
103
+ pending: 0,
104
+ quarantined: 1
105
+ });
106
+ });
107
+ it('lets a consumer discard a version it already applied', async ()=>{
108
+ const apply = Effect.succeed('applied');
109
+ expect(await run(discardIfStale(Effect.succeed(2), 1, apply))).toBe('stale');
110
+ expect(await run(discardIfStale(Effect.succeed(2), 2, apply))).toBe('stale');
111
+ expect(await run(discardIfStale(Effect.succeed(2), 3, apply))).toBe('applied');
112
+ expect(await run(discardIfStale(Effect.succeed(undefined), 1, apply))).toBe('applied');
113
+ });
114
+ });
115
+ };
116
+
117
+ //# sourceMappingURL=outbox.contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/outbox.contract.ts"],"sourcesContent":["import { type DomainEvent, Unavailable } from '@entifix/core';\nimport {\n discardIfStale,\n type EventBus,\n type Outbox,\n type OutboxEvent,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What a case needs from an outbox implementation: the port, and its relay's drain. */\nexport interface OutboxUnderTest {\n readonly outbox: Outbox;\n /** One relay pass over `outbox`, publishing through `bus`. */\n readonly drain: (\n bus: EventBus,\n maxAttempts: number,\n ) => Effect.Effect<number, unknown>;\n}\n\nlet clock = 0;\nconst event = (aggregate: string, version: number): OutboxEvent => {\n clock += 1;\n return {\n name: 'contract.changed',\n id: `${aggregate}:${String(version)}`,\n source: 'contract',\n at: new Date(Date.UTC(2026, 0, 1, 0, 0, clock)).toISOString(),\n aggregate: { type: 'contract', id: aggregate },\n version,\n data: {},\n };\n};\n\n/** A bus that records what it published and refuses the ids it is told to. */\nconst recordingBus = (refuse: ReadonlySet<string> = new Set()) => {\n const published: DomainEvent[] = [];\n const bus: EventBus = {\n publish: published_ =>\n refuse.has(published_.id)\n ? Effect.fail(new Unavailable({ dependency: 'contract-bus' }))\n : Effect.sync(() => {\n published.push(published_);\n }),\n /* v8 ignore next -- the relay only publishes; the bus port asks for both. */\n subscribe: () => Effect.void,\n };\n return { bus, published };\n};\n\n/**\n * What every {@link Outbox} and its relay must guarantee\n * ([ADR 0018](../../../../../docs/adr/0018-one-outbox-ordered-per-aggregate.md)):\n * a duplicate enqueue is recognised, each aggregate publishes in version\n * order, a failing aggregate holds back only itself, a poisoned one is\n * quarantined without blocking another, and a consumer discards a stale\n * version.\n */\nexport const describeOutboxContract = (\n name: string,\n make: () => Effect.Effect<OutboxUnderTest, unknown>,\n): void => {\n const run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n describe(`Outbox contract: ${name}`, () => {\n it('recognises a duplicate enqueue by event id', async () => {\n const { outbox } = await run(make());\n const first = event('a', 1);\n\n expect(await run(outbox.enqueue(first))).toBe('enqueued');\n expect(await run(outbox.enqueue(first))).toBe('duplicate');\n });\n\n it('publishes each aggregate in version order', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus();\n\n expect(await run(drain(bus, 3))).toBe(3);\n expect(\n published.filter(e => e.aggregate?.id === 'a').map(e => e.version),\n ).toEqual([1, 2]);\n expect((await run(outbox.stats())).pending).toBe(0);\n });\n\n // The record's point: a failing head holds back its own aggregate only.\n it('holds back only the aggregate whose head failed', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('a', 2), event('b', 1)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 3));\n\n expect(published.map(e => e.id)).toEqual(['b:1']);\n expect((await run(outbox.stats())).pending).toBe(2);\n });\n\n it('quarantines a poisoned aggregate without blocking another', async () => {\n const { outbox, drain } = await run(make());\n for (const entry of [event('a', 1), event('b', 1), event('a', 2)])\n await run(outbox.enqueue(entry));\n const { bus, published } = recordingBus(new Set(['a:1']));\n\n await run(drain(bus, 1));\n\n expect(published.map(e => e.id)).toEqual(['b:1', 'a:2']);\n expect(await run(outbox.stats())).toMatchObject({\n pending: 0,\n quarantined: 1,\n });\n });\n\n it('lets a consumer discard a version it already applied', async () => {\n const apply = Effect.succeed('applied' as const);\n\n expect(await run(discardIfStale(Effect.succeed(2), 1, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 2, apply))).toBe(\n 'stale',\n );\n expect(await run(discardIfStale(Effect.succeed(2), 3, apply))).toBe(\n 'applied',\n );\n expect(\n await run(discardIfStale(Effect.succeed(undefined), 1, apply)),\n ).toBe('applied');\n });\n });\n};\n"],"names":["Unavailable","discardIfStale","Effect","describe","expect","it","clock","event","aggregate","version","name","id","String","source","at","Date","UTC","toISOString","type","data","recordingBus","refuse","Set","published","bus","publish","published_","has","fail","dependency","sync","push","subscribe","void","describeOutboxContract","make","run","effect","runPromise","outbox","first","enqueue","toBe","drain","entry","filter","e","map","toEqual","stats","pending","toMatchObject","quarantined","apply","succeed","undefined"],"mappings":"AAAA,SAA2BA,WAAW,QAAQ,gBAA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;QACnD;QAEArC,GAAG,6DAA6D;YAC9D,MAAM,EAAEkC,MAAM,EAAEI,KAAK,EAAE,GAAG,MAAMP,IAAID;YACpC,KAAK,MAAMS,SAAS;gBAACrC,MAAM,KAAK;gBAAIA,MAAM,KAAK;gBAAIA,MAAM,KAAK;aAAG,CAC/D,MAAM6B,IAAIG,OAAOE,OAAO,CAACG;YAC3B,MAAM,EAAEpB,GAAG,EAAED,SAAS,EAAE,GAAGH,aAAa,IAAIE,IAAI;gBAAC;aAAM;YAEvD,MAAMc,IAAIO,MAAMnB,KAAK;YAErBpB,OAAOmB,UAAUwB,GAAG,CAACD,CAAAA,IAAKA,EAAEnC,EAAE,GAAGqC,OAAO,CAAC;gBAAC;gBAAO;aAAM;YACvD5C,OAAO,MAAMgC,IAAIG,OAAOU,KAAK,KAAKE,aAAa,CAAC;gBAC9CD,SAAS;gBACTE,aAAa;YACf;QACF;QAEA/C,GAAG,wDAAwD;YACzD,MAAMgD,QAAQnD,OAAOoD,OAAO,CAAC;YAE7BlD,OAAO,MAAMgC,IAAInC,eAAeC,OAAOoD,OAAO,CAAC,IAAI,GAAGD,SAASX,IAAI,CACjE;YAEFtC,OAAO,MAAMgC,IAAInC,eAAeC,OAAOoD,OAAO,CAAC,IAAI,GAAGD,SAASX,IAAI,CACjE;YAEFtC,OAAO,MAAMgC,IAAInC,eAAeC,OAAOoD,OAAO,CAAC,IAAI,GAAGD,SAASX,IAAI,CACjE;YAEFtC,OACE,MAAMgC,IAAInC,eAAeC,OAAOoD,OAAO,CAACC,YAAY,GAAGF,SACvDX,IAAI,CAAC;QACT;IACF;AACF,EAAE"}
@@ -1,4 +1,4 @@
1
- import type { DomainEvent } from '@entifix/core';
1
+ import { type DomainEvent } from '@entifix/core';
2
2
  import type { EventBus, LockService, SequenceService, TransactionInbox } from '@entifix/transactions';
3
3
  /**
4
4
  * What every {@link LockService} must guarantee: exclusivity while held,
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-ports.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/transaction-ports.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,eAAe,CAAC;AACjD,OAAO,KAAK,EACV,QAAQ,EACR,WAAW,EACX,eAAe,EAEf,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAqB/B;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,MAAM,MAAM,EACZ,iBAAiB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,KACxD,IAqDF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,GAC1C,MAAM,MAAM,EACZ,qBAAqB,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,KACpE,IA6BF,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACtC,GAAG,EAAE,QAAQ,CAAC;IACd,oEAAoE;IACpE,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,8DAA8D;IAC9D,SAAS,IAAI,WAAW,EAAE,CAAC;CAC5B;AAwCD;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,GACnC,MAAM,MAAM,EACZ,aAAa,MAAM,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC,KAC5E,IAkDF,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,gCAAgC,GAC3C,MAAM,MAAM,EACZ,WAAW,CAAC,QAAQ,EAAE,MAAM,KAAK,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,KAC5E,IAyCF,CAAC"}
1
+ {"version":3,"file":"transaction-ports.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/transaction-ports.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,WAAW,EAAiB,MAAM,eAAe,CAAC;AAChE,OAAO,KAAK,EACV,QAAQ,EACR,WAAW,EACX,eAAe,EAEf,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAqB/B;;;;;;GAMG;AACH,eAAO,MAAM,2BAA2B,GACtC,MAAM,MAAM,EACZ,iBAAiB,MAAM,WAAW,GAAG,OAAO,CAAC,WAAW,CAAC,KACxD,IAqDF,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,+BAA+B,GAC1C,MAAM,MAAM,EACZ,qBAAqB,MAAM,eAAe,GAAG,OAAO,CAAC,eAAe,CAAC,KACpE,IA6BF,CAAC;AAEF,MAAM,WAAW,uBAAuB;IACtC,GAAG,EAAE,QAAQ,CAAC;IACd,oEAAoE;IACpE,OAAO,CAAC,KAAK,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3C,8DAA8D;IAC9D,SAAS,IAAI,WAAW,EAAE,CAAC;CAC5B;AAiDD;;;;;GAKG;AACH,eAAO,MAAM,wBAAwB,GACnC,MAAM,MAAM,EACZ,aAAa,MAAM,uBAAuB,GAAG,OAAO,CAAC,uBAAuB,CAAC,KAC5E,IAkDF,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,gCAAgC,GAC3C,MAAM,MAAM,EACZ,WAAW,CAAC,QAAQ,EAAE,MAAM,KAAK,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,KAC5E,IAyCF,CAAC"}
@@ -1,4 +1,5 @@
1
- import { Duration, Effect, Exit, Fiber } from 'effect';
1
+ import { registerEvent } from '@entifix/core';
2
+ import { Duration, Effect, Exit, Fiber, Schema } from 'effect';
2
3
  import { TestClock } from 'effect/testing';
3
4
  import { describe, expect, it } from 'vitest';
4
5
  /**
@@ -106,6 +107,14 @@ const run = (effect)=>Effect.runPromise(effect);
106
107
  */ const collectInto = (sink)=>(event)=>Effect.sync(()=>{
107
108
  sink.push(event);
108
109
  });
110
+ // A transport encodes and decodes through the registry, so the suite's own
111
+ // event is registered like any other — audience-free, since nothing here
112
+ // delivers to a person.
113
+ registerEvent('contract.widget.created', Schema.Struct({
114
+ entity: Schema.String
115
+ }), {
116
+ audience: 'none'
117
+ });
109
118
  const anEvent = (id, name = 'contract.widget.created')=>({
110
119
  name,
111
120
  id,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import type { DomainEvent } from '@entifix/core';\nimport type {\n EventBus,\n LockService,\n SequenceService,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Duration, Effect, Exit, Fiber } from 'effect';\nimport { TestClock } from 'effect/testing';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds\n * costs none of the wall clock.\n */\nconst effectIt = {\n effect: (name: string, body: () => Effect.Effect<unknown, unknown>) =>\n it(name, () =>\n Effect.runPromise(\n body().pipe(Effect.provide(TestClock.layer()), Effect.scoped),\n ),\n ),\n};\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/**\n * What every {@link LockService} must guarantee: exclusivity while held,\n * availability after release, and a release that only frees the caller's own\n * lock. The last one is why `release` takes a handle rather than a key — a lock\n * that lapsed and was re-acquired by someone else must not be freed by the\n * previous holder.\n */\nexport const describeLockServiceContract = (\n name: string,\n makeLockService: () => LockService | Promise<LockService>,\n): void => {\n describe(`LockService contract: ${name}`, () => {\n it('acquires an uncontended key', async () => {\n const locks = await makeLockService();\n\n const handle = await run(locks.acquire('contract:free'));\n\n expect(handle.key).toBe('contract:free');\n expect(handle.token).toBeTruthy();\n });\n\n // An implementation may retry before giving up (the Redis adapter waits out\n // a bounded budget), so this runs on a TestClock: the assertion is about\n // exclusivity, and it should not cost seconds of wall clock to make.\n effectIt.effect('refuses a key that is already held', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n yield* locks.acquire('contract:taken');\n\n const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n\n it('makes the key available again after release', async () => {\n const locks = await makeLockService();\n const handle = await run(locks.acquire('contract:cycle'));\n\n await run(locks.release(handle));\n const reacquired = await run(locks.acquire('contract:cycle'));\n\n expect(reacquired.key).toBe('contract:cycle');\n });\n\n effectIt.effect('ignores a release whose token does not match', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n const handle = yield* locks.acquire('contract:stolen');\n\n yield* locks.release({ key: handle.key, token: 'not-mine' });\n\n // Still held, so a fresh acquisition must fail.\n const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n });\n};\n\n/**\n * What every {@link SequenceService} must guarantee: strictly increasing values\n * per name, never repeating, with names independent of one another. This is the\n * property incremental codes rest on.\n */\nexport const describeSequenceServiceContract = (\n name: string,\n makeSequenceService: () => SequenceService | Promise<SequenceService>,\n): void => {\n describe(`SequenceService contract: ${name}`, () => {\n it('starts at 1', async () => {\n const sequences = await makeSequenceService();\n\n expect(await run(sequences.next('contract:fresh'))).toBe(1);\n });\n\n it('never returns the same value twice for a name', async () => {\n const sequences = await makeSequenceService();\n\n const drawn = [\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n ];\n\n expect(drawn).toEqual([1, 2, 3]);\n expect(new Set(drawn).size).toBe(drawn.length);\n });\n\n it('keeps separate names independent', async () => {\n const sequences = await makeSequenceService();\n await run(sequences.next('contract:a'));\n await run(sequences.next('contract:a'));\n\n expect(await run(sequences.next('contract:b'))).toBe(1);\n });\n });\n};\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["Duration","Effect","Exit","Fiber","TestClock","describe","expect","it","effectIt","effect","name","body","runPromise","pipe","provide","layer","scoped","run","describeLockServiceContract","makeLockService","locks","handle","acquire","key","toBe","token","toBeTruthy","gen","promise","fiber","forkChild","adjust","minutes","exit","await","isFailure","release","reacquired","describeSequenceServiceContract","makeSequenceService","sequences","next","drawn","toEqual","Set","size","length","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","anEvent","id","source","at","Date","toISOString","correlationId","data","entity","describeEventBusContract","makeHarness","harness","bus","publish","published","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","first","second"],"mappings":"AAQA,SAASA,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,QAAQ,SAAS;AACvD,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C;;;CAGC,GACD,MAAMC,WAAW;IACfC,QAAQ,CAACC,MAAcC,OACrBJ,GAAGG,MAAM,IACPT,OAAOW,UAAU,CACfD,OAAOE,IAAI,CAACZ,OAAOa,OAAO,CAACV,UAAUW,KAAK,KAAKd,OAAOe,MAAM;AAGpE;AAEA,MAAMC,MAAM,CAAiBR,SAC3BR,OAAOW,UAAU,CAACH;AAEpB;;;;;;CAMC,GACD,OAAO,MAAMS,8BAA8B,CACzCR,MACAS;IAEAd,SAAS,CAAC,sBAAsB,EAAEK,MAAM,EAAE;QACxCH,GAAG,+BAA+B;YAChC,MAAMa,QAAQ,MAAMD;YAEpB,MAAME,SAAS,MAAMJ,IAAIG,MAAME,OAAO,CAAC;YAEvChB,OAAOe,OAAOE,GAAG,EAAEC,IAAI,CAAC;YACxBlB,OAAOe,OA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version":3,"sources":["../../src/contracts/transaction-ports.contract.ts"],"sourcesContent":["import { type DomainEvent, registerEvent } from '@entifix/core';\nimport type {\n EventBus,\n LockService,\n SequenceService,\n Subscription,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Duration, Effect, Exit, Fiber, Schema } from 'effect';\nimport { TestClock } from 'effect/testing';\nimport { describe, expect, it } from 'vitest';\n\n/**\n * Runs an Effect test on a `TestClock`, so a retry budget measured in seconds\n * costs none of the wall clock.\n */\nconst effectIt = {\n effect: (name: string, body: () => Effect.Effect<unknown, unknown>) =>\n it(name, () =>\n Effect.runPromise(\n body().pipe(Effect.provide(TestClock.layer()), Effect.scoped),\n ),\n ),\n};\n\nconst run = <TValue, TError>(effect: Effect.Effect<TValue, TError>) =>\n Effect.runPromise(effect);\n\n/**\n * What every {@link LockService} must guarantee: exclusivity while held,\n * availability after release, and a release that only frees the caller's own\n * lock. The last one is why `release` takes a handle rather than a key — a lock\n * that lapsed and was re-acquired by someone else must not be freed by the\n * previous holder.\n */\nexport const describeLockServiceContract = (\n name: string,\n makeLockService: () => LockService | Promise<LockService>,\n): void => {\n describe(`LockService contract: ${name}`, () => {\n it('acquires an uncontended key', async () => {\n const locks = await makeLockService();\n\n const handle = await run(locks.acquire('contract:free'));\n\n expect(handle.key).toBe('contract:free');\n expect(handle.token).toBeTruthy();\n });\n\n // An implementation may retry before giving up (the Redis adapter waits out\n // a bounded budget), so this runs on a TestClock: the assertion is about\n // exclusivity, and it should not cost seconds of wall clock to make.\n effectIt.effect('refuses a key that is already held', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n yield* locks.acquire('contract:taken');\n\n const fiber = yield* Effect.forkChild(locks.acquire('contract:taken'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n\n it('makes the key available again after release', async () => {\n const locks = await makeLockService();\n const handle = await run(locks.acquire('contract:cycle'));\n\n await run(locks.release(handle));\n const reacquired = await run(locks.acquire('contract:cycle'));\n\n expect(reacquired.key).toBe('contract:cycle');\n });\n\n effectIt.effect('ignores a release whose token does not match', () =>\n Effect.gen(function* () {\n const locks = yield* Effect.promise(async () => makeLockService());\n const handle = yield* locks.acquire('contract:stolen');\n\n yield* locks.release({ key: handle.key, token: 'not-mine' });\n\n // Still held, so a fresh acquisition must fail.\n const fiber = yield* Effect.forkChild(locks.acquire('contract:stolen'));\n yield* TestClock.adjust(Duration.minutes(1));\n const exit = yield* Fiber.await(fiber);\n\n expect(Exit.isFailure(exit)).toBe(true);\n }),\n );\n });\n};\n\n/**\n * What every {@link SequenceService} must guarantee: strictly increasing values\n * per name, never repeating, with names independent of one another. This is the\n * property incremental codes rest on.\n */\nexport const describeSequenceServiceContract = (\n name: string,\n makeSequenceService: () => SequenceService | Promise<SequenceService>,\n): void => {\n describe(`SequenceService contract: ${name}`, () => {\n it('starts at 1', async () => {\n const sequences = await makeSequenceService();\n\n expect(await run(sequences.next('contract:fresh'))).toBe(1);\n });\n\n it('never returns the same value twice for a name', async () => {\n const sequences = await makeSequenceService();\n\n const drawn = [\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n await run(sequences.next('contract:codes')),\n ];\n\n expect(drawn).toEqual([1, 2, 3]);\n expect(new Set(drawn).size).toBe(drawn.length);\n });\n\n it('keeps separate names independent', async () => {\n const sequences = await makeSequenceService();\n await run(sequences.next('contract:a'));\n await run(sequences.next('contract:a'));\n\n expect(await run(sequences.next('contract:b'))).toBe(1);\n });\n });\n};\n\nexport interface EventBusContractHarness {\n bus: EventBus;\n /** Delivers `event` to whatever subscribed, as the broker would. */\n deliver(event: DomainEvent): Promise<void>;\n /** Everything the bus published, decoded back into events. */\n published(): DomainEvent[];\n}\n\n/** Every subscription in this contract, unless a test says otherwise. */\nconst ANY_WIDGET_EVENT = 'contract.widget.*';\n\n/**\n * A `work` subscription for `pattern`. The mode and the ceiling are broker\n * facts with no bearing on routing, so a test about routing states them once\n * here rather than repeating them at every call.\n */\nconst on = (pattern: string): Subscription => ({\n slice: 'contract',\n pattern,\n mode: 'work',\n maxAttempts: 5,\n});\n\n/**\n * A handler that records what it is given. Shared by both routing tests so the\n * \"nothing was delivered\" case asserts on the *same* handler the positive case\n * proves works — otherwise it could pass against a handler that was simply\n * never wired up.\n */\nconst collectInto = (sink: DomainEvent[]) => (event: DomainEvent) =>\n Effect.sync(() => {\n sink.push(event);\n });\n\n// A transport encodes and decodes through the registry, so the suite's own\n// event is registered like any other — audience-free, since nothing here\n// delivers to a person.\nregisterEvent(\n 'contract.widget.created',\n Schema.Struct({ entity: Schema.String }),\n { audience: 'none' },\n);\n\nconst anEvent = (\n id: string,\n name = 'contract.widget.created',\n): DomainEvent => ({\n name,\n id,\n source: 'contract-slice',\n at: new Date('2026-01-01T00:00:00.000Z').toISOString(),\n correlationId: id,\n data: { entity: 'contract-widget' },\n});\n\n/**\n * What every {@link EventBus} must guarantee: what goes out comes back\n * unchanged, subscribers receive deliveries, and a subscriber receives only what\n * its pattern matches. The transports differ wildly (an array here, a topic\n * exchange in RabbitMQ) — the observable contract does not.\n */\nexport const describeEventBusContract = (\n name: string,\n makeHarness: () => EventBusContractHarness | Promise<EventBusContractHarness>,\n): void => {\n describe(`EventBus contract: ${name}`, () => {\n it('publishes an event verbatim', async () => {\n const harness = await makeHarness();\n const event = anEvent('tx-1');\n\n await run(harness.bus.publish(event));\n\n expect(harness.published()).toEqual([event]);\n });\n\n it('delivers published events to a subscriber', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on(ANY_WIDGET_EVENT), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-2'));\n\n expect(received.map(event => event.id)).toEqual(['tx-2']);\n });\n\n // Routing is the transport's job. A bus that hands every subscriber every\n // event lets a consumer pass while receiving traffic it never bound to —\n // which is precisely the fault the fanout exchange had.\n it('delivers nothing to a subscriber whose pattern does not match', async () => {\n const harness = await makeHarness();\n const received: DomainEvent[] = [];\n await run(\n harness.bus.subscribe(on('contract.other.*'), collectInto(received)),\n );\n\n await harness.deliver(anEvent('tx-5'));\n\n expect(received).toEqual([]);\n });\n\n it('preserves publication order', async () => {\n const harness = await makeHarness();\n\n await run(harness.bus.publish(anEvent('tx-3')));\n await run(harness.bus.publish(anEvent('tx-4')));\n\n expect(harness.published().map(event => event.id)).toEqual([\n 'tx-3',\n 'tx-4',\n ]);\n });\n });\n};\n\n/**\n * What every {@link TransactionInbox} must guarantee: a first claim is granted,\n * every repeat of it is refused, and one consumer's claim says nothing about\n * another's.\n *\n * That last one is the property with teeth. Two consumers legitimately process\n * the same event — the saga tracker's fold and the SSE hub both bind\n * `transaction.*` — so an implementation keyed on `eventId` alone passes the\n * first two cases and silently starves every consumer but the first. It looks\n * like exactly-once from inside one consumer, which is why it is asserted here\n * rather than left to each adapter's own spec.\n */\nexport const describeTransactionInboxContract = (\n name: string,\n makeInbox: (consumer: string) => TransactionInbox | Promise<TransactionInbox>,\n): void => {\n describe(`TransactionInbox contract: ${name}`, () => {\n it('grants a first claim', async () => {\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-1:completed'))).toBe('claimed');\n });\n\n it('refuses a redelivery of the same event', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-2:completed'));\n\n expect(await run(inbox.claim('tx-2:completed'))).toBe('duplicate');\n });\n\n it('refuses every repeat, not only the second', async () => {\n const inbox = await makeInbox('contract.consumer');\n await run(inbox.claim('tx-3:completed'));\n\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n expect(await run(inbox.claim('tx-3:completed'))).toBe('duplicate');\n });\n\n it('claims each step of one transaction separately', async () => {\n // `<transactionId>:<step>`, never the transaction id alone: one\n // transaction emits up to three messages, and keying on the correlation\n // id would make `completed` read as a redelivery of `accepted`.\n const inbox = await makeInbox('contract.consumer');\n\n expect(await run(inbox.claim('tx-4:accepted'))).toBe('claimed');\n expect(await run(inbox.claim('tx-4:completed'))).toBe('claimed');\n });\n\n it('does not let one consumer consume another consumer’s claim', async () => {\n const first = await makeInbox('contract.first');\n const second = await makeInbox('contract.second');\n await run(first.claim('tx-5:completed'));\n\n expect(await run(second.claim('tx-5:completed'))).toBe('claimed');\n });\n });\n};\n"],"names":["registerEvent","Duration","Effect","Exit","Fiber","Schema","TestClock","describe","expect","it","effectIt","effect","name","body","runPromise","pipe","provide","layer","scoped","run","describeLockServiceContract","makeLockService","locks","handle","acquire","key","toBe","token","toBeTruthy","gen","promise","fiber","forkChild","adjust","minutes","exit","await","isFailure","release","reacquired","describeSequenceServiceContract","makeSequenceService","sequences","next","drawn","toEqual","Set","size","length","ANY_WIDGET_EVENT","on","pattern","slice","mode","maxAttempts","collectInto","sink","event","sync","push","Struct","entity","String","audience","anEvent","id","source","at","Date","toISOString","correlationId","data","describeEventBusContract","makeHarness","harness","bus","publish","published","received","subscribe","deliver","map","describeTransactionInboxContract","makeInbox","inbox","claim","first","second"],"mappings":"AAAA,SAA2BA,aAAa,QAAQ,gBAAgB;AAQhE,SAASC,QAAQ,EAAEC,MAAM,EAAEC,IAAI,EAAEC,KAAK,EAAEC,MAAM,QAAQ,SAAS;AAC/D,SAASC,SAAS,QAAQ,iBAAiB;AAC3C,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C;;;CAGC,GACD,MAAMC,WAAW;IACfC,QAAQ,CAACC,MAAcC,OACrBJ,GAAGG,MAAM,IACPV,OAAOY,UAAU,CACfD,OAAOE,IAAI,CAACb,OAAOc,OAAO,CAACV,UAAUW,KAAK,KAAKf,OAAOgB,MAAM;AAGpE;AAEA,MAAMC,MAAM,CAAiBR,SAC3BT,OAAOY,UAAU,CAACH;AAEpB;;;;;;CAMC,GACD,OAAO,MAAMS,8BAA8B,CACzCR,MACAS;IAEAd,SAAS,CAAC,sBAAsB,EAAEK,MAAM,EAAE;QACxCH,GAAG,+BAA+B;YAChC,MAAMa,QAA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BAAyB,CAAC,CAAC,CAAC,CAAC,KACrE,IA6MF,CAAC"}
1
+ {"version":3,"file":"unit-of-work.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/unit-of-work.contract.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,UAAU,EAAe,MAAM,eAAe,CAAC;AAC7D,OAAO,KAAK,EAAe,UAAU,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,MAAM,EAAU,MAAM,QAAQ,CAAC;AAGxC,wEAAwE;AACxE,MAAM,WAAW,yBAAyB,CAAC,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC;IACnC,mDAAmD;IACnD,KAAK,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IAC9D,+DAA+D;IAC/D,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;IAClE,0DAA0D;IAC1D,MAAM,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IACrC,+CAA+C;IAC/C,QAAQ,IAAI,OAAO,CAAC,SAAS,MAAM,EAAE,CAAC,CAAC;CACxC;AAeD;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,GAAI,CAAC,EAC1C,MAAM,MAAM,EACZ,aAAa,MACX,yBAAyB,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC,CAAC,CAAC,KACrE,IA6MF,CAAC"}
@@ -7,6 +7,11 @@ const anEvent = (id)=>({
7
7
  source: 'contract-slice',
8
8
  at: '2026-01-01T00:00:00.000Z',
9
9
  correlationId: id,
10
+ aggregate: {
11
+ type: 'contract-widget',
12
+ id
13
+ },
14
+ version: 1,
10
15
  data: {}
11
16
  });
12
17
  const run = (effect)=>Effect.runPromise(effect);
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/unit-of-work.contract.ts"],"sourcesContent":["import { type DomainEvent, type StoreFault, Unavailable } from '@entifix/core';\nimport type { UnitOfWork } from '@entifix/transactions';\nimport { Effect, Option } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What {@link describeUnitOfWorkContract} needs to observe a store. */\nexport interface UnitOfWorkContractHarness<H> {\n readonly unitOfWork: UnitOfWork<H>;\n /** Writes one record through the unit's handle. */\n write(handle: H, id: string): Effect.Effect<void, StoreFault>;\n /** Whether a record exists, read through the unit's handle. */\n readIn(handle: H, id: string): Effect.Effect<boolean, StoreFault>;\n /** Whether a record is durable, read outside any unit. */\n stored(id: string): Promise<boolean>;\n /** The ids of every event the outbox holds. */\n recorded(): Promise<readonly string[]>;\n}\n\nconst anEvent = (id: string): DomainEvent => ({\n name: 'contract.widget.changed',\n id,\n source: 'contract-slice',\n at: '2026-01-01T00:00:00.000Z',\n correlationId: id,\n data: {},\n});\n\nconst run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n/**\n * What every {@link UnitOfWork} must guarantee: the writes, the events and the\n * claim of one unit commit or vanish together; a taken claim turns the next\n * unit into a `duplicate` without running it; a business failure is an\n * `aborted` value and a store failure is an error; and what a unit wrote is\n * visible to itself before it commits.\n */\nexport const describeUnitOfWorkContract = <H>(\n name: string,\n makeHarness: () =>\n UnitOfWorkContractHarness<H> | Promise<UnitOfWorkContractHarness<H>>,\n): void => {\n describe(`UnitOfWork contract: ${name}`, () => {\n it('commits the writes and the events together', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-1').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-1')))),\n Effect.as('done'),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: 'done' });\n expect(await harness.stored('w-1')).toBe(true);\n expect(await harness.recorded()).toContain('e-1');\n });\n\n it('answers a business failure as aborted, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-2').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-2')))),\n Effect.andThen(Effect.fail('outOfStock' as const)),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'aborted', reason: 'outOfStock' });\n expect(await harness.stored('w-2')).toBe(false);\n expect(await harness.recorded()).not.toContain('e-2');\n });\n\n it('surfaces a store failure as an error, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const error = await run(\n harness.unitOfWork\n .run(unit =>\n harness\n .write(unit.handle, 'w-3')\n .pipe(\n Effect.andThen(\n Effect.fail(new Unavailable({ dependency: 'store' })),\n ),\n ),\n )\n .pipe(Effect.flip),\n );\n\n expect(error).toMatchObject({ _tag: 'Unavailable' });\n expect(await harness.stored('w-3')).toBe(false);\n });\n\n it('lets a unit read its own uncommitted writes', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, 'w-4')\n .pipe(Effect.andThen(harness.readIn(unit.handle, 'w-4'))),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: true });\n });\n\n it('turns a second unit on a taken event claim into a duplicate that does not run', async () => {\n const harness = await makeHarness();\n const claim = {\n kind: 'event',\n consumer: 'contract.fold',\n eventId: 'm-1',\n } as const;\n let runs = 0;\n const body = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n return harness.write(unit.handle, `fold-${runs}`);\n });\n\n const first = await run(harness.unitOfWork.run(body, { claim }));\n const second = await run(harness.unitOfWork.run(body, { claim }));\n\n expect(first._tag).toBe('committed');\n expect(second).toEqual({ _tag: 'duplicate', replay: Option.none() });\n expect(await harness.stored('fold-2')).toBe(false);\n });\n\n it('keys an event claim on the consumer as well as the event', async () => {\n const harness = await makeHarness();\n const noop = () => Effect.void;\n\n const one = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.a', eventId: 'm-2' },\n }),\n );\n const other = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.b', eventId: 'm-2' },\n }),\n );\n\n expect(one._tag).toBe('committed');\n expect(other._tag).toBe('committed');\n });\n\n it('answers a duplicate command with what the first run remembered', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-1' } as const;\n const options = {\n claim,\n replay: (value: { paymentId: string }) => value,\n };\n\n let runs = 0;\n const capture = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n const paymentId = `pay-${runs}`;\n return harness\n .write(unit.handle, paymentId)\n .pipe(Effect.as({ paymentId }));\n });\n\n await run(harness.unitOfWork.run(capture, options));\n const again = await run(harness.unitOfWork.run(capture, options));\n\n expect(again).toEqual({\n _tag: 'duplicate',\n replay: Option.some({ paymentId: 'pay-1' }),\n });\n // A redelivered capture must not charge again, so the body never reruns.\n expect(runs).toBe(1);\n expect(await run(harness.unitOfWork.replay('c-1'))).toEqual(\n Option.some({ paymentId: 'pay-1' }),\n );\n expect(await run(harness.unitOfWork.replay('c-unknown'))).toEqual(\n Option.none(),\n );\n });\n\n it('leaves a claim untaken when its unit aborts', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-2' } as const;\n\n const refused = await run(\n harness.unitOfWork.run(() => Effect.fail('declined' as const), {\n claim,\n }),\n );\n const retried = await run(\n harness.unitOfWork.run(() => Effect.succeed('ok'), { claim }),\n );\n\n expect(refused._tag).toBe('aborted');\n expect(retried).toEqual({ _tag: 'committed', value: 'ok' });\n });\n\n it('treats an event id already in the outbox as a duplicate', async () => {\n const harness = await makeHarness();\n const announce = (id: string) =>\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, id)\n .pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-same')))),\n ),\n );\n\n await run(announce('w-5'));\n const again = await run(announce('w-6'));\n\n expect(again._tag).toBe('duplicate');\n expect(await harness.stored('w-6')).toBe(false);\n });\n\n it('runs afterCommit only on commit, and never lets it change the outcome', async () => {\n const harness = await makeHarness();\n const ran: string[] = [];\n const after = (label: string) => ({\n afterCommit: Effect.sync(() => ran.push(label)).pipe(\n Effect.andThen(Effect.fail('drain failed')),\n ),\n });\n\n const committed = await run(\n harness.unitOfWork.run(() => Effect.succeed(1), after('commit')),\n );\n await run(\n harness.unitOfWork.run(\n () => Effect.fail('no' as const),\n after('abort'),\n ),\n );\n\n expect(committed).toEqual({ _tag: 'committed', value: 1 });\n expect(ran).toEqual(['commit']);\n });\n });\n};\n"],"names":["Unavailable","Effect","Option","describe","expect","it","anEvent","id","name","source","at","correlationId","data","run","effect","runPromise","describeUnitOfWorkContract","makeHarness","harness","outcome","unitOfWork","unit","write","handle","pipe","tap","sync","emit","as","toEqual","_tag","value","stored","toBe","recorded","toContain","andThen","fail","reason","not","error","dependency","flip","toMatchObject","readIn","claim","kind","consumer","eventId","runs","body","suspend","first","second","replay","none","noop","void","one","other","commandId","options","capture","paymentId","again","some","refused","retried","succeed","announce","ran","after","label","afterCommit","push","committed"],"mappings":"AAAA,SAA4CA,WAAW,QAAQ,gBAAgB;AAE/E,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AACxC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAe9C,MAAMC,UAAU,CAACC,KAA6B,CAAA;QAC5CC,MAAM;QACND;QACAE,QAAQ;QACRC,IAAI;QACJC,eAAeJ;QACfK,MAAM,CAAC;IACT,CAAA;AAEA,MAAMC,MAAM,CAAOC,SAAgCb,OAAOc,UAAU,CAACD;AAErE;;;;;;CAMC,GACD,OAAO,MAAME,6BAA6B,CACxCR,MACAS;IAGAd,SAAS,CAAC,qBAAqB,EAAEK,MAAM,EAAE;QACvCH,GAAG,8CAA8C;YAC/C,MAAMa,UAAU,MAAMD;YAEtB,MAAME,UAAU,MAAMN,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OyB,IAAI,CAAC,IAAM4C,IAAII,IAAI,CAACF,QAAQhD,IAAI,CAClDvB,OAAOmC,OAAO,CAACnC,OAAOoC,IAAI,CAAC;gBAE/B,CAAA;YAEA,MAAMsC,YAAY,MAAM9D,IACtBK,QAAQE,UAAU,CAACP,GAAG,CAAC,IAAMZ,OAAOmE,OAAO,CAAC,IAAIG,MAAM;YAExD,MAAM1D,IACJK,QAAQE,UAAU,CAACP,GAAG,CACpB,IAAMZ,OAAOoC,IAAI,CAAC,OAClBkC,MAAM;YAIVnE,OAAOuE,WAAW9C,OAAO,CAAC;gBAAEC,MAAM;gBAAaC,OAAO;YAAE;YACxD3B,OAAOkE,KAAKzC,OAAO,CAAC;gBAAC;aAAS;QAChC;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/contracts/unit-of-work.contract.ts"],"sourcesContent":["import { type StoreFault, Unavailable } from '@entifix/core';\nimport type { OutboxEvent, UnitOfWork } from '@entifix/transactions';\nimport { Effect, Option } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\n/** What {@link describeUnitOfWorkContract} needs to observe a store. */\nexport interface UnitOfWorkContractHarness<H> {\n readonly unitOfWork: UnitOfWork<H>;\n /** Writes one record through the unit's handle. */\n write(handle: H, id: string): Effect.Effect<void, StoreFault>;\n /** Whether a record exists, read through the unit's handle. */\n readIn(handle: H, id: string): Effect.Effect<boolean, StoreFault>;\n /** Whether a record is durable, read outside any unit. */\n stored(id: string): Promise<boolean>;\n /** The ids of every event the outbox holds. */\n recorded(): Promise<readonly string[]>;\n}\n\nconst anEvent = (id: string): OutboxEvent => ({\n name: 'contract.widget.changed',\n id,\n source: 'contract-slice',\n at: '2026-01-01T00:00:00.000Z',\n correlationId: id,\n aggregate: { type: 'contract-widget', id },\n version: 1,\n data: {},\n});\n\nconst run = <A, E>(effect: Effect.Effect<A, E>) => Effect.runPromise(effect);\n\n/**\n * What every {@link UnitOfWork} must guarantee: the writes, the events and the\n * claim of one unit commit or vanish together; a taken claim turns the next\n * unit into a `duplicate` without running it; a business failure is an\n * `aborted` value and a store failure is an error; and what a unit wrote is\n * visible to itself before it commits.\n */\nexport const describeUnitOfWorkContract = <H>(\n name: string,\n makeHarness: () =>\n UnitOfWorkContractHarness<H> | Promise<UnitOfWorkContractHarness<H>>,\n): void => {\n describe(`UnitOfWork contract: ${name}`, () => {\n it('commits the writes and the events together', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-1').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-1')))),\n Effect.as('done'),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: 'done' });\n expect(await harness.stored('w-1')).toBe(true);\n expect(await harness.recorded()).toContain('e-1');\n });\n\n it('answers a business failure as aborted, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness.write(unit.handle, 'w-2').pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-2')))),\n Effect.andThen(Effect.fail('outOfStock' as const)),\n ),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'aborted', reason: 'outOfStock' });\n expect(await harness.stored('w-2')).toBe(false);\n expect(await harness.recorded()).not.toContain('e-2');\n });\n\n it('surfaces a store failure as an error, and writes nothing', async () => {\n const harness = await makeHarness();\n\n const error = await run(\n harness.unitOfWork\n .run(unit =>\n harness\n .write(unit.handle, 'w-3')\n .pipe(\n Effect.andThen(\n Effect.fail(new Unavailable({ dependency: 'store' })),\n ),\n ),\n )\n .pipe(Effect.flip),\n );\n\n expect(error).toMatchObject({ _tag: 'Unavailable' });\n expect(await harness.stored('w-3')).toBe(false);\n });\n\n it('lets a unit read its own uncommitted writes', async () => {\n const harness = await makeHarness();\n\n const outcome = await run(\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, 'w-4')\n .pipe(Effect.andThen(harness.readIn(unit.handle, 'w-4'))),\n ),\n );\n\n expect(outcome).toEqual({ _tag: 'committed', value: true });\n });\n\n it('turns a second unit on a taken event claim into a duplicate that does not run', async () => {\n const harness = await makeHarness();\n const claim = {\n kind: 'event',\n consumer: 'contract.fold',\n eventId: 'm-1',\n } as const;\n let runs = 0;\n const body = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n return harness.write(unit.handle, `fold-${runs}`);\n });\n\n const first = await run(harness.unitOfWork.run(body, { claim }));\n const second = await run(harness.unitOfWork.run(body, { claim }));\n\n expect(first._tag).toBe('committed');\n expect(second).toEqual({ _tag: 'duplicate', replay: Option.none() });\n expect(await harness.stored('fold-2')).toBe(false);\n });\n\n it('keys an event claim on the consumer as well as the event', async () => {\n const harness = await makeHarness();\n const noop = () => Effect.void;\n\n const one = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.a', eventId: 'm-2' },\n }),\n );\n const other = await run(\n harness.unitOfWork.run(noop, {\n claim: { kind: 'event', consumer: 'contract.b', eventId: 'm-2' },\n }),\n );\n\n expect(one._tag).toBe('committed');\n expect(other._tag).toBe('committed');\n });\n\n it('answers a duplicate command with what the first run remembered', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-1' } as const;\n const options = {\n claim,\n replay: (value: { paymentId: string }) => value,\n };\n\n let runs = 0;\n const capture = (unit: { handle: H }) =>\n Effect.suspend(() => {\n runs += 1;\n const paymentId = `pay-${runs}`;\n return harness\n .write(unit.handle, paymentId)\n .pipe(Effect.as({ paymentId }));\n });\n\n await run(harness.unitOfWork.run(capture, options));\n const again = await run(harness.unitOfWork.run(capture, options));\n\n expect(again).toEqual({\n _tag: 'duplicate',\n replay: Option.some({ paymentId: 'pay-1' }),\n });\n // A redelivered capture must not charge again, so the body never reruns.\n expect(runs).toBe(1);\n expect(await run(harness.unitOfWork.replay('c-1'))).toEqual(\n Option.some({ paymentId: 'pay-1' }),\n );\n expect(await run(harness.unitOfWork.replay('c-unknown'))).toEqual(\n Option.none(),\n );\n });\n\n it('leaves a claim untaken when its unit aborts', async () => {\n const harness = await makeHarness();\n const claim = { kind: 'command', commandId: 'c-2' } as const;\n\n const refused = await run(\n harness.unitOfWork.run(() => Effect.fail('declined' as const), {\n claim,\n }),\n );\n const retried = await run(\n harness.unitOfWork.run(() => Effect.succeed('ok'), { claim }),\n );\n\n expect(refused._tag).toBe('aborted');\n expect(retried).toEqual({ _tag: 'committed', value: 'ok' });\n });\n\n it('treats an event id already in the outbox as a duplicate', async () => {\n const harness = await makeHarness();\n const announce = (id: string) =>\n harness.unitOfWork.run(unit =>\n harness\n .write(unit.handle, id)\n .pipe(\n Effect.tap(() => Effect.sync(() => unit.emit(anEvent('e-same')))),\n ),\n );\n\n await run(announce('w-5'));\n const again = await run(announce('w-6'));\n\n expect(again._tag).toBe('duplicate');\n expect(await harness.stored('w-6')).toBe(false);\n });\n\n it('runs afterCommit only on commit, and never lets it change the outcome', async () => {\n const harness = await makeHarness();\n const ran: string[] = [];\n const after = (label: string) => ({\n afterCommit: Effect.sync(() => ran.push(label)).pipe(\n Effect.andThen(Effect.fail('drain failed')),\n ),\n });\n\n const committed = await run(\n harness.unitOfWork.run(() => Effect.succeed(1), after('commit')),\n );\n await run(\n harness.unitOfWork.run(\n () => Effect.fail('no' as const),\n after('abort'),\n ),\n );\n\n expect(committed).toEqual({ _tag: 'committed', value: 1 });\n expect(ran).toEqual(['commit']);\n });\n });\n};\n"],"names":["Unavailable","Effect","Option","describe","expect","it","anEvent","id","name","source","at","correlationId","aggregate","type","version","data","run","effect","runPromise","describeUnitOfWorkContract","makeHarness","harness","outcome","unitOfWork","unit","write","handle","pipe","tap","sync","emit","as","toEqual","_tag","value","stored","toBe","recorded","toContain","andThen","fail","reason","not","error","dependency","flip","toMatchObject","readIn","claim","kind","consumer","eventId","runs","body","suspend","first","second","replay","none","noop","void","one","other","commandId","options","capture","paymentId","again","some","refused","retried","succeed","announce","ran","after","label","afterCommit","push","committed"],"mappings":"AAAA,SAA0BA,WAAW,QAAQ,gB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MoD,WAAW,CAACjE,KAChBc,QAAQE,UAAU,CAACP,GAAG,CAACQ,CAAAA,OACrBH,QACGI,KAAK,CAACD,KAAKE,MAAM,EAAEnB,IACnBoB,IAAI,CACH1B,OAAO2B,GAAG,CAAC,IAAM3B,OAAO4B,IAAI,CAAC,IAAML,KAAKM,IAAI,CAACxB,QAAQ;YAI7D,MAAMU,IAAIwD,SAAS;YACnB,MAAML,QAAQ,MAAMnD,IAAIwD,SAAS;YAEjCpE,OAAO+D,MAAMlC,IAAI,EAAEG,IAAI,CAAC;YACxBhC,OAAO,MAAMiB,QAAQc,MAAM,CAAC,QAAQC,IAAI,CAAC;QAC3C;QAEA/B,GAAG,yEAAyE;YAC1E,MAAMgB,UAAU,MAAMD;YACtB,MAAMqD,MAAgB,EAAE;YACxB,MAAMC,QAAQ,CAACC,QAAmB,CAAA;oBAChCC,aAAa3E,OAAO4B,IAAI,CAAC,IAAM4C,IAAII,IAAI,CAACF,QAAQhD,IAAI,CAClD1B,OAAOsC,OAAO,CAACtC,OAAOuC,IAAI,CAAC;gBAE/B,CAAA;YAEA,MAAMsC,YAAY,MAAM9D,IACtBK,QAAQE,UAAU,CAACP,GAAG,CAAC,IAAMf,OAAOsE,OAAO,CAAC,IAAIG,MAAM;YAExD,MAAM1D,IACJK,QAAQE,UAAU,CAACP,GAAG,CACpB,IAAMf,OAAOuC,IAAI,CAAC,OAClBkC,MAAM;YAIVtE,OAAO0E,WAAW9C,OAAO,CAAC;gBAAEC,MAAM;gBAAaC,OAAO;YAAE;YACxD9B,OAAOqE,KAAKzC,OAAO,CAAC;gBAAC;aAAS;QAChC;IACF;AACF,EAAE"}
@@ -0,0 +1,15 @@
1
+ import type { DefinedVariants, Variant } from '@entifix/business';
2
+ /**
3
+ * Runs one use case's contract suite once per variant
4
+ * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):
5
+ * a variant is an implementation of the use case, so it is held to the same
6
+ * contract as every other. The `describe` names the variant, so a failure says
7
+ * which implementation broke it.
8
+ */
9
+ export declare const forEachVariant: <I, S>(defined: DefinedVariants<I, S>, suite: (impl: S, variant: Variant<S>) => void) => void;
10
+ /**
11
+ * Every variant of the given use cases that no {@link forEachVariant} call has
12
+ * run a contract against — what a conventions check asserts is empty.
13
+ */
14
+ export declare const variantsWithoutContract: (definitions: readonly DefinedVariants<unknown, unknown>[]) => readonly string[];
15
+ //# sourceMappingURL=variants.contract.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"variants.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/variants.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAgBlE;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,GAAI,CAAC,EAAE,CAAC,EACjC,SAAS,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,EAC9B,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,KAAK,IAAI,KAC5C,IASF,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,uBAAuB,GAClC,aAAa,SAAS,eAAe,CAAC,OAAO,EAAE,OAAO,CAAC,EAAE,KACxD,SAAS,MAAM,EAQf,CAAC"}
@@ -0,0 +1,39 @@
1
+ import { describe } from 'vitest';
2
+ /**
3
+ * The variants a contract suite has run against in this process, per use
4
+ * case. Shared through `globalThis` so two copies of this module — a spec
5
+ * importing the source and a helper importing the build — agree.
6
+ */ const COVERED_KEY = Symbol.for('@entifix/testing-unit/variants-covered');
7
+ const covered = ()=>{
8
+ var _holder, _COVERED_KEY, _;
9
+ const holder = globalThis;
10
+ (_ = (_holder = holder)[_COVERED_KEY = COVERED_KEY]) != null ? _ : _holder[_COVERED_KEY] = new Map();
11
+ return holder[COVERED_KEY];
12
+ };
13
+ /**
14
+ * Runs one use case's contract suite once per variant
15
+ * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):
16
+ * a variant is an implementation of the use case, so it is held to the same
17
+ * contract as every other. The `describe` names the variant, so a failure says
18
+ * which implementation broke it.
19
+ */ export const forEachVariant = (defined, suite)=>{
20
+ for (const variant of defined.variants){
21
+ var _covered_get;
22
+ const names = (_covered_get = covered().get(defined.useCase)) != null ? _covered_get : new Set();
23
+ names.add(variant.name);
24
+ covered().set(defined.useCase, names);
25
+ describe(`${defined.useCase} — variant '${variant.name}'`, ()=>{
26
+ suite(variant.impl, variant);
27
+ });
28
+ }
29
+ };
30
+ /**
31
+ * Every variant of the given use cases that no {@link forEachVariant} call has
32
+ * run a contract against — what a conventions check asserts is empty.
33
+ */ export const variantsWithoutContract = (definitions)=>definitions.flatMap((defined)=>defined.variants.filter((variant)=>{
34
+ var _ref;
35
+ var _covered_get;
36
+ return !((_ref = (_covered_get = covered().get(defined.useCase)) == null ? void 0 : _covered_get.has(variant.name)) != null ? _ref : false);
37
+ }).map((variant)=>`${defined.useCase}:${variant.name}`));
38
+
39
+ //# sourceMappingURL=variants.contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/contracts/variants.contract.ts"],"sourcesContent":["import type { DefinedVariants, Variant } from '@entifix/business';\nimport { describe } from 'vitest';\n\n/**\n * The variants a contract suite has run against in this process, per use\n * case. Shared through `globalThis` so two copies of this module — a spec\n * importing the source and a helper importing the build — agree.\n */\nconst COVERED_KEY = Symbol.for('@entifix/testing-unit/variants-covered');\n\nconst covered = (): Map<string, Set<string>> => {\n const holder = globalThis as { [COVERED_KEY]?: Map<string, Set<string>> };\n holder[COVERED_KEY] ??= new Map();\n return holder[COVERED_KEY];\n};\n\n/**\n * Runs one use case's contract suite once per variant\n * ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)):\n * a variant is an implementation of the use case, so it is held to the same\n * contract as every other. The `describe` names the variant, so a failure says\n * which implementation broke it.\n */\nexport const forEachVariant = <I, S>(\n defined: DefinedVariants<I, S>,\n suite: (impl: S, variant: Variant<S>) => void,\n): void => {\n for (const variant of defined.variants) {\n const names = covered().get(defined.useCase) ?? new Set<string>();\n names.add(variant.name);\n covered().set(defined.useCase, names);\n describe(`${defined.useCase} — variant '${variant.name}'`, () => {\n suite(variant.impl, variant);\n });\n }\n};\n\n/**\n * Every variant of the given use cases that no {@link forEachVariant} call has\n * run a contract against — what a conventions check asserts is empty.\n */\nexport const variantsWithoutContract = (\n definitions: readonly DefinedVariants<unknown, unknown>[],\n): readonly string[] =>\n definitions.flatMap(defined =>\n defined.variants\n .filter(\n variant =>\n !(covered().get(defined.useCase)?.has(variant.name) ?? false),\n )\n .map(variant => `${defined.useCase}:${variant.name}`),\n );\n"],"names":["describe","COVERED_KEY","Symbol","for","covered","holder","globalThis","Map","forEachVariant","defined","suite","variant","variants","names","get","useCase","Set","add","name","set","impl","variantsWithoutContract","definitions","flatMap","filter","has","map"],"mappings":"AACA,SAASA,QAAQ,QAAQ,SAAS;AAElC;;;;CAIC,GACD,MAAMC,cAAcC,OAAOC,GAAG,CAAC;AAE/B,MAAMC,UAAU;QAEdC,SAAOJ,cAAPI;IADA,MAAMA,SAASC;KACfD,IAAAA,CAAAA,UAAAA,OAAM,CAACJ,eAAAA,YAAY,YAAnBI,IAAAA,OAAM,CAACJ,aAAY,GAAK,IAAIM;IAC5B,OAAOF,MAAM,CAACJ,YAAY;AAC5B;AAEA;;;;;;CAMC,GACD,OAAO,MAAMO,iBAAiB,CAC5BC,SACAC;IAEA,KAAK,MAAMC,WAAWF,QAAQG,QAAQ,CAAE;YACxBR;QAAd,MAAMS,SAAQT,eAAAA,UAAUU,GAAG,CAACL,QAAQM,OAAO,aAA7BX,eAAkC,IAAIY;QACpDH,MAAMI,GAAG,CAACN,QAAQO,IAAI;QACtBd,UAAUe,GAAG,CAACV,QAAQM,OAAO,EAAEF;QAC/Bb,SAAS,GAAGS,QAAQM,OAAO,CAAC,YAAY,EAAEJ,QAAQO,IAAI,CAAC,CAAC,CAAC,EAAE;YACzDR,MAAMC,QAAQS,IAAI,EAAET;QACtB;IACF;AACF,EAAE;AAEF;;;CAGC,GACD,OAAO,MAAMU,0BAA0B,CACrCC,cAEAA,YAAYC,OAAO,CAACd,CAAAA,UAClBA,QAAQG,QAAQ,CACbY,MAAM,CACLb,CAAAA;;gBACIP;mBAAF,WAAEA,eAAAA,UAAUU,GAAG,CAACL,QAAQM,OAAO,sBAA7BX,aAAgCqB,GAAG,CAACd,QAAQO,IAAI,oBAAK;WAE1DQ,GAAG,CAACf,CAAAA,UAAW,GAAGF,QAAQM,OAAO,CAAC,CAAC,EAAEJ,QAAQO,IAAI,EAAE,GACtD"}
@@ -1,5 +1,5 @@
1
- import type { EntityRepository } from '@entifix/business';
2
- import { type EntifixError, type Entity } from '@entifix/core';
1
+ import type { EntityRepository, RepositoryFailure } from '@entifix/business';
2
+ import { type Entity } from '@entifix/core';
3
3
  export interface InMemoryEntityRepository extends EntityRepository {
4
4
  /** Everything currently stored, in insertion order. */
5
5
  readonly items: Entity[];
@@ -9,7 +9,7 @@ export interface InMemoryEntityRepository extends EntityRepository {
9
9
  * Makes the next call to any method fail with `error`, so error branches are
10
10
  * reachable without reaching for a mocking library.
11
11
  */
12
- failNext(error: EntifixError): void;
12
+ failNext(error: RepositoryFailure): void;
13
13
  }
14
14
  /**
15
15
  * In-memory {@link EntityRepository}: the default double for anything that
@@ -1 +1 @@
1
- {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,mBAAmB,CAAC;AAC1D,OAAO,EAKL,KAAK,YAAY,EACjB,KAAK,MAAM,EAOZ,MAAM,eAAe,CAAC;AAiCvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,YAAY,GAAG,IAAI,CAAC;CACrC;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBAuGF,CAAC"}
1
+ {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAKL,KAAK,MAAM,EAQZ,MAAM,eAAe,CAAC;AAiCvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC1C;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBAqGF,CAAC"}
@@ -1,4 +1,4 @@
1
- import { applyFiltering, applySorting, deserializeSingleEntity, EntifixConnError, extractMetaAccessors, serializeEntity } from '@entifix/core';
1
+ import { applyFiltering, applySorting, deserializeSingleEntity, extractMetaAccessors, NotFound, serializeEntity } from '@entifix/core';
2
2
  import { Effect } from 'effect';
3
3
  /**
4
4
  * A copy of `entity` that shares no state with it.
@@ -54,9 +54,7 @@ import { Effect } from 'effect';
54
54
  });
55
55
  const get = (id)=>guard(()=>{
56
56
  const found = items.find((item)=>item.id === id);
57
- return found === undefined ? Effect.fail(new EntifixConnError('Entity not found', undefined, {
58
- id
59
- })) : copyOf(found);
57
+ return found === undefined ? Effect.fail(new NotFound({})) : copyOf(found);
60
58
  });
61
59
  const save = (entity)=>guard(()=>{
62
60
  var _entity_id;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n EntifixConnError,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A copy of `entity` that shares no state with it.\n *\n * Through the entity's own mapping — serialize, then deserialize — because that\n * is what a real adapter does to every record on the way in and out: a caller\n * can never hold the instance the store keeps, and a member the mapping drops\n * (`hidden`, `readonly`) does not survive a save here either. A class that\n * declares no accessors has no mapping to go through, so it is copied member by\n * member instead; plain spec fixtures are the case this keeps working.\n */\nconst copyOf = <TEntity extends Entity>(\n entity: TEntity,\n): Effect.Effect<TEntity, EntifixError> => {\n const entityConstructor = entity.constructor as EntityConstructor<TEntity>;\n if (extractMetaAccessors(entityConstructor).length === 0) {\n return Effect.succeed(\n Object.assign(\n Object.create(Object.getPrototypeOf(entity) as object) as TEntity,\n entity,\n ),\n );\n }\n // `undefined` only comes back for `null`/`undefined` input, and\n // `serializeEntity` always hands over an object.\n return deserializeSingleEntity(\n entityConstructor,\n serializeEntity(entityConstructor, entity),\n ) as Effect.Effect<TEntity, EntifixError>;\n};\n\nexport interface InMemoryEntityRepository extends EntityRepository {\n /** Everything currently stored, in insertion order. */\n readonly items: Entity[];\n /** Replaces the contents, discarding whatever was there. */\n seed(items: Entity[]): void;\n /**\n * Makes the next call to any method fail with `error`, so error branches are\n * reachable without reaching for a mocking library.\n */\n failNext(error: EntifixError): void;\n}\n\n/**\n * In-memory {@link EntityRepository}: the default double for anything that\n * depends on persistence.\n *\n * Its semantics deliberately mirror `makeMongoRepository` — the same filtering\n * and sorting rules, which it takes from core's in-memory query evaluation\n * rather than keeping a copy of its own, same 1-based paging with a default page size of 10, same\n * \"entity not found\" failure, same id minting on create — and\n * `describeEntityRepositoryContract` holds both to that shared contract.\n */\nexport const makeInMemoryEntityRepository = (\n seed: Entity[] = [],\n): InMemoryEntityRepository => {\n let items = [...seed];\n let pendingFailure: EntifixError | undefined;\n\n /** Consumes a queued failure, if one was armed. */\n const guard = <TValue>(\n run: () => Effect.Effect<TValue, EntifixError>,\n ): Effect.Effect<TValue, EntifixError> => {\n if (pendingFailure !== undefined) {\n const failure = pendingFailure;\n pendingFailure = undefined;\n return Effect.fail(failure);\n }\n return run();\n };\n\n const load = <TEntity extends Entity>(request: EntityLoadRequest<TEntity>) =>\n guard(() => {\n const matched = applySorting(\n applyFiltering(items as TEntity[], request.filtering),\n request.sorting,\n );\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const start = (page - 1) * pageSize;\n\n return Effect.forEach(\n matched.slice(start, start + pageSize),\n copyOf,\n ).pipe(\n Effect.map(\n copies =>\n ({\n items: copies,\n total: matched.length,\n request,\n }) satisfies EntityPage<TEntity>,\n ),\n );\n });\n\n const get = <TEntity extends Entity>(id: EntityId) =>\n guard(() => {\n const found = items.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(\n new EntifixConnError('Entity not found', undefined, { id }),\n )\n : copyOf(found as TEntity);\n });\n\n const save = <TEntity extends Entity>(entity: TEntity) =>\n guard(() => {\n // A create arrives without an id, so the store mints one — same rule the\n // Mongo adapter follows. The Web Crypto global rather than `node:crypto`,\n // because a browser bundle cannot resolve a `node:` import and an example\n // with no backend runs this repository in the page.\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n // The store keeps its own copy and hands back another, so neither the\n // caller's instance nor the returned one can change the record without a\n // second save — which a real adapter guarantees by construction.\n return copyOf(entity).pipe(\n Effect.tap(stored =>\n Effect.sync(() => {\n const index = items.findIndex(item => item.id === stored.id);\n if (index === -1) {\n items.push(stored);\n } else {\n items[index] = stored;\n }\n }),\n ),\n Effect.flatMap(copyOf),\n );\n });\n\n const remove = <TEntity extends Entity>(entityOrId: EntityId | TEntity) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n items = items.filter(item => item.id !== id);\n return Effect.succeed(undefined);\n });\n\n return {\n load,\n get,\n save,\n delete: remove,\n get items() {\n return items;\n },\n seed: (next: Entity[]) => {\n items = [...next];\n },\n failNext: (error: EntifixError) => {\n pendingFailure = error;\n },\n // Each method closes over its own state, so nothing is required from the\n // Effect environment; that is assignable to the interface's channel.\n } as unknown as InMemoryEntityRepository;\n};\n"],"names":["applyFiltering","applySorting","deserializeSingleEntity","EntifixConnError","extractMetaAccessors","serializeEntity","Effect","copyOf","entity","entityConstructor","length","succeed","Object","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","items","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","filtering","sorting","page","pageSize","start","forEach","slice","pipe","map","copies","total","get","id","found","find","item","save","globalThis","crypto","randomUUID","tap","stored","sync","index","findIndex","push","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EACvBC,gBAAgB,EAOhBC,oBAAoB,EACpBC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIJ,qBAAqBK,mBAAmBC,MAAM,KAAK,GAAG;QACxD,OAAOJ,OAAOK,OAAO,CACnBC,OAAOC,MAAM,CACXD,OAAOE,MAAM,CAACF,OAAOG,cAAc,CAACP,UACpCA;IAGN;IACA,gEAAgE;IAChE,iDAAiD;IACjD,OAAON,wBACLO,mBACAJ,gBAAgBI,mBAAmBD;AAEvC;AAcA;;;;;;;;;CASC,GACD,OAAO,MAAMQ,+BAA+B,CAC1CC,OAAiB,EAAE;IAEnB,IAAIC,QAAQ;WAAID;KAAK;IACrB,IAAIE;IAEJ,iDAAiD,GACjD,MAAMC,QAAQ,CACZC;QAEA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AC;oBACV,MAAMC,QAAQjC,MAAMkC,SAAS,CAACT,CAAAA,OAAQA,KAAKH,EAAE,KAAKS,OAAOT,EAAE;oBAC3D,IAAIW,UAAU,CAAC,GAAG;wBAChBjC,MAAMmC,IAAI,CAACJ;oBACb,OAAO;wBACL/B,KAAK,CAACiC,MAAM,GAAGF;oBACjB;gBACF,KAEF3C,OAAOgD,OAAO,CAAC/C;QAEnB;IAEF,MAAMgD,SAAS,CAAyBC,aACtCpC,MAAM;YACJ,MAAMoB,KACJgB,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWhB,EAAE,GACbgB;YACNtC,QAAQA,MAAMuC,MAAM,CAACd,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YACzC,OAAOlC,OAAOK,OAAO,CAACW;QACxB;IAEF,OAAO;QACLG;QACAc;QACAK;QACAc,QAAQH;QACR,IAAIrC;YACF,OAAOA;QACT;QACAD,MAAM,CAAC0C;YACLzC,QAAQ;mBAAIyC;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type { EntityRepository, RepositoryFailure } from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n deserializeSingleEntity,\n type EntifixError,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n NotFound,\n serializeEntity,\n} from '@entifix/core';\nimport { Effect } from 'effect';\n\n/**\n * A copy of `entity` that shares no state with it.\n *\n * Through the entity's own mapping — serialize, then deserialize — because that\n * is what a real adapter does to every record on the way in and out: a caller\n * can never hold the instance the store keeps, and a member the mapping drops\n * (`hidden`, `readonly`) does not survive a save here either. A class that\n * declares no accessors has no mapping to go through, so it is copied member by\n * member instead; plain spec fixtures are the case this keeps working.\n */\nconst copyOf = <TEntity extends Entity>(\n entity: TEntity,\n): Effect.Effect<TEntity, EntifixError> => {\n const entityConstructor = entity.constructor as EntityConstructor<TEntity>;\n if (extractMetaAccessors(entityConstructor).length === 0) {\n return Effect.succeed(\n Object.assign(\n Object.create(Object.getPrototypeOf(entity) as object) as TEntity,\n entity,\n ),\n );\n }\n // `undefined` only comes back for `null`/`undefined` input, and\n // `serializeEntity` always hands over an object.\n return deserializeSingleEntity(\n entityConstructor,\n serializeEntity(entityConstructor, entity),\n ) as Effect.Effect<TEntity, EntifixError>;\n};\n\nexport interface InMemoryEntityRepository extends EntityRepository {\n /** Everything currently stored, in insertion order. */\n readonly items: Entity[];\n /** Replaces the contents, discarding whatever was there. */\n seed(items: Entity[]): void;\n /**\n * Makes the next call to any method fail with `error`, so error branches are\n * reachable without reaching for a mocking library.\n */\n failNext(error: RepositoryFailure): void;\n}\n\n/**\n * In-memory {@link EntityRepository}: the default double for anything that\n * depends on persistence.\n *\n * Its semantics deliberately mirror `makeMongoRepository` — the same filtering\n * and sorting rules, which it takes from core's in-memory query evaluation\n * rather than keeping a copy of its own, same 1-based paging with a default page size of 10, same\n * \"entity not found\" failure, same id minting on create — and\n * `describeEntityRepositoryContract` holds both to that shared contract.\n */\nexport const makeInMemoryEntityRepository = (\n seed: Entity[] = [],\n): InMemoryEntityRepository => {\n let items = [...seed];\n let pendingFailure: RepositoryFailure | undefined;\n\n /** Consumes a queued failure, if one was armed. */\n const guard = <TValue>(\n run: () => Effect.Effect<TValue, RepositoryFailure>,\n ): Effect.Effect<TValue, RepositoryFailure> => {\n if (pendingFailure !== undefined) {\n const failure = pendingFailure;\n pendingFailure = undefined;\n return Effect.fail(failure);\n }\n return run();\n };\n\n const load = <TEntity extends Entity>(request: EntityLoadRequest<TEntity>) =>\n guard(() => {\n const matched = applySorting(\n applyFiltering(items as TEntity[], request.filtering),\n request.sorting,\n );\n const page = request.page ?? 1;\n const pageSize = request.pageSize ?? 10;\n const start = (page - 1) * pageSize;\n\n return Effect.forEach(\n matched.slice(start, start + pageSize),\n copyOf,\n ).pipe(\n Effect.map(\n copies =>\n ({\n items: copies,\n total: matched.length,\n request,\n }) satisfies EntityPage<TEntity>,\n ),\n );\n });\n\n const get = <TEntity extends Entity>(id: EntityId) =>\n guard(() => {\n const found = items.find(item => item.id === id);\n return found === undefined\n ? Effect.fail(new NotFound({}))\n : copyOf(found as TEntity);\n });\n\n const save = <TEntity extends Entity>(entity: TEntity) =>\n guard(() => {\n // A create arrives without an id, so the store mints one — same rule the\n // Mongo adapter follows. The Web Crypto global rather than `node:crypto`,\n // because a browser bundle cannot resolve a `node:` import and an example\n // with no backend runs this repository in the page.\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n // The store keeps its own copy and hands back another, so neither the\n // caller's instance nor the returned one can change the record without a\n // second save — which a real adapter guarantees by construction.\n return copyOf(entity).pipe(\n Effect.tap(stored =>\n Effect.sync(() => {\n const index = items.findIndex(item => item.id === stored.id);\n if (index === -1) {\n items.push(stored);\n } else {\n items[index] = stored;\n }\n }),\n ),\n Effect.flatMap(copyOf),\n );\n });\n\n const remove = <TEntity extends Entity>(entityOrId: EntityId | TEntity) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n items = items.filter(item => item.id !== id);\n return Effect.succeed(undefined);\n });\n\n return {\n load,\n get,\n save,\n delete: remove,\n get items() {\n return items;\n },\n seed: (next: Entity[]) => {\n items = [...next];\n },\n failNext: (error: RepositoryFailure) => {\n pendingFailure = error;\n },\n // Each method closes over its own state, so nothing is required from the\n // Effect environment; that is assignable to the interface's channel.\n } as unknown as InMemoryEntityRepository;\n};\n"],"names":["applyFiltering","applySorting","deserializeSingleEntity","extractMetaAccessors","NotFound","serializeEntity","Effect","copyOf","entity","entityConstructor","length","succeed","Object","assign","create","getPrototypeOf","makeInMemoryEntityRepository","seed","items","pendingFailure","guard","run","undefined","failure","fail","load","request","matched","filtering","sorting","page","pageSize","start","forEach","slice","pipe","map","copies","total","get","id","found","find","item","save","globalThis","crypto","randomUUID","tap","stored","sync","index","findIndex","push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C;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
@@ -0,0 +1,22 @@
1
+ import type { FragmentCatalog, SlipStep } from '@entifix/business/flow';
2
+ import { type DomainEvent, type EntifixFailure } from '@entifix/core';
3
+ import { type FlowEngine, type FlowEventData } from '@entifix/transactions';
4
+ import { Effect } from 'effect';
5
+ /** What a fake participant does for one step: succeed with an outcome, or fail. */
6
+ export type FakeParticipant = (step: SlipStep) => Effect.Effect<unknown, EntifixFailure>;
7
+ export interface FakeFlowEngine extends FlowEngine {
8
+ /** Every `flow.*` event the engine announced, in order. */
9
+ readonly events: readonly DomainEvent<FlowEventData>[];
10
+ /** Every compensation it ran, as `compensate:<step>`, in order. */
11
+ readonly compensations: readonly string[];
12
+ }
13
+ /**
14
+ * An in-memory {@link FlowEngine} with the semantics a durable one must have
15
+ * ([ADR 0016](../../../../../docs/adr/0016-a-flow-engine-port-and-a-durable-workflow-adapter.md)):
16
+ * a failure before the commit point — the pivot's own included — compensates
17
+ * the steps that succeeded, in reverse; a failure after it suspends the flow;
18
+ * a `wait` parks it until a signal names that step. It runs synchronously and
19
+ * durably remembers nothing, which is what makes it a fake.
20
+ */
21
+ export declare const makeFakeFlowEngine: (catalog: FragmentCatalog, participant: FakeParticipant) => FakeFlowEngine;
22
+ //# sourceMappingURL=flow-engine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"flow-engine.d.ts","sourceRoot":"","sources":["../../src/doubles/flow-engine.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAQ,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAE9E,OAAO,EAAE,KAAK,WAAW,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AACtE,OAAO,EACL,KAAK,UAAU,EAEf,KAAK,aAAa,EAInB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,mFAAmF;AACnF,MAAM,MAAM,eAAe,GAAG,CAC5B,IAAI,EAAE,QAAQ,KACX,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,cAAc,CAAC,CAAC;AAE5C,MAAM,WAAW,cAAe,SAAQ,UAAU;IAChD,2DAA2D;IAC3D,QAAQ,CAAC,MAAM,EAAE,SAAS,WAAW,CAAC,aAAa,CAAC,EAAE,CAAC;IACvD,mEAAmE;IACnE,QAAQ,CAAC,aAAa,EAAE,SAAS,MAAM,EAAE,CAAC;CAC3C;AAgBD;;;;;;;GAOG;AACH,eAAO,MAAM,kBAAkB,GAC7B,SAAS,eAAe,EACxB,aAAa,eAAe,KAC3B,cAsIF,CAAC"}