@cratis/chronicle 6.67.2 → 6.67.4

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 (35) hide show
  1. package/dist/testing/EventScenario.d.ts.map +1 -1
  2. package/dist/testing/EventScenario.js +102 -51
  3. package/dist/testing/EventScenario.js.map +1 -1
  4. package/dist/testing/InProcessConstraints.d.ts +2 -1
  5. package/dist/testing/InProcessConstraints.d.ts.map +1 -1
  6. package/dist/testing/InProcessConstraints.js +8 -4
  7. package/dist/testing/InProcessConstraints.js.map +1 -1
  8. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  9. package/dist/testing/InProcessEventSequence.js +4 -2
  10. package/dist/testing/InProcessEventSequence.js.map +1 -1
  11. package/dist/testing/PropertyDefinitionSupport.d.ts +5 -0
  12. package/dist/testing/PropertyDefinitionSupport.d.ts.map +1 -0
  13. package/dist/testing/PropertyDefinitionSupport.js +37 -0
  14. package/dist/testing/PropertyDefinitionSupport.js.map +1 -0
  15. package/dist/tsconfig.tsbuildinfo +1 -1
  16. package/package.json +1 -1
  17. package/testing/EventScenario.constraint-composite.spec.ts +1 -1
  18. package/testing/EventScenario.constraint-cycles.spec.ts +1 -1
  19. package/testing/EventScenario.fixtures.spec.ts +2 -1
  20. package/testing/EventScenario.ts +119 -59
  21. package/testing/InProcessConstraints.ts +7 -4
  22. package/testing/InProcessEventSequence.ts +5 -2
  23. package/testing/PropertyDefinitionSupport.ts +36 -0
  24. package/testing/for_EventScenario/when_appending_event_sequence_constraints/event_sequence_scenario_behaviors.fixture.ts +1 -1
  25. package/testing/for_EventScenario/when_appending_event_sequence_constraints/with_legacy_decorators.legacy.spec.ts +7 -3
  26. package/testing/for_EventScenario/when_appending_event_sequence_constraints/with_standard_decorators.standard.spec.ts +7 -3
  27. package/testing/for_EventScenario/when_appending_field_combinations/combination_behaviors.fixture.ts +122 -0
  28. package/testing/for_EventScenario/when_appending_field_combinations/definition_rejection_behaviors.fixture.ts +116 -0
  29. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap.legacy.spec.ts +36 -0
  30. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap.standard.spec.ts +35 -0
  31. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap_behaviors.fixture.ts +193 -0
  32. package/testing/for_EventScenario/when_appending_field_combinations/with_legacy_decorators.legacy.spec.ts +35 -0
  33. package/testing/for_EventScenario/when_appending_field_combinations/with_standard_decorators.standard.spec.ts +34 -0
  34. package/testing/for_EventScenario/when_appending_field_types/with_unproven_schemas.legacy.spec.ts +2 -4
  35. package/testing/for_EventScenario/when_appending_scoped_constraints/with_unproven_operations.spec.ts +1 -1
@@ -104,12 +104,15 @@ export class InProcessEventSequence implements IEventSequence {
104
104
  if (getTagsFor(type).length) throw this.unsupported('artifacts.eventTypes.tags', type.name, 'Tagged events are not fixture-backed.');
105
105
  // Validate the complete schema, not only properties present on a particular event.
106
106
  const schema = metadata.schema;
107
+ if (schema.properties && Object.keys(schema.properties).length === 0 && !this._constraints?.isRemovalOnlyType(eventType.id.value)) {
108
+ throw this.unsupported('artifacts.eventTypes.schema', type.name,
109
+ 'Fieldless events must be removal-only types of a fixture-backed property constraint, including one scoped to another event sequence.');
110
+ }
107
111
  if (schema.type !== 'object' || schema.compliance?.length || schema.security?.length ||
108
112
  schema.enum !== undefined || schema.items !== undefined || schema.format !== undefined ||
109
113
  schema.additionalProperties !== false ||
110
114
  schema.required?.length !== Object.keys(schema.properties ?? {}).length ||
111
- !schema.properties || (Object.keys(schema.properties).length === 0 &&
112
- !this._constraints?.isRemovalOnlyType(eventType.id.value)) ||
115
+ !schema.properties ||
113
116
  Object.entries(schema.properties).some(([key, property]) =>
114
117
  !/^[a-z][a-zA-Z0-9]*$/.test(key) || !supportsEventField(property))) {
115
118
  throw this.unsupported('artifacts.eventTypes.schema', type.name, 'Only unclassified string, boolean, numeric, Guid, date and object fields are supported.');
@@ -0,0 +1,36 @@
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 { ConstraintCapture } from '../events/constraints/ConstraintBuilder.js';
5
+ import type { JsonSchema } from '../schemas/JsonSchema.js';
6
+
7
+ /** The two independent, single-property definitions measured in constraints-overlapping-definitions.json. */
8
+ export function supportsPropertyOverlap(definitions: ReadonlyMap<string, ConstraintCapture>, schemas: ReadonlyMap<string, JsonSchema>): boolean {
9
+ if (definitions.size !== 2) return false;
10
+ const [first, second] = [...definitions.values()];
11
+ if (!isIndependentProperty(first) || !isIndependentProperty(second)) return false;
12
+ if (JSON.stringify(first.scope) !== JSON.stringify(second.scope)) return false;
13
+ const left = first.uniqueConstraint!.eventDefinitions;
14
+ const right = second.uniqueConstraint!.eventDefinitions;
15
+ return left.length === right.length && left.every(entry => {
16
+ const other = right.find(candidate => candidate.eventTypeId === entry.eventTypeId);
17
+ if (!other || other.properties[0] === entry.properties[0]) return false;
18
+ return [entry.properties[0], other.properties[0]].every(property => {
19
+ const field = schemas.get(entry.eventTypeId)?.properties?.[property];
20
+ return isProvenOverlapKey(field);
21
+ });
22
+ });
23
+ }
24
+
25
+ function isProvenOverlapKey(schema: JsonSchema | undefined): boolean {
26
+ if (schema?.type === 'number') return schema.format === undefined;
27
+ if (schema?.type === 'string') return schema.format === undefined || schema.format === 'guid';
28
+ return false;
29
+ }
30
+
31
+ function isIndependentProperty(capture: ConstraintCapture): boolean {
32
+ const unique = capture.uniqueConstraint;
33
+ return !!unique && !capture.uniqueEventType && !unique.ignoreCasing &&
34
+ unique.removedWithEventTypeId === undefined && !unique.removedWithEventTypeIds?.length &&
35
+ unique.eventDefinitions.length > 0 && unique.eventDefinitions.every(entry => entry.properties.length === 1);
36
+ }
@@ -45,7 +45,7 @@ export function eventSequenceScenarioBehaviors(
45
45
  it('should retain every event sequence case', () => {
46
46
  should(fixture.eventSequenceCases.map(test => test.name)).deep.equal([
47
47
  'property-event-log', 'property-event-log-and-outbox', 'property-outbox',
48
- 'cycle-event-log', 'cycle-outbox', 'once-event-log', 'once-outbox'
48
+ 'cycle-event-log', 'cycle-outbox', 'once-event-log', 'once-outbox', 'fieldless-property-outbox'
49
49
  ]);
50
50
  should(fixture.expected.cases.map(test => test.name)).deep.equal(fixture.eventSequenceCases.map(test => test.name));
51
51
  });
@@ -26,6 +26,10 @@ class CycleRemoved { @field(String) label: string; constructor(label: string) {
26
26
  @removeConstraint('OracleSequencedCycle')
27
27
  class CycleExpired { @field(String) label: string; constructor(label: string) { this.label = label; } }
28
28
 
29
+ @eventType('OracleDomainCleared')
30
+ @removeConstraint('OracleSequencedKey')
31
+ class Cleared { }
32
+
29
33
  const outbox = new EventSequenceId('outbox');
30
34
 
31
35
  function constraints(caseName: string): Constructor[] {
@@ -36,7 +40,7 @@ function constraints(caseName: string): Constructor[] {
36
40
  @constraint('OracleSequencedKey')
37
41
  class Key {
38
42
  define(builder: IConstraintBuilder) {
39
- select(builder).unique(key => key.on(Text, event => event.key).removedWith(Removed).withMessage('Taken: {PropertyValue}'));
43
+ select(builder).unique(key => key.on(Text, event => event.key).removedWith(caseName.startsWith('fieldless-') ? Cleared : Removed).withMessage('Taken: {PropertyValue}'));
40
44
  }
41
45
  }
42
46
  @constraint('OracleSequencedFirst')
@@ -46,10 +50,10 @@ function constraints(caseName: string): Constructor[] {
46
50
  @constraint('OracleSequencedOnceConstraint')
47
51
  class Once { define(builder: IConstraintBuilder) { select(builder).uniqueFor(First, 'Already recorded', 'OracleSequencedOnce'); } }
48
52
  const kind = caseName.split('-')[0];
49
- return kind === 'property' ? [Key] : kind === 'once' ? [Once] : [FirstCycle, SiblingCycle];
53
+ return kind === 'property' || kind === 'fieldless' ? [Key] : kind === 'once' ? [Once] : [FirstCycle, SiblingCycle];
50
54
  }
51
55
 
52
56
  describe('when appending event sequence constraints with legacy decorators', () => {
53
- eventSequenceScenarioBehaviors({ string: Text, removed: Removed, first: First, sibling: Sibling,
57
+ eventSequenceScenarioBehaviors({ string: Text, removed: Removed, cleared: Cleared, first: First, sibling: Sibling,
54
58
  cycleRemoved: CycleRemoved, cycleExpired: CycleExpired }, constraints);
55
59
  });
@@ -25,6 +25,10 @@ class CycleRemoved { @field(String) label: string; constructor(label: string) {
25
25
  @removeConstraint('OracleSequencedCycle')
26
26
  class CycleExpired { @field(String) label: string; constructor(label: string) { this.label = label; } }
27
27
 
28
+ @eventType('OracleDomainCleared')
29
+ @removeConstraint('OracleSequencedKey')
30
+ class Cleared { }
31
+
28
32
  const outbox = new EventSequenceId('outbox');
29
33
 
30
34
  function constraints(caseName: string): Constructor[] {
@@ -35,7 +39,7 @@ function constraints(caseName: string): Constructor[] {
35
39
  @constraint('OracleSequencedKey')
36
40
  class Key {
37
41
  define(builder: IConstraintBuilder) {
38
- select(builder).unique(key => key.on(Text, event => event.key).removedWith(Removed).withMessage('Taken: {PropertyValue}'));
42
+ select(builder).unique(key => key.on(Text, event => event.key).removedWith(caseName.startsWith('fieldless-') ? Cleared : Removed).withMessage('Taken: {PropertyValue}'));
39
43
  }
40
44
  }
41
45
  @constraint('OracleSequencedFirst')
@@ -45,10 +49,10 @@ function constraints(caseName: string): Constructor[] {
45
49
  @constraint('OracleSequencedOnceConstraint')
46
50
  class Once { define(builder: IConstraintBuilder) { select(builder).uniqueFor(First, 'Already recorded', 'OracleSequencedOnce'); } }
47
51
  const kind = caseName.split('-')[0];
48
- return kind === 'property' ? [Key] : kind === 'once' ? [Once] : [FirstCycle, SiblingCycle];
52
+ return kind === 'property' || kind === 'fieldless' ? [Key] : kind === 'once' ? [Once] : [FirstCycle, SiblingCycle];
49
53
  }
50
54
 
51
55
  describe('when appending event sequence constraints with standard decorators', () => {
52
- eventSequenceScenarioBehaviors({ string: Text, removed: Removed, first: First, sibling: Sibling,
56
+ eventSequenceScenarioBehaviors({ string: Text, removed: Removed, cleared: Cleared, first: First, sibling: Sibling,
53
57
  cycleRemoved: CycleRemoved, cycleExpired: CycleExpired }, constraints);
54
58
  });
@@ -0,0 +1,122 @@
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 { chai, describe, it, vi, type Assertion } from 'vitest';
6
+ import { constraint } from '../../../events/constraints/constraint.js';
7
+ import type { IConstraint } from '../../../events/constraints/IConstraint.js';
8
+ import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
9
+ import { getEventTypeMetadata } from '../../../events/eventTypeDecorator.js';
10
+ import { EventScenario } from '../../EventScenario.js';
11
+ import { InProcessConstraints } from '../../InProcessConstraints.js';
12
+ import { UnsupportedEventSequenceOperation } from '../../UnsupportedEventSequenceOperation.js';
13
+
14
+ chai.should();
15
+ const should = (value: unknown): Assertion => (value as { should: Assertion }).should;
16
+ type Constructor = new () => object;
17
+ type Alias = 'number' | 'guid' | 'string' | 'removed';
18
+ type Entry = { source: string; type: Alias; value?: string; values?: Record<string, unknown> };
19
+ type Operation = { mode: string; overload?: string; options?: { sourceType: string; streamType: string; streamId: string }; events: Entry[] };
20
+ type Definition = { events: { type: Alias; properties: string[] }[]; name: string; message: string };
21
+ interface Fixture {
22
+ fieldCombinationCases: { name: string; eventSchemas: Record<Alias, { eventTypeId: string; properties: Record<string, string> }>;
23
+ constraintDefinitions: Definition[]; isolatedConstraintOperations: Operation[] }[];
24
+ expected: { cases: { name: string; outcomes: { success: boolean; sequences: string[]; wireViolations: unknown[]; next: string }[] }[] };
25
+ }
26
+ const fixture = JSON.parse(readFileSync(new URL('../../fixtures/constraints-field-combinations.json', import.meta.url), 'utf8')) as Fixture;
27
+
28
+ function definition(types: Record<Alias, Constructor>, declaration: Definition, mask: number, ignoreCasing = false): Constructor {
29
+ class Key implements IConstraint {
30
+ define(builder: IConstraintBuilder) {
31
+ if (mask & 1) builder.perEventSourceType();
32
+ if (mask & 2) builder.perEventStreamType();
33
+ if (mask & 4) builder.perEventStreamId();
34
+ builder.unique(key => {
35
+ key.withMessage(declaration.message);
36
+ for (const event of declaration.events) {
37
+ key.on(types[event.type], ...event.properties.map(property => (value: object) => (value as Record<string, unknown>)[property]));
38
+ }
39
+ key.removedWith(types.removed);
40
+ if (ignoreCasing) key.ignoreCasing();
41
+ return key;
42
+ });
43
+ }
44
+ }
45
+ constraint(declaration.name)(Key);
46
+ return Key;
47
+ }
48
+
49
+ function eventFor(entry: Entry, types: Record<Alias, Constructor>): object {
50
+ return Object.assign(new types[entry.type](), entry.values ?? { [entry.type === 'removed' ? 'label' : 'key']: entry.value });
51
+ }
52
+
53
+ async function append(scenario: EventScenario, operation: Operation, types: Record<Alias, Constructor>) {
54
+ const events = operation.events.map(entry => ({ eventSourceId: entry.source, event: eventFor(entry, types) }));
55
+ if (operation.mode === 'single') return [await scenario.append(events[0].eventSourceId, events[0].event, operation.options)];
56
+ if (operation.overload === 'source') return scenario.appendMany(events[0].eventSourceId, events.map(entry => entry.event), operation.options);
57
+ return scenario.appendMany(events, operation.options);
58
+ }
59
+
60
+ export function combinationBehaviors(types: Record<Alias, Constructor>): void {
61
+ it('should replay a nonempty, uniquely named oracle matrix', () => {
62
+ should(fixture.fieldCombinationCases.length).equal(3);
63
+ should(fixture.expected.cases.length).equal(24);
64
+ should(new Set(fixture.expected.cases.map(test => test.name)).size).equal(24);
65
+ });
66
+ for (const template of fixture.fieldCombinationCases) {
67
+ for (let mask = 0; mask < 8; mask++) {
68
+ describe(`when replaying ${template.name} Guid/numeric keys under scope mask ${mask}`, () => {
69
+ const constraints = [definition(types, template.constraintDefinitions[0], mask)];
70
+ const artifacts = { eventTypes: Object.values(types), constraints };
71
+ it('should match raw violations, sequences, history and failed-batch atomicity', async () => {
72
+ const expected = fixture.expected.cases.find(test => test.name === `${template.name}-${mask}`)!;
73
+ should(expected.outcomes.length).equal(template.isolatedConstraintOperations.length);
74
+ for (const alias of Object.keys(types) as Alias[]) {
75
+ const schema = getEventTypeMetadata(types[alias])!;
76
+ should(schema.eventType.id.value).equal(template.eventSchemas[alias].eventTypeId);
77
+ should(Object.keys(schema.schema.properties!).sort()).deep.equal(Object.keys(template.eventSchemas[alias].properties).sort());
78
+ }
79
+ const scenario = new EventScenario({ artifacts });
80
+ const validate = vi.spyOn(InProcessConstraints.prototype, 'validate');
81
+ try {
82
+ for (const [index, operation] of template.isolatedConstraintOperations.entries()) {
83
+ const before = [...scenario.appendedEvents];
84
+ const results = await append(scenario, operation, types);
85
+ const outcome = expected.outcomes[index];
86
+ should(results.every(result => result.isSuccess === outcome.success)).equal(true);
87
+ should(results.map(result => result.sequenceNumber.value.toString())).deep.equal(
88
+ outcome.success ? outcome.sequences : results.map(() => '0'));
89
+ const raw = validate.mock.results.at(-1)!.value as ReturnType<InProcessConstraints['validate']>;
90
+ should(raw.map(({ SequenceNumber, ...violation }) => ({ ...violation, SequenceNumber: SequenceNumber.toString() })))
91
+ .deep.equal(outcome.wireViolations);
92
+ if (!outcome.success) should(scenario.appendedEvents).deep.equal(before);
93
+ else should(scenario.appendedEvents.slice(before.length).map(entry => entry.context.eventSourceId))
94
+ .deep.equal(operation.events.map(entry => entry.source));
95
+ should((await scenario.eventSequence.getNextSequenceNumber()).value.toString()).equal(outcome.next);
96
+ }
97
+ } finally { validate.mockRestore(); }
98
+ });
99
+ it('should keep numeric, Guid and definition rejections atomic', async () => {
100
+ const scenario = new EventScenario({ artifacts });
101
+ for (const entry of [
102
+ { source: 'A', type: 'number', values: { key: 1.5 } },
103
+ { source: 'A', type: 'number', values: { key: Number.MAX_SAFE_INTEGER + 1 } },
104
+ { source: 'A', type: 'guid', values: { key: 'not-a-guid' } }
105
+ ] as Entry[]) {
106
+ const error = await append(scenario, { mode: 'batch', events: [template.isolatedConstraintOperations[0].events[0], entry] }, types)
107
+ .then(() => undefined, error => error);
108
+ should(error).instanceOf(UnsupportedEventSequenceOperation);
109
+ should(scenario.appendedEvents).deep.equal([]);
110
+ should(scenario.results).deep.equal([]);
111
+ }
112
+ const other = definition(types, { ...template.constraintDefinitions[0], name: 'OracleOtherKey' }, mask);
113
+ should(() => new EventScenario({ artifacts: { ...artifacts, constraints: [...constraints, other] } }))
114
+ .throw(UnsupportedEventSequenceOperation);
115
+ const cased = definition(types, template.constraintDefinitions[0], mask, true);
116
+ should(() => new EventScenario({ artifacts: { ...artifacts, constraints: [cased] } }))
117
+ .throw(UnsupportedEventSequenceOperation, 'Case-insensitive keys');
118
+ });
119
+ });
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,116 @@
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 { Constructor } from '@cratis/fundamentals';
5
+ import { chai, describe, it } from 'vitest';
6
+ import { constraint } from '../../../events/constraints/constraint.js';
7
+ import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
8
+ import { EventScenario } from '../../EventScenario.js';
9
+ import { UnsupportedEventSequenceOperation } from '../../UnsupportedEventSequenceOperation.js';
10
+
11
+ chai.should();
12
+
13
+ function definition(configure: (builder: IConstraintBuilder) => void, name = 'UnprovenCombinedKey'): Constructor {
14
+ class Definition { define(builder: IConstraintBuilder) { configure(builder); } }
15
+ constraint(name)(Definition);
16
+ return Definition;
17
+ }
18
+
19
+ async function rejectWithoutMutation(eventTypes: Constructor[], Claim: new () => { key: unknown }, invalid: Constructor, reason: string): Promise<void> {
20
+ const supported = definition(builder => builder.unique(key => key.on(Claim, event => event.key)), 'SupportedCombinedKey');
21
+ const scenario = new EventScenario({ artifacts: { eventTypes: [Claim], constraints: [supported] } });
22
+ (await scenario.append('A', new Claim())).isSuccess.should.be.true;
23
+ const history = [...scenario.appendedEvents];
24
+ const results = [...scenario.results];
25
+ (() => new EventScenario({ artifacts: { eventTypes, constraints: [invalid] } }))
26
+ .should.throw(UnsupportedEventSequenceOperation, reason);
27
+ scenario.appendedEvents.should.deep.equal(history);
28
+ scenario.results.should.deep.equal(results);
29
+ (await scenario.eventSequence.getNextSequenceNumber()).value.should.equal(1n);
30
+ (await scenario.append('B', new Claim())).isSuccess.should.be.false;
31
+ (await scenario.eventSequence.getNextSequenceNumber()).value.should.equal(1n);
32
+ }
33
+
34
+ export function definitionRejectionBehaviors(types: {
35
+ guid: new () => { key: unknown };
36
+ number: new () => { key: unknown };
37
+ text: new () => { key: string };
38
+ flag: new () => { key: boolean };
39
+ fieldless: new () => object;
40
+ removed: new () => { label: string };
41
+ }): void {
42
+ for (const [kind, Claim] of [['Guid', types.guid], ['numeric', types.number]] as const) {
43
+ describe(`when configuring unmeasured ${kind} definition combinations`, () => {
44
+ it('should release and reclaim an extended key with a fieldless remover', async () => {
45
+ const supported = definition(builder => builder.unique(key => key.on(Claim, event => event.key).removedWith(types.fieldless)));
46
+ const scenario = new EventScenario({ artifacts: { eventTypes: [Claim, types.fieldless], constraints: [supported] } });
47
+ (await scenario.append('A', new Claim())).isSuccess.should.be.true;
48
+ (await scenario.append('B', new Claim())).isSuccess.should.be.false;
49
+ (await scenario.append('A', new types.fieldless())).isSuccess.should.be.true;
50
+ (await scenario.append('B', new Claim())).sequenceNumber.value.should.equal(2n);
51
+ });
52
+ it('should reject an unscoped covered-and-removal event without mutating claims or advancing a sequence', async () => {
53
+ const invalid = definition(builder => builder.unique(key => key.on(Claim, event => event.key).removedWith(Claim)));
54
+ await rejectWithoutMutation([Claim], Claim, invalid, 'covered-and-removal events');
55
+ });
56
+ it('should reject a string covered-and-removal event shared with an extended key', async () => {
57
+ const invalid = definition(builder => builder.unique(key => key.on(Claim, event => event.key)
58
+ .on(types.removed, event => event.label).removedWith(types.removed)));
59
+ await rejectWithoutMutation([Claim, types.removed], Claim, invalid, 'covered-and-removal events');
60
+ });
61
+ for (let mask = 0; mask < 8; mask++) {
62
+ for (const flagFirst of [false, true]) {
63
+ it(`should reject a shared Boolean/${kind} definition under scope ${mask}, Boolean first: ${flagFirst}`, async () => {
64
+ const invalid = definition(builder => {
65
+ if (mask & 1) builder.perEventSourceType();
66
+ if (mask & 2) builder.perEventStreamType();
67
+ if (mask & 4) builder.perEventStreamId();
68
+ builder.unique(key => {
69
+ if (flagFirst) key.on(types.flag, event => event.key);
70
+ key.on(Claim, event => event.key);
71
+ if (!flagFirst) key.on(types.flag, event => event.key);
72
+ });
73
+ });
74
+ await rejectWithoutMutation([Claim, types.flag], Claim, invalid, 'Boolean keys mixed with Guid or numeric keys');
75
+ });
76
+ }
77
+ }
78
+ });
79
+ }
80
+
81
+ describe('when configuring existing string-key lifecycle shapes', () => {
82
+ it('should retain unscoped fieldless-remover release and reclaim', async () => {
83
+ const constraints = [definition(builder => builder.unique(key => key.on(types.text, event => event.key).removedWith(types.fieldless)))];
84
+ const scenario = new EventScenario({ artifacts: { eventTypes: [types.text, types.fieldless], constraints } });
85
+ const claim = () => Object.assign(new types.text(), { key: 'Alpha' });
86
+ (await scenario.append('A', claim())).isSuccess.should.be.true;
87
+ (await scenario.append('B', claim())).isSuccess.should.be.false;
88
+ (await scenario.append('A', new types.fieldless())).isSuccess.should.be.true;
89
+ (await scenario.append('B', claim())).sequenceNumber.value.should.equal(2n);
90
+ (await scenario.eventSequence.getNextSequenceNumber()).value.should.equal(3n);
91
+ });
92
+ it('should retain unscoped string covered-and-removal events', async () => {
93
+ const constraints = [definition(builder => builder.unique(key => key.on(types.text, event => event.key)
94
+ .on(types.removed, event => event.label).removedWith(types.removed)))];
95
+ const scenario = new EventScenario({ artifacts: { eventTypes: [types.text, types.removed], constraints } });
96
+ const claim = () => Object.assign(new types.text(), { key: 'Alpha' });
97
+ (await scenario.append('A', claim())).isSuccess.should.be.true;
98
+ (await scenario.append('A', Object.assign(new types.removed(), { label: 'Alpha' }))).isSuccess.should.be.true;
99
+ (await scenario.append('B', claim())).sequenceNumber.value.should.equal(2n);
100
+ (await scenario.eventSequence.getNextSequenceNumber()).value.should.equal(3n);
101
+ });
102
+ for (const scoped of [false, true]) {
103
+ it(`should retain a shared Boolean/string definition, scoped: ${scoped}`, async () => {
104
+ const constraints = [definition(builder => {
105
+ if (scoped) builder.perEventStreamId();
106
+ builder.unique(key => key.on(types.flag, event => event.key).on(types.text, event => event.key));
107
+ })];
108
+ const scenario = new EventScenario({ artifacts: { eventTypes: [types.flag, types.text], constraints } });
109
+ (await scenario.append('A', new types.flag())).isSuccess.should.be.true;
110
+ (await scenario.append('B', Object.assign(new types.text(), { key: 'True' }))).isSuccess.should.be.false;
111
+ (await scenario.append('B', Object.assign(new types.text(), { key: 'true' }))).sequenceNumber.value.should.equal(1n);
112
+ (await scenario.eventSequence.getNextSequenceNumber()).value.should.equal(2n);
113
+ });
114
+ }
115
+ });
116
+ }
@@ -0,0 +1,36 @@
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 'reflect-metadata';
5
+ import { field, Guid } from '@cratis/fundamentals';
6
+ import { describe } from 'vitest';
7
+ import { eventType } from '../../../events/eventTypeDecorator.js';
8
+ import { removalAndOverlapBehaviors } from './removal_and_overlap_behaviors.fixture.js';
9
+
10
+ @eventType('OracleCombinedNumber')
11
+ class NumberKey {
12
+ @field(Number) key = -7;
13
+ @field(String) suffix = 'Alpha';
14
+ @field(Guid) identifier = Guid.parse('abcdef01-abcd-abcd-abcd-abcdef012345');
15
+ }
16
+ @eventType('OracleCombinedGuid')
17
+ class GuidKey {
18
+ @field(Guid) key = Guid.parse('abcdef01-abcd-abcd-abcd-abcdef012345');
19
+ @field(String) suffix = 'Alpha';
20
+ @field(Number) amount = -7;
21
+ }
22
+ @eventType('OracleCombinedText')
23
+ class TextKey { @field(String) key = ''; }
24
+ @eventType('OracleCombinedBoolean')
25
+ class BooleanKey { @field(Boolean) key = true; }
26
+ @eventType('OracleOverlapFormatted')
27
+ class FormattedKey {
28
+ @field(Number) key = 7;
29
+ @field(String) suffix = 'Alpha';
30
+ }
31
+ @eventType('OracleCombinedRemoved')
32
+ class Removed { }
33
+
34
+ describe('when appending fieldless removals and overlapping definitions with legacy decorators', () => {
35
+ removalAndOverlapBehaviors({ number: NumberKey, guid: GuidKey, string: TextKey, boolean: BooleanKey, formatted: FormattedKey, removed: Removed });
36
+ });
@@ -0,0 +1,35 @@
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, Guid } from '@cratis/fundamentals';
5
+ import { describe } from 'vitest';
6
+ import { eventType } from '../../../events/eventTypeDecorator.js';
7
+ import { removalAndOverlapBehaviors } from './removal_and_overlap_behaviors.fixture.js';
8
+
9
+ @eventType('OracleCombinedNumber')
10
+ class NumberKey {
11
+ @field(Number) key = -7;
12
+ @field(String) suffix = 'Alpha';
13
+ @field(Guid) identifier = Guid.parse('abcdef01-abcd-abcd-abcd-abcdef012345');
14
+ }
15
+ @eventType('OracleCombinedGuid')
16
+ class GuidKey {
17
+ @field(Guid) key = Guid.parse('abcdef01-abcd-abcd-abcd-abcdef012345');
18
+ @field(String) suffix = 'Alpha';
19
+ @field(Number) amount = -7;
20
+ }
21
+ @eventType('OracleCombinedText')
22
+ class TextKey { @field(String) key = ''; }
23
+ @eventType('OracleCombinedBoolean')
24
+ class BooleanKey { @field(Boolean) key = true; }
25
+ @eventType('OracleOverlapFormatted')
26
+ class FormattedKey {
27
+ @field(Number) key = 7;
28
+ @field(String) suffix = 'Alpha';
29
+ }
30
+ @eventType('OracleCombinedRemoved')
31
+ class Removed { }
32
+
33
+ describe('when appending fieldless removals and overlapping definitions with standard decorators', () => {
34
+ removalAndOverlapBehaviors({ number: NumberKey, guid: GuidKey, string: TextKey, boolean: BooleanKey, formatted: FormattedKey, removed: Removed });
35
+ });
@@ -0,0 +1,193 @@
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 { chai, describe, it, vi, type Assertion } from 'vitest';
6
+ import { constraint } from '../../../events/constraints/constraint.js';
7
+ import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
8
+ import { getEventTypeMetadata } from '../../../events/eventTypeDecorator.js';
9
+ import type { JsonSchema } from '../../../schemas/JsonSchema.js';
10
+ import { EventScenario } from '../../EventScenario.js';
11
+ import { InProcessConstraints } from '../../InProcessConstraints.js';
12
+ import { UnsupportedEventSequenceOperation } from '../../UnsupportedEventSequenceOperation.js';
13
+
14
+ chai.should();
15
+ const should = (value: unknown): Assertion => (value as { should: Assertion }).should;
16
+ type Constructor = new () => object;
17
+ type Types = Record<string, Constructor>;
18
+ type Declaration = { name: string; message: string; ignoreCasing: boolean; removedWithEventTypeIds: string[];
19
+ events: { type: string; properties: string[] }[] };
20
+ type Entry = { source: string; type: string; value?: string; values?: Record<string, unknown> };
21
+ type Template = { name: string; eventSchemas: Record<string, { eventTypeId: string; properties: Record<string, string> }>;
22
+ constraintDefinitions: Declaration[]; isolatedConstraintOperations: { mode: string; events: Entry[];
23
+ options?: { sourceType: string; streamType: string; streamId: string } }[] };
24
+ type Fixture = { fieldCombinationCases: Template[]; expected: { cases: { name: string;
25
+ outcomes: { success: boolean; sequences: string[]; wireViolations: unknown[]; next: string }[] }[] } };
26
+
27
+ function definition(types: Types, declaration: Declaration, mask: number): Constructor {
28
+ class Definition {
29
+ define(builder: IConstraintBuilder) {
30
+ if (mask & 1) builder.perEventSourceType();
31
+ if (mask & 2) builder.perEventStreamType();
32
+ if (mask & 4) builder.perEventStreamId();
33
+ builder.unique(key => {
34
+ key.withMessage(declaration.message);
35
+ for (const entry of declaration.events) key.on(types[entry.type], ...entry.properties.map(property =>
36
+ (event: object) => (event as Record<string, unknown>)[property]));
37
+ for (const alias of declaration.removedWithEventTypeIds) key.removedWith(types[alias]);
38
+ if (declaration.ignoreCasing) key.ignoreCasing();
39
+ });
40
+ }
41
+ }
42
+ constraint(declaration.name)(Definition);
43
+ return Definition;
44
+ }
45
+
46
+ function eventFor(entry: Entry, types: Types): object {
47
+ return Object.assign(new types[entry.type](), entry.values ?? (entry.value === undefined ? {} : { key: entry.value }));
48
+ }
49
+
50
+ function replay(fixture: Fixture, template: Template, mask: number, types: Types): void {
51
+ it(`should replay ${template.name} with scope mask ${mask}, including raw violations and rollback`, async () => {
52
+ const selected = Object.keys(template.eventSchemas).map(alias => types[alias]);
53
+ for (const [alias, schema] of Object.entries(template.eventSchemas)) {
54
+ const metadata = getEventTypeMetadata(types[alias])!;
55
+ should(metadata.eventType.id.value).equal(schema.eventTypeId);
56
+ should(Object.keys(metadata.schema.properties!).sort()).deep.equal(Object.keys(schema.properties).sort());
57
+ }
58
+ const constraints = template.constraintDefinitions.map(declaration => definition(types, declaration, mask));
59
+ const scenario = new EventScenario({ artifacts: { eventTypes: selected, constraints } });
60
+ const expected = fixture.expected.cases.find(test => test.name === `${template.name}-${mask}`)!.outcomes;
61
+ should(expected.length).equal(template.isolatedConstraintOperations.length);
62
+ const validate = vi.spyOn(InProcessConstraints.prototype, 'validate');
63
+ try {
64
+ for (const [index, operation] of template.isolatedConstraintOperations.entries()) {
65
+ const before = [...scenario.appendedEvents];
66
+ const events = operation.events.map(entry => ({ eventSourceId: entry.source, event: eventFor(entry, types) }));
67
+ const results = operation.mode === 'single'
68
+ ? [await scenario.append(events[0].eventSourceId, events[0].event, operation.options)]
69
+ : await scenario.appendMany(events, operation.options);
70
+ const outcome = expected[index];
71
+ should(results.every(result => result.isSuccess === outcome.success)).equal(true);
72
+ should(results.map(result => result.sequenceNumber.value.toString())).deep.equal(
73
+ outcome.success ? outcome.sequences : results.map(() => '0'));
74
+ const raw = validate.mock.results.at(-1)!.value as ReturnType<InProcessConstraints['validate']>;
75
+ should(raw.map(({ SequenceNumber, ...violation }) => ({ ...violation, SequenceNumber: SequenceNumber.toString() })))
76
+ .deep.equal(outcome.wireViolations);
77
+ if (!outcome.success) should(scenario.appendedEvents).deep.equal(before);
78
+ else should(scenario.appendedEvents.slice(before.length).map(event => event.content)).deep.equal(
79
+ events.map(entry => JSON.parse(JSON.stringify(entry.event))));
80
+ should((await scenario.eventSequence.getNextSequenceNumber()).value.toString()).equal(outcome.next);
81
+ }
82
+ } finally { validate.mockRestore(); }
83
+ });
84
+ }
85
+
86
+ function overlapDeclarations(template: Template, variation: string): Declaration[] {
87
+ const declarations = structuredClone(template.constraintDefinitions);
88
+ if (variation === 'same-property') declarations[1].events = structuredClone(declarations[0].events);
89
+ if (variation === 'ignore-casing') declarations[1].ignoreCasing = true;
90
+ if (variation === 'composite') declarations[1].events.forEach(entry => entry.properties.push('key'));
91
+ if (variation === 'removal') declarations[1].removedWithEventTypeIds = ['removed'];
92
+ if (variation === 'third-definition') declarations.push({ ...declarations[1], name: 'OracleThird' });
93
+ return declarations;
94
+ }
95
+
96
+ function overlapRejections(template: Template, types: Types): void {
97
+ for (const variation of ['same-property', 'different-scope', 'ignore-casing', 'composite', 'removal', 'third-definition', 'mixed-kind']) {
98
+ it(`should reject unmeasured overlap: ${variation}`, () => {
99
+ const declarations = overlapDeclarations(template, variation);
100
+ const constraints = declarations.map((declaration, index) => definition(types, declaration, variation === 'different-scope' && index === 1 ? 1 : 0));
101
+ if (variation === 'mixed-kind') {
102
+ class Once { define(builder: IConstraintBuilder) { builder.uniqueFor(types.number, 'Once', 'OracleOnce'); } }
103
+ constraint('OracleOnce')(Once);
104
+ constraints[1] = Once;
105
+ }
106
+ const eventTypes = Object.keys(template.eventSchemas).map(alias => types[alias]);
107
+ if (variation === 'removal') eventTypes.push(types.removed);
108
+ should(() => new EventScenario({ artifacts: { eventTypes, constraints } }))
109
+ .throw(UnsupportedEventSequenceOperation);
110
+ });
111
+ }
112
+ }
113
+
114
+ function fieldlessRejections(types: Types): void {
115
+ for (const [label, alias, properties, ignoreCasing] of [
116
+ ['composite', 'number', ['key', 'suffix'], false],
117
+ ['ignore-casing', 'string', ['key'], true],
118
+ ['boolean', 'boolean', ['key'], false]
119
+ ] as const) {
120
+ it(`should reject an unmeasured scoped fieldless remover: ${label}`, () => {
121
+ const declaration: Declaration = { name: 'OracleFieldlessRejected', message: 'Taken', ignoreCasing,
122
+ removedWithEventTypeIds: ['removed'], events: [{ type: alias, properties: [...properties] }] };
123
+ const constraints = [definition(types, declaration, 1)];
124
+ should(() => new EventScenario({ artifacts: { eventTypes: [types[alias], types.removed], constraints } }))
125
+ .throw(UnsupportedEventSequenceOperation, 'Scoped fieldless removers require');
126
+ });
127
+ }
128
+ it('should identify an unrelated fieldless event accurately', () => {
129
+ should(() => new EventScenario({ artifacts: { eventTypes: [types.removed] }, constraints: 'disabled' }))
130
+ .throw(UnsupportedEventSequenceOperation, 'Fieldless events must be removal-only types');
131
+ });
132
+ }
133
+
134
+ function unprovenOverlapKeyRejections(types: Types): void {
135
+ const schemas: JsonSchema[] = [
136
+ { type: 'number', format: 'double' }, { type: 'number', format: 'decimal' }, { type: 'number', format: 'float' },
137
+ { type: 'string', format: 'date' }, { type: 'string', format: 'date-time' }, { type: 'string', format: 'email' },
138
+ { type: 'boolean' }, { type: 'integer' }, { type: 'object' }, { type: 'array' }
139
+ ];
140
+ for (const schema of schemas) {
141
+ it(`should reject overlapping ${schema.type}/${schema.format} and string keys on one event type`, () => {
142
+ const properties = getEventTypeMetadata(types.formatted)!.schema.properties!;
143
+ const original = properties.key;
144
+ properties.key = schema;
145
+ try {
146
+ const declaration: Declaration = { name: 'OracleUnprovenKey', message: 'Taken', ignoreCasing: false,
147
+ removedWithEventTypeIds: [], events: [{ type: 'formatted', properties: ['key'] }] };
148
+ const stringDeclaration: Declaration = { ...declaration, name: 'OracleIndependentString',
149
+ events: [{ type: 'formatted', properties: ['suffix'] }] };
150
+ const constraints = [declaration, stringDeclaration].map(entry => definition(types, entry, 0));
151
+ should(() => new EventScenario({ artifacts: { eventTypes: [types.formatted], constraints } }))
152
+ .throw(UnsupportedEventSequenceOperation, 'Overlapping constraints are not fixture-backed.');
153
+ } finally { properties.key = original; }
154
+ });
155
+ }
156
+ }
157
+
158
+ function claimRemoveRejection(fixture: Fixture, template: Template, mask: number, types: Types): void {
159
+ it(`should reject covered/removal extended keys under scope mask ${mask}`, () => {
160
+ // The kernel checks a covered/removal claim but does not retain it durably.
161
+ const outcomes = fixture.expected.cases.find(test => test.name === `${template.name}-${mask}`)!.outcomes;
162
+ should(outcomes.slice(0, 3).map(outcome => outcome.success)).deep.equal([true, true, false]);
163
+ const constraints = template.constraintDefinitions.map(declaration => definition(types, declaration, mask));
164
+ should(() => new EventScenario({ artifacts: { eventTypes: [types.number, types.guid, types.string], constraints } }))
165
+ .throw(UnsupportedEventSequenceOperation, 'covered-and-removal');
166
+ });
167
+ }
168
+
169
+ function registerTemplate(fixture: Fixture, template: Template, types: Types): void {
170
+ for (let mask = 0; mask < 8; mask++) {
171
+ if (template.name === 'claim-remove') claimRemoveRejection(fixture, template, mask, types);
172
+ else replay(fixture, template, mask, types);
173
+ }
174
+ if (template.name === 'overlapping') overlapRejections(template, types);
175
+ }
176
+
177
+ function registerFixture(name: string, types: Types): void {
178
+ const fixture = JSON.parse(readFileSync(new URL(`../../fixtures/constraints-${name}.json`, import.meta.url), 'utf8')) as Fixture;
179
+ describe(`with ${name}`, () => {
180
+ it('should retain every measured scope case', () => {
181
+ const expectedNames = fixture.fieldCombinationCases.flatMap(test => Array.from({ length: 8 }, (_, mask) => `${test.name}-${mask}`));
182
+ should(expectedNames.length).equal(name === 'removal-combinations' ? 16 : 8);
183
+ should(fixture.expected.cases.map(test => test.name)).deep.equal(expectedNames);
184
+ });
185
+ for (const template of fixture.fieldCombinationCases) registerTemplate(fixture, template, types);
186
+ });
187
+ }
188
+
189
+ export function removalAndOverlapBehaviors(types: Types): void {
190
+ fieldlessRejections(types);
191
+ unprovenOverlapKeyRejections(types);
192
+ for (const name of ['removal-combinations', 'overlapping-definitions']) registerFixture(name, types);
193
+ }