@cratis/chronicle 6.67.3 → 6.67.5

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 (39) hide show
  1. package/dist/testing/ConstraintKey.d.ts +17 -0
  2. package/dist/testing/ConstraintKey.d.ts.map +1 -0
  3. package/dist/testing/ConstraintKey.js +72 -0
  4. package/dist/testing/ConstraintKey.js.map +1 -0
  5. package/dist/testing/EventScenario.d.ts.map +1 -1
  6. package/dist/testing/EventScenario.js +56 -33
  7. package/dist/testing/EventScenario.js.map +1 -1
  8. package/dist/testing/InProcessConstraints.d.ts +2 -1
  9. package/dist/testing/InProcessConstraints.d.ts.map +1 -1
  10. package/dist/testing/InProcessConstraints.js +11 -51
  11. package/dist/testing/InProcessConstraints.js.map +1 -1
  12. package/dist/testing/InProcessEventSequence.d.ts.map +1 -1
  13. package/dist/testing/InProcessEventSequence.js +4 -2
  14. package/dist/testing/InProcessEventSequence.js.map +1 -1
  15. package/dist/testing/PropertyDefinitionSupport.d.ts +5 -0
  16. package/dist/testing/PropertyDefinitionSupport.d.ts.map +1 -0
  17. package/dist/testing/PropertyDefinitionSupport.js +37 -0
  18. package/dist/testing/PropertyDefinitionSupport.js.map +1 -0
  19. package/dist/tsconfig.tsbuildinfo +1 -1
  20. package/package.json +1 -1
  21. package/testing/ConstraintKey.ts +81 -0
  22. package/testing/EventScenario.constraint-cycles.spec.ts +1 -1
  23. package/testing/EventScenario.fixtures.spec.ts +2 -1
  24. package/testing/EventScenario.ts +66 -37
  25. package/testing/InProcessConstraints.ts +10 -55
  26. package/testing/InProcessEventSequence.ts +5 -2
  27. package/testing/PropertyDefinitionSupport.ts +36 -0
  28. package/testing/for_EventScenario/when_appending_event_sequence_constraints/event_sequence_scenario_behaviors.fixture.ts +1 -1
  29. package/testing/for_EventScenario/when_appending_event_sequence_constraints/with_legacy_decorators.legacy.spec.ts +7 -3
  30. package/testing/for_EventScenario/when_appending_event_sequence_constraints/with_standard_decorators.standard.spec.ts +7 -3
  31. package/testing/for_EventScenario/when_appending_field_combinations/definition_rejection_behaviors.fixture.ts +7 -3
  32. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap.legacy.spec.ts +36 -0
  33. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap.standard.spec.ts +35 -0
  34. package/testing/for_EventScenario/when_appending_field_combinations/removal_and_overlap_behaviors.fixture.ts +193 -0
  35. package/testing/for_EventScenario/when_appending_field_types/field_scenario_behaviors.fixture.ts +19 -13
  36. package/testing/for_EventScenario/when_appending_field_types/fractional_collisions.fixture.ts +91 -0
  37. package/testing/for_EventScenario/when_appending_field_types/with_fractional_collisions.legacy.spec.ts +51 -0
  38. package/testing/for_EventScenario/when_appending_field_types/with_fractional_collisions.standard.spec.ts +50 -0
  39. package/testing/for_EventScenario/when_appending_scoped_constraints/with_unproven_operations.spec.ts +1 -1
@@ -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
+ }
@@ -156,17 +156,21 @@ export function fieldScenarioBehaviors(fixtures: {
156
156
  });
157
157
  }
158
158
 
159
- for (const value of [1.5, 1e-7, Number.MAX_SAFE_INTEGER + 1, -Number.MAX_SAFE_INTEGER - 1, NaN, Infinity]) {
160
- describe(`when a constrained number contains ${value}`, () => {
161
- it('should reject the entire batch before recording results or history', async () => {
162
- const scenario = new EventScenario({ artifacts: { eventTypes: [fixtures.number], constraints: [fixtures.numberConstraint] } });
163
- const event = new fixtures.number(); event.key = value;
164
- const error = await scenario.appendMany('A', [new fixtures.number(), event]).then(() => undefined, error => error);
165
- should(error).instanceOf(UnsupportedEventSequenceOperation);
166
- should(scenario.results).have.lengthOf(0);
167
- should(scenario.appendedEvents).have.lengthOf(0);
159
+ for (const [type, constraint] of [[fixtures.number, fixtures.numberConstraint], [fixtures.double, fixtures.doubleConstraint]] as const) {
160
+ for (const value of [0.00001, -0.00001, 1e-7, 1000000000000000.2, 4503599627370495.5,
161
+ -1000000000000000.2, -4503599627370495.5, 1e21, Number.MAX_SAFE_INTEGER + 1, -Number.MAX_SAFE_INTEGER - 1, NaN, Infinity]) {
162
+ describe(`when a constrained ${type.name} contains ${value}`, () => {
163
+ it('should reject the entire batch before recording results or history', async () => {
164
+ const scenario = new EventScenario({ artifacts: { eventTypes: [type], constraints: [constraint] } });
165
+ const event = new type(); event.key = value;
166
+ const error = await scenario.appendMany('A', [new type(), event]).then(() => undefined, error => error);
167
+ should(error).instanceOf(UnsupportedEventSequenceOperation);
168
+ should(scenario.results).have.lengthOf(0);
169
+ should(scenario.appendedEvents).have.lengthOf(0);
170
+ should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(0n);
171
+ });
168
172
  });
169
- });
173
+ }
170
174
  }
171
175
 
172
176
  it('should normalize negative zero using production serialization before comparing numeric keys', async () => {
@@ -177,11 +181,13 @@ export function fieldScenarioBehaviors(fixtures: {
177
181
  should((await scenario.append('B', negative)).isSuccess).equal(false);
178
182
  });
179
183
 
180
- const fixture = JSON.parse(readFileSync(new URL('../../fixtures/constraints-field-types.json', import.meta.url), 'utf8')) as {
184
+ const kernelFixtures = ['constraints-field-types', 'constraints-fractional-field-types'].map(name =>
185
+ JSON.parse(readFileSync(new URL(`../../fixtures/${name}.json`, import.meta.url), 'utf8')) as {
181
186
  fieldConstraintCases: Array<{ kind: string; eventType: string; operations: Array<{ mode: string; events: Array<{ source: string; content: string }> }> }>;
182
187
  expected: Array<{ fieldSchema: unknown; steps: Array<{ success: boolean; sequences: string[]; wireViolations: unknown[]; history: unknown[]; next: string }> }>;
183
- };
184
- for (const [caseIndex, test] of fixture.fieldConstraintCases.entries()) {
188
+ });
189
+ for (const { fixture, caseIndex, test } of kernelFixtures.flatMap(fixture =>
190
+ fixture.fieldConstraintCases.map((test, caseIndex) => ({ fixture, test, caseIndex })))) {
185
191
  if (test.kind !== 'kernelSemantics') continue;
186
192
  describe(`when replaying the packaged ${test.eventType} constraint fixture`, () => {
187
193
  it('should match every raw violation, hash, history, sequence and atomic rejection', async () => {
@@ -0,0 +1,91 @@
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 type { Constructor } from '@cratis/fundamentals';
6
+ import { beforeEach, chai, describe, it, vi, type Assertion } from 'vitest';
7
+ import { getEventTypeMetadata } from '../../../events/eventTypeDecorator.js';
8
+ import { EventScenario, UnsupportedEventSequenceOperation } from '../../index.js';
9
+ import { InProcessConstraints } from '../../InProcessConstraints.js';
10
+
11
+ chai.should();
12
+ const should = (value: unknown): Assertion => (value as { should: Assertion }).should;
13
+
14
+ type Input = { source: string; type: 'number' | 'string'; value: number | string };
15
+ type WireViolation = { SequenceNumber: string; ConstraintName: string; Message: string; Details: Record<string, string> };
16
+ type RejectedDefinition = { name: string; eventTypes: Constructor[]; constraints: Constructor[]; eventType: Constructor<{ key: number }> };
17
+ type Fixture = {
18
+ fieldCombinationCases: Array<{ isolatedConstraintOperations: Array<{ mode: string; events: Input[] }> }>;
19
+ expected: { cases: Array<{ name: string; outcomes: Array<{
20
+ success: boolean; sequences: string[]; wireViolations: WireViolation[]; next: string;
21
+ }> }> };
22
+ };
23
+
24
+ export function fractionalCollisions(fixtures: { number: Constructor<{ key: number }>; text: Constructor<{ key: string }>;
25
+ constraint: Constructor; scoped: Constructor; rejectedDefinitions: RejectedDefinition[] }): void {
26
+ const fixture = JSON.parse(readFileSync(new URL('../../fixtures/constraints-fractional-collisions.json', import.meta.url), 'utf8')) as Fixture;
27
+ const operations = fixture.fieldCombinationCases[0].isolatedConstraintOperations;
28
+ const outcomes = fixture.expected.cases[0].outcomes;
29
+ const eventTypes = [fixtures.number, fixtures.text];
30
+
31
+ describe('when replaying unscoped string and fractional key collisions', () => {
32
+ it('should match the kernel violations and atomic ownership transitions after every request', async () => {
33
+ should(fixture.expected.cases[0].name).equal('fractional-0');
34
+ should(operations.length).equal(outcomes.length);
35
+ should(getEventTypeMetadata(fixtures.number)!.eventType.id.value).equal('OracleCombinedNumber');
36
+ should(getEventTypeMetadata(fixtures.text)!.eventType.id.value).equal('OracleCombinedText');
37
+ const scenario = new EventScenario({ artifacts: { eventTypes, constraints: [fixtures.constraint] } });
38
+ const validate = vi.spyOn(InProcessConstraints.prototype, 'validate');
39
+ try {
40
+ for (const [index, operation] of operations.entries()) {
41
+ const expected = outcomes[index];
42
+ const entries = operation.events.map(input => ({ eventSourceId: input.source,
43
+ event: Object.assign(new (input.type === 'number' ? fixtures.number : fixtures.text)(), { key: input.value }) }));
44
+ const before = [...scenario.appendedEvents];
45
+ const results = operation.mode === 'single'
46
+ ? [await scenario.append(entries[0].eventSourceId, entries[0].event)] : await scenario.appendMany(entries);
47
+ should(results.every(result => result.isSuccess === expected.success)).equal(true);
48
+ should(results.map(result => result.sequenceNumber.value.toString())).deep.equal(
49
+ expected.success ? expected.sequences : results.map(() => '0'));
50
+ const raw = validate.mock.results.at(-1)!.value as ReturnType<InProcessConstraints['validate']>;
51
+ should(raw.map(violation => ({ ...violation, SequenceNumber: violation.SequenceNumber.toString() }))).deep.equal(expected.wireViolations);
52
+ for (const result of results) {
53
+ should(result.constraintViolations.map(item => ({ id: item.constraintId, message: item.message, details: item.details })))
54
+ .deep.equal(expected.wireViolations.map(item => ({ id: item.ConstraintName,
55
+ message: `Taken: ${item.Details.PropertyName}=${item.Details.PropertyValue}`, details: item.Details })));
56
+ }
57
+ if (!expected.success) should(scenario.appendedEvents).deep.equal(before);
58
+ else should(scenario.appendedEvents.slice(before.length).map(entry => entry.context.eventSourceId))
59
+ .deep.equal(operation.events.map(entry => entry.source));
60
+ should((await scenario.eventSequence.getNextSequenceNumber()).value.toString()).equal(expected.next);
61
+ }
62
+ } finally { validate.mockRestore(); }
63
+ });
64
+ });
65
+
66
+ for (const shape of [{ name: 'scoped', eventTypes, constraints: [fixtures.scoped], eventType: fixtures.number },
67
+ ...fixtures.rejectedDefinitions]) {
68
+ describe(`when a ${shape.name} number attempts to use the new unscoped fractional domain`, () => {
69
+ let scenario: EventScenario;
70
+ let error: unknown;
71
+ let history: EventScenario['appendedEvents'];
72
+ let results: EventScenario['results'];
73
+ let next: bigint;
74
+ beforeEach(async () => {
75
+ scenario = new EventScenario({ artifacts: { eventTypes: shape.eventTypes, constraints: shape.constraints } });
76
+ should((await scenario.append('Existing', new shape.eventType())).isSuccess).equal(true);
77
+ history = [...scenario.appendedEvents];
78
+ results = [...scenario.results];
79
+ next = (await scenario.eventSequence.getNextSequenceNumber()).value;
80
+ const invalid = Object.assign(new shape.eventType(), { key: 1.5 });
81
+ error = await scenario.appendMany('A', [new shape.eventType(), invalid]).then(() => undefined, error => error);
82
+ });
83
+ it('should reject without changing existing history, results or sequence', async () => {
84
+ should(error instanceof UnsupportedEventSequenceOperation).equal(true);
85
+ should(scenario.appendedEvents).deep.equal(history);
86
+ should(scenario.results).deep.equal(results);
87
+ should((await scenario.eventSequence.getNextSequenceNumber()).value).equal(next);
88
+ });
89
+ });
90
+ }
91
+ }
@@ -0,0 +1,51 @@
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 } from '@cratis/fundamentals';
6
+ import { eventType } from '../../../events/eventTypeDecorator.js';
7
+ import { constraint } from '../../../events/constraints/constraint.js';
8
+ import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
9
+ import { fractionalCollisions } from './fractional_collisions.fixture.js';
10
+
11
+ class NumberClaimed { @field(Number) key = 1; }
12
+ eventType('OracleCombinedNumber')(NumberClaimed);
13
+ class TextClaimed { @field(String) key = ''; }
14
+ eventType('OracleCombinedText')(TextClaimed);
15
+ class PairClaimed { @field(Number) key = 1; @field(Number) suffix = 2; }
16
+ eventType('OracleFractionalPair')(PairClaimed);
17
+ class Removed {}
18
+ eventType('OracleFractionalRemoved')(Removed);
19
+ class SharedKey {
20
+ define(builder: IConstraintBuilder) {
21
+ builder.unique(key => key.on(NumberClaimed, event => event.key).on(TextClaimed, event => event.key)
22
+ .withMessage('Taken: {PropertyName}={PropertyValue}'));
23
+ }
24
+ }
25
+ constraint('OracleFractionalKey')(SharedKey);
26
+ class ScopedKey extends SharedKey {
27
+ define(builder: IConstraintBuilder) { super.define(builder.perEventSourceType()); }
28
+ }
29
+ constraint('OracleFractionalKey')(ScopedKey);
30
+ class CompositeKey {
31
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.key, event => event.suffix)); }
32
+ }
33
+ constraint('OracleFractionalComposite')(CompositeKey);
34
+ class RemovableKey {
35
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(NumberClaimed, event => event.key).removedWith(Removed)); }
36
+ }
37
+ constraint('OracleFractionalRemovable')(RemovableKey);
38
+ class OverlapLeft {
39
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.key)); }
40
+ }
41
+ constraint('OracleFractionalOverlapLeft')(OverlapLeft);
42
+ class OverlapRight {
43
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.suffix)); }
44
+ }
45
+ constraint('OracleFractionalOverlapRight')(OverlapRight);
46
+
47
+ fractionalCollisions({ number: NumberClaimed, text: TextClaimed, constraint: SharedKey, scoped: ScopedKey, rejectedDefinitions: [
48
+ { name: 'composite', eventTypes: [PairClaimed], constraints: [CompositeKey], eventType: PairClaimed },
49
+ { name: 'removable', eventTypes: [NumberClaimed, Removed], constraints: [RemovableKey], eventType: NumberClaimed },
50
+ { name: 'overlapping', eventTypes: [PairClaimed], constraints: [OverlapLeft, OverlapRight], eventType: PairClaimed }
51
+ ] });
@@ -0,0 +1,50 @@
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 { eventType } from '../../../events/eventTypeDecorator.js';
6
+ import { constraint } from '../../../events/constraints/constraint.js';
7
+ import type { IConstraintBuilder } from '../../../events/constraints/IConstraintBuilder.js';
8
+ import { fractionalCollisions } from './fractional_collisions.fixture.js';
9
+
10
+ @eventType('OracleCombinedNumber')
11
+ class NumberClaimed { @field(Number) key = 1; }
12
+ @eventType('OracleCombinedText')
13
+ class TextClaimed { @field(String) key = ''; }
14
+ @eventType('OracleFractionalPair')
15
+ class PairClaimed { @field(Number) key = 1; @field(Number) suffix = 2; }
16
+ @eventType('OracleFractionalRemoved')
17
+ class Removed {}
18
+ @constraint('OracleFractionalKey')
19
+ class SharedKey {
20
+ define(builder: IConstraintBuilder) {
21
+ builder.unique(key => key.on(NumberClaimed, event => event.key).on(TextClaimed, event => event.key)
22
+ .withMessage('Taken: {PropertyName}={PropertyValue}'));
23
+ }
24
+ }
25
+ @constraint('OracleFractionalKey')
26
+ class ScopedKey extends SharedKey {
27
+ define(builder: IConstraintBuilder) { super.define(builder.perEventSourceType()); }
28
+ }
29
+ @constraint('OracleFractionalComposite')
30
+ class CompositeKey {
31
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.key, event => event.suffix)); }
32
+ }
33
+ @constraint('OracleFractionalRemovable')
34
+ class RemovableKey {
35
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(NumberClaimed, event => event.key).removedWith(Removed)); }
36
+ }
37
+ @constraint('OracleFractionalOverlapLeft')
38
+ class OverlapLeft {
39
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.key)); }
40
+ }
41
+ @constraint('OracleFractionalOverlapRight')
42
+ class OverlapRight {
43
+ define(builder: IConstraintBuilder) { builder.unique(key => key.on(PairClaimed, event => event.suffix)); }
44
+ }
45
+
46
+ fractionalCollisions({ number: NumberClaimed, text: TextClaimed, constraint: SharedKey, scoped: ScopedKey, rejectedDefinitions: [
47
+ { name: 'composite', eventTypes: [PairClaimed], constraints: [CompositeKey], eventType: PairClaimed },
48
+ { name: 'removable', eventTypes: [NumberClaimed, Removed], constraints: [RemovableKey], eventType: NumberClaimed },
49
+ { name: 'overlapping', eventTypes: [PairClaimed], constraints: [OverlapLeft, OverlapRight], eventType: PairClaimed }
50
+ ] });
@@ -39,7 +39,7 @@ async function unsupported(action: () => unknown, reason: string): Promise<void>
39
39
  describe('when configuring unproven scoped property shapes', () => {
40
40
  for (const [name, configure, reason] of [
41
41
  ['covered removal', (builder: IConstraintBuilder) => builder.unique(value => value.on(Claim, event => event.key).removedWith(Claim)), 'Scoped covered-and-removal property events'],
42
- ['fieldless removal', (builder: IConstraintBuilder) => builder.unique(value => value.on(Claim, event => event.key).removedWith(Fieldless)), 'Scoped fieldless removal events']
42
+ ['fieldless removal', (builder: IConstraintBuilder) => builder.unique(value => value.on(Claim, event => event.key).removedWith(Fieldless).ignoreCasing()), 'Scoped fieldless removers require a case-sensitive single-property unique constraint']
43
43
  ] as const) {
44
44
  it(`should reject ${name} with its specific boundary rather than a compiler failure`, async () => {
45
45
  const eventTypes = name === 'fieldless removal' ? [Claim, Fieldless] : [Claim, Flag, Removed];