Open History to see the last commit
1/**
2 * A utility for creating a proxy that captures changes to an object
3 * and provides a way to retrieve those changes.
4 */
5
6/**
7 * Simple debug utility that only logs when debug mode is enabled
8 * Set DEBUG to true in localStorage to enable debug logging
9 */
10function debugLog(...args: Array<unknown>): void {
11 // Check if we're in a browser environment
12 const isBrowser =
13 typeof window !== `undefined` && typeof localStorage !== `undefined`
14
15 // In browser, check localStorage for debug flag
16 if (isBrowser && localStorage.getItem(`DEBUG`) === `true`) {
17 console.log(`[proxy]`, ...args)
18 }
19 // In Node.js environment, check for environment variable (though this is primarily for browser)
20 else if (
21 !isBrowser &&
22 typeof process !== `undefined` &&
23 process.env.DEBUG === `true`
24 ) {
25 console.log(`[proxy]`, ...args)
26 }
27}
28
29// Add TypedArray interface with proper type
30interface TypedArray {
31 length: number
32 [index: number]: number
33}
34
35// Update type for ChangeTracker
36interface ChangeTracker<T extends object> {
37 changes: Record<string | symbol, unknown>
38 originalObject: T
39 modified: boolean
40 copy_?: T
41 assigned_: Record<string | symbol, boolean>
42 parent?: {
43 tracker: ChangeTracker<object>
44 prop: string | symbol
45 }
46 target: T
47}
48
49/**
50 * Deep clones an object while preserving special types like Date and RegExp
51 */
52
53function deepClone<T extends unknown>(
54 obj: T,
55 visited = new WeakMap<object, unknown>()
56): T {
57 // Handle null and undefined
58 if (obj === null || obj === undefined) {
59 return obj
60 }
61
62 // Handle primitive types
63 if (typeof obj !== `object`) {
64 return obj
65 }
66
67 // If we've already cloned this object, return the cached clone
68 if (visited.has(obj as object)) {
69 return visited.get(obj as object) as T
70 }
71
72 if (obj instanceof Date) {
73 return new Date(obj.getTime()) as unknown as T
74 }
75
76 if (obj instanceof RegExp) {
77 return new RegExp(obj.source, obj.flags) as unknown as T
78 }
79
80 if (Array.isArray(obj)) {
81 const arrayClone = [] as Array<unknown>
82 visited.set(obj as object, arrayClone)
83 obj.forEach((item, index) => {
84 arrayClone[index] = deepClone(item, visited)
85 })
86 return arrayClone as unknown as T
87 }
88
89 // Handle TypedArrays
90 if (ArrayBuffer.isView(obj) && !(obj instanceof DataView)) {
91 // Get the constructor to create a new instance of the same type
92 const TypedArrayConstructor = Object.getPrototypeOf(obj).constructor
93 const clone = new TypedArrayConstructor(
94 (obj as unknown as TypedArray).length
95 ) as unknown as TypedArray
96 visited.set(obj as object, clone)
97
98 // Copy the values
99 for (let i = 0; i < (obj as unknown as TypedArray).length; i++) {
100 clone[i] = (obj as unknown as TypedArray)[i]
101 }
102
103 return clone as unknown as T
104 }
105
106 if (obj instanceof Map) {
107 const clone = new Map() as Map<unknown, unknown>
108 visited.set(obj as object, clone)
109 obj.forEach((value, key) => {
110 clone.set(key, deepClone(value, visited))
111 })
112 return clone as unknown as T
113 }
114
115 if (obj instanceof Set) {
116 const clone = new Set()
117 visited.set(obj as object, clone)
118 obj.forEach((value) => {
119 clone.add(deepClone(value, visited))
120 })
121 return clone as unknown as T
122 }
123
124 const clone = {} as Record<string | symbol, unknown>
125 visited.set(obj as object, clone)
126
127 for (const key in obj) {
128 if (Object.prototype.hasOwnProperty.call(obj, key)) {
129 clone[key] = deepClone(
130 (obj as Record<string | symbol, unknown>)[key],
131 visited
132 )
133 }
134 }
135
136 const symbolProps = Object.getOwnPropertySymbols(obj)
137 for (const sym of symbolProps) {
138 clone[sym] = deepClone(
139 (obj as Record<string | symbol, unknown>)[sym],
140 visited
141 )
142 }
143
144 return clone as T
145}
146
147/**
148 * Deep equality check that handles special types like Date, RegExp, Map, and Set
149 */
150function deepEqual<T>(a: T, b: T): boolean {
151 // Handle primitive types
152 if (a === b) return true
153
154 // If either is null or not an object, they're not equal
155 if (
156 a === null ||
157 b === null ||
158 typeof a !== `object` ||
159 typeof b !== `object`
160 ) {
161 return false
162 }
163
164 // Handle Date objects
165 if (a instanceof Date && b instanceof Date) {
166 return a.getTime() === b.getTime()
167 }
168
169 // Handle RegExp objects
170 if (a instanceof RegExp && b instanceof RegExp) {
171 return a.source === b.source && a.flags === b.flags
172 }
173
174 // Handle Map objects
175 if (a instanceof Map && b instanceof Map) {
176 if (a.size !== b.size) return false
177
178 const entries = Array.from(a.entries())
179 for (const [key, val] of entries) {
180 if (!b.has(key) || !deepEqual(val, b.get(key))) {
181 return false
182 }
183 }
184
185 return true
186 }
187
188 // Handle Set objects
189 if (a instanceof Set && b instanceof Set) {
190 if (a.size !== b.size) return false
191
192 // Convert to arrays for comparison
193 const aValues = Array.from(a)
194 const bValues = Array.from(b)
195
196 // Simple comparison for primitive values
197 if (aValues.every((val) => typeof val !== `object`)) {
198 return aValues.every((val) => b.has(val))
199 }
200
201 // For objects in sets, we need to do a more complex comparison
202 // This is a simplified approach and may not work for all cases
203 return aValues.length === bValues.length
204 }
205
206 // Handle arrays
207 if (Array.isArray(a) && Array.isArray(b)) {
208 if (a.length !== b.length) return false
209
210 for (let i = 0; i < a.length; i++) {
211 if (!deepEqual(a[i], b[i])) return false
212 }
213
214 return true
215 }
216
217 // Handle TypedArrays
218 if (
219 ArrayBuffer.isView(a) &&
220 ArrayBuffer.isView(b) &&
221 !(a instanceof DataView) &&
222 !(b instanceof DataView)
223 ) {
224 const typedA = a as unknown as TypedArray
225 const typedB = b as unknown as TypedArray
226 if (typedA.length !== typedB.length) return false
227
228 for (let i = 0; i < typedA.length; i++) {
229 if (typedA[i] !== typedB[i]) return false
230 }
231
232 return true
233 }
234
235 // Handle plain objects
236 const keysA = Object.keys(a as object)
237 const keysB = Object.keys(b as object)
238
239 if (keysA.length !== keysB.length) return false
240
241 return keysA.every(
242 (key) =>
243 Object.prototype.hasOwnProperty.call(b, key) &&
244 deepEqual((a as any)[key], (b as any)[key])
245 )
246}
247
248/**
249 * Creates a proxy that tracks changes to the target object
250 *
251 * @param target The object to proxy
252 * @param parent Optional parent information
253 * @returns An object containing the proxy and a function to get the changes
254 */
255export function createChangeProxy<T extends object>(
256 target: T,
257 parent?: { tracker: ChangeTracker<object>; prop: string | symbol }
258): {
259 proxy: T
260
261 getChanges: () => Record<string | symbol, any>
262} {
263 // Create a WeakMap to cache proxies for nested objects
264 // This prevents creating multiple proxies for the same object
265 // and handles circular references
266 const proxyCache = new WeakMap<object, object>()
267
268 // Create a change tracker to track changes to the object
269 const changeTracker: ChangeTracker<T> = {
270 changes: {},
271 originalObject: deepClone(target), // Create a deep clone to preserve the original state
272 modified: false,
273 assigned_: {},
274 parent,
275 target, // Store reference to the target object
276 }
277
278 // Mark this object and all its ancestors as modified
279 function markChanged(state: ChangeTracker<object>) {
280 if (!state.modified) {
281 state.modified = true
282
283 // Propagate the change up the parent chain
284 if (state.parent) {
285 markChanged(state.parent.tracker)
286 }
287 }
288 }
289
290 // Check if all properties in the current state have reverted to original values
291 function checkIfReverted(state: ChangeTracker<object>): boolean {
292 debugLog(
293 `checkIfReverted called with assigned keys:`,
294 Object.keys(state.assigned_)
295 )
296
297 // If there are no assigned properties, object is unchanged
298 if (
299 Object.keys(state.assigned_).length === 0 &&
300 Object.getOwnPropertySymbols(state.assigned_).length === 0
301 ) {
302 debugLog(`No assigned properties, returning true`)
303 return true
304 }
305
306 // Check each assigned regular property
307 for (const prop in state.assigned_) {
308 // If this property is marked as assigned
309 if (state.assigned_[prop] === true) {
310 const currentValue = state.copy_ ? (state.copy_ as any)[prop] : null
311 const originalValue = (state.originalObject as any)[prop]
312
313 debugLog(
314 `Checking property ${String(prop)}, current:`,
315 currentValue,
316 `original:`,
317 originalValue
318 )
319
320 // If the value is not equal to original, something is still changed
321 if (!deepEqual(currentValue, originalValue)) {
322 debugLog(`Property ${String(prop)} is different, returning false`)
323 return false
324 }
325 } else if (state.assigned_[prop] === false) {
326 // Property was deleted, so it's different from original
327 debugLog(`Property ${String(prop)} was deleted, returning false`)
328 return false
329 }
330 }
331
332 // Check each assigned symbol property
333 const symbolProps = Object.getOwnPropertySymbols(state.assigned_)
334 for (const sym of symbolProps) {
335 if (state.assigned_[sym.toString()] === true) {
336 const currentValue = state.copy_ ? (state.copy_ as any)[sym] : null
337 const originalValue = (state.originalObject as any)[sym]
338
339 // If the value is not equal to original, something is still changed
340 if (!deepEqual(currentValue, originalValue)) {
341 debugLog(`Symbol property is different, returning false`)
342 return false
343 }
344 } else if (state.assigned_[sym.toString()] === false) {
345 // Property was deleted, so it's different from original
346 debugLog(`Symbol property was deleted, returning false`)
347 return false
348 }
349 }
350
351 debugLog(`All properties match original values, returning true`)
352 // All assigned properties match their original values
353 return true
354 }
355
356 // Recursively check and update modified status based on child objects
357 function updateModifiedStatus(state: ChangeTracker<object>): boolean {
358 debugLog(
359 `updateModifiedStatus called, assigned keys:`,
360 Object.keys(state.assigned_)
361 )
362
363 // Only check for reverts if we actually have changes
364 if (
365 Object.keys(state.assigned_).length === 0 &&
366 Object.getOwnPropertySymbols(state.assigned_).length === 0
367 ) {
368 debugLog(`No assigned properties, returning false`)
369 return false
370 }
371
372 // If this object has direct changes that aren't reverted, it's modified
373 const isReverted = checkIfReverted(state)
374 debugLog(`checkIfReverted returned:`, isReverted)
375
376 if (!isReverted) {
377 debugLog(`Object has changes that aren't reverted, returning true`)
378 return true
379 }
380
381 debugLog(`All changes reverted, clearing tracking`)
382 // All changes have been reverted, clear the tracking
383 state.modified = false
384 state.changes = {}
385 state.assigned_ = {}
386
387 // If we have a parent, update its status too
388 if (state.parent) {
389 debugLog(`Checking parent status for prop:`, state.parent.prop)
390 // Tell the parent this child has reverted
391 checkParentStatus(state.parent.tracker, state.parent.prop)
392 }
393
394 return false
395 }
396
397 // Update parent status based on child changes
398 function checkParentStatus(
399 parentState: ChangeTracker<object>,
400 childProp: string | symbol
401 ) {
402 debugLog(`checkParentStatus called for child prop:`, childProp)
403
404 // Check if all properties of the parent are reverted
405 const isReverted = checkIfReverted(parentState)
406 debugLog(`Parent checkIfReverted returned:`, isReverted)
407
408 if (isReverted) {
409 debugLog(`Parent is fully reverted, clearing tracking`)
410 // If everything is reverted, clear the tracking
411 parentState.modified = false
412 parentState.changes = {}
413 parentState.assigned_ = {}
414
415 // Continue up the chain
416 if (parentState.parent) {
417 debugLog(`Continuing up the parent chain`)
418 checkParentStatus(parentState.parent.tracker, parentState.parent.prop)
419 }
420 }
421 }
422
423 // Create a proxy for the target object
424 function createObjectProxy<TObj extends object>(obj: TObj): TObj {
425 // If we've already created a proxy for this object, return it
426 if (proxyCache.has(obj)) {
427 return proxyCache.get(obj) as TObj
428 }
429
430 // Create a proxy for the object
431 const proxy = new Proxy(obj, {
432 get(ptarget, prop) {
433 const value = ptarget[prop as keyof TObj]
434
435 // If it's a getter, return the value directly
436 const desc = Object.getOwnPropertyDescriptor(ptarget, prop)
437 if (desc?.get) {
438 return value
439 }
440
441 // If the value is a function, bind it to the ptarget
442 if (typeof value === `function`) {
443 // For Map and Set methods that modify the collection
444 if (ptarget instanceof Map || ptarget instanceof Set) {
445 const methodName = prop.toString()
446 const modifyingMethods = new Set([
447 `set`,
448 `delete`,
449 `clear`,
450 `add`,
451 `pop`,
452 `push`,
453 `shift`,
454 `unshift`,
455 `splice`,
456 `sort`,
457 `reverse`,
458 ])
459
460 if (modifyingMethods.has(methodName)) {
461 return function (...args: Array<unknown>) {
462 const result = value.apply(ptarget, args)
463 markChanged(changeTracker)
464 return result
465 }
466 }
467
468 // Handle iterator methods for Map and Set
469 const iteratorMethods = new Set([
470 `entries`,
471 `keys`,
472 `values`,
473 `forEach`,
474 Symbol.iterator,
475 ])
476
477 if (iteratorMethods.has(methodName) || prop === Symbol.iterator) {
478 return function (this: unknown, ...args: Array<unknown>) {
479 const result = value.apply(ptarget, args)
480
481 // For forEach, we need to wrap the callback to track changes
482 if (methodName === `forEach`) {
483 const callback = args[0]
484 if (typeof callback === `function`) {
485 // Replace the original callback with our wrapped version
486 const wrappedCallback = function (
487 // eslint-disable-next-line
488 this: unknown,
489 // eslint-disable-next-line
490 value: unknown,
491 key: unknown,
492 collection: unknown
493 ) {
494 // Call the original callback
495 const cbresult = callback.call(
496 this,
497 value,
498 key,
499 collection
500 )
501 // Mark as changed since the callback might have modified the value
502 markChanged(changeTracker)
503 return cbresult
504 }
505 // Call forEach with our wrapped callback
506 return value.apply(ptarget, [
507 wrappedCallback,
508 ...args.slice(1),
509 ])
510 }
511 }
512
513 // For iterators (entries, keys, values, Symbol.iterator)
514 if (
515 methodName === `entries` ||
516 methodName === `values` ||
517 methodName === Symbol.iterator.toString() ||
518 prop === Symbol.iterator
519 ) {
520 // If it's an iterator, we need to wrap the returned iterator
521 // to track changes when the values are accessed and potentially modified
522 const originalIterator = result
523
524 // Create a proxy for the iterator that will mark changes when next() is called
525 return {
526 next() {
527 const nextResult = originalIterator.next()
528
529 // If we have a value and it's an object, we need to track it
530 if (
531 !nextResult.done &&
532 nextResult.value &&
533 typeof nextResult.value === `object`
534 ) {
535 // For entries, the value is a [key, value] pair
536 if (
537 methodName === `entries` &&
538 Array.isArray(nextResult.value) &&
539 nextResult.value.length === 2
540 ) {
541 // The value is at index 1 in the [key, value] pair
542 if (
543 nextResult.value[1] &&
544 typeof nextResult.value[1] === `object`
545 ) {
546 // Create a proxy for the value and replace it in the result
547 const { proxy: valueProxy } = createChangeProxy(
548 nextResult.value[1],
549 {
550 tracker: changeTracker,
551 prop:
552 typeof nextResult.value[0] === `symbol`
553 ? nextResult.value[0]
554 : String(nextResult.value[0]),
555 }
556 )
557 nextResult.value[1] = valueProxy
558 }
559 } else if (
560 methodName === `values` ||
561 methodName === Symbol.iterator.toString() ||
562 prop === Symbol.iterator
563 ) {
564 // If the value is an object, create a proxy for it
565 if (
566 typeof nextResult.value === `object` &&
567 nextResult.value !== null
568 ) {
569 // For Set, we need to track the whole object
570 // For Map, we would need the key, but we don't have it here
571 // So we'll use a symbol as a placeholder
572 const tempKey = Symbol(`iterator-value`)
573 const { proxy: valueProxy } = createChangeProxy(
574 nextResult.value,
575 {
576 tracker: changeTracker,
577 prop: tempKey,
578 }
579 )
580 nextResult.value = valueProxy
581 }
582 }
583 }
584
585 return nextResult
586 },
587 [Symbol.iterator]() {
588 return this
589 },
590 }
591 }
592
593 return result
594 }
595 }
596 }
597 return value.bind(ptarget)
598 }
599
600 // If the value is an object, create a proxy for it
601 if (
602 value &&
603 typeof value === `object` &&
604 !(value instanceof Date) &&
605 !(value instanceof RegExp)
606 ) {
607 // Create a parent reference for the nested object
608 const nestedParent = {
609 tracker: changeTracker,
610 prop: String(prop),
611 }
612
613 // Create a proxy for the nested object
614 const { proxy: nestedProxy } = createChangeProxy(value, nestedParent)
615
616 // Cache the proxy
617 proxyCache.set(value, nestedProxy)
618
619 return nestedProxy
620 }
621
622 return value
623 },
624
625 set(sobj, prop, value) {
626 const currentValue = sobj[prop as keyof TObj]
627 debugLog(
628 `set called for property ${String(prop)}, current:`,
629 currentValue,
630 `new:`,
631 value
632 )
633
634 // Special handling for array length changes
635 if (Array.isArray(sobj) && prop === `length`) {
636 const newLength = Number(value)
637 const oldLength = sobj.length
638
639 // Create a new array with the desired length
640 const newArray = Array.from({ length: newLength }, (_, i) =>
641 i < oldLength ? sobj[i] : undefined
642 )
643
644 // Track the change in the parent object since 'arr' is the property name
645 if (parent) {
646 parent.tracker.changes[parent.prop] = newArray
647 parent.tracker.assigned_[parent.prop] = true
648 markChanged(parent.tracker)
649 }
650
651 // Update the original array
652 sobj.length = newLength
653 return true
654 }
655
656 // Only track the change if the value is actually different
657 if (!deepEqual(currentValue, value)) {
658 // Check if the new value is equal to the original value
659 // Important: Use the originalObject to get the true original value
660 const originalValue = changeTracker.originalObject[prop as keyof T]
661 const isRevertToOriginal = deepEqual(value, originalValue)
662 debugLog(
663 `Value different, original:`,
664 originalValue,
665 `isRevertToOriginal:`,
666 isRevertToOriginal
667 )
668
669 if (isRevertToOriginal) {
670 debugLog(`Reverting property ${String(prop)} to original value`)
671 // If the value is reverted to its original state, remove it from changes
672 delete changeTracker.changes[prop.toString()]
673 delete changeTracker.assigned_[prop.toString()]
674
675 // Make sure the copy is updated with the original value
676 if (changeTracker.copy_) {
677 debugLog(`Updating copy with original value for ${String(prop)}`)
678 changeTracker.copy_[prop as keyof T] = deepClone(originalValue)
679 }
680
681 // Check if all properties in this object have been reverted
682 debugLog(`Checking if all properties reverted`)
683 const allReverted = checkIfReverted(changeTracker)
684 debugLog(`All reverted:`, allReverted)
685
686 if (allReverted) {
687 debugLog(`All properties reverted, clearing tracking`)
688 // If all have been reverted, clear tracking
689 changeTracker.modified = false
690 changeTracker.changes = {}
691 changeTracker.assigned_ = {}
692
693 // If we're a nested object, check if the parent needs updating
694 if (parent) {
695 debugLog(`Updating parent for property:`, parent.prop)
696 checkParentStatus(parent.tracker, parent.prop)
697 }
698 } else {
699 // Some properties are still changed
700 debugLog(`Some properties still changed, keeping modified flag`)
701 changeTracker.modified = true
702 }
703 } else {
704 debugLog(`Setting new value for property ${String(prop)}`)
705 // Create a copy of the object if it doesn't exist
706 prepareCopy(changeTracker)
707
708 // Set the value on the copy
709 if (changeTracker.copy_) {
710 changeTracker.copy_[prop as keyof T] = value
711 }
712
713 // Set the value on the original object
714 obj[prop as keyof TObj] = value
715
716 // Track that this property was assigned - store using the actual property (symbol or string)
717 changeTracker.assigned_[prop.toString()] = true
718
719 // Track the change directly with the property as the key
720 changeTracker.changes[prop.toString()] = deepClone(value)
721
722 // Mark this object and its ancestors as modified
723 debugLog(`Marking object and ancestors as modified`)
724 markChanged(changeTracker)
725 }
726 } else {
727 debugLog(`Value unchanged, not tracking`)
728 }
729
730 return true
731 },
732
733 defineProperty(ptarget, prop, descriptor) {
734 const result = Reflect.defineProperty(ptarget, prop, descriptor)
735 if (result) {
736 // Track the change if the property has a value
737 if (`value` in descriptor) {
738 changeTracker.changes[prop.toString()] = deepClone(descriptor.value)
739 changeTracker.assigned_[prop.toString()] = true
740 markChanged(changeTracker)
741 }
742 }
743 return result
744 },
745
746 setPrototypeOf(ptarget, proto) {
747 // Allow setting prototype but don't track it as a change
748 return Object.setPrototypeOf(ptarget, proto)
749 },
750
751 deleteProperty(dobj, prop) {
752 const stringProp = typeof prop === `symbol` ? prop.toString() : prop
753
754 if (stringProp in dobj) {
755 // Check if the property exists in the original object
756 const hadPropertyInOriginal =
757 stringProp in changeTracker.originalObject
758
759 // Create a copy of the object if it doesn't exist
760 prepareCopy(changeTracker)
761
762 // Delete the property from the copy
763 if (changeTracker.copy_) {
764 delete changeTracker.copy_[prop as keyof T]
765 }
766
767 // Delete the property from the original object
768 delete dobj[prop as keyof TObj]
769
770 // If the property didn't exist in the original object, removing it
771 // should revert to the original state
772 if (!hadPropertyInOriginal) {
773 delete changeTracker.changes[stringProp]
774 delete changeTracker.assigned_[stringProp]
775
776 // If this is the last change and we're not a nested object,
777 // mark the object as unmodified
778 if (
779 Object.keys(changeTracker.assigned_).length === 0 &&
780 Object.getOwnPropertySymbols(changeTracker.assigned_).length === 0
781 ) {
782 changeTracker.modified = false
783 } else {
784 // We still have changes, keep as modified
785 changeTracker.modified = true
786 }
787 } else {
788 // Mark this property as deleted
789 changeTracker.assigned_[stringProp] = false
790 changeTracker.changes[stringProp] = undefined
791 markChanged(changeTracker)
792 }
793 }
794
795 return true
796 },
797 })
798
799 // Cache the proxy
800 proxyCache.set(obj, proxy)
801
802 return proxy
803 }
804
805 // Create a proxy for the target object
806 const proxy = createObjectProxy(target)
807
808 // Return the proxy and a function to get the changes
809 return {
810 proxy,
811 getChanges: () => {
812 debugLog(
813 `getChanges called, modified:`,
814 changeTracker.modified,
815 `assigned keys:`,
816 Object.keys(changeTracker.assigned_)
817 )
818
819 // First, check if the object is still considered modified
820 if (!changeTracker.modified) {
821 debugLog(`Object not modified, returning empty object`)
822 return {}
823 }
824
825 // For deeply nested changes, we need to verify explicitly
826 if (
827 Object.keys(changeTracker.assigned_).length === 0 &&
828 Object.getOwnPropertySymbols(changeTracker.assigned_).length === 0
829 ) {
830 debugLog(`No assigned properties, checking deep equality`)
831
832 // If there are no assigned properties but the object is still marked as modified,
833 // we should check deep equality with the original object
834 if (changeTracker.copy_) {
835 debugLog(`Comparing copy with original`)
836 if (deepEqual(changeTracker.copy_, changeTracker.originalObject)) {
837 debugLog(`Copy equals original, returning empty object`)
838 changeTracker.modified = false
839 return {}
840 }
841 } else if (deepEqual(target, changeTracker.originalObject)) {
842 debugLog(`Target equals original, returning empty object`)
843 changeTracker.modified = false
844 changeTracker.changes = {}
845 changeTracker.assigned_ = {}
846 return {}
847 }
848 }
849
850 debugLog(`Forcing full check for reverted state`)
851 // Force a full check for reverted state, which will update the modified flag accordingly
852 updateModifiedStatus(changeTracker)
853
854 // If we're no longer modified after the check, return empty changes
855 // eslint-disable-next-line
856 if (!changeTracker.modified) {
857 debugLog(`No longer modified after check, returning empty object`)
858 return {}
859 }
860
861 // Handle optimization case - if the object is marked modified but actually is equal to original
862 // eslint-disable-next-line
863 if (changeTracker.modified) {
864 const objToCheck = changeTracker.copy_ || target
865 debugLog(
866 `Checking if object is equal to original:`,
867 objToCheck,
868 changeTracker.originalObject
869 )
870 if (deepEqual(objToCheck, changeTracker.originalObject)) {
871 debugLog(`Object equals original, returning empty object`)
872 changeTracker.modified = false
873 changeTracker.changes = {}
874 changeTracker.assigned_ = {}
875 return {}
876 }
877 }
878
879 // If there are assigned properties, return the changes
880 if (
881 Object.keys(changeTracker.assigned_).length > 0 ||
882 Object.getOwnPropertySymbols(changeTracker.assigned_).length > 0
883 ) {
884 // If we have a copy, use it to construct the changes
885 if (changeTracker.copy_) {
886 const changes: Record<string | symbol, unknown> = {}
887
888 // Add all assigned properties
889 for (const key in changeTracker.assigned_) {
890 if (changeTracker.assigned_[key] === true) {
891 // Property was assigned
892 changes[key] = deepClone(changeTracker.copy_[key as keyof T])
893 } else if (changeTracker.assigned_[key] === false) {
894 // Property was deleted
895 changes[key] = undefined
896 }
897 }
898
899 // Handle symbol properties - this needs special handling
900 const symbolProps = Object.getOwnPropertySymbols(
901 changeTracker.assigned_
902 )
903 for (const sym of symbolProps) {
904 if (changeTracker.assigned_[sym.toString()] === true) {
905 // Use the symbol directly instead of its string representation
906
907 const value = (changeTracker.copy_ as any)[sym]
908
909 changes[sym.toString()] = deepClone(value)
910 }
911 }
912
913 return changes
914 }
915
916 // Fall back to the existing changes object if no copy exists
917 return changeTracker.changes
918 }
919
920 // If the object is modified but has no direct changes (nested changes),
921 // but we're the root object, recursively check if unknown changes exist
922 // eslint-disable-next-line
923 if (changeTracker.modified && !parent) {
924 debugLog(`Root object with nested changes, checking deep equality`)
925
926 const currentState = changeTracker.copy_ || (target as any)
927
928 debugLog(
929 `Comparing current state with original:`,
930 currentState,
931 changeTracker.originalObject
932 )
933 if (deepEqual(currentState, changeTracker.originalObject)) {
934 // The entire object has been reverted to its original state
935 debugLog(`Current state equals original, returning empty object`)
936 changeTracker.modified = false
937 return {}
938 }
939
940 // One more deep check - compare the actual values
941 // This is needed for the case where nested properties are modified and then reverted
942 debugLog(
943 `Comparing target with original:`,
944 target,
945 changeTracker.originalObject
946 )
947 if (deepEqual(target, changeTracker.originalObject)) {
948 debugLog(`Target equals original, returning empty object`)
949 changeTracker.modified = false
950 changeTracker.changes = {}
951 changeTracker.assigned_ = {}
952 return {}
953 }
954
955 // Special case for nested object reverts
956 // If we're here, we need to check if the nested objects have been reverted
957 // even if the parent object still shows as modified
958 // eslint-disable-next-line
959 if (typeof target === `object` && target !== null) {
960 let allNestedReverted = true
961
962 // Check each property to see if it's been reverted to original
963 for (const key in target) {
964 if (Object.prototype.hasOwnProperty.call(target, key)) {
965 const currentValue = target[key]
966 const originalValue = changeTracker.originalObject[key as keyof T]
967
968 // If this property is different from original, not all are reverted
969 if (!deepEqual(currentValue, originalValue)) {
970 allNestedReverted = false
971 break
972 }
973 }
974 }
975
976 // If all nested properties match original values, return empty changes
977 if (allNestedReverted) {
978 debugLog(
979 `All nested properties match original values, returning empty object`
980 )
981 changeTracker.modified = false
982 changeTracker.changes = {}
983 changeTracker.assigned_ = {}
984 return {}
985 }
986 }
987
988 debugLog(
989 `Changes detected, returning full object:`,
990 changeTracker.copy_ || target
991 )
992 // Convert the copy or target to a Record type before returning
993 const result = changeTracker.copy_ || target
994 return result as unknown as Record<string | symbol, unknown>
995 }
996
997 // No changes
998 debugLog(`No changes detected, returning empty object`)
999 return {}
1000 },
1001 }
1002}
1003
1004/**
1005 * Creates proxies for an array of objects and tracks changes to each
1006 *
1007 * @param targets Array of objects to proxy
1008 * @returns An object containing the array of proxies and a function to get all changes
1009 */
1010export function createArrayChangeProxy<T extends object>(
1011 targets: Array<T>
1012): {
1013 proxies: Array<T>
1014 getChanges: () => Array<Record<string | symbol, unknown>>
1015} {
1016 const proxiesWithChanges = targets.map((target) => createChangeProxy(target))
1017
1018 return {
1019 proxies: proxiesWithChanges.map((p) => p.proxy),
1020 getChanges: () => proxiesWithChanges.map((p) => p.getChanges()),
1021 }
1022}
1023
1024/**
1025 * Creates a proxy for an object, passes it to a callback function,
1026 * and returns the changes made by the callback
1027 *
1028 * @param target The object to proxy
1029 * @param callback Function that receives the proxy and can make changes to it
1030 * @returns The changes made to the object
1031 */
1032export function withChangeTracking<T extends object>(
1033 target: T,
1034 callback: (proxy: T) => void
1035): Record<string | symbol, unknown> {
1036 const { proxy, getChanges } = createChangeProxy(target)
1037
1038 callback(proxy)
1039
1040 return getChanges()
1041}
1042
1043/**
1044 * Creates proxies for an array of objects, passes them to a callback function,
1045 * and returns the changes made by the callback for each object
1046 *
1047 * @param targets Array of objects to proxy
1048 * @param callback Function that receives the proxies and can make changes to them
1049 * @returns Array of changes made to each object
1050 */
1051export function withArrayChangeTracking<T extends object>(
1052 targets: Array<T>,
1053 callback: (proxies: Array<T>) => void
1054): Array<Record<string | symbol, unknown>> {
1055 const { proxies, getChanges } = createArrayChangeProxy(targets)
1056
1057 callback(proxies)
1058
1059 return getChanges()
1060}
1061
1062/**
1063 * Creates a shallow copy of the target object if it doesn't already exist
1064 */
1065function prepareCopy<T extends object>(state: ChangeTracker<T>) {
1066 if (!state.copy_) {
1067 state.copy_ = shallowCopy(state.originalObject)
1068 }
1069}
1070
1071/**
1072 * Creates a shallow copy of an object
1073 */
1074function shallowCopy<T>(obj: T): T {
1075 if (Array.isArray(obj)) {
1076 return [...obj] as unknown as T
1077 }
1078
1079 if (obj instanceof Map) {
1080 return new Map(obj) as unknown as T
1081 }
1082
1083 if (obj instanceof Set) {
1084 return new Set(obj) as unknown as T
1085 }
1086
1087 if (obj instanceof Date) {
1088 return new Date(obj.getTime()) as unknown as T
1089 }
1090
1091 if (obj instanceof RegExp) {
1092 return new RegExp(obj.source, obj.flags) as unknown as T
1093 }
1094
1095 if (obj !== null && typeof obj === `object`) {
1096 return { ...obj } as T
1097 }
1098
1099 return obj
1100}