@entifix/testing-unit 0.13.0 → 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 (38) hide show
  1. package/dist/contracts/index.d.ts +2 -0
  2. package/dist/contracts/index.d.ts.map +1 -1
  3. package/dist/contracts/index.js +2 -0
  4. package/dist/contracts/index.js.map +1 -1
  5. package/dist/contracts/push-channel.contract.d.ts +45 -0
  6. package/dist/contracts/push-channel.contract.d.ts.map +1 -0
  7. package/dist/contracts/push-channel.contract.js +135 -0
  8. package/dist/contracts/push-channel.contract.js.map +1 -0
  9. package/dist/contracts/server-push.contract.d.ts +44 -0
  10. package/dist/contracts/server-push.contract.d.ts.map +1 -0
  11. package/dist/contracts/server-push.contract.js +273 -0
  12. package/dist/contracts/server-push.contract.js.map +1 -0
  13. package/dist/doubles/entity-facet-counter.d.ts +2 -2
  14. package/dist/doubles/entity-facet-counter.d.ts.map +1 -1
  15. package/dist/doubles/entity-facet-counter.js.map +1 -1
  16. package/dist/doubles/entity-repository.js.map +1 -1
  17. package/dist/doubles/server-push.d.ts +16 -0
  18. package/dist/doubles/server-push.d.ts.map +1 -0
  19. package/dist/doubles/server-push.js +38 -0
  20. package/dist/doubles/server-push.js.map +1 -0
  21. package/dist/doubles/transaction-ports.d.ts +2 -2
  22. package/dist/doubles/transaction-ports.d.ts.map +1 -1
  23. package/dist/doubles/transaction-ports.js.map +1 -1
  24. package/dist/drivers/fake-mongo.d.ts +1 -1
  25. package/dist/drivers/fake-mongo.js.map +1 -1
  26. package/dist/drivers/fake-sql.d.ts +1 -1
  27. package/dist/drivers/fake-sql.js.map +1 -1
  28. package/dist/effect/run.d.ts +1 -1
  29. package/dist/effect/run.js +1 -1
  30. package/dist/effect/run.js.map +1 -1
  31. package/dist/http/entity-handlers.d.ts +1 -1
  32. package/dist/http/entity-handlers.js +1 -1
  33. package/dist/http/entity-handlers.js.map +1 -1
  34. package/dist/index.d.ts +1 -0
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -0
  37. package/dist/index.js.map +1 -1
  38. package/package.json +7 -7
@@ -1 +1 @@
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","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EAOvBC,oBAAoB,EACpBC,QAAQ,EACRC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIL,qBAAqBM,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;WA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AG,CAACC,CAAAA,SACT3C,OAAO4C,IAAI,CAAC;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 EntifixFailure,\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, EntifixFailure> => {\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, EntifixFailure>;\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","flatMap","remove","entityOrId","filter","delete","next","failNext","error"],"mappings":"AACA,SACEA,cAAc,EACdC,YAAY,EACZC,uBAAuB,EAOvBC,oBAAoB,EACpBC,QAAQ,EACRC,eAAe,QACV,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIL,qBAAqBM,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,IAAIF,mBAAmBG,WAAW;YAChC,MAAMC,UAAUJ;YAChBA,iBAAiBG;YACjB,OAAOhB,OAAOkB,IAAI,CAACD;QACrB;QACA,OAAOF;IACT;IAEA,MAAMI,OAAO,CAAyBC,UACpCN,MAAM;gBAKSM,eACIA;YALjB,MAAMC,UAAU1B,aACdD,eAAekB,OAAoBQ,QAAQE,SAAS,GACpDF,QAAQG,OAAO;YAEjB,MAAMC,QAAOJ,gBAAAA,QAAQI,IAAI,YAAZJ,gBAAgB;YAC7B,MAAMK,YAAWL,oBAAAA,QAAQK,QAAQ,YAAhBL,oBAAoB;YACrC,MAAMM,QAAQ,AAACF,CAAAA,OAAO,CAAA,IAAKC;YAE3B,OAAOzB,OAAO2B,OAAO,CACnBN,QAAQO,KAAK,CAACF,OAAOA,QAAQD,WAC7BxB,QACA4B,IAAI,CAC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;QACT;QACAD,MAAM,CAAC0C;YACLzC,QAAQ;mBAAIyC;aAAK;QACnB;QACAC,UAAU,CAACC;YACT1C,iBAAiB0C;QACnB;IAGF;AACF,EAAE"}
@@ -0,0 +1,16 @@
1
+ import { type DomainEvent } from '@entifix/core';
2
+ import { Effect, type Scope } from 'effect';
3
+ import type { ServerPushContractOptions, ServerPushUnderTest } from '../contracts/server-push.contract.js';
4
+ /** An in-memory push port that also remembers everything published to it. */
5
+ export interface InMemoryServerPush extends ServerPushUnderTest {
6
+ /** Every event published, in order, whether or not anyone received it. */
7
+ readonly published: () => readonly DomainEvent[];
8
+ }
9
+ /**
10
+ * A push port for a host's specs: each open connection gets its own queue,
11
+ * filtered by topic and audience exactly as the real hub does, and every
12
+ * publish is recorded so a spec can assert what a projection pushed without
13
+ * opening a stream.
14
+ */
15
+ export declare const makeInMemoryServerPush: ({ topicsOf, admits, resume, }: ServerPushContractOptions) => Effect.Effect<InMemoryServerPush, never, Scope.Scope>;
16
+ //# sourceMappingURL=server-push.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server-push.d.ts","sourceRoot":"","sources":["../../src/doubles/server-push.ts"],"names":[],"mappings":"AAAA,OAAO,EAAkB,KAAK,WAAW,EAAE,MAAM,eAAe,CAAC;AACjE,OAAO,EAAE,MAAM,EAAS,KAAK,KAAK,EAAU,MAAM,QAAQ,CAAC;AAE3D,OAAO,KAAK,EAGV,yBAAyB,EACzB,mBAAmB,EACpB,MAAM,sCAAsC,CAAC;AAE9C,6EAA6E;AAC7E,MAAM,WAAW,kBAAmB,SAAQ,mBAAmB;IAC7D,0EAA0E;IAC1E,QAAQ,CAAC,SAAS,EAAE,MAAM,SAAS,WAAW,EAAE,CAAC;CAClD;AAED;;;;;GAKG;AACH,eAAO,MAAM,sBAAsB,GAAI,+BAKpC,yBAAyB,KAAG,MAAM,CAAC,MAAM,CAC1C,kBAAkB,EAClB,KAAK,EACL,KAAK,CAAC,KAAK,CAgDT,CAAC"}
@@ -0,0 +1,38 @@
1
+ import { audienceAdmits } from '@entifix/core';
2
+ import { Effect, Queue, Stream } from 'effect';
3
+ /**
4
+ * A push port for a host's specs: each open connection gets its own queue,
5
+ * filtered by topic and audience exactly as the real hub does, and every
6
+ * publish is recorded so a spec can assert what a projection pushed without
7
+ * opening a stream.
8
+ */ export const makeInMemoryServerPush = ({ topicsOf, admits = (event, connection)=>audienceAdmits(event.audience, connection.recipient), resume = (_cursor, topics)=>Stream.make({
9
+ _tag: 'resync',
10
+ topics
11
+ }) })=>Effect.sync(()=>{
12
+ const published = [];
13
+ const open = new Map();
14
+ return {
15
+ published: ()=>[
16
+ ...published
17
+ ],
18
+ publish: (event)=>Effect.suspend(()=>{
19
+ published.push(event);
20
+ return Effect.forEach(Array.from(open), ([queue, connection])=>{
21
+ const topics = topicsOf(event).filter((topic)=>connection.topics.includes(topic));
22
+ return topics.length > 0 && admits(event, connection) ? Queue.offer(queue, {
23
+ _tag: 'event',
24
+ event,
25
+ topics
26
+ }) : Effect.void;
27
+ }, {
28
+ discard: true
29
+ });
30
+ }),
31
+ open: (connection)=>Stream.unwrap(Effect.map(Effect.acquireRelease(Effect.tap(Queue.unbounded(), (queue)=>Effect.sync(()=>open.set(queue, connection))), (queue)=>Effect.sync(()=>open.delete(queue))), (queue)=>{
32
+ const live = Stream.fromQueue(queue);
33
+ return connection.cursor === undefined ? live : Stream.concat(resume(connection.cursor, connection.topics), live);
34
+ }))
35
+ };
36
+ });
37
+
38
+ //# sourceMappingURL=server-push.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/doubles/server-push.ts"],"sourcesContent":["import { audienceAdmits, type DomainEvent } from '@entifix/core';\nimport { Effect, Queue, type Scope, Stream } from 'effect';\n\nimport type {\n PushConnectionUnderTest,\n PushMessageUnderTest,\n ServerPushContractOptions,\n ServerPushUnderTest,\n} from '../contracts/server-push.contract.js';\n\n/** An in-memory push port that also remembers everything published to it. */\nexport interface InMemoryServerPush extends ServerPushUnderTest {\n /** Every event published, in order, whether or not anyone received it. */\n readonly published: () => readonly DomainEvent[];\n}\n\n/**\n * A push port for a host's specs: each open connection gets its own queue,\n * filtered by topic and audience exactly as the real hub does, and every\n * publish is recorded so a spec can assert what a projection pushed without\n * opening a stream.\n */\nexport const makeInMemoryServerPush = ({\n topicsOf,\n admits = (event, connection) =>\n audienceAdmits(event.audience, connection.recipient),\n resume = (_cursor, topics) => Stream.make({ _tag: 'resync', topics }),\n}: ServerPushContractOptions): Effect.Effect<\n InMemoryServerPush,\n never,\n Scope.Scope\n> =>\n Effect.sync(() => {\n const published: DomainEvent[] = [];\n const open = new Map<\n Queue.Queue<PushMessageUnderTest>,\n PushConnectionUnderTest\n >();\n\n return {\n published: () => [...published],\n publish: event =>\n Effect.suspend(() => {\n published.push(event);\n return Effect.forEach(\n Array.from(open),\n ([queue, connection]) => {\n const topics = topicsOf(event).filter(topic =>\n connection.topics.includes(topic),\n );\n return topics.length > 0 && admits(event, connection)\n ? Queue.offer(queue, { _tag: 'event', event, topics })\n : Effect.void;\n },\n { discard: true },\n );\n }),\n open: connection =>\n Stream.unwrap(\n Effect.map(\n Effect.acquireRelease(\n Effect.tap(Queue.unbounded<PushMessageUnderTest>(), queue =>\n Effect.sync(() => open.set(queue, connection)),\n ),\n queue => Effect.sync(() => open.delete(queue)),\n ),\n queue => {\n const live = Stream.fromQueue(queue);\n return connection.cursor === undefined\n ? live\n : Stream.concat(\n resume(connection.cursor, connection.topics),\n live,\n );\n },\n ),\n ),\n };\n });\n"],"names":["audienceAdmits","Effect","Queue","Stream","makeInMemoryServerPush","topicsOf","admits","event","connection","audience","recipient","resume","_cursor","topics","make","_tag","sync","published","open","Map","publish","suspend","push","forEach","Array","from","queue","filter","topic","includes","length","offer","void","discard","unwrap","map","acquireRelease","tap","unbounded","set","delete","live","fromQueue","cursor","undefined","concat"],"mappings":"AAAA,SAASA,cAAc,QAA0B,gBAAgB;AACjE,SAASC,MAAM,EAAEC,KAAK,EAAcC,MAAM,QAAQ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OAAOH,WAAWmC,MAAM,EAAEnC,WAAWK,MAAM,GAC3C4B;gBAER;QAGR;IACF,GAAG"}
@@ -1,4 +1,4 @@
1
- import { type DomainEvent, type TransitionalFailure } from '@entifix/core';
1
+ import { type DomainEvent, type EntifixFailure } from '@entifix/core';
2
2
  import type { EventBus, LockService, SagaInstance, SagaStore, SequenceService, TransactionInbox } from '@entifix/transactions';
3
3
  import { Effect } from 'effect';
4
4
  export interface InMemoryLockService extends LockService {
@@ -40,7 +40,7 @@ export interface RecordingEventBus extends EventBus {
40
40
  * broker's job in production, so a double that ignored it would let a
41
41
  * consumer pass its tests while receiving traffic it never bound to.
42
42
  */
43
- deliver(event: DomainEvent): Effect.Effect<void, TransitionalFailure>;
43
+ deliver(event: DomainEvent): Effect.Effect<void, EntifixFailure>;
44
44
  /** Makes the next `publish` fail, for the broker-unavailable branch. */
45
45
  failNextPublish(): void;
46
46
  }
@@ -1 +1 @@
1
- {"version":3,"file":"transaction-ports.d.ts","sourceRoot":"","sources":["../../src/doubles/transaction-ports.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,KAAK,WAAW,EAEhB,KAAK,mBAAmB,EAEzB,MAAM,eAAe,CAAC;AACvB,OAAO,KAAK,EACV,QAAQ,EAER,WAAW,EACX,YAAY,EACZ,SAAS,EACT,eAAe,EACf,gBAAgB,EACjB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAEhC,MAAM,WAAW,mBAAoB,SAAQ,WAAW;IACtD,iDAAiD;IACjD,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC;IACxB,sDAAsD;IACtD,QAAQ,CAAC,GAAG,EAAE,aAAa,CAAC;QAAE,MAAM,EAAE,SAAS,GAAG,SAAS,CAAC;QAAC,GAAG,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC5E;;;OAGG;IACH,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;CAC9B;A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;IAClD,4EAA4E;IAC5E,QAAQ,CAAC,SAAS,EAAE,SAAS,YAAY,EAAE,CAAC;CAC7C;AAED;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,QAAO,iBAwExC,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n Contention,\n type DomainEvent,\n matchesEventPattern,\n type TransitionalFailure,\n Unavailable,\n} from '@entifix/core';\nimport type {\n EventBus,\n LockHandle,\n LockService,\n SagaInstance,\n SagaStore,\n SequenceService,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\nexport interface InMemoryLockService extends LockService {\n /** Keys currently held, in acquisition order. */\n readonly held: string[];\n /** Every acquire/release in the order it happened. */\n readonly log: ReadonlyArray<{ action: 'acquire' | 'release'; key: string }>;\n /**\n * Marks `key` as already taken by someone else, so the next `acquire` fails\n * with {@link Contention} — the 409 path of the transaction facade.\n */\n contendOn(key: string): void;\n}\n\n/**\n * In-memory {@link LockService}. Acquisition is immediate and uncontended\n * unless {@link InMemoryLockService.contendOn} says otherwise, and `release`\n * only frees a lock whose token matches — the compare-and-delete rule the Redis\n * adapter enforces with a Lua script.\n */\nexport const makeInMemoryLockService = (): InMemoryLockService => {\n const tokens = new Map<string, string>();\n const contended = new Set<string>();\n const log: Array<{ action: 'acquire' | 'release'; key: string }> = [];\n let counter = 0;\n\n return {\n acquire: key =>\n Effect.suspend(() => {\n if (contended.has(key) || tokens.has(key)) {\n return Effect.fail(new Contention());\n }\n const token = `token-${(counter += 1)}`;\n tokens.set(key, token);\n log.push({ action: 'acquire', key });\n return Effect.succeed({ key, token });\n }),\n release: (handle: LockHandle) =>\n Effect.sync(() => {\n if (tokens.get(handle.key) === handle.token) {\n tokens.delete(handle.key);\n log.push({ action: 'release', key: handle.key });\n }\n }),\n get held() {\n return [...tokens.keys()];\n },\n get log() {\n return log;\n },\n contendOn: key => {\n contended.add(key);\n },\n };\n};\n\nexport interface InMemorySequenceService extends SequenceService {\n /** The current value of every sequence drawn from so far. */\n readonly values: Readonly<Record<string, number>>;\n}\n\n/**\n * In-memory {@link SequenceService} — a plain counter per name. Atomicity is\n * what the Redis `INCR` adapter buys; single-threaded JS gives it for free here.\n */\nexport const makeInMemorySequenceService = (): InMemorySequenceService => {\n const sequences = new Map<string, number>();\n\n return {\n next: name =>\n Effect.sync(() => {\n const next = (sequences.get(name) ?? 0) + 1;\n sequences.set(name, next);\n return next;\n }),\n get values() {\n return Object.fromEntries(sequences);\n },\n };\n};\n\nexport interface RecordingEventBus extends EventBus {\n /** Every event published, in order. */\n readonly published: DomainEvent[];\n /**\n * Pushes an event to the subscribers whose pattern matches it, as a topic\n * exchange would. Deliberately not \"to all subscribers\": routing is the\n * broker's job in production, so a double that ignored it would let a\n * consumer pass its tests while receiving traffic it never bound to.\n */\n deliver(event: DomainEvent): Effect.Effect<void, TransitionalFailure>;\n /** Makes the next `publish` fail, for the broker-unavailable branch. */\n failNextPublish(): void;\n}\n\n/**\n * In-memory {@link EventBus} that records what was published rather than\n * asserting on it. Prefer reading `bus.published` in a test over a mock's call\n * assertions: the expectation then reads as state, not as a spy protocol.\n */\nexport const makeRecordingEventBus = (): RecordingEventBus => {\n const published: DomainEvent[] = [];\n const handlers: Array<{\n pattern: string;\n handle: (event: DomainEvent) => Effect.Effect<void, TransitionalFailure>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(new Unavailable({ dependency: 'bus' }));\n }\n published.push(event);\n return Effect.void;\n }),\n subscribe: (subscription, handle) =>\n Effect.sync(() => {\n // Only the pattern is retained: queue durability and the delivery\n // ceiling are broker facts with no in-memory analogue, and faking them\n // would assert against the double rather than against a broker.\n handlers.push({ pattern: subscription.pattern, handle });\n }),\n deliver: event =>\n Effect.forEach(\n handlers.filter(({ pattern }) =>\n matchesEventPattern(pattern, event.name),\n ),\n ({ handle }) => handle(event),\n { discard: true },\n ),\n get published() {\n return published;\n },\n failNextPublish: () => {\n failNext = true;\n },\n };\n};\n\n/**\n * An in-memory {@link TransactionInbox}, one per consumer, over a shared claim\n * set.\n *\n * Sharing the set across the inboxes one factory hands out is what makes the\n * contract's \"one consumer cannot consume another's claim\" case a real\n * assertion, rather than one the double satisfies by only ever having seen a\n * single consumer.\n */\nexport const makeInMemoryInboxes = () => {\n const claimed = new Set<string>();\n\n return {\n /** An inbox for `consumer`, over the shared claim set. */\n for: (consumer: string): TransactionInbox => ({\n claim: eventId =>\n Effect.sync(() => {\n const key = JSON.stringify([consumer, eventId]);\n if (claimed.has(key)) return 'duplicate' as const;\n claimed.add(key);\n return 'claimed' as const;\n }),\n }),\n get claims(): readonly { consumer: string; eventId: string }[] {\n return [...claimed].map(key => {\n const [consumer, eventId] = JSON.parse(key) as [string, string];\n return { consumer, eventId };\n });\n },\n };\n};\n\nexport interface InMemorySagaStore extends SagaStore {\n /** Every instance, as stored — for a spec to assert on state, not calls. */\n readonly instances: readonly SagaInstance[];\n}\n\n/**\n * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`\n * never overwrites, outcomes append, and a resume claim only takes an\n * unfinished instance whose `updatedAt` is past the deadline — counting the\n * attempt and re-stamping it, so the next sweep does not find it again.\n */\nexport const makeInMemorySagaStore = (): InMemorySagaStore => {\n const instances = new Map<string, SagaInstance>();\n const stamp = () => new Date().toISOString();\n const unfinished = (entry: SagaInstance) =>\n entry.state === 'RUNNING' || entry.state === 'COMPENSATING';\n const pastDeadline = (entry: SagaInstance, olderThanMs: number) =>\n entry.updatedAt < new Date(Date.now() - olderThanMs).toISOString();\n const update = (\n sagaId: string,\n change: (entry: SagaInstance) => SagaInstance,\n ) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (current !== undefined) {\n instances.set(sagaId, { ...change(current), updatedAt: stamp() });\n }\n });\n\n return {\n start: started =>\n Effect.sync(() => {\n if (!instances.has(started.sagaId)) {\n instances.set(started.sagaId, { ...started, updatedAt: stamp() });\n }\n }),\n beginStep: (sagaId, stepIndex) =>\n update(sagaId, entry => ({ ...entry, stepIndex })),\n recordOutcome: (sagaId, outcome) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: [...entry.outcomes, outcome],\n })),\n settle: (sagaId, state, error) =>\n update(sagaId, entry => ({ ...entry, state, error })),\n markCompensated: (sagaId, stepId) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: entry.outcomes.map(outcome =>\n outcome.stepId === stepId\n ? { ...outcome, compensated: true }\n : outcome,\n ),\n })),\n get: sagaId => Effect.sync(() => instances.get(sagaId)),\n findStale: olderThanMs =>\n Effect.sync(() =>\n [...instances.values()].filter(\n entry => unfinished(entry) && pastDeadline(entry, olderThanMs),\n ),\n ),\n claimForResume: (sagaId, olderThanMs) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (\n current === undefined ||\n !unfinished(current) ||\n !pastDeadline(current, olderThanMs)\n ) {\n return undefined;\n }\n const claimed = {\n ...current,\n resumeAttempts: current.resumeAttempts + 1,\n updatedAt: stamp(),\n };\n instances.set(sagaId, claimed);\n return claimed;\n }),\n get instances() {\n return [...instances.values()];\n },\n };\n};\n"],"names":["Contention","matchesEventPattern","Unavailable","Effect","makeInMemoryLockService","tokens","Map","contended","Set","log","counter","acquire","key","suspend","has","fail","token","set","push","action","succeed","release","handle","sync","get","delete","held","keys","contendOn","add","makeInMemorySequenceService","sequences","next","name","values","Object","fromEntries","makeRecordingEventBus","published","handlers","failNext","publish","event","dependency","void","subscribe","subscription","pattern","deliver","forEach","filter","discard","failNextPublish","makeInMemoryInboxes","claimed","for","consumer","claim","eventId","JSON","stringify","claims","map","parse","makeInMemorySagaStore","instances","stamp","Date","toISOString","unfinished","entry","state","pastDeadline","olderThanMs","updatedAt","now","update","sagaId","change","current","undefined","start","started","beginStep","stepIndex","recordOutcome","outcome","outcomes","settle","error","markCompensated","stepId","compensated","findStale","claimForResume","resumeAttempts"],"mappings":";AAAA,SACEA,UAAU,EAEVC,m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b,OAAOC,QAAQP,CAAAA,QAAU,aAAKA;oBAAOC;oBAAOkB;;QAC9CC,iBAAiB,CAACb,QAAQc,SACxBf,OAAOC,QAAQP,CAAAA,QAAU,aACpBA;oBACHiB,UAAUjB,MAAMiB,QAAQ,CAACzB,GAAG,CAACwB,CAAAA,UAC3BA,QAAQK,MAAM,KAAKA,SACf,aAAKL;4BAASM,aAAa;6BAC3BN;;QAGV9D,KAAKqD,CAAAA,SAAU1E,OAAOoB,IAAI,CAAC,IAAM0C,UAAUzC,GAAG,CAACqD;QAC/CgB,WAAWpB,CAAAA,cACTtE,OAAOoB,IAAI,CAAC,IACV;uBAAI0C,UAAU/B,MAAM;iBAAG,CAACgB,MAAM,CAC5BoB,CAAAA,QAASD,WAAWC,UAAUE,aAAaF,OAAOG;QAGxDqB,gBAAgB,CAACjB,QAAQJ,cACvBtE,OAAOoB,IAAI,CAAC;gBACV,MAAMwD,UAAUd,UAAUzC,GAAG,CAACqD;gBAC9B,IACEE,YAAYC,aACZ,CAACX,WAAWU,YACZ,CAACP,aAAaO,SAASN,cACvB;oBACA,OAAOO;gBACT;gBACA,MAAM1B,UAAU,aACXyB;oBACHgB,gBAAgBhB,QAAQgB,cAAc,GAAG;oBACzCrB,WAAWR;;gBAEbD,UAAUhD,GAAG,CAAC4D,QAAQvB;gBACtB,OAAOA;YACT;QACF,IAAIW;YACF,OAAO;mBAAIA,UAAU/B,MAAM;aAAG;QAChC;IACF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/transaction-ports.ts"],"sourcesContent":["import {\n Contention,\n type DomainEvent,\n type EntifixFailure,\n matchesEventPattern,\n Unavailable,\n} from '@entifix/core';\nimport type {\n EventBus,\n LockHandle,\n LockService,\n SagaInstance,\n SagaStore,\n SequenceService,\n TransactionInbox,\n} from '@entifix/transactions';\nimport { Effect } from 'effect';\n\nexport interface InMemoryLockService extends LockService {\n /** Keys currently held, in acquisition order. */\n readonly held: string[];\n /** Every acquire/release in the order it happened. */\n readonly log: ReadonlyArray<{ action: 'acquire' | 'release'; key: string }>;\n /**\n * Marks `key` as already taken by someone else, so the next `acquire` fails\n * with {@link Contention} — the 409 path of the transaction facade.\n */\n contendOn(key: string): void;\n}\n\n/**\n * In-memory {@link LockService}. Acquisition is immediate and uncontended\n * unless {@link InMemoryLockService.contendOn} says otherwise, and `release`\n * only frees a lock whose token matches — the compare-and-delete rule the Redis\n * adapter enforces with a Lua script.\n */\nexport const makeInMemoryLockService = (): InMemoryLockService => {\n const tokens = new Map<string, string>();\n const contended = new Set<string>();\n const log: Array<{ action: 'acquire' | 'release'; key: string }> = [];\n let counter = 0;\n\n return {\n acquire: key =>\n Effect.suspend(() => {\n if (contended.has(key) || tokens.has(key)) {\n return Effect.fail(new Contention());\n }\n const token = `token-${(counter += 1)}`;\n tokens.set(key, token);\n log.push({ action: 'acquire', key });\n return Effect.succeed({ key, token });\n }),\n release: (handle: LockHandle) =>\n Effect.sync(() => {\n if (tokens.get(handle.key) === handle.token) {\n tokens.delete(handle.key);\n log.push({ action: 'release', key: handle.key });\n }\n }),\n get held() {\n return [...tokens.keys()];\n },\n get log() {\n return log;\n },\n contendOn: key => {\n contended.add(key);\n },\n };\n};\n\nexport interface InMemorySequenceService extends SequenceService {\n /** The current value of every sequence drawn from so far. */\n readonly values: Readonly<Record<string, number>>;\n}\n\n/**\n * In-memory {@link SequenceService} — a plain counter per name. Atomicity is\n * what the Redis `INCR` adapter buys; single-threaded JS gives it for free here.\n */\nexport const makeInMemorySequenceService = (): InMemorySequenceService => {\n const sequences = new Map<string, number>();\n\n return {\n next: name =>\n Effect.sync(() => {\n const next = (sequences.get(name) ?? 0) + 1;\n sequences.set(name, next);\n return next;\n }),\n get values() {\n return Object.fromEntries(sequences);\n },\n };\n};\n\nexport interface RecordingEventBus extends EventBus {\n /** Every event published, in order. */\n readonly published: DomainEvent[];\n /**\n * Pushes an event to the subscribers whose pattern matches it, as a topic\n * exchange would. Deliberately not \"to all subscribers\": routing is the\n * broker's job in production, so a double that ignored it would let a\n * consumer pass its tests while receiving traffic it never bound to.\n */\n deliver(event: DomainEvent): Effect.Effect<void, EntifixFailure>;\n /** Makes the next `publish` fail, for the broker-unavailable branch. */\n failNextPublish(): void;\n}\n\n/**\n * In-memory {@link EventBus} that records what was published rather than\n * asserting on it. Prefer reading `bus.published` in a test over a mock's call\n * assertions: the expectation then reads as state, not as a spy protocol.\n */\nexport const makeRecordingEventBus = (): RecordingEventBus => {\n const published: DomainEvent[] = [];\n const handlers: Array<{\n pattern: string;\n handle: (event: DomainEvent) => Effect.Effect<void, EntifixFailure>;\n }> = [];\n let failNext = false;\n\n return {\n publish: event =>\n Effect.suspend(() => {\n if (failNext) {\n failNext = false;\n return Effect.fail(new Unavailable({ dependency: 'bus' }));\n }\n published.push(event);\n return Effect.void;\n }),\n subscribe: (subscription, handle) =>\n Effect.sync(() => {\n // Only the pattern is retained: queue durability and the delivery\n // ceiling are broker facts with no in-memory analogue, and faking them\n // would assert against the double rather than against a broker.\n handlers.push({ pattern: subscription.pattern, handle });\n }),\n deliver: event =>\n Effect.forEach(\n handlers.filter(({ pattern }) =>\n matchesEventPattern(pattern, event.name),\n ),\n ({ handle }) => handle(event),\n { discard: true },\n ),\n get published() {\n return published;\n },\n failNextPublish: () => {\n failNext = true;\n },\n };\n};\n\n/**\n * An in-memory {@link TransactionInbox}, one per consumer, over a shared claim\n * set.\n *\n * Sharing the set across the inboxes one factory hands out is what makes the\n * contract's \"one consumer cannot consume another's claim\" case a real\n * assertion, rather than one the double satisfies by only ever having seen a\n * single consumer.\n */\nexport const makeInMemoryInboxes = () => {\n const claimed = new Set<string>();\n\n return {\n /** An inbox for `consumer`, over the shared claim set. */\n for: (consumer: string): TransactionInbox => ({\n claim: eventId =>\n Effect.sync(() => {\n const key = JSON.stringify([consumer, eventId]);\n if (claimed.has(key)) return 'duplicate' as const;\n claimed.add(key);\n return 'claimed' as const;\n }),\n }),\n get claims(): readonly { consumer: string; eventId: string }[] {\n return [...claimed].map(key => {\n const [consumer, eventId] = JSON.parse(key) as [string, string];\n return { consumer, eventId };\n });\n },\n };\n};\n\nexport interface InMemorySagaStore extends SagaStore {\n /** Every instance, as stored — for a spec to assert on state, not calls. */\n readonly instances: readonly SagaInstance[];\n}\n\n/**\n * In-memory {@link SagaStore}, with the Mongo adapter's semantics: `start`\n * never overwrites, outcomes append, and a resume claim only takes an\n * unfinished instance whose `updatedAt` is past the deadline — counting the\n * attempt and re-stamping it, so the next sweep does not find it again.\n */\nexport const makeInMemorySagaStore = (): InMemorySagaStore => {\n const instances = new Map<string, SagaInstance>();\n const stamp = () => new Date().toISOString();\n const unfinished = (entry: SagaInstance) =>\n entry.state === 'RUNNING' || entry.state === 'COMPENSATING';\n const pastDeadline = (entry: SagaInstance, olderThanMs: number) =>\n entry.updatedAt < new Date(Date.now() - olderThanMs).toISOString();\n const update = (\n sagaId: string,\n change: (entry: SagaInstance) => SagaInstance,\n ) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (current !== undefined) {\n instances.set(sagaId, { ...change(current), updatedAt: stamp() });\n }\n });\n\n return {\n start: started =>\n Effect.sync(() => {\n if (!instances.has(started.sagaId)) {\n instances.set(started.sagaId, { ...started, updatedAt: stamp() });\n }\n }),\n beginStep: (sagaId, stepIndex) =>\n update(sagaId, entry => ({ ...entry, stepIndex })),\n recordOutcome: (sagaId, outcome) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: [...entry.outcomes, outcome],\n })),\n settle: (sagaId, state, error) =>\n update(sagaId, entry => ({ ...entry, state, error })),\n markCompensated: (sagaId, stepId) =>\n update(sagaId, entry => ({\n ...entry,\n outcomes: entry.outcomes.map(outcome =>\n outcome.stepId === stepId\n ? { ...outcome, compensated: true }\n : outcome,\n ),\n })),\n get: sagaId => Effect.sync(() => instances.get(sagaId)),\n findStale: olderThanMs =>\n Effect.sync(() =>\n [...instances.values()].filter(\n entry => unfinished(entry) && pastDeadline(entry, olderThanMs),\n ),\n ),\n claimForResume: (sagaId, olderThanMs) =>\n Effect.sync(() => {\n const current = instances.get(sagaId);\n if (\n current === undefined ||\n !unfinished(current) ||\n !pastDeadline(current, olderThanMs)\n ) {\n return undefined;\n }\n const claimed = {\n ...current,\n resumeAttempts: current.resumeAttempts + 1,\n updatedAt: stamp(),\n };\n instances.set(sagaId, claimed);\n return claimed;\n }),\n get instances() {\n return [...instances.values()];\n },\n };\n};\n"],"names":["Contention","matchesEventPattern","Unavailable","Effect","makeInMemoryLockService","tokens","Map","contended","Set","log","counter","acquire","key","suspend","has","fail","token","set","push","action","succeed","release","handle","sync","get","delete","held","keys","contendOn","add","makeInMemorySequenceService","sequences","next","name","values","Object","fromEntries","makeRecordingEventBus","published","handlers","failNext","publish","event","dependency","void","subscribe","subscription","pattern","deliver","forEach","filter","discard","failNextPublish","makeInMemoryInboxes","claimed","for","consumer","claim","eventId","JSON","stringify","claims","map","parse","makeInMemorySagaStore","instances","stamp","Date","toISOString","unfinished","entry","state","pastDeadline","olderThanMs","updatedAt","now","update","sagaId","change","current","undefined","start","started","beginStep","stepIndex","recordOutcome","outcome","outcomes","settle","error","markCompensated","stepId","compensated","findStale","claimForResume","resumeAttempts"],"mappings":";AAAA,SACEA,UAAU,EAGVC,mBAAmB,EACnBC,WAAW,QACN,gBAAgB;AAUvB,SAASC,MAAM,QAAQ,SAAS;AAchC;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0B;IACrC,MAAMC,SAAS,IAAIC;IACnB,MAAMC,YAAY,IAAIC;IACtB,MAAMC,MAA6D,EAAE;IACrE,IAAIC,UAAU;IAEd,OAAO;QACLC,SAASC,CAAAA,MACPT,OAAOU,OAAO,CAAC;gBACb,IAAIN,UAAUO,GAAG,CAACF,QAAQP,OAAOS,GAAG,CAACF,MAAM;oBACzC,OAAOT,OAAOY,IAAI,CAAC,IAAIf;gBACzB;gBACA,MAAMgB,QAAQ,CAAC,MAAM,EAAGN,WAAW,GAAI;gBACvCL,OAAOY,GAAG,CAACL,KAAKI;gBAChBP,IAAIS,IA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AAOG;QAGxDqB,gBAAgB,CAACjB,QAAQJ,cACvBtE,OAAOoB,IAAI,CAAC;gBACV,MAAMwD,UAAUd,UAAUzC,GAAG,CAACqD;gBAC9B,IACEE,YAAYC,aACZ,CAACX,WAAWU,YACZ,CAACP,aAAaO,SAASN,cACvB;oBACA,OAAOO;gBACT;gBACA,MAAM1B,UAAU,aACXyB;oBACHgB,gBAAgBhB,QAAQgB,cAAc,GAAG;oBACzCrB,WAAWR;;gBAEbD,UAAUhD,GAAG,CAAC4D,QAAQvB;gBACtB,OAAOA;YACT;QACF,IAAIW;YACF,OAAO;mBAAIA,UAAU/B,MAAM;aAAG;QAChC;IACF;AACF,EAAE"}
@@ -21,7 +21,7 @@ export interface FakeMongoDb {
21
21
  read(collection: string): Document[];
22
22
  /**
23
23
  * Makes every subsequent driver call reject with `error`, so the adapter's
24
- * `EntifixConnError` mapping is reachable. Pass `undefined` to restore.
24
+ * `Unavailable` mapping is reachable. Pass `undefined` to restore.
25
25
  */
26
26
  failWith(error: unknown): void;
27
27
  /**
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/drivers/fake-mongo.ts"],"sourcesContent":["/**\n * A fake of the mongodb driver, not of the repository port.\n *\n * It sits one level *below* `makeMongoRepository`, so the adapter's own code —\n * the filter translation, the projection, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would\n * skip all of it.\n *\n * Only the surface the adapter uses is implemented; anything else is a\n * deliberate `TypeError` rather than a silent no-op.\n */\n\n/** The subset of a Mongo query document the adapter produces. */\ntype QueryDocument = Record<string, unknown>;\ntype Document = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst compare = (left: unknown, right: unknown): number => {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number')\n return left - right;\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\n/** Evaluates one `{ $op: value }` condition against a document field. */\nconst matchesCondition = (actual: unknown, condition: unknown): boolean => {\n if (!isPlainObject(condition)) {\n return actual === condition;\n }\n\n return Object.entries(condition).every(([operator, operand]) => {\n switch (operator) {\n case '$eq':\n return actual === operand;\n case '$ne':\n return actual !== operand;\n case '$gt':\n return compare(actual, operand) > 0;\n case '$gte':\n return compare(actual, operand) >= 0;\n case '$lt':\n return compare(actual, operand) < 0;\n case '$lte':\n return compare(actual, operand) <= 0;\n case '$in':\n return (operand as unknown[]).includes(actual);\n // Absence, not falsiness. A settlement ledger keys \"unpaid\" on a `runId`\n // that is not there at all, and `undefined` is what a document without\n // the field reads as — so `{ $exists: false }` must be a different test\n // from `{ $eq: undefined }` would be if the serializer ever wrote one.\n case '$exists':\n return (actual !== undefined) === (operand as boolean);\n case '$nin':\n return !(operand as unknown[]).includes(actual);\n case '$not':\n return !matchesCondition(actual, operand);\n case '$regex':\n return new RegExp(\n operand as string,\n (condition['$options'] as string) ?? '',\n ).test(String(actual));\n case '$options':\n // Handled together with `$regex`.\n return true;\n default:\n throw new TypeError(`fake mongo: unsupported operator \"${operator}\"`);\n }\n });\n};\n\n/**\n * Evaluates one node of an aggregation expression — the `$expr` half of a\n * query, which is a different language from the operators above: it compares\n * two *fields of the same document* rather than a field against a constant.\n *\n * Only the shape a conditional stock write sends is implemented — a\n * `$subtract` of two field paths compared with `$gte` — and anything else is a\n * `TypeError`. That is the same rule the rest of this file follows: a fake that\n * quietly evaluated an expression it does not understand would answer `true`\n * for a document the real server would have refused, which turns an\n * oversell-prevention test into a test that asserts nothing.\n */\nconst evaluateExpression = (doc: Document, node: unknown): unknown => {\n if (typeof node === 'string' && node.startsWith('$')) {\n return doc[node.slice(1)];\n }\n if (!isPlainObject(node)) {\n return node;\n }\n\n const entries = Object.entries(node);\n if (entries.length !== 1) {\n throw new TypeError(\n `fake mongo: $expr node must have exactly one operator, got ${entries.length}`,\n );\n }\n const [operator, operand] = entries[0];\n const operands = (operand as unknown[]).map(child =>\n evaluateExpression(doc, child),\n );\n\n switch (operator) {\n case '$subtract':\n return (operands[0] as number) - (operands[1] as number);\n case '$add':\n return (operands[0] as number) + (operands[1] as number);\n case '$gte':\n return compare(operands[0], operands[1]) >= 0;\n case '$gt':\n return compare(operands[0], operands[1]) > 0;\n case '$lte':\n return compare(operands[0], operands[1]) <= 0;\n case '$lt':\n return compare(operands[0], operands[1]) < 0;\n case '$eq':\n return operands[0] === operands[1];\n default:\n throw new TypeError(\n `fake mongo: unsupported $expr operator \"${operator}\"`,\n );\n }\n};\n\n/**\n * Every value a field path names, the way the server reads one.\n *\n * A dotted path descends, and **an array on the way down is walked\n * element-wise** — which is what makes `{'items.vendorId': x}` match an order\n * with a line for that vendor rather than nothing at all. Without it a query\n * into an embedded collection silently answers empty here while working against\n * a real server, which is worse than an unsupported-operator throw: the spec\n * passes and asserts the opposite of what it claims.\n *\n * The array itself is kept as a candidate beside its elements, because the\n * server matches both — `{ tags: 'a' }` matches `{ tags: ['a'] }` and\n * `{ tags: 'a' }` alike.\n */\nconst valuesAt = (doc: Document, field: string): unknown[] => {\n let current: unknown[] = [doc];\n for (const segment of field.split('.')) {\n const next: unknown[] = [];\n for (const value of current) {\n const container = Array.isArray(value) ? value : [value];\n for (const element of container) {\n if (isPlainObject(element)) {\n next.push(element[segment]);\n }\n }\n }\n current = next;\n }\n return current.flatMap(value =>\n Array.isArray(value) ? [value, ...value] : [value],\n );\n};\n\n/** Operators that exclude a document when a single value matches them. */\nconst NEGATIVE_OPERATORS = new Set(['$ne', '$nin', '$not']);\n\nconst isNegativeCondition = (condition: unknown): boolean =>\n isPlainObject(condition) &&\n Object.keys(condition).some(operator => NEGATIVE_OPERATORS.has(operator));\n\nconst matches = (doc: Document, query: QueryDocument): boolean =>\n Object.entries(query).every(([field, condition]) => {\n if (field === '$and') {\n return (condition as QueryDocument[]).every(child => matches(doc, child));\n }\n if (field === '$or') {\n return (condition as QueryDocument[]).some(child => matches(doc, child));\n }\n if (field === '$expr') {\n return evaluateExpression(doc, condition) === true;\n }\n const candidates = valuesAt(doc, field);\n if (candidates.length === 0) {\n return matchesCondition(undefined, condition);\n }\n // A positive condition matches when **any** value at the path satisfies it;\n // a negative one only when **every** value does. That asymmetry is the\n // server's: `{ 'items.vendorId': { $ne: 'a' } }` must exclude an order that\n // has a line for `a`, not include it because some other line differs.\n return isNegativeCondition(condition)\n ? candidates.every(value => matchesCondition(value, condition))\n : candidates.some(value => matchesCondition(value, condition));\n });\n\n/** A `$field` reference to a top-level field, the only one the stages take. */\nconst fieldOf = (reference: unknown, stage: string): string => {\n if (\n typeof reference !== 'string' ||\n !reference.startsWith('$') ||\n reference.includes('.')\n ) {\n throw new TypeError(\n `fake mongo: ${stage} takes a top-level \"$field\", got ${JSON.stringify(reference)}`,\n );\n }\n return reference.slice(1);\n};\n\n/**\n * `$unwind` without `preserveNullAndEmptyArrays`: an array becomes one\n * document per element, a missing, `null` or empty one drops the document, and\n * any other value passes through as it is.\n */\nconst unwind = (docs: Document[], spec: unknown): Document[] => {\n const options = isPlainObject(spec) ? spec : { path: spec };\n if (options['preserveNullAndEmptyArrays'] === true) {\n throw new TypeError('fake mongo: $unwind cannot preserve nulls');\n }\n const field = fieldOf(options['path'], '$unwind');\n return docs.flatMap(doc => {\n const value = doc[field];\n if (value == null) return [];\n if (!Array.isArray(value)) return [doc];\n return value.map(element => ({ ...doc, [field]: element }));\n });\n};\n\n/** `$group` by one field, counting with `{ $sum: 1 }`; a missing key is `null`. */\nconst group = (docs: Document[], spec: unknown): Document[] => {\n const { _id: key, ...accumulators } = isPlainObject(spec) ? spec : {};\n const field = fieldOf(key, '$group');\n const entries = Object.entries(accumulators);\n if (\n entries.length !== 1 ||\n !isPlainObject(entries[0][1]) ||\n entries[0][1]['$sum'] !== 1\n ) {\n throw new TypeError(\n 'fake mongo: $group supports one accumulator, { $sum: 1 }',\n );\n }\n const [counted] = entries[0];\n const tally = new Map<unknown, number>();\n for (const doc of docs) {\n const value = doc[field] ?? null;\n tally.set(value, (tally.get(value) ?? 0) + 1);\n }\n return Array.from(tally, ([id, count]) => ({ _id: id, [counted]: count }));\n};\n\nconst runPipeline = (docs: Document[], pipeline: Document[]): Document[] =>\n pipeline.reduce<Document[]>((current, stage) => {\n const entries = Object.entries(stage);\n if (entries.length !== 1) {\n throw new TypeError('fake mongo: a stage has exactly one operator');\n }\n const [operator, spec] = entries[0];\n switch (operator) {\n case '$match':\n return current.filter(doc => matches(doc, spec as QueryDocument));\n case '$unwind':\n return unwind(current, spec);\n case '$group':\n return group(current, spec);\n case '$facet':\n return [\n Object.fromEntries(\n Object.entries(spec as Record<string, Document[]>).map(\n ([output, branch]) => [output, runPipeline(current, branch)],\n ),\n ),\n ];\n default:\n throw new TypeError(`fake mongo: unsupported stage \"${operator}\"`);\n }\n }, docs);\n\n/**\n * The error a real server raises when a write violates a unique index.\n *\n * The `code` matters and the message does not: callers recognise a duplicate\n * key by `error.code === 11000` (or the same code inside `writeErrors`), and a\n * fake that threw a plain `Error` would send a retry path that exists precisely\n * for this case down the \"unexpected failure\" branch instead.\n */\nclass FakeDuplicateKeyError extends Error {\n readonly code = 11000;\n\n constructor(collection: string, key: Document) {\n super(\n `fake mongo: E11000 duplicate key error collection: ${collection} dup key: ${JSON.stringify(key)}`,\n );\n this.name = 'MongoServerError';\n }\n}\n\nexport interface FakeMongoCollection {\n /** The documents currently stored, as the driver would return them. */\n readonly documents: Document[];\n}\n\nexport interface FakeMongoDb {\n /** Replaces a collection's contents. */\n seed(collection: string, documents: Document[]): void;\n /** Reads a collection's current contents. */\n read(collection: string): Document[];\n /**\n * Makes every subsequent driver call reject with `error`, so the adapter's\n * `EntifixConnError` mapping is reachable. Pass `undefined` to restore.\n */\n failWith(error: unknown): void;\n /**\n * Makes only `operation` reject, leaving the rest working — the way a read\n * that succeeds and a count that then fails reaches a distinct error branch.\n */\n failOn(operation: string, error: unknown): void;\n /**\n * Makes only the **next** `operation` reject, then work again — the shape of\n * a transient conflict, which a caller is expected to retry through.\n */\n failOnce(operation: string, error: unknown): void;\n /** Every operation performed, for assertions about what the adapter did. */\n readonly operations: ReadonlyArray<{ collection: string; op: string }>;\n /**\n * Opens a session whose `withTransaction` rolls the whole store back when its\n * body throws. What a service hands to `client.startSession()`; see the\n * implementation for why it is atomicity and not isolation.\n */\n startSession(): {\n withTransaction(body: () => Promise<unknown>): Promise<unknown>;\n /**\n * The explicit form of the same transaction: `startTransaction` takes the\n * snapshot, `abortTransaction` restores it and `commitTransaction` drops\n * it. `commitTransaction` honours `failOn`/`failOnce`, and a commit that\n * fails leaves the transaction open, as an unknown commit result does.\n */\n startTransaction(): void;\n commitTransaction(): Promise<void>;\n abortTransaction(): Promise<void>;\n inTransaction(): boolean;\n endSession(): Promise<void>;\n readonly hasEnded: boolean;\n };\n /** The object to hand to `makeMongoRepository` in place of a real `Db`. */\n readonly db: unknown;\n}\n\n/**\n * Builds an in-memory stand-in for a mongodb `Db`.\n *\n * `db` is typed `unknown` on purpose: casting it at the call site keeps this\n * package free of a hard dependency on the `mongodb` types while remaining\n * honest that it is not a real driver.\n */\nexport const makeFakeMongoDb = (\n seed: Record<string, Document[]> = {},\n): FakeMongoDb => {\n const collections = new Map<string, Document[]>(\n Object.entries(seed).map(([name, docs]) => [\n name,\n docs.map(d => ({ ...d })),\n ]),\n );\n const operations: Array<{ collection: string; op: string }> = [];\n let failure: unknown;\n const failuresByOperation = new Map<string, unknown>();\n const onceFailures = new Map<string, unknown>();\n\n /** The failure `op` should reject with now, consuming a one-shot one. */\n const failureFor = (op: string): unknown => {\n if (onceFailures.has(op)) {\n const once = onceFailures.get(op);\n onceFailures.delete(op);\n return once;\n }\n return failuresByOperation.get(op) ?? failure;\n };\n\n const documentsOf = (name: string): Document[] => {\n if (!collections.has(name)) collections.set(name, []);\n return collections.get(name) as Document[];\n };\n\n /**\n * The unique indexes `createIndex` has been asked for, per collection, as the\n * field lists they key on.\n *\n * Recording them is not bookkeeping: `updateOne` with `upsert` is atomic per\n * *document*, so two concurrent upserts for the same key each fail to see the\n * other's uncommitted insert and each create a row. The index is what makes\n * the fold singular, and a fake that accepted `createIndex` as a no-op would\n * report a service as covered while the property the index exists for went\n * untested.\n */\n const uniqueIndexes = new Map<string, string[][]>();\n\n const uniqueIndexesOf = (name: string): string[][] =>\n uniqueIndexes.get(name) ?? [];\n\n /**\n * Refuses `candidate` if it would duplicate an existing document under one of\n * the collection's unique indexes.\n *\n * `ignored` is the document being replaced by an update, which must not count\n * as its own duplicate. A key whose value is `undefined` on the candidate is\n * skipped: a real index treats a missing field as `null` and would collide,\n * but nothing in this repo indexes an optional member, and guessing wrong\n * here would fail writes the server accepts.\n */\n const assertUnique = (\n name: string,\n candidate: Document,\n ignored?: Document,\n ): void => {\n for (const fields of uniqueIndexesOf(name)) {\n if (fields.some(field => candidate[field] === undefined)) continue;\n const clash = documentsOf(name).find(\n doc =>\n doc !== ignored &&\n fields.every(field => doc[field] === candidate[field]),\n );\n if (clash !== undefined) {\n throw new FakeDuplicateKeyError(\n name,\n Object.fromEntries(fields.map(field => [field, candidate[field]])),\n );\n }\n }\n };\n\n const record = <TValue>(name: string, op: string, produce: () => TValue) => {\n operations.push({ collection: name, op });\n const rejection = failureFor(op);\n if (rejection !== undefined) return Promise.reject(rejection);\n // `try`/`catch` rather than `Promise.resolve(produce())`: a real driver\n // returns a promise and *rejects*, so a fake that threw synchronously would\n // need different handling at every call site than the thing it stands in for.\n try {\n return Promise.resolve(produce());\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n /** Applies `{ projection: { _id: 0 } }`, the only projection the adapter uses. */\n const project = (doc: Document, options?: { projection?: Document }) => {\n const copy = { ...doc };\n if (options?.projection && options.projection['_id'] === 0) {\n delete copy['_id'];\n }\n return copy;\n };\n\n const collection = (name: string) => ({\n find: (query: QueryDocument = {}, options?: { projection?: Document }) => {\n let sortSpec: Record<string, 1 | -1> = {};\n let skipCount = 0;\n let limitCount = Infinity;\n\n const cursor = {\n sort(spec: Record<string, 1 | -1>) {\n sortSpec = spec;\n return cursor;\n },\n skip(count: number) {\n skipCount = count;\n return cursor;\n },\n limit(count: number) {\n limitCount = count;\n return cursor;\n },\n toArray: () =>\n record(name, 'find', () => {\n const matched = documentsOf(name).filter(doc =>\n matches(doc, query),\n );\n const sorted = Object.entries(sortSpec).reduceRight(\n (items, [field, direction]) =>\n [...items].sort(\n (left, right) =>\n // A dotted field sorts by the value it names, as the\n // server does — one locale of a localized member, say.\n compare(\n valuesAt(left, field)[0],\n valuesAt(right, field)[0],\n ) * direction,\n ),\n matched,\n );\n return sorted\n .slice(skipCount, skipCount + limitCount)\n .map(doc => project(doc, options));\n }),\n };\n return cursor;\n },\n\n /**\n * The four stages a facet count sends — `$facet`, `$match`, `$unwind` and\n * a `$group` counting with `{ $sum: 1 }` — and nothing else: an unknown\n * stage, or a stage in a shape not listed here, is a `TypeError` rather\n * than a pass-through, for the reason `$expr` above gives.\n */\n aggregate: (pipeline: Document[]) => ({\n toArray: () =>\n record(name, 'aggregate', () =>\n runPipeline(documentsOf(name), pipeline),\n ),\n }),\n\n findOne: (query: QueryDocument, options?: { projection?: Document }) =>\n record(name, 'findOne', () => {\n const found = documentsOf(name).find(doc => matches(doc, query));\n return found === undefined ? null : project(found, options);\n }),\n\n countDocuments: (query: QueryDocument = {}) =>\n record(\n name,\n 'countDocuments',\n () => documentsOf(name).filter(doc => matches(doc, query)).length,\n ),\n\n // Used by the services' own seeding, which the e2e `mock` profile runs for\n // real so both profiles serve the same catalog.\n insertMany: (documents: Document[]) =>\n record(name, 'insertMany', () => {\n const stored = documentsOf(name);\n for (const document of documents) {\n assertUnique(name, document);\n stored.push({ ...document });\n }\n return { insertedCount: documents.length };\n }),\n\n /**\n * A single insert — how an append-only ledger grows, and how a hold is\n * written beside the counter it moved.\n *\n * The options argument is accepted and ignored except for its `session`,\n * which the transaction wrapper already handles: a caller that passes one\n * is inside `withTransaction`, and this fake's rollback is a snapshot of\n * the whole store rather than anything per-operation.\n */\n insertOne: (document: Document) =>\n record(name, 'insertOne', () => {\n assertUnique(name, document);\n documentsOf(name).push({ ...document });\n return { acknowledged: true, insertedId: document['id'] ?? null };\n }),\n\n replaceOne: (\n query: QueryDocument,\n replacement: Document,\n options?: { upsert?: boolean },\n ) =>\n record(name, 'replaceOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) {\n if (!options?.upsert) return { matchedCount: 0, upsertedCount: 0 };\n // Held to the collection's unique indexes on both branches, as\n // `updateOne` is: an upsert racing another for the same key is\n // exactly what a unique index exists to refuse, and a fake that let\n // this one through would bless the duplicate the server rejects.\n assertUnique(name, replacement);\n documents.push({ ...replacement });\n return { matchedCount: 0, upsertedCount: 1 };\n }\n assertUnique(name, replacement, documents[index]);\n documents[index] = { ...replacement };\n return { matchedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * Partial update. `$set`, `$unset`, `$addToSet`, `$inc` and `$setOnInsert`\n * are implemented — the operators the adapters, the outbox and the stock\n * ledger use — and **anything else throws**, because a fake that silently\n * accepted `$rename` without applying it would let a spec pass on an update\n * that never happened.\n *\n * `$unset` removes the field whatever value it is given, as the server\n * does; it is how the outbox clears a quarantined entry's failure note when\n * it puts the entry back in the queue.\n *\n * `$addToSet` is what links an identifier onto `user-identity.identifiers`\n * without duplicating it on a repair run; supporting it here rather than\n * ignoring it is the difference between the e2e proving the link and merely\n * not noticing its absence.\n *\n * `$inc` with `upsert` is how a quantity moves. It matters that it is a\n * real increment and not a read-modify-write even here: the whole rule it\n * implements is that an absolute-value write loses updates, so a fake that\n * computed the new total from a value it had already read would model the\n * bug rather than the fix.\n *\n * `$push` appends, and a `$set` key of the form `field.$[name].member`\n * applies to every element of `field` that `options.arrayFilters` selects —\n * the pair a saga store records an outcome with and later flags one\n * compensated. Both are what keep an array update from being a\n * read-modify-write, which is the point of using them.\n */\n updateOne: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $unset?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; arrayFilters?: readonly Document[] },\n ) =>\n record(name, 'updateOne', () => {\n const supported = [\n '$set',\n '$unset',\n '$addToSet',\n '$inc',\n '$setOnInsert',\n '$push',\n ];\n const unsupported = Object.keys(update).filter(\n operator => !supported.includes(operator),\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateOne does not implement ${unsupported.join(', ')}`,\n );\n }\n\n // A real server rejects an update whose operators both name one field,\n // and the message is the one this repro'd against: `$setOnInsert` that\n // also named a field `$inc` touches. Reproducing the refusal is what\n // keeps the fake from blessing an update Mongo would refuse.\n const conflicting = Object.keys(update.$setOnInsert ?? {}).filter(\n field => field in (update.$inc ?? {}) || field in (update.$set ?? {}),\n );\n if (conflicting.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $setOnInsert and $inc/$set: ${conflicting.join(', ')}`,\n );\n }\n // The same refusal for a field both written and removed.\n const unsetConflicts = Object.keys(update.$unset ?? {}).filter(\n field => field in (update.$set ?? {}) || field in (update.$inc ?? {}),\n );\n if (unsetConflicts.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $unset and $inc/$set: ${unsetConflicts.join(', ')}`,\n );\n }\n\n /** `$set`, `$addToSet`, `$inc` and `$push`, which apply on both branches. */\n const applyOperators = (base: Document): Document => {\n const plain = Object.entries(update.$set ?? {}).filter(\n ([field]) => !field.includes('.$['),\n );\n const updated = { ...base, ...Object.fromEntries(plain) };\n for (const [path, value] of Object.entries(update.$set ?? {})) {\n const filtered = /^([^.]+)\\.\\$\\[([^\\]]+)\\]\\.(.+)$/.exec(path);\n if (filtered === null) continue;\n const [, field, identifier, member] = filtered as unknown as [\n string,\n string,\n string,\n string,\n ];\n // The server refuses a filtered position with no filter naming it.\n const conditions = (options?.arrayFilters ?? []).flatMap(filter =>\n Object.entries(filter)\n .filter(([key]) => key.startsWith(`${identifier}.`))\n .map(\n ([key, condition]) =>\n [key.slice(identifier.length + 1), condition] as const,\n ),\n );\n if (conditions.length === 0) {\n throw new Error(\n `fake-mongo: no array filter found for identifier ${identifier}`,\n );\n }\n const current = updated[field];\n updated[field] = (Array.isArray(current) ? current : []).map(\n element =>\n isPlainObject(element) &&\n conditions.every(([key, condition]) =>\n matchesCondition(element[key], condition),\n )\n ? { ...element, [member]: value }\n : element,\n );\n }\n for (const [field, value] of Object.entries(update.$push ?? {})) {\n const current = updated[field];\n updated[field] = [\n ...(Array.isArray(current) ? current : []),\n value,\n ];\n }\n for (const [field, value] of Object.entries(update.$addToSet ?? {})) {\n const current = updated[field];\n const array = Array.isArray(current) ? current : [];\n if (!array.includes(value)) {\n updated[field] = [...array, value];\n }\n }\n for (const [field, delta] of Object.entries(update.$inc ?? {})) {\n // An absent field is created at the increment's value, which is\n // exactly why `$setOnInsert` must not also name it.\n const current = updated[field];\n updated[field] =\n (typeof current === 'number' ? current : 0) + (delta as number);\n }\n for (const field of Object.keys(update.$unset ?? {})) {\n delete updated[field];\n }\n return updated;\n };\n\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n if (index === -1) {\n if (options?.upsert !== true) {\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 0 };\n }\n // The upserted document starts from the query's *equality* fields,\n // the way a real server seeds one — an operator condition contributes\n // nothing, which is why a `$expr`-guarded upsert would insert a row\n // missing the very field it filtered on.\n const seedFields = Object.fromEntries(\n Object.entries(query).filter(\n ([field, condition]) =>\n !field.startsWith('$') && !isPlainObject(condition),\n ),\n );\n const inserted = applyOperators({\n ...seedFields,\n ...(update.$setOnInsert ?? {}),\n });\n assertUnique(name, inserted);\n documents.push(inserted);\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 1 };\n }\n\n const updated = applyOperators(documents[index]);\n assertUnique(name, updated, documents[index]);\n documents[index] = updated;\n return { matchedCount: 1, modifiedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * `$set` across every matching document, and the count of what changed.\n *\n * ⚠️ **The count is what a caller branches on.** A settlement run claims its\n * ledger lines with this and reads `modifiedCount === 0` as \"another replica\n * took them all\" — so a fake returning a fixed `1`, or the match count\n * rather than the modified count, would make the losing replica behave like\n * the winning one and the conditional claim would test nothing.\n *\n * `$set` only. Anything else throws, for the reason `updateOne` gives:\n * silently accepting an operator it does not apply lets a spec pass on an\n * update that never happened.\n */\n updateMany: (query: QueryDocument, update: { $set?: Document }) =>\n record(name, 'updateMany', () => {\n const unsupported = Object.keys(update).filter(\n operator => operator !== '$set',\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateMany does not implement ${unsupported.join(', ')}`,\n );\n }\n\n const documents = documentsOf(name);\n let modifiedCount = 0;\n documents.forEach((doc, index) => {\n if (!matches(doc, query)) return;\n const updated = { ...doc, ...(update.$set ?? {}) };\n assertUnique(name, updated, doc);\n documents[index] = updated;\n modifiedCount += 1;\n });\n return { matchedCount: modifiedCount, modifiedCount };\n }),\n\n /**\n * Update one document and hand back the result, upserting when asked.\n *\n * ⚠️ **`returnDocument: 'after'` is the only mode implemented, and the\n * default here is `'after'` rather than the driver's `'before'`** — because\n * the callers that need this primitive at all need the merged document. A\n * two-message join upserts its own half and then asks \"is the pair complete\n * now?\", which is a question only the *after* state answers. `'before'`\n * throws rather than quietly returning the wrong half.\n *\n * Implemented over {@link updateOne} so the upsert seeding rule, the\n * conflicting-path refusal and the unique-index enforcement are the same\n * ones, rather than a second copy that could drift from them.\n */\n findOneAndUpdate: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $unset?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; returnDocument?: 'before' | 'after' },\n ) =>\n record(name, 'findOneAndUpdate', async () => {\n if (options?.returnDocument === 'before') {\n throw new Error(\n 'fake-mongo: findOneAndUpdate only implements returnDocument: \"after\"',\n );\n }\n // Where the document is *before* the write, because afterwards the\n // query may no longer find it: an upsert's operator conditions need not\n // hold of the row it just inserted — `{ folded: { $exists: false } }`\n // matches nothing once `folded` has been set. `documentsOf` hands back\n // the live array, which `updateOne` mutates in place or pushes onto, so\n // the position is enough to identify it either way.\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n const result = await collection(name).updateOne(query, update, {\n upsert: options?.upsert === true,\n });\n if (result.matchedCount === 0 && result.upsertedCount === 0) {\n return null;\n }\n\n return index === -1\n ? documents[documents.length - 1]\n : documents[index];\n }),\n\n deleteOne: (query: QueryDocument) =>\n record(name, 'deleteOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) return { deletedCount: 0 };\n documents.splice(index, 1);\n return { deletedCount: 1 };\n }),\n\n /**\n * Declares an index, and **enforces it when it is unique**.\n *\n * Idempotent, like the real one: a service that ensures its index per\n * request rather than at boot — because a tenant database only appears on\n * first write — calls this on every write.\n */\n createIndex: (spec: Document, options?: Document) =>\n record(name, 'createIndex', () => {\n if (options?.['unique'] === true) {\n const fields = Object.keys(spec);\n const existing = uniqueIndexes.get(name) ?? [];\n const already = existing.some(\n candidate =>\n candidate.length === fields.length &&\n candidate.every((field, at) => field === fields[at]),\n );\n if (!already) {\n uniqueIndexes.set(name, [...existing, fields]);\n }\n }\n return { spec, options };\n }),\n });\n\n /**\n * A session whose `withTransaction` really rolls back.\n *\n * ⚠️ **It is atomicity, not isolation, and the difference decides where a\n * test may live.** The store is a single-threaded object graph, so nothing\n * runs concurrently with the body and a \"race\" here resolves in the order it\n * was written: a concurrency property — two writers contending for the last\n * unit — is green under this fake no matter what the code does, and belongs\n * in a `*.live.spec.ts` against real Mongo.\n *\n * What it *does* model is the abort path, which is worth having: a body that\n * throws leaves the store exactly as it found it, so a conditional write that\n * moves a counter and then fails to write its row cannot leave the counter\n * moved. That is a real bug shape, and one a fake without rollback would hide\n * by committing half of it.\n */\n const snapshotOf = () =>\n new Map(\n [...collections].map(([name, docs]) => [\n name,\n docs.map(doc => ({ ...doc })),\n ]),\n );\n const restore = (snapshot: Map<string, Document[]>) => {\n collections.clear();\n for (const [name, docs] of snapshot) collections.set(name, docs);\n };\n\n const startSession = () => {\n let open = true;\n let pending: Map<string, Document[]> | undefined;\n const noTransaction = () =>\n Promise.reject(new Error('fake-mongo: no transaction in progress'));\n return {\n startTransaction: () => {\n if (pending !== undefined) {\n throw new Error('fake-mongo: a transaction is already in progress');\n }\n pending = snapshotOf();\n },\n commitTransaction: () => {\n if (pending === undefined) return noTransaction();\n operations.push({ collection: '', op: 'commitTransaction' });\n const rejection = failureFor('commitTransaction');\n if (rejection !== undefined) return Promise.reject(rejection);\n pending = undefined;\n return Promise.resolve();\n },\n abortTransaction: () => {\n if (pending === undefined) return noTransaction();\n restore(pending);\n pending = undefined;\n return Promise.resolve();\n },\n inTransaction: () => pending !== undefined,\n withTransaction: async (body: () => Promise<unknown>) => {\n const snapshot = snapshotOf();\n try {\n return await body();\n } catch (error) {\n restore(snapshot);\n throw error;\n }\n },\n endSession: () => {\n open = false;\n return Promise.resolve();\n },\n get hasEnded() {\n return !open;\n },\n };\n };\n\n return {\n seed: (name, documents) => {\n collections.set(\n name,\n documents.map(doc => ({ ...doc })),\n );\n },\n read: name => documentsOf(name).map(doc => ({ ...doc })),\n failWith: error => {\n failure = error;\n },\n failOn: (operation, error) => {\n failuresByOperation.set(operation, error);\n },\n failOnce: (operation, error) => {\n onceFailures.set(operation, error);\n },\n get operations() {\n return operations;\n },\n startSession,\n db: { collection },\n };\n};\n"],"names":["isPlainObject","value","Array","isArray","compare","left","right","Date","getTime","String","localeCompare","matchesCondition","actual","condition","Object","entries","every","operator","operand","includes","undefined","RegExp","test","TypeError","evaluateExpression","doc","node","startsWith","slice","length","operands","map","child","valuesAt","field","current","segment","split","next","container","element","push","flatMap","NEGATIVE_OPERATORS","Set","isNegativeCondition","keys","some","has","matches","query","candidates","fieldOf","reference","stage","JSON","stringify","unwind","docs","spec","options","path","group","_id","key","accumulators","counted","tally","Map","set","get","from","id","count","runPipeline","pipeline","reduce","filter","fromEntries","output","branch","FakeDuplicateKeyError","Error","collection","code","name","makeFakeMongoDb","seed","collections","d","operations","failure","failuresByOperation","onceFailures","failureFor","op","once","delete","documentsOf","uniqueIndexes","uniqueIndexesOf","assertUnique","candidate","ignored","fields","clash","find","record","produce","rejection","Promise","reject","resolve","error","project","copy","projection","sortSpec","skipCount","limitCount","Infinity","cursor","sort","skip","limit","toArray","matched","sorted","reduceRight","items","direction","aggregate","findOne","found","countDocuments","insertMany","documents","stored","document","insertedCount","insertOne","acknowledged","insertedId","replaceOne","replacement","index","findIndex","upsert","matchedCount","upsertedCount","updateOne","update","supported","unsupported","join","conflicting","$setOnInsert","$inc","$set","unsetConflicts","$unset","applyOperators","base","plain","updated","filtered","exec","identifier","member","conditions","arrayFilters","$push","$addToSet","array","delta","modifiedCount","seedFields","inserted","updateMany","forEach","findOneAndUpdate","returnDocument","result","deleteOne","deletedCount","splice","createIndex","existing","already","at","snapshotOf","restore","snapshot","clear","startSession","open","pending","noTransaction","startTransaction","commitTransaction","abortTransaction","inTransaction","withTransaction","body","endSession","hasEnded","read","failWith","failOn","operation","failOnce","db"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,+DAA+D;;AAI/D,MAAMA,gBAAgB,CAACC,QACrB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAEhE,MAAMG,UAAU,CAACC,MAAeC;IAC9B,IAAID,QAAQ,QAAQC,SAAS,MAAM,OAAO;IAC1C,IAAID,QAAQ,MAAM,OAAO,CAAC;IAC1B,IAAIC,SAAS,MAAM,OAAO;IAC1B,IAAI,OAAOD,SAAS,YAAY,OAAOC,UAAU,UAC/C,OAAOD,OAAOC;IAChB,IAAID,gBAAgBE,QAAQD,iBAAiBC,MAAM;QACjD,OAAOF,KAAKG,OAAO,KAAKF,MAAME,OAAO;IACvC;IACA,OAAOC,OAAOJ,MAAMK,aAAa,CAACD,OAAOH;AAC3C;AAEA,uEAAuE,GACvE,M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AO0F,QAAQC,MAAM,CAACF;gBACnDuF,UAAUhL;gBACV,OAAO0F,QAAQE,OAAO;YACxB;YACAwF,kBAAkB;gBAChB,IAAIJ,YAAYhL,WAAW,OAAOiL;gBAClCN,QAAQK;gBACRA,UAAUhL;gBACV,OAAO0F,QAAQE,OAAO;YACxB;YACAyF,eAAe,IAAML,YAAYhL;YACjCsL,iBAAiB,OAAOC;gBACtB,MAAMX,WAAWF;gBACjB,IAAI;oBACF,OAAO,MAAMa;gBACf,EAAE,OAAO1F,OAAO;oBACd8E,QAAQC;oBACR,MAAM/E;gBACR;YACF;YACA2F,YAAY;gBACVT,OAAO;gBACP,OAAOrF,QAAQE,OAAO;YACxB;YACA,IAAI6F;gBACF,OAAO,CAACV;YACV;QACF;IACF;IAEA,OAAO;QACL5G,MAAM,CAACF,MAAMmD;YACXhD,YAAYnB,GAAG,CACbgB,MACAmD,UAAUzG,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QAE/B;QACAqL,MAAMzH,CAAAA,OAAQa,YAAYb,MAAMtD,GAAG,CAACN,CAAAA,MAAQ,aAAKA;QACjDsL,UAAU9F,CAAAA;YACRtB,UAAUsB;QACZ;QACA+F,QAAQ,CAACC,WAAWhG;YAClBrB,oBAAoBvB,GAAG,CAAC4I,WAAWhG;QACrC;QACAiG,UAAU,CAACD,WAAWhG;YACpBpB,aAAaxB,GAAG,CAAC4I,WAAWhG;QAC9B;QACA,IAAIvB;YACF,OAAOA;QACT;QACAwG;QACAiB,IAAI;YAAEhI;QAAW;IACnB;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-mongo.ts"],"sourcesContent":["/**\n * A fake of the mongodb driver, not of the repository port.\n *\n * It sits one level *below* `makeMongoRepository`, so the adapter's own code —\n * the filter translation, the projection, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would\n * skip all of it.\n *\n * Only the surface the adapter uses is implemented; anything else is a\n * deliberate `TypeError` rather than a silent no-op.\n */\n\n/** The subset of a Mongo query document the adapter produces. */\ntype QueryDocument = Record<string, unknown>;\ntype Document = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is Document =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst compare = (left: unknown, right: unknown): number => {\n if (left == null && right == null) return 0;\n if (left == null) return -1;\n if (right == null) return 1;\n if (typeof left === 'number' && typeof right === 'number')\n return left - right;\n if (left instanceof Date && right instanceof Date) {\n return left.getTime() - right.getTime();\n }\n return String(left).localeCompare(String(right));\n};\n\n/** Evaluates one `{ $op: value }` condition against a document field. */\nconst matchesCondition = (actual: unknown, condition: unknown): boolean => {\n if (!isPlainObject(condition)) {\n return actual === condition;\n }\n\n return Object.entries(condition).every(([operator, operand]) => {\n switch (operator) {\n case '$eq':\n return actual === operand;\n case '$ne':\n return actual !== operand;\n case '$gt':\n return compare(actual, operand) > 0;\n case '$gte':\n return compare(actual, operand) >= 0;\n case '$lt':\n return compare(actual, operand) < 0;\n case '$lte':\n return compare(actual, operand) <= 0;\n case '$in':\n return (operand as unknown[]).includes(actual);\n // Absence, not falsiness. A settlement ledger keys \"unpaid\" on a `runId`\n // that is not there at all, and `undefined` is what a document without\n // the field reads as — so `{ $exists: false }` must be a different test\n // from `{ $eq: undefined }` would be if the serializer ever wrote one.\n case '$exists':\n return (actual !== undefined) === (operand as boolean);\n case '$nin':\n return !(operand as unknown[]).includes(actual);\n case '$not':\n return !matchesCondition(actual, operand);\n case '$regex':\n return new RegExp(\n operand as string,\n (condition['$options'] as string) ?? '',\n ).test(String(actual));\n case '$options':\n // Handled together with `$regex`.\n return true;\n default:\n throw new TypeError(`fake mongo: unsupported operator \"${operator}\"`);\n }\n });\n};\n\n/**\n * Evaluates one node of an aggregation expression — the `$expr` half of a\n * query, which is a different language from the operators above: it compares\n * two *fields of the same document* rather than a field against a constant.\n *\n * Only the shape a conditional stock write sends is implemented — a\n * `$subtract` of two field paths compared with `$gte` — and anything else is a\n * `TypeError`. That is the same rule the rest of this file follows: a fake that\n * quietly evaluated an expression it does not understand would answer `true`\n * for a document the real server would have refused, which turns an\n * oversell-prevention test into a test that asserts nothing.\n */\nconst evaluateExpression = (doc: Document, node: unknown): unknown => {\n if (typeof node === 'string' && node.startsWith('$')) {\n return doc[node.slice(1)];\n }\n if (!isPlainObject(node)) {\n return node;\n }\n\n const entries = Object.entries(node);\n if (entries.length !== 1) {\n throw new TypeError(\n `fake mongo: $expr node must have exactly one operator, got ${entries.length}`,\n );\n }\n const [operator, operand] = entries[0];\n const operands = (operand as unknown[]).map(child =>\n evaluateExpression(doc, child),\n );\n\n switch (operator) {\n case '$subtract':\n return (operands[0] as number) - (operands[1] as number);\n case '$add':\n return (operands[0] as number) + (operands[1] as number);\n case '$gte':\n return compare(operands[0], operands[1]) >= 0;\n case '$gt':\n return compare(operands[0], operands[1]) > 0;\n case '$lte':\n return compare(operands[0], operands[1]) <= 0;\n case '$lt':\n return compare(operands[0], operands[1]) < 0;\n case '$eq':\n return operands[0] === operands[1];\n default:\n throw new TypeError(\n `fake mongo: unsupported $expr operator \"${operator}\"`,\n );\n }\n};\n\n/**\n * Every value a field path names, the way the server reads one.\n *\n * A dotted path descends, and **an array on the way down is walked\n * element-wise** — which is what makes `{'items.vendorId': x}` match an order\n * with a line for that vendor rather than nothing at all. Without it a query\n * into an embedded collection silently answers empty here while working against\n * a real server, which is worse than an unsupported-operator throw: the spec\n * passes and asserts the opposite of what it claims.\n *\n * The array itself is kept as a candidate beside its elements, because the\n * server matches both — `{ tags: 'a' }` matches `{ tags: ['a'] }` and\n * `{ tags: 'a' }` alike.\n */\nconst valuesAt = (doc: Document, field: string): unknown[] => {\n let current: unknown[] = [doc];\n for (const segment of field.split('.')) {\n const next: unknown[] = [];\n for (const value of current) {\n const container = Array.isArray(value) ? value : [value];\n for (const element of container) {\n if (isPlainObject(element)) {\n next.push(element[segment]);\n }\n }\n }\n current = next;\n }\n return current.flatMap(value =>\n Array.isArray(value) ? [value, ...value] : [value],\n );\n};\n\n/** Operators that exclude a document when a single value matches them. */\nconst NEGATIVE_OPERATORS = new Set(['$ne', '$nin', '$not']);\n\nconst isNegativeCondition = (condition: unknown): boolean =>\n isPlainObject(condition) &&\n Object.keys(condition).some(operator => NEGATIVE_OPERATORS.has(operator));\n\nconst matches = (doc: Document, query: QueryDocument): boolean =>\n Object.entries(query).every(([field, condition]) => {\n if (field === '$and') {\n return (condition as QueryDocument[]).every(child => matches(doc, child));\n }\n if (field === '$or') {\n return (condition as QueryDocument[]).some(child => matches(doc, child));\n }\n if (field === '$expr') {\n return evaluateExpression(doc, condition) === true;\n }\n const candidates = valuesAt(doc, field);\n if (candidates.length === 0) {\n return matchesCondition(undefined, condition);\n }\n // A positive condition matches when **any** value at the path satisfies it;\n // a negative one only when **every** value does. That asymmetry is the\n // server's: `{ 'items.vendorId': { $ne: 'a' } }` must exclude an order that\n // has a line for `a`, not include it because some other line differs.\n return isNegativeCondition(condition)\n ? candidates.every(value => matchesCondition(value, condition))\n : candidates.some(value => matchesCondition(value, condition));\n });\n\n/** A `$field` reference to a top-level field, the only one the stages take. */\nconst fieldOf = (reference: unknown, stage: string): string => {\n if (\n typeof reference !== 'string' ||\n !reference.startsWith('$') ||\n reference.includes('.')\n ) {\n throw new TypeError(\n `fake mongo: ${stage} takes a top-level \"$field\", got ${JSON.stringify(reference)}`,\n );\n }\n return reference.slice(1);\n};\n\n/**\n * `$unwind` without `preserveNullAndEmptyArrays`: an array becomes one\n * document per element, a missing, `null` or empty one drops the document, and\n * any other value passes through as it is.\n */\nconst unwind = (docs: Document[], spec: unknown): Document[] => {\n const options = isPlainObject(spec) ? spec : { path: spec };\n if (options['preserveNullAndEmptyArrays'] === true) {\n throw new TypeError('fake mongo: $unwind cannot preserve nulls');\n }\n const field = fieldOf(options['path'], '$unwind');\n return docs.flatMap(doc => {\n const value = doc[field];\n if (value == null) return [];\n if (!Array.isArray(value)) return [doc];\n return value.map(element => ({ ...doc, [field]: element }));\n });\n};\n\n/** `$group` by one field, counting with `{ $sum: 1 }`; a missing key is `null`. */\nconst group = (docs: Document[], spec: unknown): Document[] => {\n const { _id: key, ...accumulators } = isPlainObject(spec) ? spec : {};\n const field = fieldOf(key, '$group');\n const entries = Object.entries(accumulators);\n if (\n entries.length !== 1 ||\n !isPlainObject(entries[0][1]) ||\n entries[0][1]['$sum'] !== 1\n ) {\n throw new TypeError(\n 'fake mongo: $group supports one accumulator, { $sum: 1 }',\n );\n }\n const [counted] = entries[0];\n const tally = new Map<unknown, number>();\n for (const doc of docs) {\n const value = doc[field] ?? null;\n tally.set(value, (tally.get(value) ?? 0) + 1);\n }\n return Array.from(tally, ([id, count]) => ({ _id: id, [counted]: count }));\n};\n\nconst runPipeline = (docs: Document[], pipeline: Document[]): Document[] =>\n pipeline.reduce<Document[]>((current, stage) => {\n const entries = Object.entries(stage);\n if (entries.length !== 1) {\n throw new TypeError('fake mongo: a stage has exactly one operator');\n }\n const [operator, spec] = entries[0];\n switch (operator) {\n case '$match':\n return current.filter(doc => matches(doc, spec as QueryDocument));\n case '$unwind':\n return unwind(current, spec);\n case '$group':\n return group(current, spec);\n case '$facet':\n return [\n Object.fromEntries(\n Object.entries(spec as Record<string, Document[]>).map(\n ([output, branch]) => [output, runPipeline(current, branch)],\n ),\n ),\n ];\n default:\n throw new TypeError(`fake mongo: unsupported stage \"${operator}\"`);\n }\n }, docs);\n\n/**\n * The error a real server raises when a write violates a unique index.\n *\n * The `code` matters and the message does not: callers recognise a duplicate\n * key by `error.code === 11000` (or the same code inside `writeErrors`), and a\n * fake that threw a plain `Error` would send a retry path that exists precisely\n * for this case down the \"unexpected failure\" branch instead.\n */\nclass FakeDuplicateKeyError extends Error {\n readonly code = 11000;\n\n constructor(collection: string, key: Document) {\n super(\n `fake mongo: E11000 duplicate key error collection: ${collection} dup key: ${JSON.stringify(key)}`,\n );\n this.name = 'MongoServerError';\n }\n}\n\nexport interface FakeMongoCollection {\n /** The documents currently stored, as the driver would return them. */\n readonly documents: Document[];\n}\n\nexport interface FakeMongoDb {\n /** Replaces a collection's contents. */\n seed(collection: string, documents: Document[]): void;\n /** Reads a collection's current contents. */\n read(collection: string): Document[];\n /**\n * Makes every subsequent driver call reject with `error`, so the adapter's\n * `Unavailable` mapping is reachable. Pass `undefined` to restore.\n */\n failWith(error: unknown): void;\n /**\n * Makes only `operation` reject, leaving the rest working — the way a read\n * that succeeds and a count that then fails reaches a distinct error branch.\n */\n failOn(operation: string, error: unknown): void;\n /**\n * Makes only the **next** `operation` reject, then work again — the shape of\n * a transient conflict, which a caller is expected to retry through.\n */\n failOnce(operation: string, error: unknown): void;\n /** Every operation performed, for assertions about what the adapter did. */\n readonly operations: ReadonlyArray<{ collection: string; op: string }>;\n /**\n * Opens a session whose `withTransaction` rolls the whole store back when its\n * body throws. What a service hands to `client.startSession()`; see the\n * implementation for why it is atomicity and not isolation.\n */\n startSession(): {\n withTransaction(body: () => Promise<unknown>): Promise<unknown>;\n /**\n * The explicit form of the same transaction: `startTransaction` takes the\n * snapshot, `abortTransaction` restores it and `commitTransaction` drops\n * it. `commitTransaction` honours `failOn`/`failOnce`, and a commit that\n * fails leaves the transaction open, as an unknown commit result does.\n */\n startTransaction(): void;\n commitTransaction(): Promise<void>;\n abortTransaction(): Promise<void>;\n inTransaction(): boolean;\n endSession(): Promise<void>;\n readonly hasEnded: boolean;\n };\n /** The object to hand to `makeMongoRepository` in place of a real `Db`. */\n readonly db: unknown;\n}\n\n/**\n * Builds an in-memory stand-in for a mongodb `Db`.\n *\n * `db` is typed `unknown` on purpose: casting it at the call site keeps this\n * package free of a hard dependency on the `mongodb` types while remaining\n * honest that it is not a real driver.\n */\nexport const makeFakeMongoDb = (\n seed: Record<string, Document[]> = {},\n): FakeMongoDb => {\n const collections = new Map<string, Document[]>(\n Object.entries(seed).map(([name, docs]) => [\n name,\n docs.map(d => ({ ...d })),\n ]),\n );\n const operations: Array<{ collection: string; op: string }> = [];\n let failure: unknown;\n const failuresByOperation = new Map<string, unknown>();\n const onceFailures = new Map<string, unknown>();\n\n /** The failure `op` should reject with now, consuming a one-shot one. */\n const failureFor = (op: string): unknown => {\n if (onceFailures.has(op)) {\n const once = onceFailures.get(op);\n onceFailures.delete(op);\n return once;\n }\n return failuresByOperation.get(op) ?? failure;\n };\n\n const documentsOf = (name: string): Document[] => {\n if (!collections.has(name)) collections.set(name, []);\n return collections.get(name) as Document[];\n };\n\n /**\n * The unique indexes `createIndex` has been asked for, per collection, as the\n * field lists they key on.\n *\n * Recording them is not bookkeeping: `updateOne` with `upsert` is atomic per\n * *document*, so two concurrent upserts for the same key each fail to see the\n * other's uncommitted insert and each create a row. The index is what makes\n * the fold singular, and a fake that accepted `createIndex` as a no-op would\n * report a service as covered while the property the index exists for went\n * untested.\n */\n const uniqueIndexes = new Map<string, string[][]>();\n\n const uniqueIndexesOf = (name: string): string[][] =>\n uniqueIndexes.get(name) ?? [];\n\n /**\n * Refuses `candidate` if it would duplicate an existing document under one of\n * the collection's unique indexes.\n *\n * `ignored` is the document being replaced by an update, which must not count\n * as its own duplicate. A key whose value is `undefined` on the candidate is\n * skipped: a real index treats a missing field as `null` and would collide,\n * but nothing in this repo indexes an optional member, and guessing wrong\n * here would fail writes the server accepts.\n */\n const assertUnique = (\n name: string,\n candidate: Document,\n ignored?: Document,\n ): void => {\n for (const fields of uniqueIndexesOf(name)) {\n if (fields.some(field => candidate[field] === undefined)) continue;\n const clash = documentsOf(name).find(\n doc =>\n doc !== ignored &&\n fields.every(field => doc[field] === candidate[field]),\n );\n if (clash !== undefined) {\n throw new FakeDuplicateKeyError(\n name,\n Object.fromEntries(fields.map(field => [field, candidate[field]])),\n );\n }\n }\n };\n\n const record = <TValue>(name: string, op: string, produce: () => TValue) => {\n operations.push({ collection: name, op });\n const rejection = failureFor(op);\n if (rejection !== undefined) return Promise.reject(rejection);\n // `try`/`catch` rather than `Promise.resolve(produce())`: a real driver\n // returns a promise and *rejects*, so a fake that threw synchronously would\n // need different handling at every call site than the thing it stands in for.\n try {\n return Promise.resolve(produce());\n } catch (error) {\n return Promise.reject(error);\n }\n };\n\n /** Applies `{ projection: { _id: 0 } }`, the only projection the adapter uses. */\n const project = (doc: Document, options?: { projection?: Document }) => {\n const copy = { ...doc };\n if (options?.projection && options.projection['_id'] === 0) {\n delete copy['_id'];\n }\n return copy;\n };\n\n const collection = (name: string) => ({\n find: (query: QueryDocument = {}, options?: { projection?: Document }) => {\n let sortSpec: Record<string, 1 | -1> = {};\n let skipCount = 0;\n let limitCount = Infinity;\n\n const cursor = {\n sort(spec: Record<string, 1 | -1>) {\n sortSpec = spec;\n return cursor;\n },\n skip(count: number) {\n skipCount = count;\n return cursor;\n },\n limit(count: number) {\n limitCount = count;\n return cursor;\n },\n toArray: () =>\n record(name, 'find', () => {\n const matched = documentsOf(name).filter(doc =>\n matches(doc, query),\n );\n const sorted = Object.entries(sortSpec).reduceRight(\n (items, [field, direction]) =>\n [...items].sort(\n (left, right) =>\n // A dotted field sorts by the value it names, as the\n // server does — one locale of a localized member, say.\n compare(\n valuesAt(left, field)[0],\n valuesAt(right, field)[0],\n ) * direction,\n ),\n matched,\n );\n return sorted\n .slice(skipCount, skipCount + limitCount)\n .map(doc => project(doc, options));\n }),\n };\n return cursor;\n },\n\n /**\n * The four stages a facet count sends — `$facet`, `$match`, `$unwind` and\n * a `$group` counting with `{ $sum: 1 }` — and nothing else: an unknown\n * stage, or a stage in a shape not listed here, is a `TypeError` rather\n * than a pass-through, for the reason `$expr` above gives.\n */\n aggregate: (pipeline: Document[]) => ({\n toArray: () =>\n record(name, 'aggregate', () =>\n runPipeline(documentsOf(name), pipeline),\n ),\n }),\n\n findOne: (query: QueryDocument, options?: { projection?: Document }) =>\n record(name, 'findOne', () => {\n const found = documentsOf(name).find(doc => matches(doc, query));\n return found === undefined ? null : project(found, options);\n }),\n\n countDocuments: (query: QueryDocument = {}) =>\n record(\n name,\n 'countDocuments',\n () => documentsOf(name).filter(doc => matches(doc, query)).length,\n ),\n\n // Used by the services' own seeding, which the e2e `mock` profile runs for\n // real so both profiles serve the same catalog.\n insertMany: (documents: Document[]) =>\n record(name, 'insertMany', () => {\n const stored = documentsOf(name);\n for (const document of documents) {\n assertUnique(name, document);\n stored.push({ ...document });\n }\n return { insertedCount: documents.length };\n }),\n\n /**\n * A single insert — how an append-only ledger grows, and how a hold is\n * written beside the counter it moved.\n *\n * The options argument is accepted and ignored except for its `session`,\n * which the transaction wrapper already handles: a caller that passes one\n * is inside `withTransaction`, and this fake's rollback is a snapshot of\n * the whole store rather than anything per-operation.\n */\n insertOne: (document: Document) =>\n record(name, 'insertOne', () => {\n assertUnique(name, document);\n documentsOf(name).push({ ...document });\n return { acknowledged: true, insertedId: document['id'] ?? null };\n }),\n\n replaceOne: (\n query: QueryDocument,\n replacement: Document,\n options?: { upsert?: boolean },\n ) =>\n record(name, 'replaceOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) {\n if (!options?.upsert) return { matchedCount: 0, upsertedCount: 0 };\n // Held to the collection's unique indexes on both branches, as\n // `updateOne` is: an upsert racing another for the same key is\n // exactly what a unique index exists to refuse, and a fake that let\n // this one through would bless the duplicate the server rejects.\n assertUnique(name, replacement);\n documents.push({ ...replacement });\n return { matchedCount: 0, upsertedCount: 1 };\n }\n assertUnique(name, replacement, documents[index]);\n documents[index] = { ...replacement };\n return { matchedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * Partial update. `$set`, `$unset`, `$addToSet`, `$inc` and `$setOnInsert`\n * are implemented — the operators the adapters, the outbox and the stock\n * ledger use — and **anything else throws**, because a fake that silently\n * accepted `$rename` without applying it would let a spec pass on an update\n * that never happened.\n *\n * `$unset` removes the field whatever value it is given, as the server\n * does; it is how the outbox clears a quarantined entry's failure note when\n * it puts the entry back in the queue.\n *\n * `$addToSet` is what links an identifier onto `user-identity.identifiers`\n * without duplicating it on a repair run; supporting it here rather than\n * ignoring it is the difference between the e2e proving the link and merely\n * not noticing its absence.\n *\n * `$inc` with `upsert` is how a quantity moves. It matters that it is a\n * real increment and not a read-modify-write even here: the whole rule it\n * implements is that an absolute-value write loses updates, so a fake that\n * computed the new total from a value it had already read would model the\n * bug rather than the fix.\n *\n * `$push` appends, and a `$set` key of the form `field.$[name].member`\n * applies to every element of `field` that `options.arrayFilters` selects —\n * the pair a saga store records an outcome with and later flags one\n * compensated. Both are what keep an array update from being a\n * read-modify-write, which is the point of using them.\n */\n updateOne: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $unset?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; arrayFilters?: readonly Document[] },\n ) =>\n record(name, 'updateOne', () => {\n const supported = [\n '$set',\n '$unset',\n '$addToSet',\n '$inc',\n '$setOnInsert',\n '$push',\n ];\n const unsupported = Object.keys(update).filter(\n operator => !supported.includes(operator),\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateOne does not implement ${unsupported.join(', ')}`,\n );\n }\n\n // A real server rejects an update whose operators both name one field,\n // and the message is the one this repro'd against: `$setOnInsert` that\n // also named a field `$inc` touches. Reproducing the refusal is what\n // keeps the fake from blessing an update Mongo would refuse.\n const conflicting = Object.keys(update.$setOnInsert ?? {}).filter(\n field => field in (update.$inc ?? {}) || field in (update.$set ?? {}),\n );\n if (conflicting.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $setOnInsert and $inc/$set: ${conflicting.join(', ')}`,\n );\n }\n // The same refusal for a field both written and removed.\n const unsetConflicts = Object.keys(update.$unset ?? {}).filter(\n field => field in (update.$set ?? {}) || field in (update.$inc ?? {}),\n );\n if (unsetConflicts.length > 0) {\n throw new Error(\n `fake-mongo: updateOne has conflicting paths in $unset and $inc/$set: ${unsetConflicts.join(', ')}`,\n );\n }\n\n /** `$set`, `$addToSet`, `$inc` and `$push`, which apply on both branches. */\n const applyOperators = (base: Document): Document => {\n const plain = Object.entries(update.$set ?? {}).filter(\n ([field]) => !field.includes('.$['),\n );\n const updated = { ...base, ...Object.fromEntries(plain) };\n for (const [path, value] of Object.entries(update.$set ?? {})) {\n const filtered = /^([^.]+)\\.\\$\\[([^\\]]+)\\]\\.(.+)$/.exec(path);\n if (filtered === null) continue;\n const [, field, identifier, member] = filtered as unknown as [\n string,\n string,\n string,\n string,\n ];\n // The server refuses a filtered position with no filter naming it.\n const conditions = (options?.arrayFilters ?? []).flatMap(filter =>\n Object.entries(filter)\n .filter(([key]) => key.startsWith(`${identifier}.`))\n .map(\n ([key, condition]) =>\n [key.slice(identifier.length + 1), condition] as const,\n ),\n );\n if (conditions.length === 0) {\n throw new Error(\n `fake-mongo: no array filter found for identifier ${identifier}`,\n );\n }\n const current = updated[field];\n updated[field] = (Array.isArray(current) ? current : []).map(\n element =>\n isPlainObject(element) &&\n conditions.every(([key, condition]) =>\n matchesCondition(element[key], condition),\n )\n ? { ...element, [member]: value }\n : element,\n );\n }\n for (const [field, value] of Object.entries(update.$push ?? {})) {\n const current = updated[field];\n updated[field] = [\n ...(Array.isArray(current) ? current : []),\n value,\n ];\n }\n for (const [field, value] of Object.entries(update.$addToSet ?? {})) {\n const current = updated[field];\n const array = Array.isArray(current) ? current : [];\n if (!array.includes(value)) {\n updated[field] = [...array, value];\n }\n }\n for (const [field, delta] of Object.entries(update.$inc ?? {})) {\n // An absent field is created at the increment's value, which is\n // exactly why `$setOnInsert` must not also name it.\n const current = updated[field];\n updated[field] =\n (typeof current === 'number' ? current : 0) + (delta as number);\n }\n for (const field of Object.keys(update.$unset ?? {})) {\n delete updated[field];\n }\n return updated;\n };\n\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n if (index === -1) {\n if (options?.upsert !== true) {\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 0 };\n }\n // The upserted document starts from the query's *equality* fields,\n // the way a real server seeds one — an operator condition contributes\n // nothing, which is why a `$expr`-guarded upsert would insert a row\n // missing the very field it filtered on.\n const seedFields = Object.fromEntries(\n Object.entries(query).filter(\n ([field, condition]) =>\n !field.startsWith('$') && !isPlainObject(condition),\n ),\n );\n const inserted = applyOperators({\n ...seedFields,\n ...(update.$setOnInsert ?? {}),\n });\n assertUnique(name, inserted);\n documents.push(inserted);\n return { matchedCount: 0, modifiedCount: 0, upsertedCount: 1 };\n }\n\n const updated = applyOperators(documents[index]);\n assertUnique(name, updated, documents[index]);\n documents[index] = updated;\n return { matchedCount: 1, modifiedCount: 1, upsertedCount: 0 };\n }),\n\n /**\n * `$set` across every matching document, and the count of what changed.\n *\n * ⚠️ **The count is what a caller branches on.** A settlement run claims its\n * ledger lines with this and reads `modifiedCount === 0` as \"another replica\n * took them all\" — so a fake returning a fixed `1`, or the match count\n * rather than the modified count, would make the losing replica behave like\n * the winning one and the conditional claim would test nothing.\n *\n * `$set` only. Anything else throws, for the reason `updateOne` gives:\n * silently accepting an operator it does not apply lets a spec pass on an\n * update that never happened.\n */\n updateMany: (query: QueryDocument, update: { $set?: Document }) =>\n record(name, 'updateMany', () => {\n const unsupported = Object.keys(update).filter(\n operator => operator !== '$set',\n );\n if (unsupported.length > 0) {\n throw new Error(\n `fake-mongo: updateMany does not implement ${unsupported.join(', ')}`,\n );\n }\n\n const documents = documentsOf(name);\n let modifiedCount = 0;\n documents.forEach((doc, index) => {\n if (!matches(doc, query)) return;\n const updated = { ...doc, ...(update.$set ?? {}) };\n assertUnique(name, updated, doc);\n documents[index] = updated;\n modifiedCount += 1;\n });\n return { matchedCount: modifiedCount, modifiedCount };\n }),\n\n /**\n * Update one document and hand back the result, upserting when asked.\n *\n * ⚠️ **`returnDocument: 'after'` is the only mode implemented, and the\n * default here is `'after'` rather than the driver's `'before'`** — because\n * the callers that need this primitive at all need the merged document. A\n * two-message join upserts its own half and then asks \"is the pair complete\n * now?\", which is a question only the *after* state answers. `'before'`\n * throws rather than quietly returning the wrong half.\n *\n * Implemented over {@link updateOne} so the upsert seeding rule, the\n * conflicting-path refusal and the unique-index enforcement are the same\n * ones, rather than a second copy that could drift from them.\n */\n findOneAndUpdate: (\n query: QueryDocument,\n update: {\n $set?: Document;\n $unset?: Document;\n $addToSet?: Document;\n $inc?: Document;\n $setOnInsert?: Document;\n $push?: Document;\n },\n options?: { upsert?: boolean; returnDocument?: 'before' | 'after' },\n ) =>\n record(name, 'findOneAndUpdate', async () => {\n if (options?.returnDocument === 'before') {\n throw new Error(\n 'fake-mongo: findOneAndUpdate only implements returnDocument: \"after\"',\n );\n }\n // Where the document is *before* the write, because afterwards the\n // query may no longer find it: an upsert's operator conditions need not\n // hold of the row it just inserted — `{ folded: { $exists: false } }`\n // matches nothing once `folded` has been set. `documentsOf` hands back\n // the live array, which `updateOne` mutates in place or pushes onto, so\n // the position is enough to identify it either way.\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n\n const result = await collection(name).updateOne(query, update, {\n upsert: options?.upsert === true,\n });\n if (result.matchedCount === 0 && result.upsertedCount === 0) {\n return null;\n }\n\n return index === -1\n ? documents[documents.length - 1]\n : documents[index];\n }),\n\n deleteOne: (query: QueryDocument) =>\n record(name, 'deleteOne', () => {\n const documents = documentsOf(name);\n const index = documents.findIndex(doc => matches(doc, query));\n if (index === -1) return { deletedCount: 0 };\n documents.splice(index, 1);\n return { deletedCount: 1 };\n }),\n\n /**\n * Declares an index, and **enforces it when it is unique**.\n *\n * Idempotent, like the real one: a service that ensures its index per\n * request rather than at boot — because a tenant database only appears on\n * first write — calls this on every write.\n */\n createIndex: (spec: Document, options?: Document) =>\n record(name, 'createIndex', () => {\n if (options?.['unique'] === true) {\n const fields = Object.keys(spec);\n const existing = uniqueIndexes.get(name) ?? [];\n const already = existing.some(\n candidate =>\n candidate.length === fields.length &&\n candidate.every((field, at) => field === fields[at]),\n );\n if (!already) {\n uniqueIndexes.set(name, [...existing, fields]);\n }\n }\n return { spec, options };\n }),\n });\n\n /**\n * A session whose `withTransaction` really rolls back.\n *\n * ⚠️ **It is atomicity, not isolation, and the difference decides where a\n * test may live.** The store is a single-threaded object graph, so nothing\n * runs concurrently with the body and a \"race\" here resolves in the order it\n * was written: a concurrency property — two writers contending for the last\n * unit — is green under this fake no matter what the code does, and belongs\n * in a `*.live.spec.ts` against real Mongo.\n *\n * What it *does* model is the abort path, which is worth having: a body that\n * throws leaves the store exactly as it found it, so a conditional write that\n * moves a counter and then fails to write its row cannot leave the counter\n * moved. That is a real bug shape, and one a fake without rollback would hide\n * by committing half of it.\n */\n const snapshotOf = () =>\n new Map(\n [...collections].map(([name, docs]) => [\n name,\n docs.map(doc => ({ ...doc })),\n ]),\n );\n const restore = (snapshot: Map<string, Document[]>) => {\n collections.clear();\n for (const [name, docs] of snapshot) collections.set(name, docs);\n };\n\n const startSession = () => {\n let open = true;\n let pending: Map<string, Document[]> | undefined;\n const noTransaction = () =>\n Promise.reject(new Error('fake-mongo: no transaction in progress'));\n return {\n startTransaction: () => {\n if (pending !== undefined) {\n throw new Error('fake-mongo: a transaction is already in progress');\n }\n pending = snapshotOf();\n },\n commitTransaction: () => {\n if (pending === undefined) return noTransaction();\n operations.push({ collection: '', op: 'commitTransaction' });\n const rejection = failureFor('commitTransaction');\n if (rejection !== undefined) return Promise.reject(rejection);\n pending = undefined;\n return Promise.resolve();\n },\n abortTransaction: () => {\n if (pending === undefined) return noTransaction();\n restore(pending);\n pending = undefined;\n return Promise.resolve();\n },\n inTransaction: () => pending !== undefined,\n withTransaction: async (body: () => Promise<unknown>) => {\n const snapshot = snapshotOf();\n try {\n return await body();\n } catch (error) {\n restore(snapshot);\n throw error;\n }\n },\n endSession: () => {\n open = false;\n return Promise.resolve();\n },\n get hasEnded() {\n return !open;\n },\n };\n };\n\n return {\n seed: (name, documents) => {\n collections.set(\n name,\n documents.map(doc => ({ ...doc })),\n );\n },\n read: name => documentsOf(name).map(doc => ({ ...doc })),\n failWith: error => {\n failure = error;\n },\n failOn: (operation, error) => {\n failuresByOperation.set(operation, error);\n },\n failOnce: (operation, error) => {\n onceFailures.set(operation, error);\n },\n get operations() {\n return operations;\n },\n startSession,\n db: { collection },\n };\n};\n"],"names":["isPlainObject","value","Array","isArray","compare","left","right","Date","getTime","String","localeCompare","matchesCondition","actual","condition","Object","entries","every","operator","operand","includes","undefined","RegExp","test","TypeError","evaluateExpression","doc","node","startsWith","slice","length","operands","map","child","valuesAt","field","current","segment","split","next","container","element","push","flatMap","NEGATIVE_OPERATORS","Set","isNegativeCondition","keys","some","has","matches","query","candidates","fieldOf","reference","stage","JSON","stringify","unwind","docs","spec","options","path","group","_id","key","accumulators","counted","tally","Map","set","get","from","id","count","runPipeline","pipeline","reduce","filter","fromEntries","output","branch","FakeDuplicateKeyError","Error","collection","code","name","makeFakeMongoDb","seed","collections","d","operations","failure","failuresByOperation","onceFailures","failureFor","op","once","delete","documentsOf","uniqueIndexes","uniqueIndexesOf","assertUnique","candidate","ignored","fields","clash","find","record","produce","rejection","Promise","reject","resolve","error","project","copy","projection","sortSpec","skipCount","limitCount","Infinity","cursor","sort","skip","limit","toArray","matched","sorted","reduceRight","items","direction","aggregate","findOne","found","countDocuments","insertMany","documents","stored","document","insertedCount","insertOne","acknowledged","insertedId","replaceOne","replacement","index","findIndex","upsert","matchedCount","upsertedCount","updateOne","update","supported","unsupported","join","conflicting","$setOnInsert","$inc","$set","unsetConflicts","$unset","applyOperators","base","plain","updated","filtered","exec","identifier","member","conditions","arrayFilters","$push","$addToSet","array","delta","modifiedCount","seedFields","inserted","updateMany","forEach","findOneAndUpdate","returnDocument","result","deleteOne","deletedCount","splice","createIndex","existing","already","at","snapshotOf","restore","snapshot","clear","startSession","open","pending","noTransaction","startTransaction","commitTransaction","abortTransaction","inTransaction","withTransaction","body","endSession","hasEnded","read","failWith","failOn","operation","failOnce","db"],"mappings":"AAAA;;;;;;;;;;CAUC,GAED,+DAA+D;;AAI/D,MAAMA,gBAAgB,CAACC,QACrB,OAAOA,UAAU,YAAYA,UAAU,QAAQ,CAACC,MAAMC,OAAO,CAACF;AAEhE,MAAMG,UAAU,CAACC,MAAeC;IAC9B,IAAID,QAAQ,QAAQC,SAAS,MAAM,OAAO;IAC1C,IAA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hI;QAAW;IACnB;AACF,EAAE"}
@@ -30,7 +30,7 @@ export interface FakeSqlClient {
30
30
  */
31
31
  respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;
32
32
  /**
33
- * Makes every subsequent execution fail, so the adapter's `EntifixConnError`
33
+ * Makes every subsequent execution fail, so the adapter's `Unavailable`
34
34
  * mapping is reachable.
35
35
  */
36
36
  failWith(message: string): void;
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/drivers/fake-sql.ts"],"sourcesContent":["/**\n * A fake of the `@effect/sql` driver, not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `EntifixConnError`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Object.assign(\n Statement.make(\n Effect.succeed(connection) as never,\n pgCompiler,\n [],\n undefined,\n ),\n {\n /**\n * Runs `self` between a recorded `BEGIN` and `COMMIT`, or `ROLLBACK`\n * when it fails — enough for a spec to assert what a unit of work\n * committed and what it rolled back, though nothing is isolated.\n */\n withTransaction: <A, E, R>(self: Effect.Effect<A, E, R>) =>\n Effect.sync(() => executions.push({ sql: 'BEGIN', params: [] })).pipe(\n Effect.andThen(self),\n Effect.tapError(() =>\n Effect.sync(() =>\n executions.push({ sql: 'ROLLBACK', params: [] }),\n ),\n ),\n Effect.tap(() =>\n Effect.sync(() => executions.push({ sql: 'COMMIT', params: [] })),\n ),\n ),\n },\n ),\n };\n};\n"],"names":["Effect","SqlError","Statement","unsupported","name","TypeError","pgCompiler","makeCompiler","dialect","placeholder","index","onIdentifier","defaultEscape","onRecordUpdate","onCustom","makeFakeSqlClient","seed","responses","executions","failuresByMatch","failure","answer","sql","length","response","undefined","includes","match","rows","execute","params","push","scoped","find","entry","message","fail","reason","UnknownError","cause","Error","succeed","connection","executeUnprepared","executeRaw","executeValues","executeStream","respondTo","failWith","failOn","lastExecution","client","Object","assign","make","withTransaction","self","sync","pipe","andThen","tapError","tap"],"mappings":"AAAA;;;;;;;;;;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E;IAEJ;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/drivers/fake-sql.ts"],"sourcesContent":["/**\n * A fake of the `@effect/sql` driver, not of the repository port.\n *\n * It sits one level *below* `makeSqlRepository`, so the adapter's own code — the\n * filter translation, the clause assembly, the upsert rule, the error mapping —\n * actually runs and is measured by coverage. A fake at the port level would skip\n * all of it. Same reasoning as {@link makeFakeMongoDb}.\n *\n * What it does **not** do is execute SQL: it hands back canned rows and records\n * the statement each call compiled to, so a spec asserts on the SQL and\n * parameters the adapter produced. Running the shared\n * `describeEntityRepositoryContract` needs a real engine and belongs against real\n * Postgres, the way the driver connection Layers are covered.\n */\n\nimport { Effect } from 'effect';\nimport { SqlError } from 'effect/sql';\nimport { Statement } from 'effect/sql';\n\n/** One statement the adapter executed, already compiled. */\nexport interface FakeSqlExecution {\n /** The compiled SQL text, parameters replaced by `$1`, `$2`, … */\n readonly sql: string;\n readonly params: ReadonlyArray<unknown>;\n}\n\n/** Rows to answer with when a statement's SQL contains `match`. */\nexport interface FakeSqlResponse {\n readonly match: string;\n readonly rows: ReadonlyArray<Record<string, unknown>>;\n}\n\nexport interface FakeSqlClient {\n /**\n * Answers `rows` for any statement whose compiled SQL contains `match`. Later\n * registrations win, so a spec can override a default set up by a helper.\n */\n respondTo(match: string, rows: ReadonlyArray<Record<string, unknown>>): void;\n /**\n * Makes every subsequent execution fail, so the adapter's `Unavailable`\n * mapping is reachable.\n */\n failWith(message: string): void;\n /**\n * Makes only the statements containing `match` fail, leaving the rest working\n * — the way a select that succeeds and a count that then fails reaches a\n * distinct error branch.\n */\n failOn(match: string, message: string): void;\n /** Every statement executed, in order, for assertions about what ran. */\n readonly executions: ReadonlyArray<FakeSqlExecution>;\n /** The most recently executed statement. */\n readonly lastExecution: FakeSqlExecution | undefined;\n /**\n * The object to hand to `makeSqlRepository` in place of a real `SqlClient`.\n *\n * Typed `unknown` on purpose — casting at the call site keeps this fake honest\n * that it implements only the constructor surface the adapters use, not the\n * whole `SqlClient` (no transactions, no reactivity, no streaming).\n */\n readonly client: unknown;\n}\n\nconst unsupported = (name: string): never => {\n throw new TypeError(`fake sql: ${name} is not implemented`);\n};\n\n/**\n * The Postgres compiler's configuration, mirrored from `@effect/sql-pg` so the\n * fake emits exactly the dialect production does — `$n` placeholders and\n * double-quoted identifiers — without this package depending on the `pg` driver.\n *\n * `sql.updateValues` and the `PgJson` custom segment are deliberate `TypeError`s\n * rather than approximations: no adapter uses either, and a compiler that\n * half-emitted them would let a spec pass on SQL that real Postgres rejects.\n */\nconst pgCompiler = Statement.makeCompiler({\n dialect: 'pg',\n placeholder: index => `$${index}`,\n onIdentifier: Statement.defaultEscape('\"'),\n onRecordUpdate: () => unsupported('updateValues'),\n onCustom: () => unsupported('custom segments'),\n});\n\n/** Builds an in-memory stand-in for an `@effect/sql` client. */\nexport const makeFakeSqlClient = (\n seed: ReadonlyArray<FakeSqlResponse> = [],\n): FakeSqlClient => {\n const responses: FakeSqlResponse[] = [...seed];\n const executions: FakeSqlExecution[] = [];\n const failuresByMatch: Array<{ match: string; message: string }> = [];\n let failure: string | undefined;\n\n const answer = (sql: string) => {\n // Last registration wins, so an override does not have to remove the\n // default it replaces.\n for (let index = responses.length - 1; index >= 0; index -= 1) {\n const response = responses[index];\n if (response !== undefined && sql.includes(response.match)) {\n return response.rows;\n }\n }\n return [];\n };\n\n const execute = (sql: string, params: ReadonlyArray<unknown>) => {\n executions.push({ sql, params });\n\n const scoped = failuresByMatch.find(entry => sql.includes(entry.match));\n const message = scoped?.message ?? failure;\n if (message !== undefined) {\n return Effect.fail(\n new SqlError.SqlError({\n reason: new SqlError.UnknownError({\n cause: new Error(message),\n message,\n }),\n }),\n );\n }\n return Effect.succeed(answer(sql));\n };\n\n const connection = {\n execute: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeUnprepared: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeRaw: (sql: string, params: ReadonlyArray<unknown>) =>\n execute(sql, params),\n executeValues: () => unsupported('executeValues'),\n executeStream: () => unsupported('executeStream'),\n };\n\n return {\n respondTo: (match, rows) => {\n responses.push({ match, rows });\n },\n failWith: message => {\n failure = message;\n },\n failOn: (match, message) => {\n failuresByMatch.push({ match, message });\n },\n get executions() {\n return executions;\n },\n get lastExecution() {\n return executions[executions.length - 1];\n },\n client: Object.assign(\n Statement.make(\n Effect.succeed(connection) as never,\n pgCompiler,\n [],\n undefined,\n ),\n {\n /**\n * Runs `self` between a recorded `BEGIN` and `COMMIT`, or `ROLLBACK`\n * when it fails — enough for a spec to assert what a unit of work\n * committed and what it rolled back, though nothing is isolated.\n */\n withTransaction: <A, E, R>(self: Effect.Effect<A, E, R>) =>\n Effect.sync(() => executions.push({ sql: 'BEGIN', params: [] })).pipe(\n Effect.andThen(self),\n Effect.tapError(() =>\n Effect.sync(() =>\n executions.push({ sql: 'ROLLBACK', params: [] }),\n ),\n ),\n Effect.tap(() =>\n Effect.sync(() => executions.push({ sql: 'COMMIT', params: [] })),\n ),\n ),\n },\n ),\n };\n};\n"],"names":["Effect","SqlError","Statement","unsupported","name","TypeError","pgCompiler","makeCompiler","dialect","placeholder","index","onIdentifier","defaultEscape","onRecordUpdate","onCustom","makeFakeSqlClient","seed","responses","executions","failuresByMatch","failure","answer","sql","length","response","undefined","includes","match","rows","execute","params","push","scoped","find","entry","message","fail","reason","UnknownError","cause","Error","succeed","connection","executeUnprepared","executeRaw","executeValues","executeStream","respondTo","failWith","failOn","lastExecution","client","Object","assign","make","withTransaction","self","sync","pipe","andThen","tapError","tap"],"mappings":"AAAA;;;;;;;;;;;;;CAaC,GAED,SAASA,MAAM,QAAQ,SAAS;AAChC,SAASC,QAAQ,QAAQ,aAAa;AACtC,SAASC,SAAS,QAAQ,aAAa;AA8CvC,MAAMC,cAAc,CAACC;IACnB,MAAM,IAAIC,UAAU,CAAC,UAAU,EAAED,KAAK,mBAAmB,CAAC;AAC5D;AAEA;;;;;;;;CAQC,GACD,MAAME,aAAaJ,UAAU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