@woltz/rich-domain 1.3.0 → 1.3.2

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 (76) hide show
  1. package/dist/aggregate-changes.js +1 -1
  2. package/dist/aggregate-changes.js.map +1 -1
  3. package/dist/base-entity.d.ts.map +1 -1
  4. package/dist/base-entity.js +17 -5
  5. package/dist/base-entity.js.map +1 -1
  6. package/dist/change-tracker.d.ts +1 -1
  7. package/dist/change-tracker.d.ts.map +1 -1
  8. package/dist/change-tracker.js +20 -8
  9. package/dist/change-tracker.js.map +1 -1
  10. package/dist/criteria.js +6 -5
  11. package/dist/criteria.js.map +1 -1
  12. package/dist/domain-event-bus.js +4 -4
  13. package/dist/domain-event-bus.js.map +1 -1
  14. package/dist/domain-event.js +3 -0
  15. package/dist/domain-event.js.map +1 -1
  16. package/dist/entity-changes.js +1 -0
  17. package/dist/entity-changes.js.map +1 -1
  18. package/dist/entity-schema-registry.d.ts +4 -0
  19. package/dist/entity-schema-registry.d.ts.map +1 -1
  20. package/dist/entity-schema-registry.js +8 -6
  21. package/dist/entity-schema-registry.js.map +1 -1
  22. package/dist/exceptions.js +26 -1
  23. package/dist/exceptions.js.map +1 -1
  24. package/dist/id.js +2 -0
  25. package/dist/id.js.map +1 -1
  26. package/dist/index.d.ts +1 -1
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js.map +1 -1
  29. package/dist/paginated-result.d.ts.map +1 -1
  30. package/dist/paginated-result.js +9 -0
  31. package/dist/paginated-result.js.map +1 -1
  32. package/dist/repository/unit-of-work.js +3 -7
  33. package/dist/repository/unit-of-work.js.map +1 -1
  34. package/dist/types/domain.d.ts +0 -1
  35. package/dist/types/domain.d.ts.map +1 -1
  36. package/dist/validation-error.d.ts +15 -1
  37. package/dist/validation-error.d.ts.map +1 -1
  38. package/dist/validation-error.js +46 -3
  39. package/dist/validation-error.js.map +1 -1
  40. package/dist/value-object.d.ts.map +1 -1
  41. package/dist/value-object.js +29 -1
  42. package/dist/value-object.js.map +1 -1
  43. package/package.json +9 -11
  44. package/eslint.config.js +0 -57
  45. package/jest.config.js +0 -21
  46. package/src/aggregate-changes.ts +0 -444
  47. package/src/base-entity.ts +0 -404
  48. package/src/change-tracker.ts +0 -1133
  49. package/src/constants.ts +0 -81
  50. package/src/criteria.ts +0 -521
  51. package/src/crypto.ts +0 -31
  52. package/src/domain-event-bus.ts +0 -152
  53. package/src/domain-event.ts +0 -49
  54. package/src/entity-changes.ts +0 -146
  55. package/src/entity-schema-registry.ts +0 -502
  56. package/src/entity.ts +0 -5
  57. package/src/exceptions.ts +0 -435
  58. package/src/id.ts +0 -98
  59. package/src/index.ts +0 -52
  60. package/src/mapper.ts +0 -6
  61. package/src/paginated-result.ts +0 -238
  62. package/src/repository/base-repository.ts +0 -33
  63. package/src/repository/index.ts +0 -3
  64. package/src/repository/unit-of-work.ts +0 -76
  65. package/src/types/change-tracker.ts +0 -264
  66. package/src/types/criteria.ts +0 -159
  67. package/src/types/domain-event.ts +0 -38
  68. package/src/types/domain.ts +0 -34
  69. package/src/types/index.ts +0 -7
  70. package/src/types/standard-schema.ts +0 -19
  71. package/src/types/unit-of-work.ts +0 -46
  72. package/src/types/utils.ts +0 -20
  73. package/src/utils/criteria-operator-validation.ts +0 -209
  74. package/src/utils/helpers.ts +0 -34
  75. package/src/validation-error.ts +0 -91
  76. package/src/value-object.ts +0 -244
@@ -1,1133 +0,0 @@
1
- import { Id } from "./id";
2
- import { Entity } from "./entity";
3
- import { ValueObject } from "./value-object";
4
- import { ArrayState, HistoryEntry, TrackedItem } from "./types";
5
- import { EntityChangeState } from "./types/change-tracker";
6
- import { AggregateChanges } from "./aggregate-changes";
7
-
8
- /**
9
- * Callback for validation on property change.
10
- * Return false to reject the change, or throw an error.
11
- */
12
- export type OnChangeValidator = (
13
- path: string,
14
- oldValue: any,
15
- newValue: any
16
- ) => boolean | void;
17
-
18
- /**
19
- * Tracks changes in Aggregates using Proxy.
20
- *
21
- * Features:
22
- * - Tracks changes in primitive properties
23
- * - Tracks changes in nested entities (1:1)
24
- * - Tracks changes in collections (1:N)
25
- * - Supports Value Objects with identityKey
26
- * - Calculates depth automatically
27
- * - Generates AggregateChanges for persistence
28
- * - Supports validation on change via onChangeValidator
29
- */
30
- export class ChangeTracker {
31
- private history: HistoryEntry[] = [];
32
- private originalValues: Map<string, any> = new Map();
33
- private trackedArrays: Map<string, ArrayState> = new Map();
34
- private trackedEntities: Map<string, TrackedItem> = new Map();
35
- private onChangeValidator?: OnChangeValidator;
36
-
37
- constructor(
38
- private target: any,
39
- private rootEntityName: string,
40
- private path: string = "",
41
- private depth: number = 0,
42
- private parentId?: string,
43
- private parentEntity?: string,
44
- private rootTracker?: ChangeTracker
45
- ) {
46
- if (!rootTracker) {
47
- this.rootTracker = this;
48
- }
49
- this.captureInitialState();
50
- }
51
-
52
- /**
53
- * Sets a validator callback that will be called on every property change.
54
- * The validator can:
55
- * - Return false to reject the change (value will be reverted)
56
- * - Throw an error to reject the change with an error
57
- * - Return true/undefined to accept the change
58
- */
59
- setOnChangeValidator(validator: OnChangeValidator): void {
60
- this.getRootTracker().onChangeValidator = validator;
61
- }
62
-
63
- private captureInitialState(): void {
64
- if (this.depth > 0) return;
65
- this.captureEntityState(this.target, this.rootEntityName, "", 0);
66
- }
67
-
68
- private captureEntityState(
69
- obj: any,
70
- entityName: string,
71
- path: string,
72
- depth: number,
73
- parentId?: string,
74
- parentEntity?: string
75
- ): void {
76
- if (!obj || typeof obj !== "object") return;
77
-
78
- const id = this.getEntityId(obj);
79
- const key = path || "root";
80
-
81
- this.trackedEntities.set(key, {
82
- entity: obj,
83
- metadata: {
84
- entityName,
85
- depth,
86
- parentId,
87
- parentEntity,
88
- path,
89
- },
90
- originalState: this.deepClone(obj),
91
- });
92
-
93
- const propsToScan = obj.props || obj;
94
-
95
- for (const [propName, value] of Object.entries(propsToScan)) {
96
- if (propName === "id") continue;
97
-
98
- const propPath = path ? `${path}.${propName}` : propName;
99
-
100
- if (Array.isArray(value)) {
101
- this.captureArrayState(value, propPath, depth + 1, id, entityName);
102
- } else if (this.isEntityOrVO(value)) {
103
- const nestedName = this.getEntityName(value);
104
- this.captureEntityState(
105
- value,
106
- nestedName,
107
- propPath,
108
- depth + 1,
109
- id,
110
- entityName
111
- );
112
- }
113
- }
114
- }
115
-
116
- private captureArrayState(
117
- arr: any[],
118
- path: string,
119
- depth: number,
120
- parentId?: string,
121
- parentEntity?: string
122
- ): void {
123
- const entityName = arr.length > 0 ? this.getEntityName(arr[0]) : "Unknown";
124
-
125
- this.trackedArrays.set(path, {
126
- cloned: this.cloneArray(arr),
127
- original: arr.slice(),
128
- metadata: {
129
- entityName,
130
- depth,
131
- parentId,
132
- parentEntity,
133
- path,
134
- },
135
- });
136
-
137
- arr.forEach((item, index) => {
138
- if (this.isEntityOrVO(item)) {
139
- const itemPath = `${path}[${index}]`;
140
- this.captureEntityState(
141
- item,
142
- this.getEntityName(item),
143
- itemPath,
144
- depth,
145
- parentId,
146
- parentEntity
147
- );
148
- }
149
- });
150
- }
151
-
152
- createProxy(): any {
153
- const handler: ProxyHandler<any> = {
154
- get: (target, prop, receiver) => {
155
- const value = Reflect.get(target, prop, receiver);
156
-
157
- if (this.shouldSkipProperty(prop)) {
158
- return value;
159
- }
160
-
161
- if (typeof value === "function") {
162
- return value.bind(target);
163
- }
164
-
165
- const currentPath = this.buildPath(String(prop));
166
-
167
- if (Array.isArray(value)) {
168
- return this.createArrayProxy(value, currentPath);
169
- }
170
-
171
- if (this.isEntityOrVO(value)) {
172
- const nestedTracker = new ChangeTracker(
173
- value,
174
- this.getEntityName(value),
175
- currentPath,
176
- this.depth + 1,
177
- this.getEntityId(this.target),
178
- this.rootEntityName,
179
- this.rootTracker
180
- );
181
- return nestedTracker.createProxy();
182
- }
183
-
184
- return value;
185
- },
186
-
187
- set: (target, prop, newValue, receiver) => {
188
- const currentPath = this.buildPath(String(prop));
189
- const oldValue = Reflect.get(target, prop, receiver);
190
-
191
- if (!Array.isArray(newValue) && oldValue === newValue) {
192
- return true;
193
- }
194
-
195
- const rootTracker = this.getRootTracker();
196
- if (rootTracker.onChangeValidator) {
197
- try {
198
- const result = rootTracker.onChangeValidator(
199
- currentPath,
200
- oldValue,
201
- newValue
202
- );
203
- if (result === false) {
204
- return true;
205
- }
206
- } catch (error) {
207
- throw error;
208
- }
209
- }
210
-
211
- if (!rootTracker.originalValues.has(currentPath)) {
212
- rootTracker.originalValues.set(currentPath, oldValue);
213
- }
214
-
215
- rootTracker.history.push({
216
- path: currentPath,
217
- previousValue: oldValue,
218
- currentValue: newValue,
219
- timestamp: Date.now(),
220
- });
221
-
222
- const result = Reflect.set(target, prop, newValue, receiver);
223
-
224
- if (Array.isArray(newValue)) {
225
- this.handleArrayAssignment(currentPath, oldValue);
226
- } else if (this.isEntityOrVO(newValue) || this.isEntityOrVO(oldValue)) {
227
- this.handleEntityChange(currentPath, oldValue, newValue);
228
- }
229
-
230
- return result;
231
- },
232
- };
233
-
234
- const proxy = new Proxy(this.target, handler);
235
- Object.defineProperty(proxy, "__isProxy", { value: true, writable: false });
236
- return proxy;
237
- }
238
-
239
- private createArrayProxy(array: any[], path: string): any[] {
240
- const tracker = this;
241
- const rootTracker = this.getRootTracker();
242
-
243
- if (!rootTracker.trackedArrays.has(path)) {
244
- const parentId = this.getEntityId(this.target);
245
- rootTracker.captureArrayState(
246
- array,
247
- path,
248
- this.depth + 1,
249
- parentId,
250
- this.rootEntityName
251
- );
252
- }
253
-
254
- return new Proxy(array, {
255
- get(target, prop, receiver) {
256
- const value = Reflect.get(target, prop, receiver);
257
-
258
- if (typeof value === "function") {
259
- const mutatingMethods = [
260
- "push",
261
- "pop",
262
- "shift",
263
- "unshift",
264
- "splice",
265
- "sort",
266
- "reverse",
267
- ];
268
-
269
- if (mutatingMethods.includes(String(prop))) {
270
- return function (...args: any[]) {
271
- const oldArray = target.slice();
272
-
273
- if (rootTracker.onChangeValidator) {
274
- try {
275
- const result = rootTracker.onChangeValidator(path, oldArray, [
276
- ...oldArray,
277
- ...args,
278
- ]);
279
- if (result === false) {
280
- return undefined;
281
- }
282
- } catch (error) {
283
- throw error;
284
- }
285
- }
286
-
287
- const result = value.apply(target, args);
288
-
289
- rootTracker.history.push({
290
- path,
291
- previousValue: oldArray,
292
- currentValue: target.slice(),
293
- timestamp: Date.now(),
294
- });
295
-
296
- return result;
297
- };
298
- }
299
- return value.bind(target);
300
- }
301
-
302
- if (!isNaN(Number(prop)) && tracker.isEntityOrVO(value)) {
303
- const nestedPath = `${path}[${String(prop)}]`;
304
- const nestedTracker = new ChangeTracker(
305
- value,
306
- tracker.getEntityName(value),
307
- nestedPath,
308
- tracker.depth + 1,
309
- tracker.getEntityId(tracker.target),
310
- tracker.rootEntityName,
311
- rootTracker
312
- );
313
- return nestedTracker.createProxy();
314
- }
315
-
316
- return value;
317
- },
318
-
319
- set(target, prop, newValue, receiver) {
320
- if (!isNaN(Number(prop))) {
321
- const oldArray = target.slice();
322
-
323
- if (rootTracker.onChangeValidator) {
324
- try {
325
- const result = rootTracker.onChangeValidator(
326
- path,
327
- oldArray,
328
- newValue
329
- );
330
- if (result === false) {
331
- return true;
332
- }
333
- } catch (error) {
334
- throw error;
335
- }
336
- }
337
-
338
- const result = Reflect.set(target, prop, newValue, receiver);
339
-
340
- rootTracker.history.push({
341
- path,
342
- previousValue: oldArray,
343
- currentValue: target.slice(),
344
- timestamp: Date.now(),
345
- });
346
-
347
- return result;
348
- }
349
- return Reflect.set(target, prop, newValue, receiver);
350
- },
351
- });
352
- }
353
-
354
- /**
355
- * Returns all detected changes as AggregateChanges.
356
- */
357
- getChanges<TEntityMap = Record<string, any>>(): AggregateChanges<TEntityMap> {
358
- const changes = new AggregateChanges<TEntityMap>();
359
- const rootTracker = this.getRootTracker();
360
-
361
- this.analyzeRootChanges(changes, rootTracker);
362
- this.analyzeCollectionChanges(changes, rootTracker);
363
- this.analyzeEntityChanges(changes, rootTracker);
364
-
365
- return changes;
366
- }
367
-
368
- private analyzeRootChanges(
369
- changes: AggregateChanges<any>,
370
- rootTracker: ChangeTracker
371
- ): void {
372
- const changedFields: Record<string, any> = {};
373
- let hasChanges = false;
374
-
375
- for (const [path, originalValue] of rootTracker.originalValues) {
376
- if (path.includes(".") || path.includes("[")) continue;
377
-
378
- const currentValue = this.target[path];
379
-
380
- if (!this.isEqual(originalValue, currentValue)) {
381
- changedFields[path] = currentValue;
382
- hasChanges = true;
383
- }
384
- }
385
-
386
- if (hasChanges) {
387
- const id = this.getEntityId(this.target);
388
- if (id) {
389
- changes.addUpdate(
390
- this.rootEntityName,
391
- id,
392
- this.target,
393
- changedFields,
394
- 0
395
- );
396
- }
397
- }
398
- }
399
-
400
- private analyzeCollectionChanges(
401
- changes: AggregateChanges<any>,
402
- rootTracker: ChangeTracker
403
- ): void {
404
- const allTrackedArrays = new Map<string, ArrayState>();
405
- const processedArrays = new Set<any>();
406
-
407
- for (const [path, arrayState] of rootTracker.trackedArrays) {
408
- const currentArray = this.getValueAtPath(this.target, path);
409
- if (Array.isArray(currentArray) && !processedArrays.has(currentArray)) {
410
- allTrackedArrays.set(path, arrayState);
411
- processedArrays.add(currentArray);
412
- }
413
- }
414
-
415
- this.collectNestedArrays(
416
- this.target,
417
- "",
418
- allTrackedArrays,
419
- processedArrays
420
- );
421
-
422
- for (const [path, arrayState] of allTrackedArrays) {
423
- const currentArray = this.getValueAtPath(this.target, path);
424
- if (!Array.isArray(currentArray)) continue;
425
-
426
- const { created, updated, deleted } = this.detectArrayChanges(
427
- arrayState.cloned,
428
- arrayState.original,
429
- currentArray
430
- );
431
-
432
- const { depth, parentId, parentEntity } = arrayState.metadata;
433
-
434
- const relationField = this.extractRelationField(path);
435
-
436
- for (const item of created) {
437
- const itemEntityName = this.getEntityName(item);
438
- changes.addCreate(
439
- itemEntityName,
440
- item,
441
- depth,
442
- parentId,
443
- parentEntity,
444
- relationField
445
- );
446
-
447
- this.markNestedItemsAsCreated(item, depth, changes);
448
- }
449
-
450
- for (const item of updated) {
451
- const id = this.getEntityId(item);
452
- if (id) {
453
- const original = arrayState.cloned.find(
454
- (o) => this.getEntityId(o) === id
455
- );
456
- const changedFields = this.detectChangedFields(original, item);
457
- if (Object.keys(changedFields).length > 0) {
458
- const itemEntityName = this.getEntityName(item);
459
- changes.addUpdate(itemEntityName, id, item, changedFields, depth);
460
- }
461
- }
462
- }
463
-
464
- for (const item of deleted) {
465
- const id = this.getEntityId(item);
466
- const key = this.getItemKey(item);
467
- if (id || key) {
468
- const itemEntityName = this.getEntityName(item);
469
- const deleteId = id || key!;
470
- changes.addDelete(
471
- itemEntityName,
472
- deleteId,
473
- item,
474
- depth,
475
- relationField,
476
- parentId,
477
- parentEntity
478
- );
479
-
480
- this.markNestedItemsAsDeleted(item, depth, changes, rootTracker);
481
- }
482
- }
483
- }
484
- }
485
-
486
- /**
487
- * Recursively marks all nested items as created when a parent is created.
488
- */
489
- private markNestedItemsAsCreated(
490
- item: any,
491
- parentDepth: number,
492
- changes: AggregateChanges<any>
493
- ): void {
494
- if (!item || typeof item !== "object") return;
495
-
496
- const propsToScan = item.props || item;
497
- const parentId = this.getEntityId(item);
498
- const parentEntity = this.getEntityName(item);
499
-
500
- for (const [propName, value] of Object.entries(propsToScan)) {
501
- if (propName === "id") continue;
502
-
503
- if (Array.isArray(value)) {
504
- const relationField = propName;
505
-
506
- for (const child of value) {
507
- if (this.isEntityOrVO(child)) {
508
- const childEntityName = this.getEntityName(child);
509
- changes.addCreate(
510
- childEntityName,
511
- child,
512
- parentDepth + 1,
513
- parentId,
514
- parentEntity,
515
- relationField
516
- );
517
- this.markNestedItemsAsCreated(child, parentDepth + 1, changes);
518
- }
519
- }
520
- } else if (this.isEntityOrVO(value)) {
521
- const childEntityName = this.getEntityName(value);
522
- changes.addCreate(
523
- childEntityName,
524
- value,
525
- parentDepth + 1,
526
- parentId,
527
- parentEntity,
528
- propName
529
- );
530
- this.markNestedItemsAsCreated(value, parentDepth + 1, changes);
531
- }
532
- }
533
- }
534
-
535
- /**
536
- * Recursively marks all nested items as deleted when a parent is deleted.
537
- * Uses the original captured state to find nested items.
538
- */
539
- private markNestedItemsAsDeleted(
540
- item: any,
541
- parentDepth: number,
542
- changes: AggregateChanges<any>,
543
- rootTracker: ChangeTracker
544
- ): void {
545
- if (!item || typeof item !== "object") return;
546
-
547
- const itemId = this.getEntityId(item);
548
- if (!itemId) return;
549
-
550
- for (const [path, arrayState] of rootTracker.trackedArrays) {
551
- if (arrayState.metadata.parentId === itemId) {
552
- const relationField = this.extractRelationField(path);
553
- const parentEntity = arrayState.metadata.parentEntity;
554
- const parentId = arrayState.metadata.parentId;
555
-
556
- for (const nestedItem of arrayState.cloned) {
557
- const id =
558
- typeof nestedItem === "object" && nestedItem !== null
559
- ? nestedItem.id
560
- : undefined;
561
- if (id) {
562
- const entityName = arrayState.metadata.entityName;
563
- changes.addDelete(
564
- entityName,
565
- id,
566
- nestedItem,
567
- parentDepth + 1,
568
- relationField,
569
- parentEntity,
570
- parentId
571
- );
572
-
573
- this.markNestedJsonItemAsDeleted(
574
- id,
575
- parentDepth + 1,
576
- changes,
577
- rootTracker
578
- );
579
- }
580
- }
581
- }
582
- }
583
- }
584
-
585
- /**
586
- * Recursively marks nested items as deleted from a JSON object.
587
- * This is used when processing cloned (JSON) state.
588
- */
589
- private markNestedJsonItemAsDeleted(
590
- itemId: string,
591
- parentDepth: number,
592
- changes: AggregateChanges<any>,
593
- rootTracker: ChangeTracker
594
- ): void {
595
- for (const [path, arrayState] of rootTracker.trackedArrays) {
596
- if (arrayState.metadata.parentId === itemId) {
597
- const relationField = this.extractRelationField(path);
598
-
599
- for (const nestedJsonItem of arrayState.cloned) {
600
- if (typeof nestedJsonItem !== "object" || nestedJsonItem === null)
601
- continue;
602
-
603
- const nestedId = nestedJsonItem.id;
604
- const entityName = arrayState.metadata.entityName;
605
- const parentEntity = arrayState.metadata.parentEntity;
606
- const parentId = arrayState.metadata.parentId;
607
-
608
- if (nestedId) {
609
- changes.addDelete(
610
- entityName,
611
- nestedId,
612
- nestedJsonItem,
613
- parentDepth + 1,
614
- relationField,
615
- parentId,
616
- parentEntity
617
- );
618
-
619
- this.markNestedJsonItemAsDeleted(
620
- nestedId,
621
- parentDepth + 1,
622
- changes,
623
- rootTracker
624
- );
625
- } else {
626
- const key = this.extractIdentityKeyFromJson(
627
- nestedJsonItem,
628
- arrayState.original
629
- );
630
- if (key) {
631
- changes.addDelete(
632
- entityName,
633
- key,
634
- nestedJsonItem,
635
- parentDepth + 1,
636
- relationField,
637
- parentId,
638
- parentEntity
639
- );
640
- }
641
- }
642
- }
643
- }
644
- }
645
- }
646
-
647
- /**
648
- * Extracts identity key from a JSON object by looking at the original ValueObject instances.
649
- */
650
- private extractIdentityKeyFromJson(
651
- jsonItem: any,
652
- originalArray: any[]
653
- ): string | undefined {
654
- for (const originalItem of originalArray) {
655
- if (this.isEntityOrVO(originalItem)) {
656
- const originalJson = this.deepClone(originalItem);
657
- if (JSON.stringify(originalJson) === JSON.stringify(jsonItem)) {
658
- const key = this.getItemKey(originalItem);
659
- if (key) return key;
660
- }
661
- }
662
- }
663
-
664
- if (jsonItem.id) return jsonItem.id;
665
-
666
- return undefined;
667
- }
668
-
669
- private collectNestedArrays(
670
- obj: any,
671
- basePath: string,
672
- allArrays: Map<string, ArrayState>,
673
- processedArrays: Set<any>
674
- ): void {
675
- if (!obj || typeof obj !== "object") return;
676
-
677
- for (const [propName, value] of Object.entries(obj)) {
678
- if (propName === "id" || propName === "proxy" || propName === "_props")
679
- continue;
680
-
681
- const propPath = basePath ? `${basePath}.${propName}` : propName;
682
-
683
- if (Array.isArray(value)) {
684
- value.forEach((item, index) => {
685
- if (this.isEntityOrVO(item)) {
686
- this.collectNestedArrays(
687
- item,
688
- `${propPath}[${index}]`,
689
- allArrays,
690
- processedArrays
691
- );
692
- }
693
- });
694
- } else if (this.isEntityOrVO(value)) {
695
- this.collectNestedArrays(value, propPath, allArrays, processedArrays);
696
- }
697
- }
698
- }
699
-
700
- private analyzeEntityChanges(
701
- changes: AggregateChanges<any>,
702
- rootTracker: ChangeTracker
703
- ): void {
704
- for (const [path, trackedItem] of rootTracker.trackedEntities) {
705
- if (path === "root") continue;
706
- if (path.includes("[")) continue;
707
-
708
- const currentValue = this.getValueAtPath(this.target, path);
709
- const originalValue = trackedItem.originalState;
710
- const originalEntity = trackedItem.entity;
711
- const { entityName, depth, parentId, parentEntity } =
712
- trackedItem.metadata;
713
-
714
- const relationField = this.extractRelationField(path);
715
-
716
- const state = this.detectEntityChangeState(originalValue, currentValue);
717
-
718
- switch (state) {
719
- case "created":
720
- changes.addCreate(
721
- entityName,
722
- currentValue,
723
- depth,
724
- parentId,
725
- parentEntity,
726
- relationField
727
- );
728
- break;
729
-
730
- case "deleted":
731
- const id = this.getEntityId(originalValue);
732
- if (id) {
733
- changes.addDelete(
734
- entityName,
735
- id,
736
- originalEntity,
737
- depth,
738
- relationField,
739
- parentId,
740
- parentEntity
741
- );
742
- }
743
- break;
744
-
745
- case "replaced":
746
- const oldId = this.getEntityId(originalValue);
747
- if (oldId) {
748
- changes.addDelete(
749
- entityName,
750
- oldId,
751
- originalEntity,
752
- depth,
753
- relationField,
754
- parentId,
755
- parentEntity
756
- );
757
- }
758
- changes.addCreate(
759
- entityName,
760
- currentValue,
761
- depth,
762
- parentId,
763
- parentEntity,
764
- relationField
765
- );
766
- break;
767
-
768
- case "updated":
769
- const updateId = this.getEntityId(currentValue);
770
- if (updateId) {
771
- const changedFields = this.detectChangedFields(
772
- originalValue,
773
- currentValue
774
- );
775
- if (Object.keys(changedFields).length > 0) {
776
- changes.addUpdate(
777
- entityName,
778
- updateId,
779
- currentValue,
780
- changedFields,
781
- depth
782
- );
783
- }
784
- }
785
- break;
786
- }
787
- }
788
- }
789
-
790
- private detectEntityChangeState(
791
- previous: any,
792
- current: any
793
- ): EntityChangeState {
794
- if (previous === null && current !== null) {
795
- return "created";
796
- }
797
-
798
- if (previous !== null && current === null) {
799
- return "deleted";
800
- }
801
-
802
- if (previous !== null && current !== null) {
803
- const prevId = this.getEntityId(previous);
804
- const currId = this.getEntityId(current);
805
-
806
- if (prevId && currId && prevId === currId) {
807
- return this.hasChanged(previous, current) ? "updated" : "unchanged";
808
- } else {
809
- return "replaced";
810
- }
811
- }
812
-
813
- return "unchanged";
814
- }
815
-
816
- private detectArrayChanges(
817
- oldCloned: any[],
818
- oldOriginal: any[],
819
- newArray: any[]
820
- ): { created: any[]; updated: any[]; deleted: any[] } {
821
- const created: any[] = [];
822
- const updated: any[] = [];
823
- const deleted: any[] = [];
824
-
825
- const oldMap = new Map<string, any>();
826
- const newMap = new Map<string, any>();
827
-
828
- oldCloned.forEach((item) => {
829
- const key = this.getItemKey(item);
830
- if (key) oldMap.set(key, item);
831
- });
832
-
833
- newArray.forEach((item) => {
834
- const key = this.getItemKey(item);
835
- if (key) newMap.set(key, item);
836
- });
837
-
838
- newArray.forEach((item) => {
839
- const key = this.getItemKey(item);
840
- if (!key) {
841
- created.push(item);
842
- } else if (!oldMap.has(key)) {
843
- created.push(item);
844
- } else if (this.hasChanged(oldMap.get(key), item)) {
845
- updated.push(item);
846
- }
847
- });
848
-
849
- oldOriginal.forEach((item) => {
850
- const key = this.getItemKey(item);
851
- if (key && !newMap.has(key)) {
852
- deleted.push(item);
853
- }
854
- });
855
-
856
- return { created, updated, deleted };
857
- }
858
-
859
- private detectChangedFields(
860
- original: any,
861
- current: any
862
- ): Record<string, any> {
863
- const changes: Record<string, any> = {};
864
-
865
- if (!original || !current) return changes;
866
-
867
- const origProps = original.props || original;
868
- const currProps = current.props || current;
869
-
870
- for (const key of Object.keys(currProps)) {
871
- if (key === "id") continue;
872
-
873
- const origValue = origProps[key];
874
- const currValue = currProps[key];
875
-
876
- if (Array.isArray(currValue) || this.isEntityOrVO(currValue)) {
877
- continue;
878
- }
879
-
880
- if (!this.isEqual(origValue, currValue)) {
881
- changes[key] = currValue;
882
- }
883
- }
884
-
885
- return changes;
886
- }
887
-
888
- private handleArrayAssignment(path: string, oldValue: any): void {
889
- const rootTracker = this.getRootTracker();
890
-
891
- if (!rootTracker.trackedArrays.has(path)) {
892
- const parentId = this.getEntityId(this.target);
893
- rootTracker.captureArrayState(
894
- Array.isArray(oldValue) ? oldValue : [],
895
- path,
896
- this.depth + 1,
897
- parentId,
898
- this.rootEntityName
899
- );
900
- }
901
- }
902
-
903
- private handleEntityChange(path: string, oldValue: any, newValue: any): void {
904
- const rootTracker = this.getRootTracker();
905
- const entityName = newValue
906
- ? this.getEntityName(newValue)
907
- : this.getEntityName(oldValue);
908
-
909
- const existingTracked = rootTracker.trackedEntities.get(path);
910
-
911
- rootTracker.trackedEntities.set(path, {
912
- entity: existingTracked?.entity || oldValue,
913
- metadata: {
914
- entityName,
915
- depth: this.depth + 1,
916
- parentId: this.getEntityId(this.target),
917
- parentEntity: this.rootEntityName,
918
- path,
919
- },
920
- originalState: existingTracked?.originalState,
921
- });
922
- }
923
-
924
- private getRootTracker(): ChangeTracker {
925
- return this.rootTracker || this;
926
- }
927
-
928
- private buildPath(prop: string): string {
929
- return this.path ? `${this.path}.${prop}` : prop;
930
- }
931
-
932
- private shouldSkipProperty(prop: string | symbol): boolean {
933
- const skipProps = [
934
- "__isProxy",
935
- "__tracker",
936
- "__originalTarget",
937
- "__path",
938
- "constructor",
939
- "prototype",
940
- ];
941
- return skipProps.includes(String(prop));
942
- }
943
-
944
- private getValueAtPath(obj: any, path: string): any {
945
- if (!path) return obj;
946
-
947
- const parts = path.split(/[.\[\]]+/).filter(Boolean);
948
- let current = obj;
949
-
950
- for (const part of parts) {
951
- if (current === null || current === undefined) return undefined;
952
-
953
- const propsToAccess = current.props || current;
954
- current = propsToAccess[part];
955
- }
956
-
957
- return current;
958
- }
959
-
960
- private extractRelationField(path: string): string {
961
- const withoutIndices = path.replace(/\[\d+\]/g, "");
962
- const parts = withoutIndices.split(".");
963
- return parts[parts.length - 1];
964
- }
965
-
966
- private getItemKey(item: any): string | undefined {
967
- const id = this.getEntityId(item);
968
- if (id) return id;
969
-
970
- if (item instanceof ValueObject && item.hasIdentityKey()) {
971
- return item.getIdentityKey() || undefined;
972
- }
973
-
974
- return undefined;
975
- }
976
-
977
- private getEntityId(item: any): string | undefined {
978
- if (!item) return undefined;
979
- if (item.id instanceof Id) return item.id.value;
980
- if (item.id !== undefined) return String(item.id);
981
- return undefined;
982
- }
983
-
984
- private getEntityName(item: any): string {
985
- if (!item) return "Unknown";
986
- return item.constructor?.name || "Unknown";
987
- }
988
-
989
- private isEntityOrVO(value: any): boolean {
990
- if (value === null || value === undefined) return false;
991
- return value instanceof Entity || value instanceof ValueObject;
992
- }
993
-
994
- private isEqual(a: any, b: any): boolean {
995
- if (a === b) return true;
996
- if (a instanceof Id && b instanceof Id) return a.value === b.value;
997
- if (a instanceof Date && b instanceof Date)
998
- return a.getTime() === b.getTime();
999
-
1000
- try {
1001
- return this.hasChanged(a, b) === false;
1002
- } catch {
1003
- return this.deepEqual(a, b);
1004
- }
1005
- }
1006
-
1007
- private deepEqual(a: any, b: any): boolean {
1008
- if (a === b) return true;
1009
- if (a == null || b == null) return a === b;
1010
- if (typeof a !== typeof b) return false;
1011
- if (typeof a !== "object") return a === b;
1012
-
1013
- if (Array.isArray(a) !== Array.isArray(b)) return false;
1014
- if (Array.isArray(a)) {
1015
- if (a.length !== b.length) return false;
1016
- for (let i = 0; i < a.length; i++) {
1017
- if (!this.deepEqual(a[i], b[i])) return false;
1018
- }
1019
- return true;
1020
- }
1021
-
1022
- const keysA = Object.keys(a).filter((key) => {
1023
- const value = a[key];
1024
- return (
1025
- typeof value !== "object" ||
1026
- value instanceof Date ||
1027
- value instanceof Id ||
1028
- value === null
1029
- );
1030
- });
1031
- const keysB = Object.keys(b).filter((key) => {
1032
- const value = b[key];
1033
- return (
1034
- typeof value !== "object" ||
1035
- value instanceof Date ||
1036
- value instanceof Id ||
1037
- value === null
1038
- );
1039
- });
1040
-
1041
- if (keysA.length !== keysB.length) return false;
1042
-
1043
- for (const key of keysA) {
1044
- if (!keysB.includes(key)) return false;
1045
- if (!this.isEqual(a[key], b[key])) return false;
1046
- }
1047
-
1048
- return true;
1049
- }
1050
-
1051
- private hasChanged(obj1: any, obj2: any): boolean {
1052
- const json1 = this.normalizeAndStringify(this.deepClone(obj1));
1053
- const json2 = this.normalizeAndStringify(this.deepClone(obj2));
1054
- return json1 !== json2;
1055
- }
1056
-
1057
- private cloneArray(arr: any[]): any[] {
1058
- return arr.map((item) => this.deepClone(item));
1059
- }
1060
-
1061
- private deepClone(obj: any): any {
1062
- if (obj === null || obj === undefined || typeof obj !== "object") {
1063
- return obj;
1064
- }
1065
-
1066
- if (obj instanceof Id) {
1067
- return obj.value;
1068
- }
1069
-
1070
- if (typeof obj.toJSON === "function") {
1071
- return obj.toJSON();
1072
- }
1073
-
1074
- if (Array.isArray(obj)) {
1075
- return obj.map((item) => this.deepClone(item));
1076
- }
1077
-
1078
- if (obj instanceof Date) {
1079
- return new Date(obj.getTime());
1080
- }
1081
-
1082
- try {
1083
- return structuredClone(obj);
1084
- } catch {
1085
- const cloned: any = {};
1086
- for (const key in obj) {
1087
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
1088
- cloned[key] = this.deepClone(obj[key]);
1089
- }
1090
- }
1091
- return cloned;
1092
- }
1093
- }
1094
-
1095
- private normalizeAndStringify(obj: any): string {
1096
- if (obj === null || typeof obj !== "object") {
1097
- return JSON.stringify(obj);
1098
- }
1099
-
1100
- if (Array.isArray(obj)) {
1101
- return `[${obj
1102
- .map((item) => this.normalizeAndStringify(item))
1103
- .join(",")}]`;
1104
- }
1105
-
1106
- const keys = Object.keys(obj).sort();
1107
- const parts = keys.map(
1108
- (key) => `"${key}":${this.normalizeAndStringify(obj[key])}`
1109
- );
1110
- return `{${parts.join(",")}}`;
1111
- }
1112
-
1113
- getHistory(): HistoryEntry[] {
1114
- return [...this.getRootTracker().history];
1115
- }
1116
-
1117
- clearHistory(): void {
1118
- const rootTracker = this.getRootTracker();
1119
- rootTracker.history = [];
1120
- rootTracker.originalValues.clear();
1121
- rootTracker.trackedArrays.clear();
1122
- rootTracker.trackedEntities.clear();
1123
- this.captureInitialState();
1124
- }
1125
-
1126
- markAsClean(): void {
1127
- this.clearHistory();
1128
- }
1129
-
1130
- getTarget(): any {
1131
- return this.target;
1132
- }
1133
- }