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