@cratis/chronicle 6.70.1 → 6.71.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/projections/IProjections.d.ts +27 -1
  2. package/dist/projections/IProjections.d.ts.map +1 -1
  3. package/dist/projections/ProjectionDefinitionCompiler.d.ts +11 -0
  4. package/dist/projections/ProjectionDefinitionCompiler.d.ts.map +1 -1
  5. package/dist/projections/ProjectionDefinitionCompiler.js +42 -18
  6. package/dist/projections/ProjectionDefinitionCompiler.js.map +1 -1
  7. package/dist/projections/Projections.d.ts +9 -0
  8. package/dist/projections/Projections.d.ts.map +1 -1
  9. package/dist/projections/Projections.js +62 -11
  10. package/dist/projections/Projections.js.map +1 -1
  11. package/dist/projections/RuntimeProjectionDefinitions.d.ts +26 -0
  12. package/dist/projections/RuntimeProjectionDefinitions.d.ts.map +1 -0
  13. package/dist/projections/RuntimeProjectionDefinitions.js +55 -0
  14. package/dist/projections/RuntimeProjectionDefinitions.js.map +1 -0
  15. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.d.ts +42 -0
  16. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.d.ts.map +1 -0
  17. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.js +115 -0
  18. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.js.map +1 -0
  19. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.d.ts +20 -0
  20. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.d.ts.map +1 -0
  21. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.js +20 -0
  22. package/dist/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.js.map +1 -0
  23. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts +15 -0
  24. package/dist/testing/projections/ProjectionCountChildrenCapabilities.d.ts.map +1 -0
  25. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js +62 -0
  26. package/dist/testing/projections/ProjectionCountChildrenCapabilities.js.map +1 -0
  27. package/dist/testing/projections/ProjectionRootCapabilities.d.ts.map +1 -1
  28. package/dist/testing/projections/ProjectionRootCapabilities.js +6 -1
  29. package/dist/testing/projections/ProjectionRootCapabilities.js.map +1 -1
  30. package/dist/tsconfig.tsbuildinfo +1 -1
  31. package/package.json +2 -2
  32. package/projections/IProjections.ts +30 -1
  33. package/projections/ProjectionDefinitionCompiler.ts +46 -17
  34. package/projections/Projections.ts +72 -12
  35. package/projections/RuntimeProjectionDefinitions.ts +68 -0
  36. package/projections/for_Projections/given/default_runtime_registration.fixture.ts +53 -0
  37. package/projections/for_Projections/given/runtime_registration.fixture.ts +51 -0
  38. package/projections/for_Projections/when_mixing_runtime_registration_styles.spec.ts +73 -0
  39. package/projections/for_Projections/when_reconnecting_with_runtime_projections.spec.ts +36 -0
  40. package/projections/for_Projections/when_registering_at_runtime.spec.ts +72 -0
  41. package/projections/for_Projections/when_registering_with_the_default_provider.spec.ts +116 -0
  42. package/projections/for_Projections/when_runtime_registration_fails.spec.ts +106 -0
  43. package/testing/for_ReadModelScenario/when_counting_with_children/given/compiled_projection.ts +55 -0
  44. package/testing/for_ReadModelScenario/when_counting_with_children/given/lifecycle.ts +24 -0
  45. package/testing/for_ReadModelScenario/when_counting_with_children/with_a_fluent_projection.spec.ts +94 -0
  46. package/testing/for_ReadModelScenario/when_counting_with_children/with_legacy_decorators.legacy.spec.ts +39 -0
  47. package/testing/for_ReadModelScenario/when_counting_with_children/with_standard_decorators.standard.spec.ts +40 -0
  48. package/testing/projections/ProjectionCountChildrenCapabilities.ts +71 -0
  49. package/testing/projections/ProjectionRootCapabilities.ts +4 -1
  50. package/testing/projections/for_ProjectionCapabilities/when_validating_count_with_children.spec.ts +87 -0
@@ -0,0 +1,106 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { describe, expect, it } from 'vitest';
5
+ import { Added, BoundModel, defineRuntime, RuntimeModel, runtime_registration } from './given/runtime_registration.fixture.js';
6
+
7
+ function expectNotRetained(context: ReturnType<typeof runtime_registration>): void {
8
+ expect(context.projections.hasFor('runtime-model')).toBe(false);
9
+ expect(context.projections.hasForModel(RuntimeModel)).toBe(false);
10
+ expect(() => context.projections.getProjectionIdFor(RuntimeModel)).toThrow('No projection found for read model');
11
+ }
12
+
13
+ describe('when runtime registration conflicts with discovery', () => {
14
+ it('should reject a runtime identifier already used by a discovered model-bound projection', async () => {
15
+ const context = runtime_registration();
16
+ context.artifacts.readModels.push(BoundModel);
17
+ await expect(context.projections.registerFor(RuntimeModel, defineRuntime, 'BoundModel')).rejects.toThrow("Projection id 'BoundModel' is already discovered");
18
+ expect(context.registerReadModel).not.toHaveBeenCalled();
19
+ expect(context.registerProjection).not.toHaveBeenCalled();
20
+ });
21
+
22
+ it('should reject a discovery refresh that tries to overwrite a runtime identifier', async () => {
23
+ const context = runtime_registration();
24
+ await context.projections.registerFor(RuntimeModel, defineRuntime, 'BoundModel');
25
+ context.artifacts.readModels.push(BoundModel);
26
+ await expect(context.projections.discover()).rejects.toThrow("Projection id 'BoundModel' is already registered at runtime");
27
+ expect(context.projections.getProjectionIdFor(RuntimeModel).value).toBe('BoundModel');
28
+ });
29
+ });
30
+
31
+ describe('when runtime identifiers conflict', () => {
32
+ it('should reject a second registration without replacing the retained definition', async () => {
33
+ const context = runtime_registration();
34
+ await context.projections.registerFor(RuntimeModel, defineRuntime);
35
+ await expect(context.projections.registerFor(RuntimeModel, builder => builder.passive())).rejects.toThrow('already registered at runtime');
36
+ await context.projections.register();
37
+ expect(context.registerProjection).toHaveBeenCalledTimes(2);
38
+ expect(context.registerProjection.mock.calls[1][0]).toEqual(context.registerProjection.mock.calls[0][0]);
39
+ });
40
+
41
+ it('should reserve in-flight identifiers and release them on failure', async () => {
42
+ const context = runtime_registration();
43
+ let rejectRegistration!: (error: Error) => void;
44
+ let started!: () => void;
45
+ const pending = new Promise<void>(resolve => { started = resolve; });
46
+ context.registerProjection.mockImplementationOnce(() => {
47
+ started();
48
+ return new Promise((_resolve, reject) => { rejectRegistration = reject; });
49
+ });
50
+ const registration = context.projections.registerFor(RuntimeModel, defineRuntime).catch(error => error);
51
+ await pending;
52
+ expectNotRetained(context);
53
+ await expect(context.projections.registerFor(RuntimeModel, defineRuntime)).rejects.toThrow('already registered at runtime');
54
+ rejectRegistration(new Error('Rejected declaration'));
55
+ expect(await registration).toBeInstanceOf(Error);
56
+ await context.projections.registerFor(RuntimeModel, defineRuntime);
57
+ expect(context.projections.hasForModel(RuntimeModel)).toBe(true);
58
+ });
59
+
60
+ it('should refuse a second projection for the same read model', async () => {
61
+ const context = runtime_registration();
62
+ await context.projections.registerFor(RuntimeModel, defineRuntime);
63
+ await expect(context.projections.registerFor(RuntimeModel, defineRuntime, 'another')).rejects.toThrow('already has a projection');
64
+ expect(context.registerProjection).toHaveBeenCalledTimes(1);
65
+ });
66
+ });
67
+
68
+ describe('when the kernel rejects runtime registration', () => {
69
+ it('should surface the failure without retaining a definition, and allow a later retry', async () => {
70
+ const context = runtime_registration();
71
+ context.registerProjection.mockRejectedValueOnce(new Error('Invalid declaration'));
72
+ await expect(context.projections.registerFor(RuntimeModel, defineRuntime)).rejects.toThrow('Invalid declaration');
73
+ expectNotRetained(context);
74
+ await context.projections.register();
75
+ expect(context.registerProjection).toHaveBeenCalledTimes(1);
76
+ await context.projections.registerFor(RuntimeModel, defineRuntime);
77
+ expect(context.projections.hasForModel(RuntimeModel)).toBe(true);
78
+ });
79
+
80
+ it('should not retain anything when read model registration fails', async () => {
81
+ const context = runtime_registration();
82
+ context.registerReadModel.mockRejectedValueOnce(new Error('Invalid schema'));
83
+ await expect(context.projections.registerFor(RuntimeModel, defineRuntime)).rejects.toThrow('Invalid schema');
84
+ expectNotRetained(context);
85
+ expect(context.registerProjection).not.toHaveBeenCalled();
86
+ });
87
+ });
88
+
89
+ describe('when validating an explicit runtime projection', () => {
90
+ it('should surface existing builder validation before contacting the kernel', async () => {
91
+ const context = runtime_registration();
92
+ await expect(context.projections.registerFor(RuntimeModel, builder => {
93
+ builder.from(Added, from => from.usingKeyFromContext('unknownContextProperty'));
94
+ })).rejects.toThrow('unknownContextProperty');
95
+ expectNotRetained(context);
96
+ expect(context.registerReadModel).not.toHaveBeenCalled();
97
+ expect(context.registerProjection).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('should refuse a type without model-bound decorators', async () => {
101
+ const context = runtime_registration();
102
+ await expect(context.projections.registerModelBound(RuntimeModel)).rejects.toThrow('has no model-bound projection');
103
+ expectNotRetained(context);
104
+ expect(context.registerReadModel).not.toHaveBeenCalled();
105
+ });
106
+ });
@@ -0,0 +1,55 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field } from '@cratis/fundamentals';
5
+ import type { IClientArtifactsProvider } from '../../../../artifacts/IClientArtifactsProvider.js';
6
+ import { eventType } from '../../../../events/eventTypeDecorator.js';
7
+ import type { IProjectionBuilderFor } from '../../../../projections/declarative/IProjectionBuilderFor.js';
8
+ import { projection } from '../../../../projections/declarative/projection.js';
9
+ import { ProjectionDefinitionCompiler } from '../../../../projections/ProjectionDefinitionCompiler.js';
10
+
11
+ @eventType('Counted')
12
+ export class Counted {
13
+ @field(Number) readonly total: number;
14
+ constructor(total: number) { this.total = total; }
15
+ }
16
+ @eventType('ItemChanged')
17
+ export class ItemChanged {
18
+ @field(String) readonly itemId: string;
19
+ @field(String) readonly name: string;
20
+ constructor(itemId: string, name: string) { this.itemId = itemId; this.name = name; }
21
+ }
22
+ @eventType('ItemRemoved')
23
+ export class ItemRemoved {
24
+ @field(String) readonly itemId: string;
25
+ constructor(itemId: string) { this.itemId = itemId; }
26
+ }
27
+ @eventType('Removed')
28
+ export class Removed {}
29
+ export class Item {
30
+ @field(String) itemId!: string;
31
+ @field(String) name!: string;
32
+ }
33
+ export class Totals {
34
+ @field(String) id!: string;
35
+ @field(Number) total!: number;
36
+ @field(Array, { genericArguments: [Item] }) items!: Item[];
37
+ }
38
+ @projection('count-children', Totals)
39
+ export class TotalsProjection {
40
+ define(builder: IProjectionBuilderFor<Totals>): void {
41
+ builder.from(Counted, from => from.count(model => model.total))
42
+ .children<Item>(model => model.items, child => child.identifiedBy(item => item.itemId)
43
+ .from(ItemChanged, from => from.usingKey(event => event.itemId))
44
+ .removedWith(ItemRemoved, removal => removal.usingKey(event => event.itemId)))
45
+ .removedWith(Removed);
46
+ }
47
+ }
48
+ export const artifacts = {
49
+ readModels: [Totals], projections: [TotalsProjection], eventTypes: [Counted, ItemChanged, ItemRemoved, Removed],
50
+ globalForHandlers: [], reducers: [], reactors: [], seeders: [], constraints: [], webhooks: [], eventTypeMigrations: []
51
+ } satisfies IClientArtifactsProvider;
52
+
53
+ export function compile() {
54
+ return new ProjectionDefinitionCompiler(artifacts, 'test').compile([TotalsProjection], []);
55
+ }
@@ -0,0 +1,24 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ReadModelScenario } from '../../../ReadModelScenario.js';
5
+ import { Counted, ItemChanged, ItemRemoved, Removed } from './compiled_projection.js';
6
+
7
+ type CountedParent = { id: string; total: number; items: Array<{ itemId: string; name: string }> };
8
+
9
+ export async function lifecycle<T extends CountedParent>(scenario: ReadModelScenario<T>) {
10
+ scenario.given.forEventSource('A').events(new Counted(9000), new Counted(8000));
11
+ scenario.given.forEventSource('A').events(new ItemChanged('one', 'first'), new ItemChanged('two', 'second'), new ItemChanged('one', 'updated'), new Counted(7000));
12
+ scenario.given.forEventSource('B').events(new Counted(6000), new ItemChanged('one', 'independent'));
13
+ const first = (await scenario.instanceForEventSourceId('A'))!;
14
+ const other = (await scenario.instanceForEventSourceId('B'))!;
15
+ scenario.given.forEventSource('A').events(new ItemRemoved('one'), new ItemRemoved('unknown'));
16
+ const remaining = (await scenario.instanceForEventSourceId('A'))!;
17
+ scenario.given.forEventSource('A').events(new Removed());
18
+ const removed = await scenario.instanceForEventSourceId('A');
19
+ const surviving = (await scenario.instanceForEventSourceId('B'))!;
20
+ scenario.given.forEventSource('A').events(new Counted(5000), new ItemChanged('new', 'recreated'));
21
+ const recreated = (await scenario.instanceForEventSourceId('A'))!;
22
+ const repeated = (await scenario.instanceForEventSourceId('A'))!;
23
+ return { first, other, remaining, removed, surviving, recreated, repeated };
24
+ }
@@ -0,0 +1,94 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { readFileSync } from 'node:fs';
5
+ import { beforeAll, chai, describe, it } from 'vitest';
6
+ import type { JsonSchema } from '../../../schemas/JsonSchema.js';
7
+ import type { IProjectionBuilderFor } from '../../../projections/declarative/IProjectionBuilderFor.js';
8
+ import { projection } from '../../../projections/declarative/projection.js';
9
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
10
+ import { artifacts, compile, Counted, Item, ItemChanged, ItemRemoved, Removed, Totals } from './given/compiled_projection.js';
11
+ import { lifecycle } from './given/lifecycle.js';
12
+
13
+ chai.should();
14
+
15
+ class MappedProjection {
16
+ define(builder: IProjectionBuilderFor<Totals>): void {
17
+ builder.from(Counted)
18
+ .children<Item>(model => model.items, child => child.identifiedBy(item => item.itemId)
19
+ .from(ItemChanged, from => from.usingKey(event => event.itemId))
20
+ .removedWith(ItemRemoved, removal => removal.usingKey(event => event.itemId)))
21
+ .removedWith(Removed);
22
+ }
23
+ }
24
+ projection('mapped-children', Totals)(MappedProjection);
25
+
26
+ describe('when compiling a root count with typed children', () => {
27
+ let wire: ReturnType<typeof compile>['definitions'][number];
28
+ let schema: JsonSchema;
29
+ beforeAll(() => {
30
+ const compiled = compile();
31
+ wire = compiled.definitions[0];
32
+ schema = JSON.parse(compiled.readModels[0].Schema);
33
+ });
34
+ for (const name of ['count-children-root-first.json', 'count-children-child-first.json']) {
35
+ it(`should match the real compiler wire and schemas in ${name}`, () => {
36
+ const fixture = JSON.parse(readFileSync(new URL(`../../projections/fixtures/${name}`, import.meta.url), 'utf8'));
37
+ const compiled = compile();
38
+ const definition = compiled.definitions[0];
39
+ // Only the oracle input omits registration metadata; client output retains it.
40
+ const { LastUpdated, ...emittedFields } = JSON.parse(JSON.stringify(definition));
41
+ LastUpdated.should.deep.equal(fixture.compilerLastUpdated);
42
+ Object.hasOwn(fixture.wireDefinition, 'LastUpdated').should.be.false;
43
+ const oracleFields = Object.hasOwn(emittedFields, 'NoAutoMapProperties')
44
+ ? emittedFields : { ...emittedFields, NoAutoMapProperties: [] };
45
+ oracleFields.should.deep.equal(fixture.wireDefinition);
46
+ definition.LastUpdated!.should.deep.equal(fixture.compilerLastUpdated);
47
+ JSON.parse(compiled.readModels[0].Schema).should.deep.equal(fixture.readModel.schema);
48
+ const emittedSchemas = [...compiled.eventSchemas.get(definition)!.values()];
49
+ const oracleSchemas = emittedSchemas.map(({ eventType, ...fields }) => {
50
+ // The kernel EventType constructor defaults only a false tombstone flag.
51
+ const { Tombstone, ...header } = eventType;
52
+ Tombstone.should.be.false;
53
+ return { ...fields, eventType: header };
54
+ });
55
+ oracleSchemas.should.deep.equal(fixture.eventSchemas);
56
+ emittedSchemas.every(entry => Object.hasOwn(entry.eventType, 'Tombstone') && entry.eventType.Tombstone === false).should.be.true;
57
+ });
58
+ }
59
+
60
+ it('should admit count with children through the ordinary public constructor', () => {
61
+ (() => new ReadModelScenario(Totals, artifacts)).should.not.throw();
62
+ });
63
+
64
+ it('should preserve the existing non-arithmetic child-before-parent placeholder path', async () => {
65
+ const ordinary = new ReadModelScenario(Totals, { ...artifacts, projections: [MappedProjection] });
66
+ ordinary.given.forEventSource('A').events(new ItemChanged('one', 'first'), new ItemChanged('one', 'updated'));
67
+ (await ordinary.instance)!.items.should.deep.equal([{ itemId: 'one', name: 'updated' }]);
68
+ ordinary.given.forEventSource('A').events(new Counted(9000));
69
+ (await ordinary.instance)!.items.should.deep.equal([{ itemId: 'one', name: 'updated' }]);
70
+ (await ordinary.instance)!.total.should.equal(9000);
71
+ });
72
+
73
+ it('should compile one root count subscription', () => wire.From[0].Value.Properties.should.deep.equal({ total: '$count' }));
74
+ it('should compile an explicitly typed child collection', () => schema.properties!.items.should.deep.equal({
75
+ type: 'array', items: {
76
+ $schema: 'https://json-schema.org/draft/2020-12/schema', title: 'Item', type: 'object',
77
+ properties: { itemId: { type: 'string' }, name: { type: 'string' } },
78
+ required: ['itemId', 'name'], additionalProperties: false
79
+ }
80
+ }));
81
+ });
82
+
83
+ describe('when counting a parent with fluent children and no initial values', () => {
84
+ let result: Awaited<ReturnType<typeof lifecycle<Totals>>>;
85
+ beforeAll(async () => { result = await lifecycle(new ReadModelScenario(Totals, artifacts)); });
86
+ it('should count root events without assigning their same-named payload', () => result.first.total.should.equal(3));
87
+ it('should update children without changing the root count', () => result.first.items.should.deep.equal([
88
+ { itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }
89
+ ]));
90
+ it('should remove only the matching child and ignore unknown children', () => result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]));
91
+ it('should leave the other parent independent', () => [result.other.total, result.surviving.id, result.removed].should.deep.equal([1, 'B', null]));
92
+ it('should discard old children and count on root recreation', () => [result.recreated.total, result.recreated.items].should.deep.equal([1, [{ itemId: 'new', name: 'recreated' }]]));
93
+ it('should not count an unchanged repeated read twice', () => result.repeated.should.deep.equal(result.recreated));
94
+ });
@@ -0,0 +1,39 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field } from '@cratis/fundamentals';
5
+ import { beforeAll, chai, describe, it } from 'vitest';
6
+ import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
7
+ import { count } from '../../../projections/modelBound/count.js';
8
+ import { removedWith } from '../../../projections/modelBound/removedWith.js';
9
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
10
+ import { Counted, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
11
+ import { lifecycle } from './given/lifecycle.js';
12
+
13
+ chai.should();
14
+ @removedWith(ItemRemoved, 'itemId')
15
+ class Item {
16
+ @field(String) itemId!: string;
17
+ @field(String) name!: string;
18
+ }
19
+ @removedWith(Removed)
20
+ class Totals {
21
+ @field(String) id!: string;
22
+ @field(Number) @count(Counted) total!: number;
23
+ @field(Array) @childrenFrom(ItemChanged, { childType: Item, key: 'itemId', identifiedBy: 'itemId' })
24
+ items!: Item[];
25
+ }
26
+ const artifacts = { eventTypes: [Counted, ItemChanged, ItemRemoved, Removed], readModels: [Totals], reducers: [], projections: [] };
27
+
28
+ describe('when counting a parent with legacy-decorator children and no initial values', () => {
29
+ let result: Awaited<ReturnType<typeof lifecycle<Totals>>>;
30
+ beforeAll(async () => { result = await lifecycle(new ReadModelScenario(Totals, artifacts)); });
31
+ it('should count root events without assigning their same-named payload', () => result.first.total.should.equal(3));
32
+ it('should update children without changing the root count', () => result.first.items.should.deep.equal([
33
+ { itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }
34
+ ]));
35
+ it('should remove only the matching child and ignore unknown children', () => result.remaining.items.should.deep.equal([{ itemId: 'two', name: 'second' }]));
36
+ it('should leave the other parent independent', () => [result.other.total, result.surviving.id, result.removed].should.deep.equal([1, 'B', null]));
37
+ it('should discard old children and count on root recreation', () => [result.recreated.total, result.recreated.items].should.deep.equal([1, [{ itemId: 'new', name: 'recreated' }]]));
38
+ it('should not count an unchanged repeated read twice', () => result.repeated.should.deep.equal(result.recreated));
39
+ });
@@ -0,0 +1,40 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import { field } from '@cratis/fundamentals';
5
+ import { beforeAll, chai, describe, it, type Assertion } from 'vitest';
6
+ import { childrenFrom } from '../../../projections/modelBound/childrenFrom.js';
7
+ import { count } from '../../../projections/modelBound/count.js';
8
+ import { removedWith } from '../../../projections/modelBound/removedWith.js';
9
+ import { ReadModelScenario } from '../../ReadModelScenario.js';
10
+ import { Counted, ItemChanged, ItemRemoved, Removed } from './given/compiled_projection.js';
11
+ import { lifecycle } from './given/lifecycle.js';
12
+
13
+ chai.should();
14
+ function should(value: unknown): Assertion { return (value as { should: Assertion }).should; }
15
+ @removedWith(ItemRemoved, 'itemId')
16
+ class Item {
17
+ @field(String) itemId!: string;
18
+ @field(String) name!: string;
19
+ }
20
+ @removedWith(Removed)
21
+ class Totals {
22
+ @field(String) id!: string;
23
+ @field(Number) @count(Counted) total!: number;
24
+ @field(Array, { genericArguments: [Item] }) @childrenFrom(ItemChanged, { key: 'itemId', identifiedBy: 'itemId' })
25
+ items!: Item[];
26
+ }
27
+ const artifacts = { eventTypes: [Counted, ItemChanged, ItemRemoved, Removed], readModels: [Totals], reducers: [], projections: [] };
28
+
29
+ describe('when counting a parent with standard-decorator children and no initial values', () => {
30
+ let result: Awaited<ReturnType<typeof lifecycle<Totals>>>;
31
+ beforeAll(async () => { result = await lifecycle(new ReadModelScenario(Totals, artifacts)); });
32
+ it('should count root events without assigning their same-named payload', () => should(result.first.total).equal(3));
33
+ it('should update children without changing the root count', () => should(result.first.items).deep.equal([
34
+ { itemId: 'one', name: 'updated' }, { itemId: 'two', name: 'second' }
35
+ ]));
36
+ it('should remove only the matching child and ignore unknown children', () => should(result.remaining.items).deep.equal([{ itemId: 'two', name: 'second' }]));
37
+ it('should leave the other parent independent', () => should([result.other.total, result.surviving.id, result.removed]).deep.equal([1, 'B', null]));
38
+ it('should discard old children and count on root recreation', () => should([result.recreated.total, result.recreated.items]).deep.equal([1, [{ itemId: 'new', name: 'recreated' }]]));
39
+ it('should not count an unchanged repeated read twice', () => should(result.repeated).deep.equal(result.recreated));
40
+ });
@@ -0,0 +1,71 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ChildrenDefinition } from '@cratis/chronicle.contracts';
5
+ import type { FromRecord, RemovedWithRecord } from '../../projections/declarative/ProjectionBuilderCore.js';
6
+ import type { JsonSchema } from '../../schemas/JsonSchema.js';
7
+
8
+ /** The measured intersection of root counting and independent typed children. */
9
+ export class ProjectionCountChildrenCapabilities {
10
+ static supports(schema: JsonSchema, wire: Record<string, unknown>): boolean {
11
+ const from = wire.From as FromRecord[] ?? [];
12
+ const children = Object.entries(wire.Children as Record<string, ChildrenDefinition> ?? {});
13
+ if (!this.singleCount(from) || children.length !== 1) return false;
14
+ const [collection, child] = children[0];
15
+ const count = Object.keys(from[0].Value.Properties)[0];
16
+ return this.rootShape(schema, count, collection)
17
+ && this.childShape(schema.properties?.[collection], child)
18
+ && this.independentEvents(from, wire, child) && this.noInteractions(wire);
19
+ }
20
+
21
+ private static singleCount(from: FromRecord[]): boolean {
22
+ if (from.length !== 1) return false;
23
+ const expressions = Object.values(from[0].Value.Properties ?? {});
24
+ return expressions.length === 1 && expressions[0] === '$count';
25
+ }
26
+
27
+ private static rootShape(schema: JsonSchema, count: string, collection: string): boolean {
28
+ const properties = schema.properties ?? {};
29
+ return this.exactRootMembers(properties, count, collection)
30
+ && this.plainString(properties.id) && this.countTarget(properties[count]);
31
+ }
32
+
33
+ private static exactRootMembers(properties: Record<string, JsonSchema>, count: string, collection: string): boolean {
34
+ const allowed = new Set(['id', count, collection]);
35
+ const names = Object.keys(properties);
36
+ return allowed.size === 3 && names.length === 3 && names.every(property => allowed.has(property));
37
+ }
38
+
39
+ private static countTarget(schema?: JsonSchema): boolean {
40
+ return schema?.type === 'number' && [undefined, '', 'double'].includes(schema.format);
41
+ }
42
+
43
+ private static plainString(schema?: JsonSchema): boolean {
44
+ return schema?.type === 'string' && !schema.format;
45
+ }
46
+
47
+ private static childShape(collection: JsonSchema | undefined, child: ChildrenDefinition): boolean {
48
+ return collection?.type === 'array' && this.stringItems(collection.items, child.IdentifiedBy)
49
+ && child.From.length > 0 && child.Join.length === 0;
50
+ }
51
+
52
+ private static stringItems(items: JsonSchema | undefined, identifier: string): boolean {
53
+ if (items?.type !== 'object' || !items.properties) return false;
54
+ return this.plainString(items.properties[identifier])
55
+ && Object.values(items.properties).every(property => this.plainString(property));
56
+ }
57
+
58
+ private static independentEvents(from: FromRecord[], wire: Record<string, unknown>, child: ChildrenDefinition): boolean {
59
+ const removals = wire.RemovedWith as RemovedWithRecord[] ?? [];
60
+ const rootEvents = new Set([...from, ...removals].map(entry => entry.Key.Id));
61
+ return [...child.From, ...child.RemovedWith].every(entry => {
62
+ if (!entry.Key) return false;
63
+ return !rootEvents.has(entry.Key.Id);
64
+ });
65
+ }
66
+
67
+ private static noInteractions(wire: Record<string, unknown>): boolean {
68
+ return (wire.InitialModelState ?? '{}') === '{}'
69
+ && (wire.Join as unknown[] ?? []).length === 0;
70
+ }
71
+ }
@@ -6,6 +6,7 @@ import type { FromRecord, RemovedWithRecord } from '../../projections/declarativ
6
6
  import { eventContractPath } from '../../projections/eventContractPath.js';
7
7
  import type { JsonSchema } from '../../schemas/JsonSchema.js';
8
8
  import { ProjectionArithmetic } from './ProjectionArithmetic.js';
9
+ import { ProjectionCountChildrenCapabilities } from './ProjectionCountChildrenCapabilities.js';
9
10
  import type { ProjectionCapabilityReject } from './ProjectionCapabilityReject.js';
10
11
  import type { ProjectionEventSchemaResolver } from './ProjectionEventSchemaResolver.js';
11
12
  import { ProjectionMappingCapabilities } from './ProjectionMappingCapabilities.js';
@@ -39,7 +40,9 @@ export class ProjectionRootCapabilities {
39
40
  }
40
41
 
41
42
  private checkAccumulatorChildren(accumulators: Set<string>): void {
42
- if (accumulators.size && Object.keys(this.wire.Children as object ?? {}).length) {
43
+ if (!accumulators.size) return;
44
+ if (!Object.keys(this.wire.Children as object ?? {}).length) return;
45
+ if (!ProjectionCountChildrenCapabilities.supports(this.schema, this.wire)) {
43
46
  this.reject('Children', 'root arithmetic combined with children requires a kernel-backed test');
44
47
  }
45
48
  }
@@ -0,0 +1,87 @@
1
+ // Copyright (c) Cratis. All rights reserved.
2
+ // Licensed under the MIT license. See LICENSE file in the project root for full license information.
3
+
4
+ import type { ProjectionDefinition } from '@cratis/chronicle.contracts';
5
+ import { EventType } from '../../../events/EventType.js';
6
+ import { beforeEach, chai, describe, it } from 'vitest';
7
+ import type { JsonSchema } from '../../../schemas/JsonSchema.js';
8
+ import { compile, Totals } from '../../for_ReadModelScenario/when_counting_with_children/given/compiled_projection.js';
9
+ import type { ScenarioEvent } from '../../ScenarioEvent.js';
10
+ import { ProjectionReadModelProcessor } from '../ProjectionReadModelProcessor.js';
11
+ import { UnsupportedProjectionOperation } from '../UnsupportedProjectionOperation.js';
12
+
13
+ chai.should();
14
+
15
+ type Candidate = { compiled: ReturnType<typeof compile>; definition: ProjectionDefinition; schema: JsonSchema };
16
+ type Mutation = (candidate: Candidate) => void;
17
+ const boundaries: Array<[string, Mutation]> = [
18
+ ...['$increment', '$decrement', '$add(total)', '$subtract(total)'].map(expression => [expression,
19
+ ({ definition }: Candidate) => { definition.From[0].Value.Properties.total = expression; }] as [string, Mutation]),
20
+ ['int32 count', ({ schema }) => { schema.properties!.total = { type: 'integer', format: 'int32' }; }],
21
+ ['float count', ({ schema }) => { schema.properties!.total = { type: 'number', format: 'float' }; }],
22
+ ['GUID root identifier', ({ schema }) => { schema.properties!.id.format = 'uuid'; }],
23
+ ['numeric root identifier', ({ schema }) => { schema.properties!.id = { type: 'number' }; }],
24
+ ['extra root property', ({ schema }) => { schema.properties!.name = { type: 'string' }; }],
25
+ ['extra root mapping', ({ definition }) => { definition.From[0].Value.Properties.id = '$eventSourceId'; }],
26
+ ['multiple root subscriptions', ({ definition }) => { definition.From.push(structuredClone(definition.From[0])); }],
27
+ ['initial values', ({ definition }) => { definition.InitialModelState = '{"total":0}'; }],
28
+ ['root join', ({ definition }) => { definition.Join.push({ Key: definition.From[0].Key, Value: { On: 'id', Properties: {}, Key: '$eventSourceId' } }); }],
29
+ ['multiple child collections', ({ definition }) => { definition.Children.other = structuredClone(definition.Children.items); }],
30
+ ['untyped children', ({ schema }) => { delete schema.properties!.items.items!.properties; }],
31
+ ['numeric child property', ({ schema }) => { schema.properties!.items.items!.properties!.name = { type: 'number' }; }],
32
+ ['formatted child property', ({ schema }) => { schema.properties!.items.items!.properties!.name.format = 'uuid'; }],
33
+ ['numeric child identifier', ({ schema }) => { schema.properties!.items.items!.properties!.itemId = { type: 'number' }; }],
34
+ ['missing child identifier', ({ schema }) => { delete schema.properties!.items.items!.properties!.itemId; }],
35
+ ['child without From', ({ definition }) => { definition.Children.items.From = []; }],
36
+ ['child From without event Key', ({ definition }) => { delete definition.Children.items.From[0].Key; }],
37
+ ['child removal without event Key', ({ definition }) => { delete definition.Children.items.RemovedWith[0].Key; }],
38
+ ['shared root and child From', ({ definition }) => { definition.Children.items.From[0].Key = definition.From[0].Key; }],
39
+ ['shared root From and child removal', ({ definition }) => { definition.Children.items.RemovedWith[0].Key = definition.From[0].Key; }],
40
+ ['shared root removal and child From', ({ definition }) => { definition.Children.items.From[0].Key = definition.RemovedWith[0].Key; }],
41
+ ['shared root and child removal', ({ definition }) => { definition.Children.items.RemovedWith[0].Key = definition.RemovedWith[0].Key; }],
42
+ ['custom root key', ({ definition }) => { definition.From[0].Value.Key = 'total'; }],
43
+ ['custom child parent key', ({ definition }) => { definition.Children.items.From[0].Value.ParentKey = 'itemId'; }]
44
+ ];
45
+
46
+ function candidate(): Candidate {
47
+ const compiled = compile();
48
+ return { compiled, definition: compiled.definitions[0], schema: JSON.parse(compiled.readModels[0].Schema) };
49
+ }
50
+
51
+ // A constructor failure must precede processing even when events are supplied.
52
+ const seeded: ScenarioEvent = {
53
+ sourceId: 'A', content: { total: 9000 },
54
+ context: {
55
+ eventSourceId: 'A', eventType: new EventType('Counted', 1), sequenceNumber: 0n,
56
+ occurred: new Date('2025-01-01T00:00:00Z'), correlationId: '00000000-0000-0000-0000-000000000000',
57
+ causation: [], tags: []
58
+ }
59
+ };
60
+ const histories: Array<[string, ScenarioEvent[]]> = [['empty', []], ['seeded', [seeded]]];
61
+ for (const [name, mutate] of boundaries) {
62
+ for (const [historyName, history] of histories) {
63
+ describe(`when rejecting count with children: ${name}, ${historyName} history`, () => {
64
+ let act: () => Promise<unknown>;
65
+ beforeEach(() => {
66
+ const value = candidate();
67
+ mutate(value);
68
+ value.compiled.readModels[0].Schema = JSON.stringify(value.schema);
69
+ act = () => new ProjectionReadModelProcessor(Totals, value.compiled, value.definition).process(history);
70
+ });
71
+ it('should reject before replay', () => act.should.throw(UnsupportedProjectionOperation));
72
+ });
73
+ }
74
+ }
75
+
76
+ for (const format of [undefined, 'double']) {
77
+ describe(`when admitting count with ${format ?? 'unformatted number'} and typed children`, () => {
78
+ let act: () => ProjectionReadModelProcessor<Totals>;
79
+ beforeEach(() => {
80
+ const value = candidate();
81
+ value.schema.properties!.total.format = format;
82
+ value.compiled.readModels[0].Schema = JSON.stringify(value.schema);
83
+ act = () => new ProjectionReadModelProcessor(Totals, value.compiled, value.definition);
84
+ });
85
+ it('should admit the empty-history constructor', () => act.should.not.throw());
86
+ });
87
+ }