@nest-yalc-2/omnikernel-module 2.2.2 → 2.2.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 (74) hide show
  1. package/package.json +17 -15
  2. package/src/__tests__/omni-collection.entity.spec.ts +49 -49
  3. package/src/__tests__/omni-collection.service.spec.ts +83 -83
  4. package/src/__tests__/omni-document.entity.spec.ts +55 -55
  5. package/src/__tests__/omni-document.service.spec.ts +83 -83
  6. package/src/__tests__/omni-extension-projection-constraints.spec.ts +518 -518
  7. package/src/__tests__/omni-extension-projection.registration.spec.ts +947 -946
  8. package/src/__tests__/omni-extension-projection.service.spec.ts +806 -806
  9. package/src/__tests__/omni-external-ref.entity.spec.ts +36 -36
  10. package/src/__tests__/omni-external-ref.service.spec.ts +252 -252
  11. package/src/__tests__/omni-named.entity.spec.ts +33 -33
  12. package/src/__tests__/omni-record.entity.spec.ts +32 -32
  13. package/src/__tests__/omni-record.service.spec.ts +107 -107
  14. package/src/__tests__/omni-relation-semantics.spec.ts +102 -102
  15. package/src/__tests__/omni-relation.entity.spec.ts +38 -38
  16. package/src/__tests__/omni-scope-substrate.spec.ts +81 -81
  17. package/src/__tests__/omni-scoped.backend.spec.ts +115 -115
  18. package/src/__tests__/omni-scoped.service.spec.ts +354 -354
  19. package/src/__tests__/omnikernel.diagnostics.spec.ts +94 -94
  20. package/src/__tests__/omnikernel.module.spec.ts +38 -40
  21. package/src/__tests__/omnikernel.persistence.spec.ts +154 -154
  22. package/src/__tests__/omnikernel.public-api.spec.ts +238 -238
  23. package/src/__tests__/omnikernel.query.service.spec.ts +155 -155
  24. package/src/base/omni-base.entity.ts +41 -41
  25. package/src/base/omni-external-ref.entity.ts +53 -53
  26. package/src/base/omni-named.entity.ts +16 -16
  27. package/src/base/omni-record.entity.ts +51 -51
  28. package/src/base/omni-relation.entity.ts +72 -72
  29. package/src/index.ts +49 -49
  30. package/src/omni-collection-kind.enum.ts +10 -10
  31. package/src/omni-collection.backend.ts +16 -16
  32. package/src/omni-collection.dto.ts +170 -170
  33. package/src/omni-collection.entity.ts +21 -21
  34. package/src/omni-collection.service.ts +75 -75
  35. package/src/omni-document-kind.enum.ts +12 -12
  36. package/src/omni-document.backend.ts +16 -16
  37. package/src/omni-document.dto.ts +198 -198
  38. package/src/omni-document.entity.ts +30 -30
  39. package/src/omni-document.service.ts +75 -75
  40. package/src/omni-dto.helpers.ts +21 -21
  41. package/src/omni-extension-projection.definition.ts +294 -294
  42. package/src/omni-extension-projection.resource.ts +274 -274
  43. package/src/omni-extension-projection.service.ts +452 -452
  44. package/src/omni-external-ref-binding.validator.ts +53 -53
  45. package/src/omni-external-ref-internal-type.enum.ts +11 -11
  46. package/src/omni-external-ref.backend.ts +25 -25
  47. package/src/omni-external-ref.dto.ts +128 -128
  48. package/src/omni-external-ref.service.ts +255 -255
  49. package/src/omni-migration.ts +365 -365
  50. package/src/omni-named.backend.ts +11 -11
  51. package/src/omni-named.dto.ts +86 -86
  52. package/src/omni-projection.catalog.ts +345 -345
  53. package/src/omni-projection.lifecycle.ts +53 -53
  54. package/src/omni-record-status.enum.ts +11 -11
  55. package/src/omni-record.backend.ts +19 -19
  56. package/src/omni-record.dto.ts +157 -157
  57. package/src/omni-record.service.ts +113 -113
  58. package/src/omni-relation-kind.contract.ts +49 -49
  59. package/src/omni-relation-kind.enum.ts +12 -12
  60. package/src/omni-relation-projection.definition.ts +166 -166
  61. package/src/omni-relation-projection.resource.ts +360 -360
  62. package/src/omni-relation-projection.service.ts +610 -610
  63. package/src/omni-relation-semantics.ts +52 -52
  64. package/src/omni-relation-status.enum.ts +11 -11
  65. package/src/omni-relation.backend.ts +21 -21
  66. package/src/omni-relation.dto.ts +142 -142
  67. package/src/omni-relation.service.ts +159 -159
  68. package/src/omni-scope.ts +161 -161
  69. package/src/omni-scoped.backend.ts +110 -110
  70. package/src/omni-scoped.repository.ts +34 -34
  71. package/src/omni-scoped.service.ts +338 -338
  72. package/src/omnikernel.diagnostics.ts +83 -83
  73. package/src/omnikernel.module.ts +97 -97
  74. package/src/omnikernel.query.service.ts +108 -108
@@ -1,452 +1,452 @@
1
- import type { CrudGenFindManyOptions } from '@nest-yalc-2/crud-gen';
2
- import {
3
- PROJECTION_INTEGER_MAX,
4
- ProjectionResourceService,
5
- type ProjectionDialect,
6
- type ProjectionValuePatch,
7
- } from '@nest-yalc-2/crud-gen';
8
- import { YalcEventService } from '@nest-yalc-2/event-manager';
9
- import {
10
- In,
11
- IsNull,
12
- type DataSource,
13
- type EntityManager,
14
- type ObjectLiteral,
15
- type Repository,
16
- } from 'typeorm';
17
- import { OmniRecordEntity } from './base/omni-record.entity.js';
18
- import {
19
- createOmniProjectionReaderCatalog,
20
- type OmniProjectionReaderCatalog,
21
- } from './omni-projection.catalog.js';
22
- import type { OmniExtensionProjectionDefinition } from './omni-extension-projection.definition.js';
23
- import type { OmniProjectionLifecycle } from './omni-projection.lifecycle.js';
24
- import type { OmniScope } from './omni-scope.js';
25
-
26
- function hasOwn(input: Record<string, unknown>, field: string): boolean {
27
- return Object.prototype.hasOwnProperty.call(input, field);
28
- }
29
-
30
- function isUniqueConstraint(error: unknown): boolean {
31
- const candidate = error as { driverError?: { code?: unknown } } | undefined;
32
- const code = candidate?.driverError?.code;
33
- return code === 'SQLITE_CONSTRAINT' || code === '23505';
34
- }
35
-
36
- function isRetryableTransactionError(error: unknown): boolean {
37
- const candidate = error as {
38
- code?: unknown;
39
- driverError?: { code?: unknown };
40
- };
41
- const code = candidate?.driverError?.code ?? candidate?.code;
42
- return (
43
- code === '40001' ||
44
- code === 'SQLITE_BUSY' ||
45
- code === 'SQLITE_BUSY_SNAPSHOT'
46
- );
47
- }
48
-
49
- /**
50
- * Generated-CRUD compatible store for a dedicated extension table. It keeps
51
- * the Omni record as the only root identity and revision owner, while the
52
- * extension table owns projected columns and its native JSON payload.
53
- */
54
- export class OmniExtensionProjectionService<
55
- Extension extends ObjectLiteral,
56
- > extends ProjectionResourceService<Extension> {
57
- constructor(
58
- extensionRepository: Repository<Extension>,
59
- private readonly ownerRepository: Repository<OmniRecordEntity>,
60
- private readonly dataSource: DataSource,
61
- scope: OmniScope,
62
- dialect: ProjectionDialect,
63
- events: YalcEventService,
64
- private readonly omniDefinition: OmniExtensionProjectionDefinition,
65
- private readonly lifecycle?: OmniProjectionLifecycle<
66
- OmniExtensionProjectionDefinition,
67
- Extension
68
- >,
69
- private readonly readerCatalog?: OmniProjectionReaderCatalog,
70
- ) {
71
- super(extensionRepository, scope, dialect, events, omniDefinition);
72
- }
73
-
74
- override async getEntity(
75
- conditions: Record<string, unknown>,
76
- _fields?: string[],
77
- _relations?: string[],
78
- _databaseName?: string,
79
- options?: { failOnNull?: boolean },
80
- ): Promise<Extension | null> {
81
- const guid = this.guidFromConditions(conditions);
82
- const entity = await this.readOne(guid);
83
- if (!entity && options?.failOnNull) this.notFound();
84
- return entity;
85
- }
86
-
87
- override async getEntityListExtended(
88
- findOptions: CrudGenFindManyOptions<Extension> = {},
89
- withCount = false,
90
- ): Promise<Extension[] | [Extension[], number]> {
91
- const [extensions, count] = await this.dialect.findMany(
92
- this.repository,
93
- this.definition,
94
- this.scope.scopeId,
95
- this.filtersFromFindOptions(findOptions),
96
- this.sortingFromFindOptions(findOptions),
97
- this.pageFromFindOptions(findOptions),
98
- );
99
- const guidColumn = this.definition.identity.column;
100
- const guids = extensions.map(
101
- (extension) =>
102
- (extension as Record<string, unknown>)[guidColumn] as string,
103
- );
104
- if (guids.length === 0) return withCount ? [[], count] : [];
105
-
106
- const owners = await this.ownerRepository.find({
107
- where: {
108
- scopeId: this.scope.scopeId,
109
- guid: In(guids),
110
- kind: this.omniDefinition.owner.kind,
111
- payloadSchemaId: this.omniDefinition.owner.schema.id,
112
- payloadSchemaVersion: this.omniDefinition.owner.schema.version,
113
- deletedAt: IsNull(),
114
- },
115
- });
116
- const ownersByGuid = new Map(owners.map((owner) => [owner.guid, owner]));
117
- if (ownersByGuid.size !== extensions.length) {
118
- throw new Error(
119
- 'Omni extension projection invariant failed: an extension owner is unavailable.',
120
- );
121
- }
122
- const projected = extensions.map((extension) =>
123
- this.merge(extension, ownersByGuid.get((extension as any)[guidColumn])!),
124
- );
125
- return withCount ? [projected, count] : projected;
126
- }
127
-
128
- override async createEntity(
129
- input: Record<string, unknown>,
130
- ): Promise<Extension> {
131
- this.rejectUnknownInput(input, true);
132
- const extension = this.createExtension(input);
133
- const guid = extension[this.definition.identity.column] as string;
134
- const owner = this.ownerRepository.create({
135
- scopeId: this.scope.scopeId,
136
- guid,
137
- title: this.omniDefinition.owner.title,
138
- kind: this.omniDefinition.owner.kind,
139
- status: this.omniDefinition.owner.status,
140
- payload: null,
141
- payloadSchemaId: this.omniDefinition.owner.schema.id,
142
- payloadSchemaVersion: this.omniDefinition.owner.schema.version,
143
- });
144
-
145
- try {
146
- return await this.mutate(async (manager) => {
147
- await this.lifecycle?.beforeCreate?.({
148
- definition: this.omniDefinition,
149
- scope: this.scope,
150
- manager,
151
- readers: this.readers(manager),
152
- input,
153
- });
154
- await manager.getRepository(OmniRecordEntity).save(owner);
155
- const saved = await manager
156
- .getRepository(this.repository.target)
157
- .save(extension as Extension);
158
- return this.merge(saved, owner);
159
- });
160
- } catch (error) {
161
- if (isUniqueConstraint(error)) this.identityConflict();
162
- throw error;
163
- }
164
- }
165
-
166
- override async updateEntity(
167
- conditions: Record<string, unknown>,
168
- input: Record<string, unknown>,
169
- ): Promise<Extension> {
170
- this.rejectUnknownInput(input, false);
171
- const guid = this.guidFromConditions(conditions);
172
- const expectedRevision = input.expectedRevision;
173
- if (
174
- typeof expectedRevision !== 'number' ||
175
- !Number.isInteger(expectedRevision) ||
176
- expectedRevision < 1 ||
177
- expectedRevision >= PROJECTION_INTEGER_MAX
178
- ) {
179
- this.invalid(
180
- `expectedRevision must be an integer between 1 and ${PROJECTION_INTEGER_MAX - 1}.`,
181
- );
182
- }
183
- const patch = this.createValuePatch(guid, input);
184
-
185
- return this.mutate(async (manager) => {
186
- const owners = manager.getRepository(OmniRecordEntity);
187
- const extensions = manager.getRepository(this.repository.target);
188
- const currentOwner = await this.findOwner(guid, manager);
189
- const currentExtension = await extensions.findOne({
190
- where: {
191
- [this.definition.scope.column]: this.scope.scopeId,
192
- [this.definition.identity.column]: guid,
193
- } as any,
194
- });
195
- if (!currentOwner) this.notFound();
196
- if (currentOwner.revision !== expectedRevision) {
197
- await this.throwUpdateMiss(guid, manager);
198
- }
199
- if (!currentExtension) {
200
- throw new Error(
201
- 'Omni extension projection invariant failed: extension row is unavailable.',
202
- );
203
- }
204
- await this.lifecycle?.beforeUpdate?.({
205
- definition: this.omniDefinition,
206
- scope: this.scope,
207
- manager,
208
- readers: this.readers(manager),
209
- input,
210
- current: this.merge(currentExtension, currentOwner),
211
- });
212
- const result = await owners
213
- .createQueryBuilder()
214
- .update()
215
- .set({ revision: () => '"revision" + 1' })
216
- .where(
217
- '"scopeId" = :scopeId AND "guid" = :guid AND "revision" = :expectedRevision AND "kind" = :kind AND "payloadSchemaId" = :schemaId AND "payloadSchemaVersion" = :schemaVersion AND "deletedAt" IS NULL',
218
- {
219
- scopeId: this.scope.scopeId,
220
- guid,
221
- expectedRevision,
222
- kind: this.omniDefinition.owner.kind,
223
- schemaId: this.omniDefinition.owner.schema.id,
224
- schemaVersion: this.omniDefinition.owner.schema.version,
225
- },
226
- )
227
- .execute();
228
- if (!result.affected) await this.throwUpdateMiss(guid, manager);
229
-
230
- const patched = await this.dialect.patchValues(
231
- extensions,
232
- this.definition,
233
- patch,
234
- );
235
- if (patched !== 1) {
236
- throw new Error(
237
- 'Omni extension projection invariant failed: extension row is unavailable.',
238
- );
239
- }
240
- const extension = await extensions.findOneOrFail({
241
- where: {
242
- [this.definition.scope.column]: this.scope.scopeId,
243
- [this.definition.identity.column]: guid,
244
- } as any,
245
- });
246
- const owner = await owners.findOneOrFail({
247
- where: { scopeId: this.scope.scopeId, guid },
248
- });
249
- return this.merge(extension, owner);
250
- });
251
- }
252
-
253
- override async deleteEntity(
254
- conditions: Record<string, unknown>,
255
- ): Promise<boolean> {
256
- const guid = this.guidFromConditions(conditions);
257
- await this.mutate(async (manager) => {
258
- const owner = await this.findOwner(guid, manager);
259
- if (!owner) this.notFound();
260
- const extension = await manager
261
- .getRepository(this.repository.target)
262
- .findOne({
263
- where: {
264
- [this.definition.scope.column]: this.scope.scopeId,
265
- [this.definition.identity.column]: guid,
266
- } as any,
267
- });
268
- if (!extension) {
269
- throw new Error(
270
- 'Omni extension projection invariant failed: extension row is unavailable.',
271
- );
272
- }
273
- await this.lifecycle?.beforeDelete?.({
274
- definition: this.omniDefinition,
275
- scope: this.scope,
276
- manager,
277
- readers: this.readers(manager),
278
- input: {},
279
- current: this.merge(extension, owner),
280
- });
281
- const result = await manager.getRepository(OmniRecordEntity).delete({
282
- scopeId: this.scope.scopeId,
283
- guid,
284
- kind: this.omniDefinition.owner.kind,
285
- payloadSchemaId: this.omniDefinition.owner.schema.id,
286
- payloadSchemaVersion: this.omniDefinition.owner.schema.version,
287
- });
288
- if (!result.affected) this.notFound();
289
- });
290
- return true;
291
- }
292
-
293
- private createExtension(
294
- input: Record<string, unknown>,
295
- ): Record<string, unknown> {
296
- const extension: Record<string, unknown> = {
297
- [this.definition.scope.column]: this.scope.scopeId,
298
- [this.definition.payload.column]: this.createPayload(input),
299
- };
300
- for (const field of this.definition.fields) {
301
- const value = input[field.name];
302
- if (field.requiredOnCreate && (value === undefined || value === null)) {
303
- this.invalid(`Projection field ${field.name} is required on create.`);
304
- }
305
- if (value === null && !field.nullable) {
306
- this.invalid(`Projection field ${field.name} cannot be null.`);
307
- }
308
- if (value !== undefined && field.storage === 'column') {
309
- extension[field.column ?? field.name] = this.normalizeValue(
310
- field,
311
- value,
312
- );
313
- }
314
- }
315
- return extension;
316
- }
317
-
318
- private readers(manager: EntityManager) {
319
- return (
320
- this.readerCatalog ??
321
- createOmniProjectionReaderCatalog([
322
- {
323
- type: 'extension',
324
- id: this.omniDefinition.id,
325
- entity: this.repository.target,
326
- definition: this.omniDefinition,
327
- },
328
- ])
329
- ).bind(manager, this.scope);
330
- }
331
-
332
- private async mutate<T>(
333
- work: (manager: EntityManager) => Promise<T>,
334
- ): Promise<T> {
335
- try {
336
- if (this.lifecycle) {
337
- return await this.dataSource.transaction('SERIALIZABLE', work);
338
- }
339
- return await this.dataSource.transaction(work);
340
- } catch (error) {
341
- if (isRetryableTransactionError(error)) {
342
- throw this.events.errorConflict(
343
- 'projection.concurrent.write.conflict',
344
- {
345
- response: {
346
- message:
347
- 'Omni projection concurrent write conflict; retry the mutation.',
348
- },
349
- },
350
- );
351
- }
352
- throw error;
353
- }
354
- }
355
-
356
- private createValuePatch(
357
- guid: string,
358
- input: Record<string, unknown>,
359
- ): ProjectionValuePatch {
360
- const patch: ProjectionValuePatch = {
361
- scopeId: this.scope.scopeId,
362
- guid,
363
- columnValues: {},
364
- jsonValues: [],
365
- };
366
- for (const field of this.definition.fields) {
367
- if (
368
- field.name === this.definition.identity.column ||
369
- !hasOwn(input, field.name)
370
- ) {
371
- continue;
372
- }
373
- const value = input[field.name];
374
- if (value === null && !field.nullable) {
375
- this.invalid(`Projection field ${field.name} cannot be null.`);
376
- }
377
- const normalized = this.normalizeValue(field, value);
378
- if (field.storage === 'column') {
379
- patch.columnValues[field.column ?? field.name] = normalized;
380
- } else {
381
- patch.jsonValues.push({ field, value: normalized });
382
- }
383
- }
384
- if (
385
- Object.keys(patch.columnValues).length === 0 &&
386
- patch.jsonValues.length === 0
387
- ) {
388
- this.invalid('Projection update requires at least one writable field.');
389
- }
390
- return patch;
391
- }
392
-
393
- private async readOne(guid: string): Promise<Extension | null> {
394
- const extension = await this.repository.findOne({
395
- where: {
396
- [this.definition.scope.column]: this.scope.scopeId,
397
- [this.definition.identity.column]: guid,
398
- } as any,
399
- });
400
- if (!extension) return null;
401
- const owner = await this.findOwner(guid);
402
- return owner ? this.merge(extension, owner) : null;
403
- }
404
-
405
- private async findOwner(
406
- guid: string,
407
- manager?: EntityManager,
408
- ): Promise<OmniRecordEntity | null> {
409
- return (
410
- manager?.getRepository(OmniRecordEntity) ?? this.ownerRepository
411
- ).findOne({
412
- where: {
413
- scopeId: this.scope.scopeId,
414
- guid,
415
- kind: this.omniDefinition.owner.kind,
416
- payloadSchemaId: this.omniDefinition.owner.schema.id,
417
- payloadSchemaVersion: this.omniDefinition.owner.schema.version,
418
- deletedAt: IsNull(),
419
- },
420
- });
421
- }
422
-
423
- private merge(extension: Extension, owner: OmniRecordEntity): Extension {
424
- return {
425
- ...(this.project(extension) as Record<string, unknown>),
426
- scopeId: owner.scopeId,
427
- guid: owner.guid,
428
- [this.definition.revision.column]: owner.revision,
429
- createdAt: owner.createdAt,
430
- updatedAt: owner.updatedAt,
431
- deletedAt: owner.deletedAt,
432
- } as unknown as Extension;
433
- }
434
-
435
- private async throwUpdateMiss(
436
- guid: string,
437
- manager: EntityManager,
438
- ): Promise<never> {
439
- if (!(await this.findOwner(guid, manager))) this.notFound();
440
- throw this.events.errorConflict('projection.revision.conflict', {
441
- response: { message: 'Projection resource revision is stale.' },
442
- });
443
- }
444
-
445
- private identityConflict(): never {
446
- throw this.events.errorConflict('projection.identity.conflict', {
447
- response: {
448
- message: 'Projection identity already exists in this scope.',
449
- },
450
- });
451
- }
452
- }
1
+ import type { CrudGenFindManyOptions } from '@nest-yalc-2/crud-gen';
2
+ import {
3
+ PROJECTION_INTEGER_MAX,
4
+ ProjectionResourceService,
5
+ type ProjectionDialect,
6
+ type ProjectionValuePatch,
7
+ } from '@nest-yalc-2/crud-gen';
8
+ import { YalcEventService } from '@nest-yalc-2/event-manager';
9
+ import {
10
+ In,
11
+ IsNull,
12
+ type DataSource,
13
+ type EntityManager,
14
+ type ObjectLiteral,
15
+ type Repository,
16
+ } from 'typeorm';
17
+ import { OmniRecordEntity } from './base/omni-record.entity.js';
18
+ import {
19
+ createOmniProjectionReaderCatalog,
20
+ type OmniProjectionReaderCatalog,
21
+ } from './omni-projection.catalog.js';
22
+ import type { OmniExtensionProjectionDefinition } from './omni-extension-projection.definition.js';
23
+ import type { OmniProjectionLifecycle } from './omni-projection.lifecycle.js';
24
+ import type { OmniScope } from './omni-scope.js';
25
+
26
+ function hasOwn(input: Record<string, unknown>, field: string): boolean {
27
+ return Object.prototype.hasOwnProperty.call(input, field);
28
+ }
29
+
30
+ function isUniqueConstraint(error: unknown): boolean {
31
+ const candidate = error as { driverError?: { code?: unknown } } | undefined;
32
+ const code = candidate?.driverError?.code;
33
+ return code === 'SQLITE_CONSTRAINT' || code === '23505';
34
+ }
35
+
36
+ function isRetryableTransactionError(error: unknown): boolean {
37
+ const candidate = error as {
38
+ code?: unknown;
39
+ driverError?: { code?: unknown };
40
+ };
41
+ const code = candidate?.driverError?.code ?? candidate?.code;
42
+ return (
43
+ code === '40001' ||
44
+ code === 'SQLITE_BUSY' ||
45
+ code === 'SQLITE_BUSY_SNAPSHOT'
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Generated-CRUD compatible store for a dedicated extension table. It keeps
51
+ * the Omni record as the only root identity and revision owner, while the
52
+ * extension table owns projected columns and its native JSON payload.
53
+ */
54
+ export class OmniExtensionProjectionService<
55
+ Extension extends ObjectLiteral,
56
+ > extends ProjectionResourceService<Extension> {
57
+ constructor(
58
+ extensionRepository: Repository<Extension>,
59
+ private readonly ownerRepository: Repository<OmniRecordEntity>,
60
+ private readonly dataSource: DataSource,
61
+ scope: OmniScope,
62
+ dialect: ProjectionDialect,
63
+ events: YalcEventService,
64
+ private readonly omniDefinition: OmniExtensionProjectionDefinition,
65
+ private readonly lifecycle?: OmniProjectionLifecycle<
66
+ OmniExtensionProjectionDefinition,
67
+ Extension
68
+ >,
69
+ private readonly readerCatalog?: OmniProjectionReaderCatalog,
70
+ ) {
71
+ super(extensionRepository, scope, dialect, events, omniDefinition);
72
+ }
73
+
74
+ override async getEntity(
75
+ conditions: Record<string, unknown>,
76
+ _fields?: string[],
77
+ _relations?: string[],
78
+ _databaseName?: string,
79
+ options?: { failOnNull?: boolean },
80
+ ): Promise<Extension | null> {
81
+ const guid = this.guidFromConditions(conditions);
82
+ const entity = await this.readOne(guid);
83
+ if (!entity && options?.failOnNull) this.notFound();
84
+ return entity;
85
+ }
86
+
87
+ override async getEntityListExtended(
88
+ findOptions: CrudGenFindManyOptions<Extension> = {},
89
+ withCount = false,
90
+ ): Promise<Extension[] | [Extension[], number]> {
91
+ const [extensions, count] = await this.dialect.findMany(
92
+ this.repository,
93
+ this.definition,
94
+ this.scope.scopeId,
95
+ this.filtersFromFindOptions(findOptions),
96
+ this.sortingFromFindOptions(findOptions),
97
+ this.pageFromFindOptions(findOptions),
98
+ );
99
+ const guidColumn = this.definition.identity.column;
100
+ const guids = extensions.map(
101
+ (extension) =>
102
+ (extension as Record<string, unknown>)[guidColumn] as string,
103
+ );
104
+ if (guids.length === 0) return withCount ? [[], count] : [];
105
+
106
+ const owners = await this.ownerRepository.find({
107
+ where: {
108
+ scopeId: this.scope.scopeId,
109
+ guid: In(guids),
110
+ kind: this.omniDefinition.owner.kind,
111
+ payloadSchemaId: this.omniDefinition.owner.schema.id,
112
+ payloadSchemaVersion: this.omniDefinition.owner.schema.version,
113
+ deletedAt: IsNull(),
114
+ },
115
+ });
116
+ const ownersByGuid = new Map(owners.map((owner) => [owner.guid, owner]));
117
+ if (ownersByGuid.size !== extensions.length) {
118
+ throw new Error(
119
+ 'Omni extension projection invariant failed: an extension owner is unavailable.',
120
+ );
121
+ }
122
+ const projected = extensions.map((extension) =>
123
+ this.merge(extension, ownersByGuid.get((extension as any)[guidColumn])!),
124
+ );
125
+ return withCount ? [projected, count] : projected;
126
+ }
127
+
128
+ override async createEntity(
129
+ input: Record<string, unknown>,
130
+ ): Promise<Extension> {
131
+ this.rejectUnknownInput(input, true);
132
+ const extension = this.createExtension(input);
133
+ const guid = extension[this.definition.identity.column] as string;
134
+ const owner = this.ownerRepository.create({
135
+ scopeId: this.scope.scopeId,
136
+ guid,
137
+ title: this.omniDefinition.owner.title,
138
+ kind: this.omniDefinition.owner.kind,
139
+ status: this.omniDefinition.owner.status,
140
+ payload: null,
141
+ payloadSchemaId: this.omniDefinition.owner.schema.id,
142
+ payloadSchemaVersion: this.omniDefinition.owner.schema.version,
143
+ });
144
+
145
+ try {
146
+ return await this.mutate(async (manager) => {
147
+ await this.lifecycle?.beforeCreate?.({
148
+ definition: this.omniDefinition,
149
+ scope: this.scope,
150
+ manager,
151
+ readers: this.readers(manager),
152
+ input,
153
+ });
154
+ await manager.getRepository(OmniRecordEntity).save(owner);
155
+ const saved = await manager
156
+ .getRepository(this.repository.target)
157
+ .save(extension as Extension);
158
+ return this.merge(saved, owner);
159
+ });
160
+ } catch (error) {
161
+ if (isUniqueConstraint(error)) this.identityConflict();
162
+ throw error;
163
+ }
164
+ }
165
+
166
+ override async updateEntity(
167
+ conditions: Record<string, unknown>,
168
+ input: Record<string, unknown>,
169
+ ): Promise<Extension> {
170
+ this.rejectUnknownInput(input, false);
171
+ const guid = this.guidFromConditions(conditions);
172
+ const expectedRevision = input.expectedRevision;
173
+ if (
174
+ typeof expectedRevision !== 'number' ||
175
+ !Number.isInteger(expectedRevision) ||
176
+ expectedRevision < 1 ||
177
+ expectedRevision >= PROJECTION_INTEGER_MAX
178
+ ) {
179
+ this.invalid(
180
+ `expectedRevision must be an integer between 1 and ${PROJECTION_INTEGER_MAX - 1}.`,
181
+ );
182
+ }
183
+ const patch = this.createValuePatch(guid, input);
184
+
185
+ return this.mutate(async (manager) => {
186
+ const owners = manager.getRepository(OmniRecordEntity);
187
+ const extensions = manager.getRepository(this.repository.target);
188
+ const currentOwner = await this.findOwner(guid, manager);
189
+ const currentExtension = await extensions.findOne({
190
+ where: {
191
+ [this.definition.scope.column]: this.scope.scopeId,
192
+ [this.definition.identity.column]: guid,
193
+ } as any,
194
+ });
195
+ if (!currentOwner) this.notFound();
196
+ if (currentOwner.revision !== expectedRevision) {
197
+ await this.throwUpdateMiss(guid, manager);
198
+ }
199
+ if (!currentExtension) {
200
+ throw new Error(
201
+ 'Omni extension projection invariant failed: extension row is unavailable.',
202
+ );
203
+ }
204
+ await this.lifecycle?.beforeUpdate?.({
205
+ definition: this.omniDefinition,
206
+ scope: this.scope,
207
+ manager,
208
+ readers: this.readers(manager),
209
+ input,
210
+ current: this.merge(currentExtension, currentOwner),
211
+ });
212
+ const result = await owners
213
+ .createQueryBuilder()
214
+ .update()
215
+ .set({ revision: () => '"revision" + 1' })
216
+ .where(
217
+ '"scopeId" = :scopeId AND "guid" = :guid AND "revision" = :expectedRevision AND "kind" = :kind AND "payloadSchemaId" = :schemaId AND "payloadSchemaVersion" = :schemaVersion AND "deletedAt" IS NULL',
218
+ {
219
+ scopeId: this.scope.scopeId,
220
+ guid,
221
+ expectedRevision,
222
+ kind: this.omniDefinition.owner.kind,
223
+ schemaId: this.omniDefinition.owner.schema.id,
224
+ schemaVersion: this.omniDefinition.owner.schema.version,
225
+ },
226
+ )
227
+ .execute();
228
+ if (!result.affected) await this.throwUpdateMiss(guid, manager);
229
+
230
+ const patched = await this.dialect.patchValues(
231
+ extensions,
232
+ this.definition,
233
+ patch,
234
+ );
235
+ if (patched !== 1) {
236
+ throw new Error(
237
+ 'Omni extension projection invariant failed: extension row is unavailable.',
238
+ );
239
+ }
240
+ const extension = await extensions.findOneOrFail({
241
+ where: {
242
+ [this.definition.scope.column]: this.scope.scopeId,
243
+ [this.definition.identity.column]: guid,
244
+ } as any,
245
+ });
246
+ const owner = await owners.findOneOrFail({
247
+ where: { scopeId: this.scope.scopeId, guid },
248
+ });
249
+ return this.merge(extension, owner);
250
+ });
251
+ }
252
+
253
+ override async deleteEntity(
254
+ conditions: Record<string, unknown>,
255
+ ): Promise<boolean> {
256
+ const guid = this.guidFromConditions(conditions);
257
+ await this.mutate(async (manager) => {
258
+ const owner = await this.findOwner(guid, manager);
259
+ if (!owner) this.notFound();
260
+ const extension = await manager
261
+ .getRepository(this.repository.target)
262
+ .findOne({
263
+ where: {
264
+ [this.definition.scope.column]: this.scope.scopeId,
265
+ [this.definition.identity.column]: guid,
266
+ } as any,
267
+ });
268
+ if (!extension) {
269
+ throw new Error(
270
+ 'Omni extension projection invariant failed: extension row is unavailable.',
271
+ );
272
+ }
273
+ await this.lifecycle?.beforeDelete?.({
274
+ definition: this.omniDefinition,
275
+ scope: this.scope,
276
+ manager,
277
+ readers: this.readers(manager),
278
+ input: {},
279
+ current: this.merge(extension, owner),
280
+ });
281
+ const result = await manager.getRepository(OmniRecordEntity).delete({
282
+ scopeId: this.scope.scopeId,
283
+ guid,
284
+ kind: this.omniDefinition.owner.kind,
285
+ payloadSchemaId: this.omniDefinition.owner.schema.id,
286
+ payloadSchemaVersion: this.omniDefinition.owner.schema.version,
287
+ });
288
+ if (!result.affected) this.notFound();
289
+ });
290
+ return true;
291
+ }
292
+
293
+ private createExtension(
294
+ input: Record<string, unknown>,
295
+ ): Record<string, unknown> {
296
+ const extension: Record<string, unknown> = {
297
+ [this.definition.scope.column]: this.scope.scopeId,
298
+ [this.definition.payload.column]: this.createPayload(input),
299
+ };
300
+ for (const field of this.definition.fields) {
301
+ const value = input[field.name];
302
+ if (field.requiredOnCreate && (value === undefined || value === null)) {
303
+ this.invalid(`Projection field ${field.name} is required on create.`);
304
+ }
305
+ if (value === null && !field.nullable) {
306
+ this.invalid(`Projection field ${field.name} cannot be null.`);
307
+ }
308
+ if (value !== undefined && field.storage === 'column') {
309
+ extension[field.column ?? field.name] = this.normalizeValue(
310
+ field,
311
+ value,
312
+ );
313
+ }
314
+ }
315
+ return extension;
316
+ }
317
+
318
+ private readers(manager: EntityManager) {
319
+ return (
320
+ this.readerCatalog ??
321
+ createOmniProjectionReaderCatalog([
322
+ {
323
+ type: 'extension',
324
+ id: this.omniDefinition.id,
325
+ entity: this.repository.target,
326
+ definition: this.omniDefinition,
327
+ },
328
+ ])
329
+ ).bind(manager, this.scope);
330
+ }
331
+
332
+ private async mutate<T>(
333
+ work: (manager: EntityManager) => Promise<T>,
334
+ ): Promise<T> {
335
+ try {
336
+ if (this.lifecycle) {
337
+ return await this.dataSource.transaction('SERIALIZABLE', work);
338
+ }
339
+ return await this.dataSource.transaction(work);
340
+ } catch (error) {
341
+ if (isRetryableTransactionError(error)) {
342
+ throw this.events.errorConflict(
343
+ 'projection.concurrent.write.conflict',
344
+ {
345
+ response: {
346
+ message:
347
+ 'Omni projection concurrent write conflict; retry the mutation.',
348
+ },
349
+ },
350
+ );
351
+ }
352
+ throw error;
353
+ }
354
+ }
355
+
356
+ private createValuePatch(
357
+ guid: string,
358
+ input: Record<string, unknown>,
359
+ ): ProjectionValuePatch {
360
+ const patch: ProjectionValuePatch = {
361
+ scopeId: this.scope.scopeId,
362
+ guid,
363
+ columnValues: {},
364
+ jsonValues: [],
365
+ };
366
+ for (const field of this.definition.fields) {
367
+ if (
368
+ field.name === this.definition.identity.column ||
369
+ !hasOwn(input, field.name)
370
+ ) {
371
+ continue;
372
+ }
373
+ const value = input[field.name];
374
+ if (value === null && !field.nullable) {
375
+ this.invalid(`Projection field ${field.name} cannot be null.`);
376
+ }
377
+ const normalized = this.normalizeValue(field, value);
378
+ if (field.storage === 'column') {
379
+ patch.columnValues[field.column ?? field.name] = normalized;
380
+ } else {
381
+ patch.jsonValues.push({ field, value: normalized });
382
+ }
383
+ }
384
+ if (
385
+ Object.keys(patch.columnValues).length === 0 &&
386
+ patch.jsonValues.length === 0
387
+ ) {
388
+ this.invalid('Projection update requires at least one writable field.');
389
+ }
390
+ return patch;
391
+ }
392
+
393
+ private async readOne(guid: string): Promise<Extension | null> {
394
+ const extension = await this.repository.findOne({
395
+ where: {
396
+ [this.definition.scope.column]: this.scope.scopeId,
397
+ [this.definition.identity.column]: guid,
398
+ } as any,
399
+ });
400
+ if (!extension) return null;
401
+ const owner = await this.findOwner(guid);
402
+ return owner ? this.merge(extension, owner) : null;
403
+ }
404
+
405
+ private async findOwner(
406
+ guid: string,
407
+ manager?: EntityManager,
408
+ ): Promise<OmniRecordEntity | null> {
409
+ return (
410
+ manager?.getRepository(OmniRecordEntity) ?? this.ownerRepository
411
+ ).findOne({
412
+ where: {
413
+ scopeId: this.scope.scopeId,
414
+ guid,
415
+ kind: this.omniDefinition.owner.kind,
416
+ payloadSchemaId: this.omniDefinition.owner.schema.id,
417
+ payloadSchemaVersion: this.omniDefinition.owner.schema.version,
418
+ deletedAt: IsNull(),
419
+ },
420
+ });
421
+ }
422
+
423
+ private merge(extension: Extension, owner: OmniRecordEntity): Extension {
424
+ return {
425
+ ...(this.project(extension) as Record<string, unknown>),
426
+ scopeId: owner.scopeId,
427
+ guid: owner.guid,
428
+ [this.definition.revision.column]: owner.revision,
429
+ createdAt: owner.createdAt,
430
+ updatedAt: owner.updatedAt,
431
+ deletedAt: owner.deletedAt,
432
+ } as unknown as Extension;
433
+ }
434
+
435
+ private async throwUpdateMiss(
436
+ guid: string,
437
+ manager: EntityManager,
438
+ ): Promise<never> {
439
+ if (!(await this.findOwner(guid, manager))) this.notFound();
440
+ throw this.events.errorConflict('projection.revision.conflict', {
441
+ response: { message: 'Projection resource revision is stale.' },
442
+ });
443
+ }
444
+
445
+ private identityConflict(): never {
446
+ throw this.events.errorConflict('projection.identity.conflict', {
447
+ response: {
448
+ message: 'Projection identity already exists in this scope.',
449
+ },
450
+ });
451
+ }
452
+ }