@entifix/testing-unit 0.23.14 → 0.23.16

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.
@@ -73,6 +73,37 @@ export interface EntityRepositoryRevisionContractOptions {
73
73
  * and moves it, and a stale save writes nothing — including when two race.
74
74
  */
75
75
  export declare const describeEntityRepositoryRevisionContract: (name: string, { makeRepository }: EntityRepositoryRevisionContractOptions) => void;
76
+ /**
77
+ * The entity the unique contract runs against: a revised record with an
78
+ * optional code no two records may share (ADR 0034). The code is stored under
79
+ * an alias, so an adapter that indexes the member's name rather than its stored
80
+ * key fails the suite.
81
+ */
82
+ export declare class UniqueWidget implements Entity {
83
+ #private;
84
+ get id(): EntityId;
85
+ set id(value: EntityId);
86
+ get name(): string | undefined;
87
+ set name(value: string | undefined);
88
+ get code(): string | undefined;
89
+ set code(value: string | undefined);
90
+ get revision(): number | undefined;
91
+ set revision(value: number | undefined);
92
+ }
93
+ export declare const makeUniqueWidget: (id: EntityId, name: string, code?: string, revision?: number) => UniqueWidget;
94
+ export interface EntityRepositoryUniqueContractOptions {
95
+ /**
96
+ * Builds a repository over `seed`, whose records are stored at revision 1.
97
+ * Called fresh for each test.
98
+ */
99
+ makeRepository(seed: UniqueWidget[]): EntityRepository | Promise<EntityRepository>;
100
+ }
101
+ /**
102
+ * What a member declared `unique` means on every adapter that writes: no two
103
+ * records hold one value, a collision names the member's stored key, an absent
104
+ * value never collides, and two creates racing for one value leave one winner.
105
+ */
106
+ export declare const describeEntityRepositoryUniqueContract: (name: string, { makeRepository }: EntityRepositoryUniqueContractOptions) => void;
76
107
  declare const STATED_PHASES: readonly ["draft", "released"];
77
108
  /**
78
109
  * The entity the state contract runs against: a record saved and deleted only
@@ -1 +1 @@
1
- {"version":3,"file":"entity-repository.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/entity-repository.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,mBAAmB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,MAAM,MAAM,EACZ,OAAO,CAAC,OAAO,aAAa,EAAE,MAAM,CAAC,KACpC,YAMF,CAAC;AAEF,MAAM,WAAW,oCAAoC;IACnD,mEAAmE;IACnE,cAAc,CACZ,IAAI,EAAE,YAAY,EAAE,GACnB,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACjD;AAED;;;;;GAKG;AACH,eAAO,MAAM,qCAAqC,GAChD,MAAM,MAAM,EACZ,oBAAoB,oCAAoC,KACvD,IAwHF,CAAC"}
1
+ {"version":3,"file":"entity-repository.contract.d.ts","sourceRoot":"","sources":["../../src/contracts/entity-repository.contract.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAqB,MAAM,mBAAmB,CAAC;AAC7E,OAAO,EAEL,KAAK,MAAM,EAEX,KAAK,QAAQ,EAEd,MAAM,eAAe,CAAC;AAMvB;;;;GAIG;AAEH,qBACa,cAAe,YAAW,MAAM;;IAO3C,IACI,EAAE,IAAI,QAAQ,CAEjB;IACD,IAAI,EAAE,CAAC,KAAK,EAAE,QAAQ,EAErB;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IACI,IAAI,IAAI,MAAM,GAAG,SAAS,CAE7B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,SAAS,EAEjC;IAED,IACI,IAAI,IAAI,SAAS,MAAM,EAAE,CAE5B;IACD,IAAI,IAAI,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,EAEhC;IAED,IACI,KAAK,IAAI,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,CAExD;IACD,IAAI,KAAK,CAAC,KAAK,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,GAAG,SAAS,EAE5D;CACF;AAED,eAAO,MAAM,kB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;AAED,eAAO,MAAM,gBAAgB,GAC3B,IAAI,QAAQ,EACZ,MAAM,MAAM,EACZ,OAAO,CAAC,OAAO,aAAa,EAAE,MAAM,CAAC,KACpC,YAMF,CAAC;AAEF,MAAM,WAAW,oCAAoC;IACnD,mEAAmE;IACnE,cAAc,CACZ,IAAI,EAAE,YAAY,EAAE,GACnB,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CACjD;AAED;;;;;GAKG;AACH,eAAO,MAAM,qCAAqC,GAChD,MAAM,MAAM,EACZ,oBAAoB,oCAAoC,KACvD,IAwHF,CAAC"}
@@ -1,7 +1,7 @@
1
1
  import { _ as _apply_decs_2203_r } from "@swc/helpers/_/_apply_decs_2203_r";
2
2
  import { _ as _class_private_field_loose_base } from "@swc/helpers/_/_class_private_field_loose_base";
3
3
  import { _ as _class_private_field_loose_key } from "@swc/helpers/_/_class_private_field_loose_key";
4
- var _dec, _initClass, _dec1, _dec2, _dec3, _dec4, _dec5, _initProto, _dec6, _initClass1, _dec7, _dec8, _dec9, _initProto1, _dec10, _initClass2, _dec11, _dec12, _dec13, _initProto2;
4
+ var _dec, _initClass, _dec1, _dec2, _dec3, _dec4, _dec5, _initProto, _dec6, _initClass1, _dec7, _dec8, _dec9, _initProto1, _dec10, _initClass2, _dec11, _dec12, _dec13, _dec14, _initProto2, _dec15, _initClass3, _dec16, _dec17, _dec18, _initProto3;
5
5
  import { accessor, entity, RELEVANCE } from '@entifix/core';
6
6
  import { Exit } from 'effect';
7
7
  import { describe, expect, it } from 'vitest';
@@ -770,6 +770,164 @@ export const makeRevisedWidget = (id, name, revision)=>{
770
770
  });
771
771
  });
772
772
  };
773
+ _dec10 = entity({
774
+ key: 'unique-widget'
775
+ }), _dec11 = accessor({
776
+ type: 'id'
777
+ }), _dec12 = accessor({
778
+ type: 'string'
779
+ }), _dec13 = accessor({
780
+ type: 'string',
781
+ unique: true,
782
+ alias: 'sku'
783
+ }), _dec14 = accessor({
784
+ type: 'revision'
785
+ });
786
+ let _UniqueWidget;
787
+ var _id2 = /*#__PURE__*/ _class_private_field_loose_key("_id"), _name2 = /*#__PURE__*/ _class_private_field_loose_key("_name"), _code = /*#__PURE__*/ _class_private_field_loose_key("_code"), _revision1 = /*#__PURE__*/ _class_private_field_loose_key("_revision");
788
+ let UniqueWidget = class UniqueWidget {
789
+ get id() {
790
+ return _class_private_field_loose_base(this, _id2)[_id2];
791
+ }
792
+ set id(value) {
793
+ _class_private_field_loose_base(this, _id2)[_id2] = value;
794
+ }
795
+ get name() {
796
+ return _class_private_field_loose_base(this, _name2)[_name2];
797
+ }
798
+ set name(value) {
799
+ _class_private_field_loose_base(this, _name2)[_name2] = value;
800
+ }
801
+ get code() {
802
+ return _class_private_field_loose_base(this, _code)[_code];
803
+ }
804
+ set code(value) {
805
+ _class_private_field_loose_base(this, _code)[_code] = value;
806
+ }
807
+ get revision() {
808
+ return _class_private_field_loose_base(this, _revision1)[_revision1];
809
+ }
810
+ set revision(value) {
811
+ _class_private_field_loose_base(this, _revision1)[_revision1] = value;
812
+ }
813
+ constructor(){
814
+ Object.defineProperty(this, _id2, {
815
+ writable: true,
816
+ value: void 0
817
+ });
818
+ Object.defineProperty(this, _name2, {
819
+ writable: true,
820
+ value: void 0
821
+ });
822
+ Object.defineProperty(this, _code, {
823
+ writable: true,
824
+ value: void 0
825
+ });
826
+ Object.defineProperty(this, _revision1, {
827
+ writable: true,
828
+ value: void 0
829
+ });
830
+ _initProto2(this);
831
+ }
832
+ };
833
+ ({ e: [_initProto2], c: [_UniqueWidget, _initClass2] } = _apply_decs_2203_r(UniqueWidget, [
834
+ [
835
+ _dec11,
836
+ 3,
837
+ "id"
838
+ ],
839
+ [
840
+ _dec12,
841
+ 3,
842
+ "name"
843
+ ],
844
+ [
845
+ _dec13,
846
+ 3,
847
+ "code"
848
+ ],
849
+ [
850
+ _dec14,
851
+ 3,
852
+ "revision"
853
+ ]
854
+ ], [
855
+ _dec10
856
+ ]));
857
+ _initClass2();
858
+ export const makeUniqueWidget = (id, name, code, revision)=>{
859
+ const widget = new _UniqueWidget();
860
+ widget.id = id;
861
+ widget.name = name;
862
+ widget.code = code;
863
+ widget.revision = revision;
864
+ return widget;
865
+ };
866
+ /**
867
+ * What a member declared `unique` means on every adapter that writes: no two
868
+ * records hold one value, a collision names the member's stored key, an absent
869
+ * value never collides, and two creates racing for one value leave one winner.
870
+ */ export const describeEntityRepositoryUniqueContract = (name, { makeRepository })=>{
871
+ describe(`EntityRepository unique contract: ${name}`, ()=>{
872
+ const seeded = ()=>[
873
+ makeUniqueWidget('u-1', 'Alpha', 'A-1', 1),
874
+ makeUniqueWidget('u-2', 'Beta', undefined, 1)
875
+ ];
876
+ const failureOf = (effect)=>runFailure(effect);
877
+ it('refuses a create holding a value another record holds, naming the stored key', async ()=>{
878
+ const repository = await makeRepository(seeded());
879
+ const failure = await failureOf(repository.save(makeUniqueWidget(undefined, 'Gamma', 'A-1')));
880
+ expect(failure).toMatchObject({
881
+ _tag: 'DuplicateKey',
882
+ key: 'sku'
883
+ });
884
+ const page = await run(repository.load({}));
885
+ expect(page.items).toHaveLength(2);
886
+ });
887
+ it("refuses an update onto another record's value and leaves both unchanged", async ()=>{
888
+ var _stored_code;
889
+ const repository = await makeRepository(seeded());
890
+ const failure = await failureOf(repository.save(makeUniqueWidget('u-2', 'Beta', 'A-1', 1)));
891
+ expect(failure).toMatchObject({
892
+ _tag: 'DuplicateKey',
893
+ key: 'sku'
894
+ });
895
+ const stored = await run(repository.get('u-2'));
896
+ // Absent, however the store spells it: SQL reads an empty column as null.
897
+ expect((_stored_code = stored.code) != null ? _stored_code : undefined).toBeUndefined();
898
+ expect(stored.revision).toBe(1);
899
+ });
900
+ it('saves a record that keeps its own value', async ()=>{
901
+ const repository = await makeRepository(seeded());
902
+ const saved = await run(repository.save(makeUniqueWidget('u-1', 'Alpha renamed', 'A-1', 1)));
903
+ expect(saved.revision).toBe(2);
904
+ });
905
+ it('never counts two absent values as a collision', async ()=>{
906
+ const repository = await makeRepository(seeded());
907
+ const created = await run(repository.save(makeUniqueWidget(undefined, 'Gamma')));
908
+ expect(created.revision).toBe(1);
909
+ const page = await run(repository.load({}));
910
+ expect(page.items.filter((item)=>item.code == null)).toHaveLength(2);
911
+ });
912
+ it('frees a value its holder gave up', async ()=>{
913
+ const repository = await makeRepository(seeded());
914
+ await run(repository.save(makeUniqueWidget('u-1', 'Alpha', 'A-2', 1)));
915
+ const created = await run(repository.save(makeUniqueWidget(undefined, 'Gamma', 'A-1')));
916
+ expect(created.code).toBe('A-1');
917
+ });
918
+ it('leaves exactly one winner when creates race for one value', async ()=>{
919
+ const repository = await makeRepository(seeded());
920
+ const exits = await Promise.all([
921
+ 'Left',
922
+ 'Middle',
923
+ 'Right'
924
+ ].map((label)=>runExit(repository.save(makeUniqueWidget(undefined, label, 'B-1')))));
925
+ expect(exits.filter((exit)=>Exit.isSuccess(exit))).toHaveLength(1);
926
+ const page = await run(repository.load({}));
927
+ expect(page.items.filter((item)=>item.code === 'B-1')).toHaveLength(1);
928
+ });
929
+ });
930
+ };
773
931
  const STATED_PHASES = [
774
932
  'draft',
775
933
  'released'
@@ -780,34 +938,34 @@ const IN_DRAFT = {
780
938
  'draft'
781
939
  ]
782
940
  };
783
- _dec10 = entity({
941
+ _dec15 = entity({
784
942
  key: 'stated-widget',
785
943
  writableWhen: IN_DRAFT,
786
944
  deletableWhen: IN_DRAFT,
787
945
  readOnlyReasonKey: 'entity:stated-widget.readOnly'
788
- }), _dec11 = accessor({
946
+ }), _dec16 = accessor({
789
947
  type: 'id'
790
- }), _dec12 = accessor({
948
+ }), _dec17 = accessor({
791
949
  type: 'string'
792
- }), _dec13 = accessor({
950
+ }), _dec18 = accessor({
793
951
  type: 'enum',
794
952
  enumValues: STATED_PHASES,
795
953
  alias: 'stage'
796
954
  });
797
955
  let _StatedWidget;
798
- var _id2 = /*#__PURE__*/ _class_private_field_loose_key("_id"), _name2 = /*#__PURE__*/ _class_private_field_loose_key("_name"), _phase = /*#__PURE__*/ _class_private_field_loose_key("_phase");
956
+ var _id3 = /*#__PURE__*/ _class_private_field_loose_key("_id"), _name3 = /*#__PURE__*/ _class_private_field_loose_key("_name"), _phase = /*#__PURE__*/ _class_private_field_loose_key("_phase");
799
957
  let StatedWidget = class StatedWidget {
800
958
  get id() {
801
- return _class_private_field_loose_base(this, _id2)[_id2];
959
+ return _class_private_field_loose_base(this, _id3)[_id3];
802
960
  }
803
961
  set id(value) {
804
- _class_private_field_loose_base(this, _id2)[_id2] = value;
962
+ _class_private_field_loose_base(this, _id3)[_id3] = value;
805
963
  }
806
964
  get name() {
807
- return _class_private_field_loose_base(this, _name2)[_name2];
965
+ return _class_private_field_loose_base(this, _name3)[_name3];
808
966
  }
809
967
  set name(value) {
810
- _class_private_field_loose_base(this, _name2)[_name2] = value;
968
+ _class_private_field_loose_base(this, _name3)[_name3] = value;
811
969
  }
812
970
  get phase() {
813
971
  return _class_private_field_loose_base(this, _phase)[_phase];
@@ -816,11 +974,11 @@ let StatedWidget = class StatedWidget {
816
974
  _class_private_field_loose_base(this, _phase)[_phase] = value;
817
975
  }
818
976
  constructor(){
819
- Object.defineProperty(this, _id2, {
977
+ Object.defineProperty(this, _id3, {
820
978
  writable: true,
821
979
  value: void 0
822
980
  });
823
- Object.defineProperty(this, _name2, {
981
+ Object.defineProperty(this, _name3, {
824
982
  writable: true,
825
983
  value: void 0
826
984
  });
@@ -828,29 +986,29 @@ let StatedWidget = class StatedWidget {
828
986
  writable: true,
829
987
  value: void 0
830
988
  });
831
- _initProto2(this);
989
+ _initProto3(this);
832
990
  }
833
991
  };
834
- ({ e: [_initProto2], c: [_StatedWidget, _initClass2] } = _apply_decs_2203_r(StatedWidget, [
992
+ ({ e: [_initProto3], c: [_StatedWidget, _initClass3] } = _apply_decs_2203_r(StatedWidget, [
835
993
  [
836
- _dec11,
994
+ _dec16,
837
995
  3,
838
996
  "id"
839
997
  ],
840
998
  [
841
- _dec12,
999
+ _dec17,
842
1000
  3,
843
1001
  "name"
844
1002
  ],
845
1003
  [
846
- _dec13,
1004
+ _dec18,
847
1005
  3,
848
1006
  "phase"
849
1007
  ]
850
1008
  ], [
851
- _dec10
1009
+ _dec15
852
1010
  ]));
853
- _initClass2();
1011
+ _initClass3();
854
1012
  export const makeStatedWidget = (id, name, phase)=>{
855
1013
  const widget = new _StatedWidget();
856
1014
  widget.id = id;
@@ -942,6 +1100,6 @@ export const makeStatedWidget = (id, name, phase)=>{
942
1100
  });
943
1101
  });
944
1102
  };
945
- export { _ContractWidget as ContractWidget, _RevisedWidget as RevisedWidget, _StatedWidget as StatedWidget };
1103
+ export { _ContractWidget as ContractWidget, _RevisedWidget as RevisedWidget, _UniqueWidget as UniqueWidget, _StatedWidget as StatedWidget };
946
1104
 
947
1105
  //# sourceMappingURL=entity-repository.contract.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/contracts/entity-repository.contract.ts"],"sourcesContent":["import type { EntityRepository, RepositoryFailure } from '@entifix/business';\nimport {\n accessor,\n type Entity,\n entity,\n type EntityId,\n RELEVANCE,\n} from '@entifix/core';\nimport { Effect, Exit } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport { run, runExit, runFailure } from '../effect/run.js';\n\n/**\n * The entity every implementation of the contract is exercised against. It is\n * declared here rather than by each caller so the suite controls exactly which\n * fields exist.\n */\n// `labelMember` is what relevance scores against (ADR 0033).\n@entity({ key: 'contract-widget', labelMember: 'name' })\nexport class ContractWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #size?: number;\n #tags: readonly string[] = [];\n #title?: Readonly<Record<string, string>>;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'number' })\n get size(): number | undefined {\n return this.#size;\n }\n set size(value: number | undefined) {\n this.#size = value;\n }\n\n @accessor({ type: 'scalarCollection', filterable: true })\n get tags(): readonly string[] {\n return this.#tags;\n }\n set tags(value: readonly string[]) {\n this.#tags = value;\n }\n\n @accessor({ type: 'localized' })\n get title(): Readonly<Record<string, string>> | undefined {\n return this.#title;\n }\n set title(value: Readonly<Record<string, string>> | undefined) {\n this.#title = value;\n }\n}\n\nexport const makeContractWidget = (\n id: EntityId,\n name: string,\n size: number,\n tags: readonly string[] = [],\n): ContractWidget => {\n const widget = new ContractWidget();\n widget.id = id;\n widget.name = name;\n widget.size = size;\n widget.tags = tags;\n return widget;\n};\n\nexport interface EntityRepositoryContractOptions {\n /**\n * Builds a repository over `seed`. Called fresh for each test, so no state\n * leaks between them.\n */\n makeRepository(\n seed: ContractWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * The reads every {@link EntityRepository} must answer alike: `load` with its\n * paging, filtering and sorting, and `get`. A read-only adapter — one over\n * static files, say — runs this half alone, since it refuses `save` and\n * `delete` by design.\n */\nexport const describeEntityRepositoryReadContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository read contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('keeps a record unchanged when a read instance is mutated without a save', async () => {\n await withRepository(async repository => {\n const read = await run(repository.get<ContractWidget>('w-1'));\n read.name = 'Mutated';\n\n const again = await run(repository.get<ContractWidget>('w-1'));\n expect(again.name).toBe('Alpha');\n\n const page = await run(repository.load<ContractWidget>({}));\n page.items[0]!.name = 'Mutated';\n const reloaded = await run(repository.load<ContractWidget>({}));\n expect(reloaded.items[0]!.name).toBe('Alpha');\n });\n });\n\n it('loads every stored entity with its total', async () => {\n await withRepository(async repository => {\n const page = await run(repository.load<ContractWidget>({}));\n\n expect(page.total).toBe(3);\n expect(page.items.map(item => item.name)).toEqual([\n 'Alpha',\n 'Beta',\n 'Gamma',\n ]);\n });\n });\n\n it('echoes the request it served on the page', async () => {\n await withRepository(async repository => {\n const request = { page: 1, pageSize: 2 };\n const page = await run(repository.load<ContractWidget>(request));\n\n expect(page.request).toEqual(request);\n });\n });\n\n it('pages with a 1-based page number', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({ page: 2, pageSize: 2 }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.name).toBe('Gamma');\n // The total counts matches, not the page.\n expect(page.total).toBe(3);\n });\n });\n\n it('filters by an equality operator', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'eq', value: 'Beta' }],\n }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.id).toBe('w-2');\n expect(page.total).toBe(1);\n });\n });\n\n it('filters by a range operator', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'size', operator: 'between', start: 15, end: 35 },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('matches `like` case-insensitively on a substring', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'like', value: 'et' }],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2']);\n });\n });\n\n it('matches `like` and `nlike` with accents ignored on both sides', async () => {\n await withRepository(\n async repository => {\n const like = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'cafe' },\n ],\n }),\n );\n const accented = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'NIÑO' },\n ],\n }),\n );\n const nlike = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'nlike', value: 'café' },\n ],\n }),\n );\n\n expect(like.items.map(item => item.id)).toEqual(['w-1']);\n expect(accented.items.map(item => item.id)).toEqual(['w-2']);\n expect(nlike.items.map(item => item.id)).toEqual(['w-2']);\n },\n [\n makeContractWidget('w-1', 'Café de Olla', 10),\n makeContractWidget('w-2', 'nino', 20),\n ],\n );\n });\n\n it('matches `in` and `nin` against any element of an array member', async () => {\n await withRepository(\n async repository => {\n const tagged = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'tags', operator: 'in', values: ['blue', 'red'] },\n ],\n }),\n );\n expect(tagged.items.map(item => item.id)).toEqual(['w-1', 'w-3']);\n\n const untagged = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'tags', operator: 'nin', values: ['blue', 'red'] },\n ],\n }),\n );\n expect(untagged.items.map(item => item.id)).toEqual(['w-2']);\n },\n [\n makeContractWidget('w-1', 'Alpha', 10, ['blue', 'green']),\n makeContractWidget('w-2', 'Beta', 20, ['green']),\n makeContractWidget('w-3', 'Gamma', 30, ['red']),\n ],\n );\n });\n\n it('matches `==` against any element of an array member', async () => {\n await withRepository(\n async repository => {\n const blue = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'tags', operator: 'eq', value: 'blue' }],\n }),\n );\n expect(blue.items.map(item => item.id)).toEqual(['w-1']);\n\n const green = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'tags', operator: 'eq', value: 'green' }],\n }),\n );\n expect(green.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n },\n [\n makeContractWidget('w-1', 'Alpha', 10, ['blue', 'green']),\n makeContractWidget('w-2', 'Beta', 20, ['green']),\n makeContractWidget('w-3', 'Gamma', 30, ['red']),\n ],\n );\n });\n\n it('filters and sorts a localized member one locale at a time', async () => {\n const titled = (\n id: string,\n name: string,\n title: Record<string, string>,\n ) => {\n const widget = makeContractWidget(id, name, 0);\n widget.title = title;\n return widget;\n };\n await withRepository(\n async repository => {\n const found = await run(\n repository.load<ContractWidget>({\n filtering: [\n {\n property: 'title.es' as keyof ContractWidget,\n operator: 'like',\n value: 'SOPA',\n },\n ],\n }),\n );\n expect(found.items.map(item => item.id)).toEqual(['w-2']);\n\n const sorted = await run(\n repository.load<ContractWidget>({\n sorting: [\n {\n 0: {\n property: 'title.en' as keyof ContractWidget,\n type: 'asc',\n },\n },\n ],\n }),\n );\n expect(sorted.items.map(item => item.id)).toEqual([\n 'w-3',\n 'w-1',\n 'w-2',\n ]);\n expect(sorted.items[0]?.title).toEqual({\n en: 'Apple',\n es: 'Manzana',\n });\n },\n [\n titled('w-1', 'Alpha', { en: 'Bread', es: 'Pan' }),\n titled('w-2', 'Beta', { en: 'Soup', es: 'Sopa' }),\n titled('w-3', 'Gamma', { en: 'Apple', es: 'Manzana' }),\n ],\n );\n });\n\n it('sorts descending when asked to', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n sorting: [{ 0: { property: 'size', type: 'desc' } }],\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20, 10]);\n });\n });\n\n it('ranks by relevance: a label prefix, then a word start, then anywhere', async () => {\n // ADR 0033: one point per word matched elsewhere, two for a word that\n // starts a word of the label, three for one the label starts with;\n // ties fall to the next key.\n await withRepository(\n async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'lamp' },\n ],\n sorting: [\n {\n 0: { property: RELEVANCE, type: 'desc' },\n 1: { property: 'size', type: 'asc' },\n },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual([\n 'w-4',\n 'w-2',\n 'w-3',\n 'w-1',\n ]);\n expect(page.total).toBe(4);\n },\n [\n makeContractWidget('w-1', 'Superlamp', 10),\n makeContractWidget('w-2', 'Desk lamp', 20),\n makeContractWidget('w-3', 'Floor lamp', 30),\n makeContractWidget('w-4', 'Lámpara', 40),\n makeContractWidget('w-5', 'Chair', 50),\n ],\n );\n });\n\n it('falls to the next key when relevance has no word to weigh', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n sorting: [\n {\n 0: { property: RELEVANCE, type: 'desc' },\n 1: { property: 'size', type: 'desc' },\n },\n ],\n page: 1,\n pageSize: 2,\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20]);\n });\n });\n\n it('reads a single entity by id', async () => {\n await withRepository(async repository => {\n const found = await run(repository.get<ContractWidget>('w-2'));\n\n expect(found.id).toBe('w-2');\n expect(found.name).toBe('Beta');\n });\n });\n\n it('fails rather than resolving undefined for an unknown id', async () => {\n await withRepository(async repository => {\n const exit = await runExit(repository.get<ContractWidget>('missing'));\n\n expect(Exit.isFailure(exit)).toBe(true);\n });\n });\n\n it('loads an empty page from an empty store', async () => {\n await withRepository(async repository => {\n const page = await run(repository.load<ContractWidget>({}));\n\n expect(page.items).toEqual([]);\n expect(page.total).toBe(0);\n }, []);\n });\n });\n};\n\n/** The writes every {@link EntityRepository} that accepts them must honour. */\nexport const describeEntityRepositoryWriteContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository write contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('keeps a saved record unchanged when the saved instance is mutated afterwards', async () => {\n await withRepository(async repository => {\n const widget = makeContractWidget('w-9', 'Delta', 40);\n const returned = await run(repository.save(widget));\n\n widget.name = 'Mutated';\n returned.name = 'Mutated too';\n\n const stored = await run(repository.get<ContractWidget>('w-9'));\n expect(stored.name).toBe('Delta');\n });\n });\n\n it('mints an id when saving an entity that has none', async () => {\n await withRepository(async repository => {\n const created = await run(\n repository.save<ContractWidget>(\n makeContractWidget(undefined, 'Delta', 40),\n ),\n );\n\n expect(created.id).toBeDefined();\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(4);\n });\n });\n\n it('overwrites in place when saving an entity that already has an id', async () => {\n await withRepository(async repository => {\n await run(\n repository.save<ContractWidget>(\n makeContractWidget('w-2', 'Renamed', 25),\n ),\n );\n\n const found = await run(repository.get<ContractWidget>('w-2'));\n expect(found.name).toBe('Renamed');\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('deletes by id', async () => {\n await withRepository(async repository => {\n await run(repository.delete<ContractWidget>('w-1'));\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('deletes by entity', async () => {\n await withRepository(async repository => {\n await run(\n repository.delete<ContractWidget>(\n makeContractWidget('w-3', 'Gamma', 30),\n ),\n );\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n });\n });\n\n it('treats deleting an unknown id as a no-op', async () => {\n await withRepository(async repository => {\n await run(repository.delete<ContractWidget>('missing'));\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n });\n};\n\n/**\n * The behaviour every {@link EntityRepository} must exhibit, regardless of what\n * backs it: both halves.\n *\n * Run it against the in-memory fake *and* against each real adapter. That is\n * what stops a fake from drifting into a more forgiving version of the thing it\n * stands in for — the failure mode where a suite is green and production is\n * not. `entifix-ts-testing-integration` will run this same suite against real\n * infrastructure later.\n */\nexport const describeEntityRepositoryContract = (\n name: string,\n options: EntityRepositoryContractOptions,\n): void => {\n describeEntityRepositoryReadContract(name, options);\n describeEntityRepositoryWriteContract(name, options);\n};\n\n/**\n * The entity the revision contract runs against: {@link ContractWidget}'s\n * shape plus the one member that makes its saves checked (ADR 0032).\n */\n@entity({ key: 'revised-widget' })\nexport class RevisedWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #revision?: number;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'revision' })\n get revision(): number | undefined {\n return this.#revision;\n }\n set revision(value: number | undefined) {\n this.#revision = value;\n }\n}\n\nexport const makeRevisedWidget = (\n id: EntityId,\n name: string,\n revision?: number,\n): RevisedWidget => {\n const widget = new RevisedWidget();\n widget.id = id;\n widget.name = name;\n widget.revision = revision;\n return widget;\n};\n\nexport interface EntityRepositoryRevisionContractOptions {\n /**\n * Builds a repository over `seed`, whose records are stored at revision 1.\n * Called fresh for each test.\n */\n makeRepository(\n seed: RevisedWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * What a save of an entity that declares a `revision` means on every adapter\n * that writes: a create never overwrites, an update names the revision it read\n * and moves it, and a stale save writes nothing — including when two race.\n */\nexport const describeEntityRepositoryRevisionContract = (\n name: string,\n { makeRepository }: EntityRepositoryRevisionContractOptions,\n): void => {\n describe(`EntityRepository revision contract: ${name}`, () => {\n const seeded = () => [\n makeRevisedWidget('r-1', 'Alpha', 1),\n makeRevisedWidget('r-2', 'Beta', 1),\n ];\n\n const failureOf = (effect: ReturnType<EntityRepository['get']>) =>\n runFailure(effect) as Promise<{ _tag: string; current?: number }>;\n\n it('carries the revision on a record and on a list row', async () => {\n const repository = await makeRepository(seeded());\n\n const one = await run(repository.get<RevisedWidget>('r-1'));\n const page = await run(repository.load<RevisedWidget>({}));\n\n expect(one.revision).toBe(1);\n expect(page.items.map(item => item.revision)).toEqual([1, 1]);\n });\n\n it('creates at revision 1, minting an id when there is none', async () => {\n const repository = await makeRepository(seeded());\n\n const created = await run(\n repository.save<RevisedWidget>(makeRevisedWidget(undefined, 'Gamma')),\n );\n\n expect(created.id).toBeDefined();\n expect(created.revision).toBe(1);\n const stored = await run(repository.get<RevisedWidget>(created.id));\n expect(stored.revision).toBe(1);\n });\n\n it('creates under a client-minted id', async () => {\n const repository = await makeRepository(seeded());\n\n const created = await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-9', 'Mine')),\n );\n\n expect(created.id).toBe('r-9');\n expect(created.revision).toBe(1);\n });\n\n it('refuses a create over an existing id and leaves the record unchanged', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Overwrite')),\n );\n\n expect(failure._tag).toBe('StaleRevision');\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('Alpha');\n expect(stored.revision).toBe(1);\n });\n\n it('answers revision n + 1 to an update at n', async () => {\n const repository = await makeRepository(seeded());\n\n const updated = await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Renamed', 1)),\n );\n\n expect(updated.revision).toBe(2);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('Renamed');\n expect(stored.revision).toBe(2);\n });\n\n it('refuses a second update at the revision already spent, naming the current one', async () => {\n const repository = await makeRepository(seeded());\n await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'First', 1)),\n );\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Second', 1)),\n );\n\n expect(failure._tag).toBe('StaleRevision');\n expect(failure.current).toBe(2);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('First');\n });\n\n it('answers NotFound to an update of a record that is gone', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-404', 'Ghost', 1)),\n );\n\n expect(failure._tag).toBe('NotFound');\n });\n\n it('does not check a delete', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<RevisedWidget>('r-1'));\n\n const page = await run(repository.load<RevisedWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['r-2']);\n });\n\n it('leaves exactly one winner when two saves name the same revision', async () => {\n const repository = await makeRepository(seeded());\n\n const exits = await Promise.all([\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Left', 1)),\n ),\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Right', 1)),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n expect(exits.filter(exit => Exit.isFailure(exit))).toHaveLength(1);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.revision).toBe(2);\n expect(['Left', 'Right']).toContain(stored.name);\n });\n\n it('leaves exactly one winner when two creates name the same id', async () => {\n const repository = await makeRepository(seeded());\n\n const exits = await Promise.all([\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-7', 'Left')),\n ),\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-7', 'Right')),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n const page = await run(repository.load<RevisedWidget>({}));\n expect(page.items.filter(item => item.id === 'r-7')).toHaveLength(1);\n });\n });\n};\n\nconst STATED_PHASES = ['draft', 'released'] as const;\nconst IN_DRAFT = { member: 'phase', in: ['draft'] } as const;\n\n/**\n * The entity the state contract runs against: a record saved and deleted only\n * in `draft` ([ADR 0029](../../../../../docs/adr/0029-a-verb-declares-the-states-it-is-legal-from.md)).\n * Its state is stored under an alias, so an adapter that conditions on the\n * member's name rather than its stored key fails the suite.\n */\n@entity({\n key: 'stated-widget',\n writableWhen: IN_DRAFT,\n deletableWhen: IN_DRAFT,\n readOnlyReasonKey: 'entity:stated-widget.readOnly',\n})\nexport class StatedWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #phase?: string;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'enum', enumValues: STATED_PHASES, alias: 'stage' })\n get phase(): string | undefined {\n return this.#phase;\n }\n set phase(value: string | undefined) {\n this.#phase = value;\n }\n}\n\nexport const makeStatedWidget = (\n id: EntityId,\n name: string,\n phase: (typeof STATED_PHASES)[number],\n): StatedWidget => {\n const widget = new StatedWidget();\n widget.id = id;\n widget.name = name;\n widget.phase = phase;\n return widget;\n};\n\nexport interface EntityRepositoryStateContractOptions {\n /** Builds a repository over `seed`. Called fresh for each test. */\n makeRepository(\n seed: StatedWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * What a write conditioned on a record's state means on every adapter that\n * writes: the condition is part of the write, a record in another state is\n * refused `UnavailableInState` and left as it was, and a save racing a move out\n * of the allowed states leaves exactly one winner.\n */\nexport const describeEntityRepositoryStateContract = (\n name: string,\n { makeRepository }: EntityRepositoryStateContractOptions,\n): void => {\n describe(`EntityRepository state contract: ${name}`, () => {\n const seeded = () => [\n makeStatedWidget('s-1', 'Alpha', 'draft'),\n makeStatedWidget('s-2', 'Beta', 'released'),\n ];\n const expect_ = { expect: IN_DRAFT };\n\n const failureOf = (effect: Effect.Effect<unknown, RepositoryFailure>) =>\n runFailure(effect) as Promise<{\n _tag: string;\n member?: string;\n state?: string;\n allowed?: readonly string[];\n }>;\n\n it('saves a record that holds an allowed state', async () => {\n const repository = await makeRepository(seeded());\n\n await run(\n repository.save(makeStatedWidget('s-1', 'Renamed', 'draft'), expect_),\n );\n\n const stored = await run(repository.get<StatedWidget>('s-1'));\n expect(stored.name).toBe('Renamed');\n });\n\n it('moves a record out of the allowed states in the write that checks them', async () => {\n const repository = await makeRepository(seeded());\n\n await run(\n repository.save(makeStatedWidget('s-1', 'Alpha', 'released'), expect_),\n );\n\n const stored = await run(repository.get<StatedWidget>('s-1'));\n expect(stored.phase).toBe('released');\n });\n\n it('refuses a save of a record in another state, naming both, and writes nothing', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save(makeStatedWidget('s-2', 'Changed', 'draft'), expect_),\n );\n\n expect(failure).toMatchObject({\n _tag: 'UnavailableInState',\n member: 'phase',\n state: 'released',\n allowed: ['draft'],\n });\n const stored = await run(repository.get<StatedWidget>('s-2'));\n expect(stored.name).toBe('Beta');\n expect(stored.phase).toBe('released');\n });\n\n it('answers NotFound to a conditioned save of a record that is not there, and creates nothing', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save(makeStatedWidget('s-9', 'Ghost', 'draft'), expect_),\n );\n\n expect(failure._tag).toBe('NotFound');\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('deletes a record that holds an allowed state', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<StatedWidget>('s-1', expect_));\n\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['s-2']);\n });\n\n it('refuses a delete of a record in another state and keeps it', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.delete<StatedWidget>('s-2', expect_),\n );\n\n expect(failure).toMatchObject({\n _tag: 'UnavailableInState',\n state: 'released',\n });\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('treats a conditioned delete of an unknown id as a no-op', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<StatedWidget>('s-9', expect_));\n\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('leaves exactly one winner when a release races a conditioned delete', async () => {\n const repository = await makeRepository(seeded());\n\n const exits: Exit.Exit<unknown, RepositoryFailure>[] = await Promise.all([\n runExit<unknown, RepositoryFailure>(\n repository.save(\n makeStatedWidget('s-1', 'Alpha', 'released'),\n expect_,\n ),\n ),\n runExit<unknown, RepositoryFailure>(\n repository.delete<StatedWidget>('s-1', expect_),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n expect(exits.filter(exit => Exit.isFailure(exit))).toHaveLength(1);\n });\n });\n};\n"],"names":["accessor","entity","RELEVANCE","Exit","describe","expect","it","run","runExit","runFailure","key","labelMember","type","filterable","ContractWidget","id","value","name","size","tags","title","makeContractWidget","widget","describeEntityRepositoryReadContract","makeRepository","seeded","withRepository","use","seed","repository","read","get","again","toBe","page","load","items","reloaded","total","map","item","toEqual","request","pageSize","toHaveLength","filtering","property","operator","start","end","like","accented","nlike","tagged","values","untagged","blue","green","titled","sorted","found","sorting","en","es","exit","isFailure","describeEntityRepositoryWriteContract","returned","save","stored","created","undefined","toBeDefined","delete","describeEntityRepositoryContract","options","RevisedWidget","revision","makeRevisedWidget","describeEntityRepositoryRevisionContract","failureOf","effect","one","failure","_tag","updated","current","exits","Promise","all","filter","isSuccess","toContain","STATED_PHASES","IN_DRAFT","member","in","writableWhen","deletableWhen","readOnlyReasonKey","enumValues","alias","StatedWidget","phase","makeStatedWidget","describeEntityRepositoryStateContract","expect_","toMatchObject","state","allowed"],"mappings":";;;;AACA,SACEA,QAAQ,EAERC,MAAM,EAENC,SAAS,QACJ,gBAAgB;AACvB,SAAiBC,IAAI,QAAQ,SAAS;AACtC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C,SAASC,GAAG,EAAEC,OAAO,EAAEC,UAAU,QAAQ,mBAAmB;OAQ3DR,OAAO;IAAES,KAAK;IAAmBC,aAAa;AAAO,YAQnDX,SAAS;IAAEY,MAAM;AAAK,YAQtBZ,SAAS;IAAEY,MAAM;AAAS,YAQ1BZ,SAAS;IAAEY,MAAM;AAAS,YAQ1BZ,SAAS;IAAEY,MAAM;IAAoBC,YAAY;AAAK,YAQtDb,SAAS;IAAEY,MAAM;AAAY;;IAtC9B,2DACA,+DACA,+DACA,+DACA;AALK,IAAA,AAAME,iBAAN,MAAMA;IAOX,IACIC,KAAe;QACjB,OAAO,gCAAA,IAAI,EAAC,KAAA;IACd;IACA,IAAIA,GAAGC,KAAe,EAAE;QACtB,gCAAA,IAAI,EAAC,KAAA,OAAMA;IACb;IAEA,IACIC,OAA2B;QAC7B,OAAO,gCAAA,IAAI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nC,GAAG,8DAA8D;YAC/D,MAAMuB,aAAa,MAAML,eAAeC;YAExC,MAAM0D,UAAU,MAAMH,UACpBnD,WAAW4C,MAAM,CAAe,OAAOiC;YAGzCrG,OAAO8E,SAASwB,aAAa,CAAC;gBAC5BvB,MAAM;gBACNwB,OAAO;YACT;YACA,MAAM1E,OAAO,MAAM3B,IAAIsB,WAAWM,IAAI,CAAe,CAAC;YACtD9B,OAAO6B,KAAKI,KAAK,EAAEL,IAAI,CAAC;QAC1B;QAEA3B,GAAG,2DAA2D;YAC5D,MAAMuB,aAAa,MAAML,eAAeC;YAExC,MAAMlB,IAAIsB,WAAW4C,MAAM,CAAe,OAAOiC;YAEjD,MAAMxE,OAAO,MAAM3B,IAAIsB,WAAWM,IAAI,CAAe,CAAC;YACtD9B,OAAO6B,KAAKI,KAAK,EAAEL,IAAI,CAAC;QAC1B;QAEA3B,GAAG,uEAAuE;YACxE,MAAMuB,aAAa,MAAML,eAAeC;YAExC,MAAM8D,QAAiD,MAAMC,QAAQC,GAAG,CAAC;gBACvEjF,QACEqB,WAAWuC,IAAI,CACboC,iBAAiB,OAAO,SAAS,aACjCE;gBAGJlG,QACEqB,WAAW4C,MAAM,CAAe,OAAOiC;aAE1C;YAEDrG,OAAOkF,MAAMG,MAAM,CAAC1B,CAAAA,OAAQ7D,KAAKwF,SAAS,CAAC3B,QAAQpB,YAAY,CAAC;YAChEvC,OAAOkF,MAAMG,MAAM,CAAC1B,CAAAA,OAAQ7D,KAAK8D,SAAS,CAACD,QAAQpB,YAAY,CAAC;QAClE;IACF;AACF,EAAE;SA/6BF,AAAa9B,mBAAAA,cA8CZ,EAqfD,AAAa8D,kBAAAA,aA4BZ,EA8LD,AAAa0B,iBAAAA,YA4BZ"}
1
+ {"version":3,"sources":["../../src/contracts/entity-repository.contract.ts"],"sourcesContent":["import type { EntityRepository, RepositoryFailure } from '@entifix/business';\nimport {\n accessor,\n type Entity,\n entity,\n type EntityId,\n RELEVANCE,\n} from '@entifix/core';\nimport { Effect, Exit } from 'effect';\nimport { describe, expect, it } from 'vitest';\n\nimport { run, runExit, runFailure } from '../effect/run.js';\n\n/**\n * The entity every implementation of the contract is exercised against. It is\n * declared here rather than by each caller so the suite controls exactly which\n * fields exist.\n */\n// `labelMember` is what relevance scores against (ADR 0033).\n@entity({ key: 'contract-widget', labelMember: 'name' })\nexport class ContractWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #size?: number;\n #tags: readonly string[] = [];\n #title?: Readonly<Record<string, string>>;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'number' })\n get size(): number | undefined {\n return this.#size;\n }\n set size(value: number | undefined) {\n this.#size = value;\n }\n\n @accessor({ type: 'scalarCollection', filterable: true })\n get tags(): readonly string[] {\n return this.#tags;\n }\n set tags(value: readonly string[]) {\n this.#tags = value;\n }\n\n @accessor({ type: 'localized' })\n get title(): Readonly<Record<string, string>> | undefined {\n return this.#title;\n }\n set title(value: Readonly<Record<string, string>> | undefined) {\n this.#title = value;\n }\n}\n\nexport const makeContractWidget = (\n id: EntityId,\n name: string,\n size: number,\n tags: readonly string[] = [],\n): ContractWidget => {\n const widget = new ContractWidget();\n widget.id = id;\n widget.name = name;\n widget.size = size;\n widget.tags = tags;\n return widget;\n};\n\nexport interface EntityRepositoryContractOptions {\n /**\n * Builds a repository over `seed`. Called fresh for each test, so no state\n * leaks between them.\n */\n makeRepository(\n seed: ContractWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * The reads every {@link EntityRepository} must answer alike: `load` with its\n * paging, filtering and sorting, and `get`. A read-only adapter — one over\n * static files, say — runs this half alone, since it refuses `save` and\n * `delete` by design.\n */\nexport const describeEntityRepositoryReadContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository read contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('keeps a record unchanged when a read instance is mutated without a save', async () => {\n await withRepository(async repository => {\n const read = await run(repository.get<ContractWidget>('w-1'));\n read.name = 'Mutated';\n\n const again = await run(repository.get<ContractWidget>('w-1'));\n expect(again.name).toBe('Alpha');\n\n const page = await run(repository.load<ContractWidget>({}));\n page.items[0]!.name = 'Mutated';\n const reloaded = await run(repository.load<ContractWidget>({}));\n expect(reloaded.items[0]!.name).toBe('Alpha');\n });\n });\n\n it('loads every stored entity with its total', async () => {\n await withRepository(async repository => {\n const page = await run(repository.load<ContractWidget>({}));\n\n expect(page.total).toBe(3);\n expect(page.items.map(item => item.name)).toEqual([\n 'Alpha',\n 'Beta',\n 'Gamma',\n ]);\n });\n });\n\n it('echoes the request it served on the page', async () => {\n await withRepository(async repository => {\n const request = { page: 1, pageSize: 2 };\n const page = await run(repository.load<ContractWidget>(request));\n\n expect(page.request).toEqual(request);\n });\n });\n\n it('pages with a 1-based page number', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({ page: 2, pageSize: 2 }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.name).toBe('Gamma');\n // The total counts matches, not the page.\n expect(page.total).toBe(3);\n });\n });\n\n it('filters by an equality operator', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'eq', value: 'Beta' }],\n }),\n );\n\n expect(page.items).toHaveLength(1);\n expect(page.items[0]?.id).toBe('w-2');\n expect(page.total).toBe(1);\n });\n });\n\n it('filters by a range operator', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'size', operator: 'between', start: 15, end: 35 },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('matches `like` case-insensitively on a substring', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'name', operator: 'like', value: 'et' }],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual(['w-2']);\n });\n });\n\n it('matches `like` and `nlike` with accents ignored on both sides', async () => {\n await withRepository(\n async repository => {\n const like = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'cafe' },\n ],\n }),\n );\n const accented = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'NIÑO' },\n ],\n }),\n );\n const nlike = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'nlike', value: 'café' },\n ],\n }),\n );\n\n expect(like.items.map(item => item.id)).toEqual(['w-1']);\n expect(accented.items.map(item => item.id)).toEqual(['w-2']);\n expect(nlike.items.map(item => item.id)).toEqual(['w-2']);\n },\n [\n makeContractWidget('w-1', 'Café de Olla', 10),\n makeContractWidget('w-2', 'nino', 20),\n ],\n );\n });\n\n it('matches `in` and `nin` against any element of an array member', async () => {\n await withRepository(\n async repository => {\n const tagged = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'tags', operator: 'in', values: ['blue', 'red'] },\n ],\n }),\n );\n expect(tagged.items.map(item => item.id)).toEqual(['w-1', 'w-3']);\n\n const untagged = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'tags', operator: 'nin', values: ['blue', 'red'] },\n ],\n }),\n );\n expect(untagged.items.map(item => item.id)).toEqual(['w-2']);\n },\n [\n makeContractWidget('w-1', 'Alpha', 10, ['blue', 'green']),\n makeContractWidget('w-2', 'Beta', 20, ['green']),\n makeContractWidget('w-3', 'Gamma', 30, ['red']),\n ],\n );\n });\n\n it('matches `==` against any element of an array member', async () => {\n await withRepository(\n async repository => {\n const blue = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'tags', operator: 'eq', value: 'blue' }],\n }),\n );\n expect(blue.items.map(item => item.id)).toEqual(['w-1']);\n\n const green = await run(\n repository.load<ContractWidget>({\n filtering: [{ property: 'tags', operator: 'eq', value: 'green' }],\n }),\n );\n expect(green.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n },\n [\n makeContractWidget('w-1', 'Alpha', 10, ['blue', 'green']),\n makeContractWidget('w-2', 'Beta', 20, ['green']),\n makeContractWidget('w-3', 'Gamma', 30, ['red']),\n ],\n );\n });\n\n it('filters and sorts a localized member one locale at a time', async () => {\n const titled = (\n id: string,\n name: string,\n title: Record<string, string>,\n ) => {\n const widget = makeContractWidget(id, name, 0);\n widget.title = title;\n return widget;\n };\n await withRepository(\n async repository => {\n const found = await run(\n repository.load<ContractWidget>({\n filtering: [\n {\n property: 'title.es' as keyof ContractWidget,\n operator: 'like',\n value: 'SOPA',\n },\n ],\n }),\n );\n expect(found.items.map(item => item.id)).toEqual(['w-2']);\n\n const sorted = await run(\n repository.load<ContractWidget>({\n sorting: [\n {\n 0: {\n property: 'title.en' as keyof ContractWidget,\n type: 'asc',\n },\n },\n ],\n }),\n );\n expect(sorted.items.map(item => item.id)).toEqual([\n 'w-3',\n 'w-1',\n 'w-2',\n ]);\n expect(sorted.items[0]?.title).toEqual({\n en: 'Apple',\n es: 'Manzana',\n });\n },\n [\n titled('w-1', 'Alpha', { en: 'Bread', es: 'Pan' }),\n titled('w-2', 'Beta', { en: 'Soup', es: 'Sopa' }),\n titled('w-3', 'Gamma', { en: 'Apple', es: 'Manzana' }),\n ],\n );\n });\n\n it('sorts descending when asked to', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n sorting: [{ 0: { property: 'size', type: 'desc' } }],\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20, 10]);\n });\n });\n\n it('ranks by relevance: a label prefix, then a word start, then anywhere', async () => {\n // ADR 0033: one point per word matched elsewhere, two for a word that\n // starts a word of the label, three for one the label starts with;\n // ties fall to the next key.\n await withRepository(\n async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n filtering: [\n { property: 'name', operator: 'like', value: 'lamp' },\n ],\n sorting: [\n {\n 0: { property: RELEVANCE, type: 'desc' },\n 1: { property: 'size', type: 'asc' },\n },\n ],\n }),\n );\n\n expect(page.items.map(item => item.id)).toEqual([\n 'w-4',\n 'w-2',\n 'w-3',\n 'w-1',\n ]);\n expect(page.total).toBe(4);\n },\n [\n makeContractWidget('w-1', 'Superlamp', 10),\n makeContractWidget('w-2', 'Desk lamp', 20),\n makeContractWidget('w-3', 'Floor lamp', 30),\n makeContractWidget('w-4', 'Lámpara', 40),\n makeContractWidget('w-5', 'Chair', 50),\n ],\n );\n });\n\n it('falls to the next key when relevance has no word to weigh', async () => {\n await withRepository(async repository => {\n const page = await run(\n repository.load<ContractWidget>({\n sorting: [\n {\n 0: { property: RELEVANCE, type: 'desc' },\n 1: { property: 'size', type: 'desc' },\n },\n ],\n page: 1,\n pageSize: 2,\n }),\n );\n\n expect(page.items.map(item => item.size)).toEqual([30, 20]);\n });\n });\n\n it('reads a single entity by id', async () => {\n await withRepository(async repository => {\n const found = await run(repository.get<ContractWidget>('w-2'));\n\n expect(found.id).toBe('w-2');\n expect(found.name).toBe('Beta');\n });\n });\n\n it('fails rather than resolving undefined for an unknown id', async () => {\n await withRepository(async repository => {\n const exit = await runExit(repository.get<ContractWidget>('missing'));\n\n expect(Exit.isFailure(exit)).toBe(true);\n });\n });\n\n it('loads an empty page from an empty store', async () => {\n await withRepository(async repository => {\n const page = await run(repository.load<ContractWidget>({}));\n\n expect(page.items).toEqual([]);\n expect(page.total).toBe(0);\n }, []);\n });\n });\n};\n\n/** The writes every {@link EntityRepository} that accepts them must honour. */\nexport const describeEntityRepositoryWriteContract = (\n name: string,\n { makeRepository }: EntityRepositoryContractOptions,\n): void => {\n describe(`EntityRepository write contract: ${name}`, () => {\n const seeded = () => [\n makeContractWidget('w-1', 'Alpha', 10),\n makeContractWidget('w-2', 'Beta', 20),\n makeContractWidget('w-3', 'Gamma', 30),\n ];\n\n const withRepository = async (\n use: (repository: EntityRepository) => Promise<void>,\n seed: ContractWidget[] = seeded(),\n ) => {\n await use(await makeRepository(seed));\n };\n\n it('keeps a saved record unchanged when the saved instance is mutated afterwards', async () => {\n await withRepository(async repository => {\n const widget = makeContractWidget('w-9', 'Delta', 40);\n const returned = await run(repository.save(widget));\n\n widget.name = 'Mutated';\n returned.name = 'Mutated too';\n\n const stored = await run(repository.get<ContractWidget>('w-9'));\n expect(stored.name).toBe('Delta');\n });\n });\n\n it('mints an id when saving an entity that has none', async () => {\n await withRepository(async repository => {\n const created = await run(\n repository.save<ContractWidget>(\n makeContractWidget(undefined, 'Delta', 40),\n ),\n );\n\n expect(created.id).toBeDefined();\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(4);\n });\n });\n\n it('overwrites in place when saving an entity that already has an id', async () => {\n await withRepository(async repository => {\n await run(\n repository.save<ContractWidget>(\n makeContractWidget('w-2', 'Renamed', 25),\n ),\n );\n\n const found = await run(repository.get<ContractWidget>('w-2'));\n expect(found.name).toBe('Renamed');\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n\n it('deletes by id', async () => {\n await withRepository(async repository => {\n await run(repository.delete<ContractWidget>('w-1'));\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-2', 'w-3']);\n });\n });\n\n it('deletes by entity', async () => {\n await withRepository(async repository => {\n await run(\n repository.delete<ContractWidget>(\n makeContractWidget('w-3', 'Gamma', 30),\n ),\n );\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['w-1', 'w-2']);\n });\n });\n\n it('treats deleting an unknown id as a no-op', async () => {\n await withRepository(async repository => {\n await run(repository.delete<ContractWidget>('missing'));\n\n const page = await run(repository.load<ContractWidget>({}));\n expect(page.total).toBe(3);\n });\n });\n });\n};\n\n/**\n * The behaviour every {@link EntityRepository} must exhibit, regardless of what\n * backs it: both halves.\n *\n * Run it against the in-memory fake *and* against each real adapter. That is\n * what stops a fake from drifting into a more forgiving version of the thing it\n * stands in for — the failure mode where a suite is green and production is\n * not. `entifix-ts-testing-integration` will run this same suite against real\n * infrastructure later.\n */\nexport const describeEntityRepositoryContract = (\n name: string,\n options: EntityRepositoryContractOptions,\n): void => {\n describeEntityRepositoryReadContract(name, options);\n describeEntityRepositoryWriteContract(name, options);\n};\n\n/**\n * The entity the revision contract runs against: {@link ContractWidget}'s\n * shape plus the one member that makes its saves checked (ADR 0032).\n */\n@entity({ key: 'revised-widget' })\nexport class RevisedWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #revision?: number;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'revision' })\n get revision(): number | undefined {\n return this.#revision;\n }\n set revision(value: number | undefined) {\n this.#revision = value;\n }\n}\n\nexport const makeRevisedWidget = (\n id: EntityId,\n name: string,\n revision?: number,\n): RevisedWidget => {\n const widget = new RevisedWidget();\n widget.id = id;\n widget.name = name;\n widget.revision = revision;\n return widget;\n};\n\nexport interface EntityRepositoryRevisionContractOptions {\n /**\n * Builds a repository over `seed`, whose records are stored at revision 1.\n * Called fresh for each test.\n */\n makeRepository(\n seed: RevisedWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * What a save of an entity that declares a `revision` means on every adapter\n * that writes: a create never overwrites, an update names the revision it read\n * and moves it, and a stale save writes nothing — including when two race.\n */\nexport const describeEntityRepositoryRevisionContract = (\n name: string,\n { makeRepository }: EntityRepositoryRevisionContractOptions,\n): void => {\n describe(`EntityRepository revision contract: ${name}`, () => {\n const seeded = () => [\n makeRevisedWidget('r-1', 'Alpha', 1),\n makeRevisedWidget('r-2', 'Beta', 1),\n ];\n\n const failureOf = (effect: ReturnType<EntityRepository['get']>) =>\n runFailure(effect) as Promise<{ _tag: string; current?: number }>;\n\n it('carries the revision on a record and on a list row', async () => {\n const repository = await makeRepository(seeded());\n\n const one = await run(repository.get<RevisedWidget>('r-1'));\n const page = await run(repository.load<RevisedWidget>({}));\n\n expect(one.revision).toBe(1);\n expect(page.items.map(item => item.revision)).toEqual([1, 1]);\n });\n\n it('creates at revision 1, minting an id when there is none', async () => {\n const repository = await makeRepository(seeded());\n\n const created = await run(\n repository.save<RevisedWidget>(makeRevisedWidget(undefined, 'Gamma')),\n );\n\n expect(created.id).toBeDefined();\n expect(created.revision).toBe(1);\n const stored = await run(repository.get<RevisedWidget>(created.id));\n expect(stored.revision).toBe(1);\n });\n\n it('creates under a client-minted id', async () => {\n const repository = await makeRepository(seeded());\n\n const created = await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-9', 'Mine')),\n );\n\n expect(created.id).toBe('r-9');\n expect(created.revision).toBe(1);\n });\n\n it('refuses a create over an existing id and leaves the record unchanged', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Overwrite')),\n );\n\n expect(failure._tag).toBe('StaleRevision');\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('Alpha');\n expect(stored.revision).toBe(1);\n });\n\n it('answers revision n + 1 to an update at n', async () => {\n const repository = await makeRepository(seeded());\n\n const updated = await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Renamed', 1)),\n );\n\n expect(updated.revision).toBe(2);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('Renamed');\n expect(stored.revision).toBe(2);\n });\n\n it('refuses a second update at the revision already spent, naming the current one', async () => {\n const repository = await makeRepository(seeded());\n await run(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'First', 1)),\n );\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Second', 1)),\n );\n\n expect(failure._tag).toBe('StaleRevision');\n expect(failure.current).toBe(2);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.name).toBe('First');\n });\n\n it('answers NotFound to an update of a record that is gone', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<RevisedWidget>(makeRevisedWidget('r-404', 'Ghost', 1)),\n );\n\n expect(failure._tag).toBe('NotFound');\n });\n\n it('does not check a delete', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<RevisedWidget>('r-1'));\n\n const page = await run(repository.load<RevisedWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['r-2']);\n });\n\n it('leaves exactly one winner when two saves name the same revision', async () => {\n const repository = await makeRepository(seeded());\n\n const exits = await Promise.all([\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Left', 1)),\n ),\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-1', 'Right', 1)),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n expect(exits.filter(exit => Exit.isFailure(exit))).toHaveLength(1);\n const stored = await run(repository.get<RevisedWidget>('r-1'));\n expect(stored.revision).toBe(2);\n expect(['Left', 'Right']).toContain(stored.name);\n });\n\n it('leaves exactly one winner when two creates name the same id', async () => {\n const repository = await makeRepository(seeded());\n\n const exits = await Promise.all([\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-7', 'Left')),\n ),\n runExit(\n repository.save<RevisedWidget>(makeRevisedWidget('r-7', 'Right')),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n const page = await run(repository.load<RevisedWidget>({}));\n expect(page.items.filter(item => item.id === 'r-7')).toHaveLength(1);\n });\n });\n};\n\n/**\n * The entity the unique contract runs against: a revised record with an\n * optional code no two records may share (ADR 0034). The code is stored under\n * an alias, so an adapter that indexes the member's name rather than its stored\n * key fails the suite.\n */\n@entity({ key: 'unique-widget' })\nexport class UniqueWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #code?: string;\n #revision?: number;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'string', unique: true, alias: 'sku' })\n get code(): string | undefined {\n return this.#code;\n }\n set code(value: string | undefined) {\n this.#code = value;\n }\n\n @accessor({ type: 'revision' })\n get revision(): number | undefined {\n return this.#revision;\n }\n set revision(value: number | undefined) {\n this.#revision = value;\n }\n}\n\nexport const makeUniqueWidget = (\n id: EntityId,\n name: string,\n code?: string,\n revision?: number,\n): UniqueWidget => {\n const widget = new UniqueWidget();\n widget.id = id;\n widget.name = name;\n widget.code = code;\n widget.revision = revision;\n return widget;\n};\n\nexport interface EntityRepositoryUniqueContractOptions {\n /**\n * Builds a repository over `seed`, whose records are stored at revision 1.\n * Called fresh for each test.\n */\n makeRepository(\n seed: UniqueWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * What a member declared `unique` means on every adapter that writes: no two\n * records hold one value, a collision names the member's stored key, an absent\n * value never collides, and two creates racing for one value leave one winner.\n */\nexport const describeEntityRepositoryUniqueContract = (\n name: string,\n { makeRepository }: EntityRepositoryUniqueContractOptions,\n): void => {\n describe(`EntityRepository unique contract: ${name}`, () => {\n const seeded = () => [\n makeUniqueWidget('u-1', 'Alpha', 'A-1', 1),\n makeUniqueWidget('u-2', 'Beta', undefined, 1),\n ];\n\n const failureOf = (effect: ReturnType<EntityRepository['get']>) =>\n runFailure(effect) as Promise<{ _tag: string; key?: string }>;\n\n it('refuses a create holding a value another record holds, naming the stored key', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<UniqueWidget>(\n makeUniqueWidget(undefined, 'Gamma', 'A-1'),\n ),\n );\n\n expect(failure).toMatchObject({ _tag: 'DuplicateKey', key: 'sku' });\n const page = await run(repository.load<UniqueWidget>({}));\n expect(page.items).toHaveLength(2);\n });\n\n it(\"refuses an update onto another record's value and leaves both unchanged\", async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save<UniqueWidget>(\n makeUniqueWidget('u-2', 'Beta', 'A-1', 1),\n ),\n );\n\n expect(failure).toMatchObject({ _tag: 'DuplicateKey', key: 'sku' });\n const stored = await run(repository.get<UniqueWidget>('u-2'));\n // Absent, however the store spells it: SQL reads an empty column as null.\n expect(stored.code ?? undefined).toBeUndefined();\n expect(stored.revision).toBe(1);\n });\n\n it('saves a record that keeps its own value', async () => {\n const repository = await makeRepository(seeded());\n\n const saved = await run(\n repository.save<UniqueWidget>(\n makeUniqueWidget('u-1', 'Alpha renamed', 'A-1', 1),\n ),\n );\n\n expect(saved.revision).toBe(2);\n });\n\n it('never counts two absent values as a collision', async () => {\n const repository = await makeRepository(seeded());\n\n const created = await run(\n repository.save<UniqueWidget>(makeUniqueWidget(undefined, 'Gamma')),\n );\n\n expect(created.revision).toBe(1);\n const page = await run(repository.load<UniqueWidget>({}));\n expect(page.items.filter(item => item.code == null)).toHaveLength(2);\n });\n\n it('frees a value its holder gave up', async () => {\n const repository = await makeRepository(seeded());\n\n await run(\n repository.save<UniqueWidget>(\n makeUniqueWidget('u-1', 'Alpha', 'A-2', 1),\n ),\n );\n const created = await run(\n repository.save<UniqueWidget>(\n makeUniqueWidget(undefined, 'Gamma', 'A-1'),\n ),\n );\n\n expect(created.code).toBe('A-1');\n });\n\n it('leaves exactly one winner when creates race for one value', async () => {\n const repository = await makeRepository(seeded());\n\n const exits = await Promise.all(\n ['Left', 'Middle', 'Right'].map(label =>\n runExit(\n repository.save<UniqueWidget>(\n makeUniqueWidget(undefined, label, 'B-1'),\n ),\n ),\n ),\n );\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n const page = await run(repository.load<UniqueWidget>({}));\n expect(page.items.filter(item => item.code === 'B-1')).toHaveLength(1);\n });\n });\n};\n\nconst STATED_PHASES = ['draft', 'released'] as const;\nconst IN_DRAFT = { member: 'phase', in: ['draft'] } as const;\n\n/**\n * The entity the state contract runs against: a record saved and deleted only\n * in `draft` ([ADR 0029](../../../../../docs/adr/0029-a-verb-declares-the-states-it-is-legal-from.md)).\n * Its state is stored under an alias, so an adapter that conditions on the\n * member's name rather than its stored key fails the suite.\n */\n@entity({\n key: 'stated-widget',\n writableWhen: IN_DRAFT,\n deletableWhen: IN_DRAFT,\n readOnlyReasonKey: 'entity:stated-widget.readOnly',\n})\nexport class StatedWidget implements Entity {\n #id?: EntityId;\n #name?: string;\n #phase?: string;\n\n @accessor({ type: 'id' })\n get id(): EntityId {\n return this.#id;\n }\n set id(value: EntityId) {\n this.#id = value;\n }\n\n @accessor({ type: 'string' })\n get name(): string | undefined {\n return this.#name;\n }\n set name(value: string | undefined) {\n this.#name = value;\n }\n\n @accessor({ type: 'enum', enumValues: STATED_PHASES, alias: 'stage' })\n get phase(): string | undefined {\n return this.#phase;\n }\n set phase(value: string | undefined) {\n this.#phase = value;\n }\n}\n\nexport const makeStatedWidget = (\n id: EntityId,\n name: string,\n phase: (typeof STATED_PHASES)[number],\n): StatedWidget => {\n const widget = new StatedWidget();\n widget.id = id;\n widget.name = name;\n widget.phase = phase;\n return widget;\n};\n\nexport interface EntityRepositoryStateContractOptions {\n /** Builds a repository over `seed`. Called fresh for each test. */\n makeRepository(\n seed: StatedWidget[],\n ): EntityRepository | Promise<EntityRepository>;\n}\n\n/**\n * What a write conditioned on a record's state means on every adapter that\n * writes: the condition is part of the write, a record in another state is\n * refused `UnavailableInState` and left as it was, and a save racing a move out\n * of the allowed states leaves exactly one winner.\n */\nexport const describeEntityRepositoryStateContract = (\n name: string,\n { makeRepository }: EntityRepositoryStateContractOptions,\n): void => {\n describe(`EntityRepository state contract: ${name}`, () => {\n const seeded = () => [\n makeStatedWidget('s-1', 'Alpha', 'draft'),\n makeStatedWidget('s-2', 'Beta', 'released'),\n ];\n const expect_ = { expect: IN_DRAFT };\n\n const failureOf = (effect: Effect.Effect<unknown, RepositoryFailure>) =>\n runFailure(effect) as Promise<{\n _tag: string;\n member?: string;\n state?: string;\n allowed?: readonly string[];\n }>;\n\n it('saves a record that holds an allowed state', async () => {\n const repository = await makeRepository(seeded());\n\n await run(\n repository.save(makeStatedWidget('s-1', 'Renamed', 'draft'), expect_),\n );\n\n const stored = await run(repository.get<StatedWidget>('s-1'));\n expect(stored.name).toBe('Renamed');\n });\n\n it('moves a record out of the allowed states in the write that checks them', async () => {\n const repository = await makeRepository(seeded());\n\n await run(\n repository.save(makeStatedWidget('s-1', 'Alpha', 'released'), expect_),\n );\n\n const stored = await run(repository.get<StatedWidget>('s-1'));\n expect(stored.phase).toBe('released');\n });\n\n it('refuses a save of a record in another state, naming both, and writes nothing', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save(makeStatedWidget('s-2', 'Changed', 'draft'), expect_),\n );\n\n expect(failure).toMatchObject({\n _tag: 'UnavailableInState',\n member: 'phase',\n state: 'released',\n allowed: ['draft'],\n });\n const stored = await run(repository.get<StatedWidget>('s-2'));\n expect(stored.name).toBe('Beta');\n expect(stored.phase).toBe('released');\n });\n\n it('answers NotFound to a conditioned save of a record that is not there, and creates nothing', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.save(makeStatedWidget('s-9', 'Ghost', 'draft'), expect_),\n );\n\n expect(failure._tag).toBe('NotFound');\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('deletes a record that holds an allowed state', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<StatedWidget>('s-1', expect_));\n\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.items.map(item => item.id)).toEqual(['s-2']);\n });\n\n it('refuses a delete of a record in another state and keeps it', async () => {\n const repository = await makeRepository(seeded());\n\n const failure = await failureOf(\n repository.delete<StatedWidget>('s-2', expect_),\n );\n\n expect(failure).toMatchObject({\n _tag: 'UnavailableInState',\n state: 'released',\n });\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('treats a conditioned delete of an unknown id as a no-op', async () => {\n const repository = await makeRepository(seeded());\n\n await run(repository.delete<StatedWidget>('s-9', expect_));\n\n const page = await run(repository.load<StatedWidget>({}));\n expect(page.total).toBe(2);\n });\n\n it('leaves exactly one winner when a release races a conditioned delete', async () => {\n const repository = await makeRepository(seeded());\n\n const exits: Exit.Exit<unknown, RepositoryFailure>[] = await Promise.all([\n runExit<unknown, RepositoryFailure>(\n repository.save(\n makeStatedWidget('s-1', 'Alpha', 'released'),\n expect_,\n ),\n ),\n runExit<unknown, RepositoryFailure>(\n repository.delete<StatedWidget>('s-1', expect_),\n ),\n ]);\n\n expect(exits.filter(exit => Exit.isSuccess(exit))).toHaveLength(1);\n expect(exits.filter(exit => Exit.isFailure(exit))).toHaveLength(1);\n });\n });\n};\n"],"names":["accessor","entity","RELEVANCE","Exit","describe","expect","it","run","runExit","runFailure","key","labelMember","type","filterable","ContractWidget","id","value","name","size","tags","title","makeContractWidget","widget","describeEntityRepositoryReadContract","makeRepository","seeded","withRepository","use","seed","repository","read","get","again","toBe","page","load","items","reloaded","total","map","item","toEqual","request","pageSize","toHaveLength","filtering","property","operator","start","end","like","accented","nlike","tagged","values","untagged","blue","green","titled","sorted","found","sorting","en","es","exit","isFailure","describeEntityRepositoryWriteContract","returned","save","stored","created","undefined","toBeDefined","delete","describeEntityRepositoryContract","options","RevisedWidget","revision","makeRevisedWidget","describeEntityRepositoryRevisionContract","failureOf","effect","one","failure","_tag","updated","current","exits","Promise","all","filter","isSuccess","toContain","unique","alias","UniqueWidget","code","makeUniqueWidget","describeEntityRepositoryUniqueContract","toMatchObject","toBeUndefined","saved","label","STATED_PHASES","IN_DRAFT","member","in","writableWhen","deletableWhen","readOnlyReasonKey","enumValues","StatedWidget","phase","makeStatedWidget","describeEntityRepositoryStateContract","expect_","state","allowed"],"mappings":";;;;AACA,SACEA,QAAQ,EAERC,MAAM,EAENC,SAAS,QACJ,gBAAgB;AACvB,SAAiBC,IAAI,QAAQ,SAAS;AACtC,SAASC,QAAQ,EAAEC,MAAM,EAAEC,EAAE,QAAQ,SAAS;AAE9C,SAASC,GAAG,EAAEC,OAAO,EAAEC,UAAU,QAAQ,mBAAmB;OAQ3DR,OAAO;IAAES,KAAK;IAAmBC,aAAa;AAAO,YAQnDX,SAAS;IAAEY,MAAM;AAAK,YAQtBZ,SAAS;IAAEY,MAAM;AAAS,YAQ1BZ,SAAS;IAAEY,MAAM;AAAS,YAQ1BZ,SAAS;IAAEY,MAAM;IAAoBC,YAAY;AAAK,YAQtDb,SAAS;IAAEY,MAAM;AAAY;;IAtC9B,2DACA,+DACA,+DACA,+DACA;AALK,IAAA,AAAME,iBAAN,MAAMA;IAOX,IACIC,KAAe;QACjB,OAAO,gCAAA,IAAI,EAAC,KAAA;IACd;IACA,IAAIA,GAAGC,KAAe,EAAE;QACtB,gCAAA,IAAI,EAAC,KAAA,OAAMA;IACb;IAEA,IACIC,OAA2B;QAC7B,OAAO,gCAAA,IAAI,EAAC,OAAA;IACd;IACA,IAAIA,KAAKD,KAAyB,EAAE;QAClC,gCAAA,IAAI,EAAC,OAAA,SAAQA;IACf;IAEA,IACIE,OAA2B;QAC7B,OAAO,gCAAA,IAAI,EAAC,OAAA;IACd;IACA,IAAIA,KAAKF,KAAyB,EAAE;QAClC,gCAAA,IAAI,EAAC,OAAA,SAAQA;IACf;IAEA,IACIG,OAA0B;QAC5B,OAAO,gCAAA,IAAI,EAAC,OAAA;IACd;IACA,IAAIA,KAAKH,KAAwB,EAAE;QACjC,gCAAA,IAAI,EAAC,OAAA,SAAQA;IACf;IAEA,IACII,QAAsD;QACxD,OAAO,gCAAA,IAAI,EAAC,QAAA;IACd;IACA,IAAIA,MAA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I,KAAK,EAAEL,IAAI,CAAC;QAC1B;QAEA3B,GAAG,uEAAuE;YACxE,MAAMuB,aAAa,MAAML,eAAeC;YAExC,MAAM8D,QAAiD,MAAMC,QAAQC,GAAG,CAAC;gBACvEjF,QACEqB,WAAWuC,IAAI,CACb6C,iBAAiB,OAAO,SAAS,aACjCE;gBAGJ3G,QACEqB,WAAW4C,MAAM,CAAe,OAAO0C;aAE1C;YAED9G,OAAOkF,MAAMG,MAAM,CAAC1B,CAAAA,OAAQ7D,KAAKwF,SAAS,CAAC3B,QAAQpB,YAAY,CAAC;YAChEvC,OAAOkF,MAAMG,MAAM,CAAC1B,CAAAA,OAAQ7D,KAAK8D,SAAS,CAACD,QAAQpB,YAAY,CAAC;QAClE;IACF;AACF,EAAE;SAlmCF,AAAa9B,mBAAAA,cA8CZ,EAqfD,AAAa8D,kBAAAA,aA4BZ,EAsLD,AAAamB,iBAAAA,YAqCZ,EAsJD,AAAagB,iBAAAA,YA4BZ"}
@@ -1 +1 @@
1
- {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAML,KAAK,MAAM,EAcZ,MAAM,eAAe,CAAC;AAiCvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC1C;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBA+LF,CAAC"}
1
+ {"version":3,"file":"entity-repository.d.ts","sourceRoot":"","sources":["../../src/doubles/entity-repository.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,iBAAiB,EAClB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAOL,KAAK,MAAM,EAeZ,MAAM,eAAe,CAAC;AAiCvB,MAAM,WAAW,wBAAyB,SAAQ,gBAAgB;IAChE,uDAAuD;IACvD,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,CAAC;IACzB,4DAA4D;IAC5D,IAAI,CAAC,KAAK,EAAE,MAAM,EAAE,GAAG,IAAI,CAAC;IAC5B;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,iBAAiB,GAAG,IAAI,CAAC;CAC1C;AAED;;;;;;;;;GASG;AACH,eAAO,MAAM,4BAA4B,GACvC,OAAM,MAAM,EAAO,KAClB,wBA6NF,CAAC"}
@@ -1,5 +1,5 @@
1
1
  import { _ as _extends } from "@swc/helpers/_/_extends";
2
- import { applyFiltering, applySorting, declaresRevision, deserializeSingleEntity, extractMetaAccessors, extractMetaEntity, isUseCaseAvailable, NotFound, readRevision, serializeEntity, StaleRevision, UnavailableInState } from '@entifix/core';
2
+ import { applyFiltering, applySorting, declaresRevision, deserializeSingleEntity, DuplicateKey, extractMetaAccessors, extractMetaEntity, isUseCaseAvailable, NotFound, readRevision, serializeEntity, StaleRevision, UnavailableInState, uniqueMembersOf } from '@entifix/core';
3
3
  import { Effect } from 'effect';
4
4
  /**
5
5
  * A copy of `entity` that shares no state with it.
@@ -59,6 +59,22 @@ import { Effect } from 'effect';
59
59
  return found === undefined ? Effect.fail(new NotFound({})) : copyOf(found);
60
60
  });
61
61
  /**
62
+ * The unique rule (ADR 0034): no other record may hold a value `candidate`
63
+ * holds in a member its entity declares `unique`. An absent value never
64
+ * collides. Called in the same synchronous step as the write it guards.
65
+ */ const clashOf = (candidate)=>{
66
+ const members = uniqueMembersOf(candidate.constructor);
67
+ for (const member of members){
68
+ const value = candidate[member.name];
69
+ if (value == null) continue;
70
+ const clash = items.some((item)=>item.constructor === candidate.constructor && item.id !== candidate.id && item[member.name] === value);
71
+ if (clash) return new DuplicateKey({
72
+ key: member.key
73
+ });
74
+ }
75
+ return undefined;
76
+ };
77
+ /**
62
78
  * The revision rule (ADR 0032): a create never overwrites, an update names
63
79
  * the revision it read, and a mismatch writes nothing. The decision and the
64
80
  * write share one synchronous step, so two saves cannot both pass at one
@@ -88,6 +104,8 @@ import { Effect } from 'effect';
88
104
  }));
89
105
  }
90
106
  }
107
+ const clash = clashOf(stored);
108
+ if (clash !== undefined) return Effect.fail(clash);
91
109
  const next = (read != null ? read : 0) + 1;
92
110
  stored.revision = next;
93
111
  entity.revision = next;
@@ -138,13 +156,16 @@ import { Effect } from 'effect';
138
156
  // The store keeps its own copy and hands back another, so neither the
139
157
  // caller's instance nor the returned one can change the record without a
140
158
  // second save — which a real adapter guarantees by construction.
141
- return copyOf(entity).pipe(Effect.tap((stored)=>Effect.sync(()=>{
159
+ return copyOf(entity).pipe(Effect.tap((stored)=>Effect.suspend(()=>{
160
+ const clash = clashOf(stored);
161
+ if (clash !== undefined) return Effect.fail(clash);
142
162
  const index = items.findIndex((item)=>item.id === stored.id);
143
163
  if (index === -1) {
144
164
  items.push(stored);
145
165
  } else {
146
166
  items[index] = stored;
147
167
  }
168
+ return Effect.void;
148
169
  })), Effect.flatMap(copyOf));
149
170
  });
150
171
  const remove = (entityOrId, options)=>guard(()=>{
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type {\n EntityRepository,\n EntityWriteOptions,\n RepositoryFailure,\n} from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n declaresRevision,\n deserializeSingleEntity,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n extractMetaEntity,\n isUseCaseAvailable,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n UnavailableInState,\n type UseCaseAvailability,\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 // Relevance scores against the words the filtering asks for.\n request.filtering,\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 /**\n * The revision rule (ADR 0032): a create never overwrites, an update names\n * the revision it read, and a mismatch writes nothing. The decision and the\n * write share one synchronous step, so two saves cannot both pass at one\n * revision — the property the adapters get from one conditional statement.\n */\n const saveRevised = <TEntity extends Entity>(entity: TEntity) => {\n const key = extractMetaEntity(\n entity.constructor as EntityConstructor<TEntity>,\n ).key;\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n return copyOf(entity).pipe(\n Effect.flatMap(stored =>\n Effect.suspend(() => {\n const read = readRevision(entity);\n const index = items.findIndex(item => item.id === stored.id);\n if (read === undefined) {\n if (index !== -1) {\n return Effect.fail(new StaleRevision({ entity: key }));\n }\n } else {\n if (index === -1) return Effect.fail(new NotFound({ entity: key }));\n const current = readRevision(items[index]);\n if (current !== read) {\n return Effect.fail(new StaleRevision({ entity: key, current }));\n }\n }\n const next = (read ?? 0) + 1;\n (stored as { revision?: number }).revision = next;\n (entity as { revision?: number }).revision = next;\n if (index === -1) items.push(stored);\n else items[index] = stored;\n return copyOf(stored);\n }),\n ),\n );\n };\n\n /**\n * The state rule of a conditioned write: the stored record must hold one of\n * `expect`'s states. Checked in the same synchronous step as the write, so\n * nothing can move the record between the two.\n */\n const refusal = (\n stored: Entity,\n expect: UseCaseAvailability,\n ): UnavailableInState | undefined => {\n if (isUseCaseAvailable({ availableWhen: expect }, stored)) return undefined;\n const state = (stored as unknown as Record<string, unknown>)[expect.member];\n return new UnavailableInState({\n entity:\n extractMetaEntity(stored.constructor as EntityConstructor<Entity>)\n .key ?? stored.constructor.name,\n member: expect.member,\n ...(typeof state === 'string' ? { state } : {}),\n allowed: [...expect.in],\n });\n };\n\n const save = <TEntity extends Entity>(\n entity: TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const expect = options?.expect;\n if (expect !== undefined) {\n // A save with `expect` is an update: it never creates.\n const stored = items.find(\n item => entity.id !== undefined && item.id === entity.id,\n );\n if (stored === undefined) return Effect.fail(new NotFound({}));\n const refused = refusal(stored, expect);\n if (refused !== undefined) return Effect.fail(refused);\n }\n return declaresRevision(entity.constructor as EntityConstructor<TEntity>)\n ? saveRevised(entity)\n : storeCopy(entity);\n });\n\n const storeCopy = <TEntity extends Entity>(entity: TEntity) =>\n Effect.suspend(() => {\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>(\n entityOrId: EntityId | TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n const stored = items.find(item => item.id === id);\n const refused =\n stored === undefined || options?.expect === undefined\n ? undefined\n : refusal(stored, options.expect);\n if (refused !== undefined) return Effect.fail(refused);\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","declaresRevision","deserializeSingleEntity","extractMetaAccessors","extractMetaEntity","isUseCaseAvailable","NotFound","readRevision","serializeEntity","StaleRevision","UnavailableInState","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","saveRevised","key","globalThis","crypto","randomUUID","flatMap","stored","suspend","read","index","findIndex","current","next","revision","push","refusal","expect","availableWhen","state","member","name","allowed","in","save","options","refused","storeCopy","tap","sync","remove","entityOrId","filter","delete","failNext","error"],"mappings":";AAKA,SACEA,cAAc,EACdC,YAAY,EACZC,gBAAgB,EAChBC,uBAAuB,EAOvBC,oBAAoB,EACpBC,iBAAiB,EACjBC,kBAAkB,EAClBC,QAAQ,EACRC,YAAY,EACZC,eAAe,EACfC,aAAa,EACbC,kBAAkB,QAEb,gBAAgB;AACvB,SAASC,MAAM,QAAQ,SAAS;AAEhC;;;;;;;;;CASC,GACD,MAAMC,SAAS,CACbC;IAEA,MAAMC,oBAAoBD,OAAO,WAAW;IAC5C,IAAIV,qBAAqBW,mBAAmBC,MAAM,KAAK,GAAG;QACxD,OAAOJ,OAAOK,OAAO,CACnBC,OAAOC,MAAM,CACXD,OAAOE,MAAM,CAACF,OAAOG,cAAc,CAACP,UACpCA;IAGN;IACA,gEAAgE;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MwC,IAAI,CAACR;oBACb,OAAO;wBACLhC,KAAK,CAACmC,MAAM,GAAGH;oBACjB;gBACF,KAEF5C,OAAO2C,OAAO,CAAC1C;QAEnB;IAEF,MAAMkE,SAAS,CACbC,YACAN,UAEAhD,MAAM;YACJ,MAAMoB,KACJkC,cAAc,QAAQ,OAAOA,eAAe,WACxCA,WAAWlC,EAAE,GACbkC;YACN,MAAMxB,SAAShC,MAAMwB,IAAI,CAACC,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YAC9C,MAAM6B,UACJnB,WAAW5B,aAAa8C,CAAAA,2BAAAA,QAASR,MAAM,MAAKtC,YACxCA,YACAqC,QAAQT,QAAQkB,QAAQR,MAAM;YACpC,IAAIS,YAAY/C,WAAW,OAAOhB,OAAOkB,IAAI,CAAC6C;YAC9CnD,QAAQA,MAAMyD,MAAM,CAAChC,CAAAA,OAAQA,KAAKH,EAAE,KAAKA;YACzC,OAAOlC,OAAOK,OAAO,CAACW;QACxB;IAEF,OAAO;QACLG;QACAc;QACA4B;QACAS,QAAQH;QACR,IAAIvD;YACF,OAAOA;QACT;QACAD,MAAM,CAACuC;YACLtC,QAAQ;mBAAIsC;aAAK;QACnB;QACAqB,UAAU,CAACC;YACT3D,iBAAiB2D;QACnB;IAGF;AACF,EAAE"}
1
+ {"version":3,"sources":["../../src/doubles/entity-repository.ts"],"sourcesContent":["import type {\n EntityRepository,\n EntityWriteOptions,\n RepositoryFailure,\n} from '@entifix/business';\nimport {\n applyFiltering,\n applySorting,\n declaresRevision,\n deserializeSingleEntity,\n DuplicateKey,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n type EntityLoadRequest,\n type EntityPage,\n extractMetaAccessors,\n extractMetaEntity,\n isUseCaseAvailable,\n NotFound,\n readRevision,\n serializeEntity,\n StaleRevision,\n UnavailableInState,\n uniqueMembersOf,\n type UseCaseAvailability,\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 // Relevance scores against the words the filtering asks for.\n request.filtering,\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 /**\n * The unique rule (ADR 0034): no other record may hold a value `candidate`\n * holds in a member its entity declares `unique`. An absent value never\n * collides. Called in the same synchronous step as the write it guards.\n */\n const clashOf = (candidate: Entity): DuplicateKey | undefined => {\n const members = uniqueMembersOf(\n candidate.constructor as EntityConstructor<Entity>,\n );\n for (const member of members) {\n const value = (candidate as unknown as Record<string, unknown>)[\n member.name\n ];\n if (value == null) continue;\n const clash = items.some(\n item =>\n item.constructor === candidate.constructor &&\n item.id !== candidate.id &&\n (item as unknown as Record<string, unknown>)[member.name] === value,\n );\n if (clash) return new DuplicateKey({ key: member.key });\n }\n return undefined;\n };\n\n /**\n * The revision rule (ADR 0032): a create never overwrites, an update names\n * the revision it read, and a mismatch writes nothing. The decision and the\n * write share one synchronous step, so two saves cannot both pass at one\n * revision — the property the adapters get from one conditional statement.\n */\n const saveRevised = <TEntity extends Entity>(entity: TEntity) => {\n const key = extractMetaEntity(\n entity.constructor as EntityConstructor<TEntity>,\n ).key;\n entity.id = entity.id ?? globalThis.crypto.randomUUID();\n return copyOf(entity).pipe(\n Effect.flatMap(stored =>\n Effect.suspend(() => {\n const read = readRevision(entity);\n const index = items.findIndex(item => item.id === stored.id);\n if (read === undefined) {\n if (index !== -1) {\n return Effect.fail(new StaleRevision({ entity: key }));\n }\n } else {\n if (index === -1) return Effect.fail(new NotFound({ entity: key }));\n const current = readRevision(items[index]);\n if (current !== read) {\n return Effect.fail(new StaleRevision({ entity: key, current }));\n }\n }\n const clash = clashOf(stored);\n if (clash !== undefined) return Effect.fail(clash);\n const next = (read ?? 0) + 1;\n (stored as { revision?: number }).revision = next;\n (entity as { revision?: number }).revision = next;\n if (index === -1) items.push(stored);\n else items[index] = stored;\n return copyOf(stored);\n }),\n ),\n );\n };\n\n /**\n * The state rule of a conditioned write: the stored record must hold one of\n * `expect`'s states. Checked in the same synchronous step as the write, so\n * nothing can move the record between the two.\n */\n const refusal = (\n stored: Entity,\n expect: UseCaseAvailability,\n ): UnavailableInState | undefined => {\n if (isUseCaseAvailable({ availableWhen: expect }, stored)) return undefined;\n const state = (stored as unknown as Record<string, unknown>)[expect.member];\n return new UnavailableInState({\n entity:\n extractMetaEntity(stored.constructor as EntityConstructor<Entity>)\n .key ?? stored.constructor.name,\n member: expect.member,\n ...(typeof state === 'string' ? { state } : {}),\n allowed: [...expect.in],\n });\n };\n\n const save = <TEntity extends Entity>(\n entity: TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const expect = options?.expect;\n if (expect !== undefined) {\n // A save with `expect` is an update: it never creates.\n const stored = items.find(\n item => entity.id !== undefined && item.id === entity.id,\n );\n if (stored === undefined) return Effect.fail(new NotFound({}));\n const refused = refusal(stored, expect);\n if (refused !== undefined) return Effect.fail(refused);\n }\n return declaresRevision(entity.constructor as EntityConstructor<TEntity>)\n ? saveRevised(entity)\n : storeCopy(entity);\n });\n\n const storeCopy = <TEntity extends Entity>(entity: TEntity) =>\n Effect.suspend(() => {\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.suspend(() => {\n const clash = clashOf(stored);\n if (clash !== undefined) return Effect.fail(clash);\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 return Effect.void;\n }),\n ),\n Effect.flatMap(copyOf),\n );\n });\n\n const remove = <TEntity extends Entity>(\n entityOrId: EntityId | TEntity,\n options?: EntityWriteOptions,\n ) =>\n guard(() => {\n const id =\n entityOrId != null && typeof entityOrId === 'object'\n ? entityOrId.id\n : entityOrId;\n const stored = items.find(item => item.id === id);\n const refused =\n stored === undefined || options?.expect === undefined\n ? undefined\n : refusal(stored, options.expect);\n if (refused !== undefined) return Effect.fail(refused);\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","declaresRevision","deserializeSingleEntity","DuplicateKey","extractMetaAccessors","extractMetaEntity","isUseCaseAvailable","NotFound","readRevision","serializeEntity","StaleRevision","UnavailableInState","uniqueMembersOf","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","clashOf","candidate","members","member","value","name","clash","some","key","saveRevised","globalThis","crypto","randomUUID","flatMap","stored","suspend","read","index","findIndex","current","next","revision","push","refusal","expect","availableWhen","state","allowed","in","save","options","refused","storeCopy","tap","void","remove","entityOrId","filter","delete","failNext","error"],"mapp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WA8lBF,CAAC"}
@@ -295,6 +295,10 @@ const runPipeline = (docs, pipeline)=>pipeline.reduce((current, stage)=>{
295
295
  constructor(collection, key){
296
296
  super(`fake mongo: E11000 duplicate key error collection: ${collection} dup key: ${JSON.stringify(key)}`), this.code = 11000;
297
297
  this.name = 'MongoServerError';
298
+ this.keyPattern = Object.fromEntries(Object.keys(key).map((field)=>[
299
+ field,
300
+ 1
301
+ ]));
298
302
  }
299
303
  };
300
304
  /**
@@ -346,12 +350,12 @@ const runPipeline = (docs, pipeline)=>pipeline.reduce((current, stage)=>{
346
350
  *
347
351
  * `ignored` is the document being replaced by an update, which must not count
348
352
  * as its own duplicate. A key whose value is `undefined` on the candidate is
349
- * skipped: a real index treats a missing field as `null` and would collide,
350
- * but nothing in this repo indexes an optional member, and guessing wrong
351
- * here would fail writes the server accepts.
353
+ * skipped, as is `null`: a unique member is indexed **partially**, over the
354
+ * documents that hold a value (ADR 0034), so an absent value never collides —
355
+ * which is what every unique index in this repo asks for.
352
356
  */ const assertUnique = (name, candidate, ignored)=>{
353
357
  for (const fields of uniqueIndexesOf(name)){
354
- if (fields.some((field)=>candidate[field] === undefined)) continue;
358
+ if (fields.some((field)=>candidate[field] == null)) continue;
355
359
  const clash = documentsOf(name).find((doc)=>doc !== ignored && fields.every((field)=>doc[field] === candidate[field]));
356
360
  if (clash !== undefined) {
357
361
  throw new FakeDuplicateKeyError(name, Object.fromEntries(fields.map((field)=>[
@@ -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 // A relevance score (ADR 0033): a regex test on a field, as `$regexMatch`\n // takes it — an object, not a list of operands.\n if (operator === '$regexMatch') {\n const { input, regex, options } = operand as {\n readonly input: unknown;\n readonly regex: string;\n readonly options?: string;\n };\n const value = evaluateExpression(doc, input);\n return (\n typeof value === 'string' && new RegExp(regex, options ?? '').test(value)\n );\n }\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 as number[]).reduce((sum, value) => sum + value, 0);\n case '$cond':\n return operands[0] === true ? operands[1] : operands[2];\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\n/**\n * Documents in a `{ field: 1 | -1 }` order, the first key deciding, as the\n * server sorts a `find` and a `$sort` stage alike.\n */\nconst sortDocuments = (\n docs: Document[],\n sortSpec: Record<string, number>,\n): Document[] =>\n 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 server does —\n // one locale of a localized member, say.\n compare(valuesAt(left, field)[0], valuesAt(right, field)[0]) *\n direction,\n ),\n docs,\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 // The stages a relevance load sends (ADR 0033): a computed field, the\n // order by it, the page, and the field dropped again.\n case '$addFields':\n return current.map(doc => ({\n ...doc,\n ...Object.fromEntries(\n Object.entries(spec as Document).map(([field, expression]) => [\n field,\n evaluateExpression(doc, expression),\n ]),\n ),\n }));\n case '$sort':\n return sortDocuments(current, spec as Record<string, number>);\n case '$skip':\n return current.slice(spec as number);\n case '$limit':\n return current.slice(0, spec as number);\n case '$project':\n return current.map(doc => {\n const kept = { ...doc };\n for (const [field, include] of Object.entries(spec as Document)) {\n if (include !== 0) {\n throw new TypeError(\n 'fake mongo: $project supports exclusion only',\n );\n }\n delete kept[field];\n }\n return kept;\n });\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 = sortDocuments(matched, sortSpec);\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","input","regex","options","operands","map","child","reduce","sum","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","path","group","_id","key","accumulators","counted","tally","Map","set","get","from","id","count","sortDocuments","sortSpec","reduceRight","items","direction","sort","runPipeline","pipeline","filter","fromEntries","expression","kept","include","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","skipCount","limitCount","Infinity","cursor","skip","limit","toArray","matched","sorted","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,MAAMK,mBAAmB,CAACC,QAAiBC;IACzC,IAAI,CAACb,cAAca,YAAY;QAC7B,OAAOD,WAAWC;IACpB;IAEA,OAAOC,OAAOC,OAAO,CAACF,WAAWG,KAAK,CAAC,CAAC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F,eAAe,IAAML,YAAYvL;YACjC6L,iBAAiB,OAAOC;gBACtB,MAAMX,WAAWF;gBACjB,IAAI;oBACF,OAAO,MAAMa;gBACf,EAAE,OAAOrF,OAAO;oBACdyE,QAAQC;oBACR,MAAM1E;gBACR;YACF;YACAsF,YAAY;gBACVT,OAAO;gBACP,OAAOhF,QAAQE,OAAO;YACxB;YACA,IAAIwF;gBACF,OAAO,CAACV;YACV;QACF;IACF;IAEA,OAAO;QACLvG,MAAM,CAACF,MAAM8C;YACX3C,YAAY3B,GAAG,CACbwB,MACA8C,UAAU7G,GAAG,CAACT,CAAAA,MAAQ,aAAKA;QAE/B;QACA4L,MAAMpH,CAAAA,OAAQa,YAAYb,MAAM/D,GAAG,CAACT,CAAAA,MAAQ,aAAKA;QACjD6L,UAAUzF,CAAAA;YACRtB,UAAUsB;QACZ;QACA0F,QAAQ,CAACC,WAAW3F;YAClBrB,oBAAoB/B,GAAG,CAAC+I,WAAW3F;QACrC;QACA4F,UAAU,CAACD,WAAW3F;YACpBpB,aAAahC,GAAG,CAAC+I,WAAW3F;QAC9B;QACA,IAAIvB;YACF,OAAOA;QACT;QACAmG;QACAiB,IAAI;YAAE3H;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 // A relevance score (ADR 0033): a regex test on a field, as `$regexMatch`\n // takes it — an object, not a list of operands.\n if (operator === '$regexMatch') {\n const { input, regex, options } = operand as {\n readonly input: unknown;\n readonly regex: string;\n readonly options?: string;\n };\n const value = evaluateExpression(doc, input);\n return (\n typeof value === 'string' && new RegExp(regex, options ?? '').test(value)\n );\n }\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 as number[]).reduce((sum, value) => sum + value, 0);\n case '$cond':\n return operands[0] === true ? operands[1] : operands[2];\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\n/**\n * Documents in a `{ field: 1 | -1 }` order, the first key deciding, as the\n * server sorts a `find` and a `$sort` stage alike.\n */\nconst sortDocuments = (\n docs: Document[],\n sortSpec: Record<string, number>,\n): Document[] =>\n 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 server does —\n // one locale of a localized member, say.\n compare(valuesAt(left, field)[0], valuesAt(right, field)[0]) *\n direction,\n ),\n docs,\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 // The stages a relevance load sends (ADR 0033): a computed field, the\n // order by it, the page, and the field dropped again.\n case '$addFields':\n return current.map(doc => ({\n ...doc,\n ...Object.fromEntries(\n Object.entries(spec as Document).map(([field, expression]) => [\n field,\n evaluateExpression(doc, expression),\n ]),\n ),\n }));\n case '$sort':\n return sortDocuments(current, spec as Record<string, number>);\n case '$skip':\n return current.slice(spec as number);\n case '$limit':\n return current.slice(0, spec as number);\n case '$project':\n return current.map(doc => {\n const kept = { ...doc };\n for (const [field, include] of Object.entries(spec as Document)) {\n if (include !== 0) {\n throw new TypeError(\n 'fake mongo: $project supports exclusion only',\n );\n }\n delete kept[field];\n }\n return kept;\n });\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 /** The index's fields, as the server names them, so a caller can tell which index refused. */\n readonly keyPattern: Document;\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 this.keyPattern = Object.fromEntries(\n Object.keys(key).map(field => [field, 1]),\n );\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, as is `null`: a unique member is indexed **partially**, over the\n * documents that hold a value (ADR 0034), so an absent value never collides —\n * which is what every unique index in this repo asks for.\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] == null)) 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 = sortDocuments(matched, sortSpec);\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","input","regex","options","operands","map","child","reduce","sum","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","path","group","_id","key","accumulators","counted","tally","Map","set","get","from","id","count","sortDocuments","sortSpec","reduceRight","items","direction","sort","runPipeline","pipeline","filter","fromEntries","expression","kept","include","output","branch","FakeDuplicateKeyError","Error","collection","code","name","keyPattern","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","skipCount","limitCount","Infinity","cursor","skip","limit","toArray","matched","sorted","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,MAAMK,mBAAmB,CAACC,QAAiBC;IACzC,IAAI,CAACb,cAAca,YAAY;QAC7B,OAAOD,WAAWC;IACpB;IAEA,OAAOC,OAAOC,OAAO,CAACF,WAAWG,KAAK,CAAC,CAAC,CAACC,UAAUC,QAAQ;QACzD,OA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IAAIJ,YAAYxL,WAAW,OAAOyL;gBAClCN,QAAQK;gBACRA,UAAUxL;gBACV,OAAOuG,QAAQE,OAAO;YACxB;YACAoF,eAAe,IAAML,YAAYxL;YACjC8L,iBAAiB,OAAOC;gBACtB,MAAMX,WAAWF;gBACjB,IAAI;oBACF,OAAO,MAAMa;gBACf,EAAE,OAAOrF,OAAO;oBACdyE,QAAQC;oBACR,MAAM1E;gBACR;YACF;YACAsF,YAAY;gBACVT,OAAO;gBACP,OAAOhF,QAAQE,OAAO;YACxB;YACA,IAAIwF;gBACF,OAAO,CAACV;YACV;QACF;IACF;IAEA,OAAO;QACLvG,MAAM,CAACH,MAAM+C;YACX3C,YAAY5B,GAAG,CACbwB,MACA+C,UAAU9G,GAAG,CAACT,CAAAA,MAAQ,aAAKA;QAE/B;QACA6L,MAAMrH,CAAAA,OAAQc,YAAYd,MAAM/D,GAAG,CAACT,CAAAA,MAAQ,aAAKA;QACjD8L,UAAUzF,CAAAA;YACRtB,UAAUsB;QACZ;QACA0F,QAAQ,CAACC,WAAW3F;YAClBrB,oBAAoBhC,GAAG,CAACgJ,WAAW3F;QACrC;QACA4F,UAAU,CAACD,WAAW3F;YACpBpB,aAAajC,GAAG,CAACgJ,WAAW3F;QAC9B;QACA,IAAIvB;YACF,OAAOA;QACT;QACAmG;QACAiB,IAAI;YAAE5H;QAAW;IACnB;AACF,EAAE"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/testing-unit",
3
- "version": "0.23.14",
3
+ "version": "0.23.16",
4
4
  "description": "Test doubles for entifix: in-memory ports, driver fakes for Mongo, Redis, RabbitMQ and SQL, MSW handlers and port contract suites.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -72,9 +72,9 @@
72
72
  },
73
73
  "dependencies": {
74
74
  "@swc/helpers": "0.5.23",
75
- "@entifix/business": "0.23.14",
76
- "@entifix/core": "0.23.14",
77
- "@entifix/transactions": "0.23.14"
75
+ "@entifix/business": "0.23.16",
76
+ "@entifix/core": "0.23.16",
77
+ "@entifix/transactions": "0.23.16"
78
78
  },
79
79
  "peerDependencies": {
80
80
  "@testing-library/react": "*",
@@ -82,7 +82,7 @@
82
82
  "msw": ">=3",
83
83
  "react": "*",
84
84
  "vitest": "*",
85
- "@entifix/react-controls": "0.23.14"
85
+ "@entifix/react-controls": "0.23.16"
86
86
  },
87
87
  "peerDependenciesMeta": {
88
88
  "@entifix/react-controls": {