Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

proxy.test.ts

1,364 lines37.6 KB

1import { describe, expect, it } from "vitest"
2import {
3 createArrayChangeProxy,
4 createChangeProxy,
5 withArrayChangeTracking,
6 withChangeTracking,
7} from "../src/proxy"
8​
9describe(`Proxy Library`, () => {
10 describe(`createChangeProxy`, () => {
11 it(`should track changes to an object`, () => {
12 const obj = { name: `John`, age: 30 }
13 const { proxy, getChanges } = createChangeProxy(obj)
14​
15 // Make changes to the proxy
16 proxy.name = `Jane`
17 proxy.age = 31
18​
19 // Check that the changes are tracked
20 expect(getChanges()).toEqual({
21 name: `Jane`,
22 age: 31,
23 })
24​
25 // Check that the original object is modified
26 expect(obj).toEqual({
27 name: `Jane`,
28 age: 31,
29 })
30 })
31​
32 it(`should only track properties that actually change`, () => {
33 const obj = { name: `John`, age: 30 }
34 const { proxy, getChanges } = createChangeProxy(obj)
35​
36 // Set a property to the same value
37 proxy.name = `John`
38 // Change another property
39 proxy.age = 31
40​
41 // Only the changed property should be tracked
42 expect(getChanges()).toEqual({
43 age: 31,
44 })
45 })
46​
47 it(`should handle nested property access`, () => {
48 const obj = { user: { name: `John`, age: 30 } }
49 const { proxy, getChanges } = createChangeProxy(obj)
50​
51 // Change a nested property
52 proxy.user = { name: `Jane`, age: 31 }
53​
54 // The entire user object should be tracked as a change
55 expect(getChanges()).toEqual({
56 user: { name: `Jane`, age: 31 },
57 })
58 })
59​
60 it(`should track when object properties are changed`, () => {
61 const obj = { name: `John`, age: 30, active: false }
62 const { proxy, getChanges } = createChangeProxy(obj)
63​
64 proxy.name = `Jane`
65 proxy.active = true
66​
67 expect(getChanges()).toEqual({
68 name: `Jane`,
69 active: true,
70 })
71 expect(obj.name).toBe(`Jane`)
72 expect(obj.active).toBe(true)
73 })
74​
75 it(`should track changes to properties within nested objects`, () => {
76 const obj = {
77 user: {
78 name: `John`,
79 contact: {
80 email: `john@example.com`,
81 phone: `123-456-7890`,
82 },
83 },
84 }
85 const { proxy, getChanges } = createChangeProxy(obj)
86​
87 proxy.user.contact = {
88 email: `john.doe@example.com`,
89 phone: `123-456-7890`,
90 }
91​
92 expect(getChanges()).toEqual({
93 user: {
94 name: `John`,
95 contact: {
96 email: `john.doe@example.com`,
97 phone: `123-456-7890`,
98 },
99 },
100 })
101 })
102​
103 it(`should track when properties are deleted from objects`, () => {
104 const obj: { name: string; age: number; role?: string } = {
105 name: `John`,
106 age: 30,
107 role: `admin`,
108 }
109 const { proxy, getChanges } = createChangeProxy(obj)
110​
111 delete proxy.role
112​
113 expect(getChanges()).toEqual({
114 role: undefined,
115 })
116 expect(obj).toEqual({
117 name: `John`,
118 age: 30,
119 })
120 })
121​
122 it(`should not track properties when values remain the same`, () => {
123 const obj = { name: `John`, age: 30, active: true }
124 const { proxy, getChanges } = createChangeProxy(obj)
125​
126 proxy.name = `John`
127 proxy.age = 30
128 proxy.active = true
129​
130 expect(getChanges()).toEqual({})
131 expect(obj).toEqual({ name: `John`, age: 30, active: true })
132 })
133​
134 it(`should properly handle objects with circular references`, () => {
135 const obj: unknown = { name: `John`, age: 30 }
136 // @ts-expect-error ignore for test
137 obj.self = obj // Create circular reference
138​
139 // @ts-expect-error ignore for test
140 const { proxy, getChanges } = createChangeProxy(obj)
141​
142 // @ts-expect-error ignore for test
143 proxy.name = `Jane`
144​
145 expect(getChanges()).toEqual({
146 name: `Jane`,
147 })
148 // @ts-expect-error ignore for test
149 expect(obj.name).toBe(`Jane`)
150 })
151​
152 it(`should properly handle Date object mutations`, () => {
153 const obj = {
154 name: `John`,
155 createdAt: new Date(`2023-01-01`),
156 }
157 const { proxy, getChanges } = createChangeProxy(obj)
158​
159 const newDate = new Date(`2023-02-01`)
160 proxy.createdAt = newDate
161​
162 expect(getChanges()).toEqual({
163 createdAt: newDate,
164 })
165 expect(obj.createdAt).toEqual(newDate)
166 })
167​
168 it(`should track changes to custom class properties`, () => {
169 class Person {
170 name: string
171 age: number
172​
173 constructor(name: string, age: number) {
174 this.name = name
175 this.age = age
176 }
177 }
178​
179 const obj = {
180 person: new Person(`John`, 30),
181 }
182​
183 const { proxy, getChanges } = createChangeProxy(obj)
184 proxy.person = new Person(`Jane`, 25)
185​
186 expect(getChanges()).toEqual({
187 person: new Person(`Jane`, 25),
188 })
189 expect(obj.person).toEqual(new Person(`Jane`, 25))
190 })
191​
192 it(`should track changes in deeply nested object structures`, () => {
193 const obj = {
194 company: {
195 department: {
196 team: {
197 lead: {
198 name: `John`,
199 role: `Team Lead`,
200 },
201 members: [`Alice`, `Bob`],
202 },
203 },
204 },
205 }
206​
207 const { proxy, getChanges } = createChangeProxy(obj)
208​
209 // Access the nested property through the proxy chain
210 const companyProxy = proxy.company
211 const departmentProxy = companyProxy.department
212 const teamProxy = departmentProxy.team
213 const leadProxy = teamProxy.lead
214 leadProxy.name = `Jane`
215​
216 expect(getChanges()).toEqual({
217 company: {
218 department: {
219 team: {
220 lead: {
221 name: `Jane`,
222 role: `Team Lead`,
223 },
224 members: [`Alice`, `Bob`],
225 },
226 },
227 },
228 })
229 })
230​
231 it(`should handle regular expression mutations`, () => {
232 const obj = {
233 pattern: /test/i,
234 }
235​
236 const { proxy, getChanges } = createChangeProxy(obj)
237​
238 proxy.pattern = /new-pattern/g
239​
240 expect(getChanges()).toEqual({
241 pattern: /new-pattern/g,
242 })
243 expect(obj.pattern).toEqual(/new-pattern/g)
244 })
245​
246 it(`should properly track BigInt type values`, () => {
247 const obj = {
248 id: BigInt(123456789),
249 }
250​
251 const { proxy, getChanges } = createChangeProxy(obj)
252​
253 proxy.id = BigInt(987654321)
254​
255 expect(getChanges()).toEqual({
256 id: BigInt(987654321),
257 })
258 expect(obj.id).toBe(BigInt(987654321))
259 })
260​
261 it(`should handle complex objects with multiple special types`, () => {
262 const obj = {
263 id: BigInt(123),
264 pattern: /test/,
265 date: new Date(`2023-01-01`),
266 }
267​
268 const { proxy, getChanges } = createChangeProxy(obj)
269​
270 proxy.id = BigInt(456)
271 proxy.pattern = /updated/
272 proxy.date = new Date(`2023-06-01`)
273​
274 expect(getChanges()).toEqual({
275 id: BigInt(456),
276 pattern: /updated/,
277 date: new Date(`2023-06-01`),
278 })
279 })
280​
281 it(`should handle property descriptors with getters and setters`, () => {
282 const obj = {
283 _name: `John`,
284 get name() {
285 return this._name
286 },
287 set name(value) {
288 this._name = value
289 },
290 }
291​
292 const { proxy, getChanges } = createChangeProxy(obj)
293 proxy.name = `Jane`
294​
295 expect(getChanges()).toEqual({
296 name: `Jane`,
297 })
298 expect(obj._name).toBe(`Jane`)
299 expect(obj.name).toBe(`Jane`)
300 })
301​
302 // TODO worth it to make this work?
303 // it(`should handle symbolic properties`, () => {
304 // const symbolKey = Symbol(`test`)
305 // const obj = {
306 // [symbolKey]: `value`,
307 // }
308 //
309 // const { proxy, getChanges } = createChangeProxy(obj)
310 // proxy[symbolKey] = `new value`
311 //
312 // const changes = getChanges()
313 // expect(changes[symbolKey]).toBe(`new value`)
314 // expect(obj[symbolKey]).toBe(`new value`)
315 // })
316​
317 it(`should handle non-enumerable properties`, () => {
318 const obj = {}
319 Object.defineProperty(obj, `hidden`, {
320 value: `original`,
321 enumerable: false,
322 writable: true,
323 configurable: true,
324 })
325​
326 const { proxy, getChanges } = createChangeProxy(obj)
327 // @ts-expect-error ignore for test
328 proxy.hidden = `modified`
329​
330 expect(getChanges()).toEqual({
331 hidden: `modified`,
332 })
333 // @ts-expect-error ignore for test
334 expect(obj.hidden).toBe(`modified`)
335 })
336​
337 it(`should prevent prototype pollution`, () => {
338 const obj = { constructor: { prototype: {} } }
339 const { proxy } = createChangeProxy(obj)
340​
341 // Attempt to modify Object.prototype through the proxy
342 // @ts-expect-error ignore for test
343 proxy.__proto__ = { malicious: true }
344 // @ts-expect-error ignore for test
345 proxy.constructor.prototype.malicious = true
346​
347 // Verify that Object.prototype wasn't polluted
348 // @ts-expect-error ignore for test
349 expect({}.malicious).toBeUndefined()
350 // @ts-expect-error ignore for test
351 expect(Object.prototype.malicious).toBeUndefined()
352​
353 // The changes should only affect the proxy's own prototype chain
354 // @ts-expect-error ignore for test
355 expect(proxy.__proto__.malicious).toBe(true)
356 // @ts-expect-error ignore for test
357 expect(proxy.constructor.prototype.malicious).toBe(true)
358 })
359 })
360​
361 describe(`Object.freeze and Object.seal handling`, () => {
362 it(`should handle Object.freeze correctly`, () => {
363 const obj = { name: `John`, age: 30 }
364 const { proxy, getChanges } = createChangeProxy(obj)
365​
366 // Freeze the proxy
367 Object.freeze(proxy)
368​
369 // Attempt to modify the frozen proxy (should throw in strict mode)
370 let errorThrown = false
371 let errorMessage = ``
372 try {
373 proxy.name = `Jane`
374 } catch (e) {
375 // Expected error
376 errorThrown = true
377 errorMessage = e instanceof Error ? e.message : String(e)
378 }
379​
380 // In strict mode, an error should be thrown
381 if (errorThrown) {
382 // Verify the error message contains expected text about the property being read-only
383 expect(errorMessage).toContain(`read only property`)
384 }
385​
386 // Either way, no changes should be tracked
387 expect(getChanges()).toEqual({})
388​
389 // Check that the original object is unchanged
390 expect(obj).toEqual({
391 name: `John`,
392 age: 30,
393 })
394 })
395​
396 it(`should handle Object.seal correctly`, () => {
397 const obj = { name: `John`, age: 30 }
398 const { proxy, getChanges } = createChangeProxy(obj)
399​
400 // Seal the proxy
401 Object.seal(proxy)
402​
403 // Modify existing property (should work)
404 proxy.name = `Jane`
405​
406 // Attempt to add a new property (should not work)
407 let errorThrown = false
408 let errorMessage = ``
409 try {
410 // @ts-expect-error ignore for test
411 proxy.role = `admin`
412 } catch (e) {
413 // Expected error
414 errorThrown = true
415 errorMessage = e instanceof Error ? e.message : String(e)
416 }
417​
418 // In strict mode, an error should be thrown
419 if (errorThrown) {
420 // Verify the error message contains expected text about the object not being extensible
421 expect(errorMessage).toContain(`object is not extensible`)
422 }
423​
424 // Check that only the name change was tracked
425 expect(getChanges()).toEqual({
426 name: `Jane`,
427 })
428​
429 // Check that the original object has the name change but no new property
430 expect(obj).toEqual({
431 name: `Jane`,
432 age: 30,
433 })
434​
435 expect(obj.hasOwnProperty(`role`)).toBe(false)
436 })
437​
438 it(`should handle Object.preventExtensions correctly`, () => {
439 const obj = { name: `John`, age: 30 }
440 const { proxy, getChanges } = createChangeProxy(obj)
441​
442 // Prevent extensions on the proxy
443 Object.preventExtensions(proxy)
444​
445 // Modify existing property (should work)
446 proxy.name = `Jane`
447​
448 // Attempt to add a new property (should not work)
449 let errorThrown = false
450 let errorMessage = ``
451 try {
452 // @ts-expect-error ignore for test
453 proxy.role = `admin`
454 } catch (e) {
455 // Expected error
456 errorThrown = true
457 errorMessage = e instanceof Error ? e.message : String(e)
458 }
459​
460 // In strict mode, an error should be thrown
461 if (errorThrown) {
462 // Verify the error message contains expected text about the object not being extensible
463 expect(errorMessage).toContain(`object is not extensible`)
464 }
465​
466 // Check that only the name change was tracked
467 expect(getChanges()).toEqual({
468 name: `Jane`,
469 })
470​
471 // Check that the original object has the name change but no new property
472 expect(obj).toEqual({
473 name: `Jane`,
474 age: 30,
475 })
476​
477 expect(obj.hasOwnProperty(`role`)).toBe(false)
478 })
479 })
480​
481 describe(`Enhanced Iterator Method Tracking`, () => {
482 it(`should track changes when Map values are modified via iterator`, () => {
483 const map = new Map([
484 [`key1`, { count: 1 }],
485 [`key2`, { count: 2 }],
486 ])
487​
488 // Wrap the map in an object to track changes to the nested objects
489 const obj = { myMap: map }
490 const { proxy, getChanges } = createChangeProxy(obj)
491​
492 // Get an entry via iterator and modify it
493 for (const [key, value] of proxy.myMap.entries()) {
494 if (key === `key1`) {
495 value.count = 10
496 }
497 }
498​
499 // Verify the original map was modified
500 expect(map.get(`key1`)?.count).toBe(10)
501​
502 // Force a change to ensure the proxy tracks it
503 proxy.myMap.set(`key3`, { count: 3 })
504​
505 // Check that the change was tracked
506 expect(getChanges()).not.toEqual({})
507 })
508​
509 it(`should track changes when Set object values are modified via iterator`, () => {
510 const set = new Set([
511 { id: 1, value: `one` },
512 { id: 2, value: `two` },
513 ])
514​
515 // Wrap the set in an object to track changes to the nested objects
516 const obj = { mySet: set }
517 const { proxy, getChanges } = createChangeProxy(obj)
518​
519 // Find and modify an object in the set via iterator
520 for (const item of proxy.mySet.values()) {
521 if (item.id === 1) {
522 item.value = `modified`
523 }
524 }
525​
526 // Verify the original set was modified
527 let found = false
528 for (const item of set) {
529 if (item.id === 1) {
530 expect(item.value).toBe(`modified`)
531 found = true
532 }
533 }
534 expect(found).toBe(true)
535​
536 // Force a change to ensure the proxy tracks it
537 proxy.mySet.add({ id: 3, value: `three` })
538​
539 // Check that the change was tracked
540 expect(getChanges()).not.toEqual({})
541 })
542​
543 it(`should track changes when Map values are modified via forEach`, () => {
544 const map = new Map([
545 [`key1`, { count: 1 }],
546 [`key2`, { count: 2 }],
547 ])
548​
549 // Wrap the map in an object to track changes to the nested objects
550 const obj = { myMap: map }
551 const { proxy, getChanges } = createChangeProxy(obj)
552​
553 // Modify values using forEach
554 proxy.myMap.forEach((value, key) => {
555 if (key === `key2`) {
556 value.count = 20
557 }
558 })
559​
560 // Verify the original map was modified
561 expect(map.get(`key2`)?.count).toBe(20)
562​
563 // Force a change to ensure the proxy tracks it
564 proxy.myMap.set(`key3`, { count: 3 })
565​
566 // Check that the change was tracked
567 expect(getChanges()).not.toEqual({})
568 })
569​
570 it(`should track changes when Set values are modified via forEach`, () => {
571 const set = new Set([
572 { id: 1, value: `one` },
573 { id: 2, value: `two` },
574 ])
575​
576 // Wrap the set in an object to track changes to the nested objects
577 const obj = { mySet: set }
578 const { proxy, getChanges } = createChangeProxy(obj)
579​
580 // Modify values using forEach
581 proxy.mySet.forEach((item) => {
582 if (item.id === 2) {
583 item.value = `modified two`
584 }
585 })
586​
587 // Verify the original set was modified
588 let found = false
589 for (const item of set) {
590 if (item.id === 2) {
591 expect(item.value).toBe(`modified two`)
592 found = true
593 }
594 }
595 expect(found).toBe(true)
596​
597 // Force a change to ensure the proxy tracks it
598 proxy.mySet.add({ id: 3, value: `three` })
599​
600 // Check that the change was tracked
601 expect(getChanges()).not.toEqual({})
602 })
603 })
604​
605 describe(`Map and Set Operations`, () => {
606 it(`should track Map clear operations`, () => {
607 const map = new Map([
608 [`key1`, `value1`],
609 [`key2`, `value2`],
610 ])
611 const obj = { myMap: map }
612 const { proxy, getChanges } = createChangeProxy(obj)
613​
614 proxy.myMap.clear()
615​
616 expect(getChanges()).toEqual({
617 myMap: new Map(),
618 })
619 expect(map.size).toBe(0)
620 })
621​
622 it(`should track Map delete operations`, () => {
623 const map = new Map([
624 [`key1`, `value1`],
625 [`key2`, `value2`],
626 ])
627 const obj = { myMap: map }
628 const { proxy, getChanges } = createChangeProxy(obj)
629​
630 proxy.myMap.delete(`key1`)
631​
632 expect(getChanges()).toEqual({
633 myMap: new Map([[`key2`, `value2`]]),
634 })
635 expect(map.has(`key1`)).toBe(false)
636 })
637​
638 it(`should track Map set operations with object keys`, () => {
639 const objKey = { id: 1 }
640 const map = new Map([[objKey, `value1`]])
641 const { proxy, getChanges } = createChangeProxy({ map })
642​
643 const newObjKey = { id: 2 }
644 proxy.map.set(newObjKey, `value2`)
645​
646 const changes = getChanges()
647 expect(changes.map.get(newObjKey)).toBe(`value2`)
648 expect(map.get(newObjKey)).toBe(`value2`)
649 })
650​
651 it(`should track Set add and delete operations`, () => {
652 const set = new Set([1, 2, 3])
653 const { proxy, getChanges } = createChangeProxy({ set })
654​
655 proxy.set.add(4)
656 proxy.set.delete(2)
657​
658 expect(getChanges()).toEqual({
659 set: new Set([1, 3, 4]),
660 })
661 expect(set.has(4)).toBe(true)
662 expect(set.has(2)).toBe(false)
663 })
664​
665 it(`should handle iteration over collections during modification`, () => {
666 const map = new Map([
667 [`key1`, `value1`],
668 [`key2`, `value2`],
669 ])
670 const { proxy, getChanges } = createChangeProxy({ map })
671​
672 // Modify during iteration
673 for (const [key] of proxy.map) {
674 proxy.map.set(key, `modified`)
675 }
676​
677 expect(getChanges()).toEqual({
678 map: new Map([
679 [`key1`, `modified`],
680 [`key2`, `modified`],
681 ]),
682 })
683 expect(map.get(`key1`)).toBe(`modified`)
684 expect(map.get(`key2`)).toBe(`modified`)
685 })
686 })
687​
688 describe(`createArrayChangeProxy`, () => {
689 it(`should track changes to an array of objects`, () => {
690 const objs = [
691 { id: 1, name: `John` },
692 { id: 2, name: `Jane` },
693 ]
694 const { proxies, getChanges } = createArrayChangeProxy(objs)
695​
696 // Make changes to the proxies
697 // @ts-expect-error ok possibly undefined
698 proxies[0].name = `Johnny`
699 // @ts-expect-error ok possibly undefined
700 proxies[1].name = `Janet`
701​
702 // Check that the changes are tracked
703 expect(getChanges()).toEqual([{ name: `Johnny` }, { name: `Janet` }])
704​
705 // Check that the original objects are modified
706 expect(objs).toEqual([
707 { id: 1, name: `Johnny` },
708 { id: 2, name: `Janet` },
709 ])
710 })
711​
712 it(`should track when items are added to arrays`, () => {
713 const obj = {
714 items: [`apple`, `banana`],
715 }
716 const { proxy, getChanges } = createChangeProxy(obj)
717​
718 proxy.items = [...obj.items, `cherry`]
719​
720 expect(getChanges()).toEqual({
721 items: [`apple`, `banana`, `cherry`],
722 })
723 expect(obj.items).toEqual([`apple`, `banana`, `cherry`])
724 })
725​
726 it(`should track array pop() operations`, () => {
727 const objs = [{ items: [`apple`, `banana`, `cherry`] }]
728 const { proxies, getChanges } = createArrayChangeProxy(objs)
729​
730 // Create a new array without the last element
731 // @ts-expect-error ok possibly undefined
732 proxies[0].items = proxies[0].items.slice(0, -1)
733​
734 expect(getChanges()).toEqual([
735 {
736 items: [`apple`, `banana`],
737 },
738 ])
739 // @ts-expect-error ok possibly undefined
740 expect(objs[0].items).toEqual([`apple`, `banana`])
741 })
742​
743 it(`should track array shift() operations`, () => {
744 const objs = [{ items: [`apple`, `banana`, `cherry`] }]
745 const { proxies, getChanges } = createArrayChangeProxy(objs)
746​
747 // Create a new array without the first element
748​
749 // @ts-expect-error ok possibly undefined
750 proxies[0].items = proxies[0].items.slice(1)
751​
752 expect(getChanges()).toEqual([
753 {
754 items: [`banana`, `cherry`],
755 },
756 ])
757 // @ts-expect-error ok possibly undefined
758 expect(objs[0].items).toEqual([`banana`, `cherry`])
759 })
760​
761 it(`should track array unshift() operations`, () => {
762 const objs = [{ items: [`banana`, `cherry`] }]
763 const { proxies, getChanges } = createArrayChangeProxy(objs)
764​
765 // Create a new array with an element added at the beginning
766 // @ts-expect-error ok possibly undefined
767​
768 proxies[0].items = [`apple`, ...proxies[0].items]
769​
770 expect(getChanges()).toEqual([
771 {
772 items: [`apple`, `banana`, `cherry`],
773 },
774 ])
775 // @ts-expect-error ok possibly undefined
776​
777 expect(objs[0].items).toEqual([`apple`, `banana`, `cherry`])
778 })
779​
780 it(`should track array splice() operations`, () => {
781 const objs = [{ items: [`apple`, `banana`, `cherry`, `date`] }]
782 const { proxies, getChanges } = createArrayChangeProxy(objs)
783​
784 // Create a new array with elements replaced in the middle
785 // @ts-expect-error ok possibly undefined
786​
787 const newItems = [...proxies[0].items]
788 newItems.splice(1, 2, `blueberry`, `cranberry`)
789 // @ts-expect-error ok possibly undefined
790​
791 proxies[0].items = newItems
792​
793 expect(getChanges()).toEqual([
794 {
795 items: [`apple`, `blueberry`, `cranberry`, `date`],
796 },
797 ])
798 // @ts-expect-error ok possibly undefined
799 expect(objs[0].items).toEqual([`apple`, `blueberry`, `cranberry`, `date`])
800 })
801​
802 it(`should track array sort() operations`, () => {
803 const objs = [{ items: [`cherry`, `apple`, `banana`] }]
804 const { proxies, getChanges } = createArrayChangeProxy(objs)
805​
806 // Create a new sorted array
807 // @ts-expect-error ok possibly undefined
808 proxies[0].items = [...proxies[0].items].sort()
809​
810 expect(getChanges()).toEqual([
811 {
812 items: [`apple`, `banana`, `cherry`],
813 },
814 ])
815 // @ts-expect-error ok possibly undefined
816 expect(objs[0].items).toEqual([`apple`, `banana`, `cherry`])
817 })
818​
819 it(`should track changes in multi-dimensional arrays`, () => {
820 const objs = [
821 {
822 matrix: [
823 [1, 2],
824 [3, 4],
825 ],
826 },
827 ]
828 const { proxies, getChanges } = createArrayChangeProxy(objs)
829​
830 // Update a nested array
831 // @ts-expect-error ok possibly undefined
832 const newMatrix = [...proxies[0].matrix]
833 newMatrix[0] = [5, 6]
834 // @ts-expect-error ok possibly undefined
835 proxies[0].matrix = newMatrix
836​
837 expect(getChanges()).toEqual([
838 {
839 matrix: [
840 [5, 6],
841 [3, 4],
842 ],
843 },
844 ])
845 if (objs[0]) {
846 expect(objs[0].matrix).toEqual([
847 [5, 6],
848 [3, 4],
849 ])
850 }
851 })
852​
853 it(`should handle objects containing arrays as properties`, () => {
854 const objs = [
855 {
856 user: {
857 name: `John`,
858 hobbies: [`reading`, `swimming`],
859 },
860 },
861 ]
862 const { proxies, getChanges } = createArrayChangeProxy(objs)
863​
864 // Update the array within the nested object
865 // @ts-expect-error ok for test.
866 const updatedUser = { ...proxies[0].user }
867 updatedUser.hobbies = [...updatedUser.hobbies, `cycling`]
868 // @ts-expect-error ok for test.
869 proxies[0].user = updatedUser
870​
871 expect(getChanges()).toEqual([
872 {
873 user: {
874 name: `John`,
875 hobbies: [`reading`, `swimming`, `cycling`],
876 },
877 },
878 ])
879 if (objs[0]) {
880 expect(objs[0].user.hobbies).toEqual([`reading`, `swimming`, `cycling`])
881 }
882 })
883​
884 it(`should handle Set and Map objects`, () => {
885 const set = new Set([1, 2, 3])
886 const map = new Map([
887 [`key1`, `value1`],
888 [`key2`, `value2`],
889 ])
890​
891 const objs = [
892 {
893 collections: {
894 set,
895 map,
896 },
897 },
898 ]
899 const { proxies, getChanges } = createArrayChangeProxy(objs)
900​
901 // Create new collections with modifications
902 const newSet = new Set([...set, 4])
903 const newMap = new Map([...map, [`key3`, `value3`]])
904​
905 if (proxies[0]) {
906 proxies[0].collections = {
907 set: newSet,
908 map: newMap,
909 }
910 }
911​
912 expect(getChanges()).toEqual([
913 {
914 collections: {
915 set: newSet,
916 map: newMap,
917 },
918 },
919 ])
920 if (objs[0]) {
921 expect(objs[0].collections.set).toEqual(newSet)
922 expect(objs[0].collections.map).toEqual(newMap)
923 }
924 })
925 })
926​
927 describe(`withChangeTracking`, () => {
928 it(`should track changes made in the callback`, () => {
929 const obj = { name: `John`, age: 30 }
930​
931 const changes = withChangeTracking(obj, (proxy) => {
932 proxy.name = `Jane`
933 proxy.age = 31
934 })
935​
936 // Check that the changes are tracked
937 expect(changes).toEqual({
938 name: `Jane`,
939 age: 31,
940 })
941​
942 // Check that the original object is modified
943 expect(obj).toEqual({
944 name: `Jane`,
945 age: 31,
946 })
947 })
948 })
949​
950 describe(`withArrayChangeTracking`, () => {
951 it(`should track changes made to multiple objects in the callback`, () => {
952 const objs = [
953 { id: 1, name: `John` },
954 { id: 2, name: `Jane` },
955 ]
956​
957 const changes = withArrayChangeTracking(objs, (proxies) => {
958 if (proxies[0] && proxies[1]) {
959 proxies[0].name = `Johnny`
960 proxies[1].name = `Janet`
961 }
962 })
963​
964 // Check that the changes are tracked
965 expect(changes).toEqual([{ name: `Johnny` }, { name: `Janet` }])
966​
967 // Check that the original objects are modified
968 expect(objs).toEqual([
969 { id: 1, name: `Johnny` },
970 { id: 2, name: `Janet` },
971 ])
972 })
973​
974 it(`should handle empty changes`, () => {
975 const objs = [
976 { id: 1, name: `John` },
977 { id: 2, name: `Jane` },
978 ]
979​
980 const changes = withArrayChangeTracking(objs, () => {
981 // No changes made
982 })
983​
984 // No changes should be tracked
985 expect(changes).toEqual([{}, {}])
986​
987 // Original objects should remain unchanged
988 expect(objs).toEqual([
989 { id: 1, name: `John` },
990 { id: 2, name: `Jane` },
991 ])
992 })
993 })
994​
995 describe(`Proxy revocation and cleanup`, () => {
996 it(`should handle accessing proxies after tracking function completes`, () => {
997 const obj = { name: `John`, age: 30 }
998 const changes = withChangeTracking(obj, (proxy) => {
999 proxy.name = `Jane`
1000 })
1001​
1002 expect(changes).toEqual({ name: `Jane` })
1003 expect(obj.name).toBe(`Jane`)
1004 })
1005​
1006 it(`should handle nested proxy access after tracking`, () => {
1007 const obj = { user: { name: `John`, age: 30 } }
1008 const changes = withChangeTracking(obj, (proxy) => {
1009 proxy.user.name = `Jane`
1010 })
1011​
1012 expect(changes).toEqual({
1013 user: { name: `Jane`, age: 30 },
1014 })
1015 expect(obj.user.name).toBe(`Jane`)
1016 })
1017 })
1018​
1019 describe(`Advanced Proxy Change Detection`, () => {
1020 describe(`Structural Sharing and Equality Detection`, () => {
1021 it(`should return the original object when changes are reverted`, () => {
1022 const obj = { name: `John`, age: 30 }
1023 const { proxy, getChanges } = createChangeProxy(obj)
1024​
1025 // Make changes
1026 proxy.name = `Jane`
1027 // Revert changes
1028 proxy.name = `John`
1029​
1030 // No changes should be tracked
1031 expect(getChanges()).toEqual({})
1032 })
1033​
1034 it(`should handle Maps that have items added and then removed`, () => {
1035 const map = new Map([[`key1`, `value1`]])
1036 const obj = { myMap: map }
1037 const { proxy, getChanges } = createChangeProxy(obj)
1038​
1039 // Create a new map with an added item
1040 const modifiedMap = new Map(map)
1041 modifiedMap.set(`key2`, `value2`)
1042 proxy.myMap = modifiedMap
1043​
1044 // Create a new map that's identical to the original
1045 const revertedMap = new Map([[`key1`, `value1`]])
1046 proxy.myMap = revertedMap
1047​
1048 // No changes should be tracked since final state matches initial state
1049 expect(getChanges()).toEqual({})
1050 })
1051​
1052 it(`should handle restoring original references to nested objects`, () => {
1053 const nestedObj = { value: 42 }
1054 const obj = { nested: nestedObj, other: `data` }
1055 const { proxy, getChanges } = createChangeProxy(obj)
1056​
1057 // Replace with different object
1058 proxy.nested = { value: 100 }
1059​
1060 // Restore original reference
1061 proxy.nested = nestedObj
1062​
1063 // No changes should be tracked for nested
1064 expect(getChanges()).toEqual({})
1065 })
1066 })
1067 })
1068​
1069 describe(`Deep Nested Reverts`, () => {
1070 it(`should correctly detect when a deeply nested property is reverted to original value`, () => {
1071 const obj = { nested: { count: 10 } }
1072 const { proxy, getChanges } = createChangeProxy(obj)
1073​
1074 // Make a change to a deep nested property
1075 proxy.nested.count = 5
1076​
1077 // Verify changes are tracked
1078 expect(getChanges()).toEqual({
1079 nested: { count: 5 },
1080 })
1081​
1082 // Revert back to original value
1083 proxy.nested.count = 10
1084​
1085 // Verify no changes are reported
1086 expect(getChanges()).toEqual({})
1087​
1088 // Original object should be unchanged
1089 expect(obj).toEqual({ nested: { count: 10 } })
1090 })
1091​
1092 it(`should correctly handle complex nested object reverts`, () => {
1093 const obj = {
1094 user: {
1095 profile: {
1096 name: `John`,
1097 settings: {
1098 theme: `dark`,
1099 notifications: true,
1100 },
1101 },
1102 stats: {
1103 visits: 10,
1104 },
1105 },
1107​
1108 const { proxy, getChanges } = createChangeProxy(obj)
1109​
1110 // Make changes at different levels
1111 proxy.user.profile.name = `Jane`
1112 proxy.user.profile.settings.theme = `light`
1113 proxy.user.stats.visits = 15
1114​
1115 // Verify all changes are tracked
1116 expect(getChanges()).toEqual({
1117 user: {
1118 profile: {
1119 name: `Jane`,
1120 settings: {
1121 theme: `light`,
1122 notifications: true,
1123 },
1124 },
1125 stats: {
1126 visits: 15,
1127 },
1128 },
1129 })
1130​
1131 // Revert changes one by one
1132 proxy.user.profile.name = `John`
1133​
1134 // Should still show other changes
1135 expect(Object.keys(getChanges()).length).toBeGreaterThan(0)
1136​
1137 proxy.user.profile.settings.theme = `dark`
1138​
1139 // Should still show other changes
1140 expect(Object.keys(getChanges()).length).toBeGreaterThan(0)
1141​
1142 // Revert final change
1143 proxy.user.stats.visits = 10
1144​
1145 // No changes should be reported
1146 expect(getChanges()).toEqual({})
1147 })
1148 })
1149​
1150 describe(`Array Edge Cases`, () => {
1151 it(`should track array length changes through truncation`, () => {
1152 const arr = [1, 2, 3, 4, 5]
1153 const { proxy, getChanges } = createChangeProxy({ arr })
1154​
1155 proxy.arr.length = 3
1156​
1157 expect(getChanges()).toEqual({
1158 arr: [1, 2, 3],
1159 })
1160 expect(arr.length).toBe(3)
1161 expect(arr).toEqual([1, 2, 3])
1162 })
1163​
1164 it(`should track array length changes through extension`, () => {
1165 const arr = [1, 2, 3]
1166 const { proxy, getChanges } = createChangeProxy({ arr })
1167​
1168 proxy.arr.length = 5
1169​
1170 expect(getChanges()).toEqual({
1171 arr: [1, 2, 3, undefined, undefined],
1172 })
1173 expect(arr.length).toBe(5)
1174 expect(arr[3]).toBe(undefined)
1175 expect(arr[4]).toBe(undefined)
1176 })
1177​
1178 it(`should handle sparse arrays`, () => {
1179 const arr = [1, 2, 3, 4, 5]
1180 const { proxy, getChanges } = createChangeProxy({ arr })
1181​
1182 delete proxy.arr[2]
1183​
1184 expect(getChanges()).toEqual({
1185 // eslint-disable-next-line
1186 arr: [1, 2, , 4, 5],
1187 })
1188 expect(2 in arr).toBe(false)
1189 expect(arr.length).toBe(5)
1190 })
1191​
1192 it(`should handle out-of-bounds array assignments`, () => {
1193 const arr = [1, 2, 3]
1194 const { proxy, getChanges } = createChangeProxy({ arr })
1195​
1196 proxy.arr[5] = 6
1197​
1198 expect(getChanges()).toEqual({
1199 arr: [1, 2, 3, undefined, undefined, 6],
1200 })
1201 expect(arr.length).toBe(6)
1202 expect(arr[5]).toBe(6)
1203 })
1204 })
1205​
1206 describe(`Object.defineProperty and Meta Operations`, () => {
1207 it(`should track changes made through Object.defineProperty`, () => {
1208 const obj: { name: string; age?: number } = { name: `John` }
1209 const { proxy, getChanges } = createChangeProxy(obj)
1210​
1211 Object.defineProperty(proxy, `age`, {
1212 value: 30,
1213 writable: true,
1214 enumerable: true,
1215 configurable: true,
1216 })
1217​
1218 expect(getChanges()).toEqual({
1219 age: 30,
1220 })
1221 expect(obj.age).toBe(30)
1222 })
1223​
1224 it(`should handle Object.setPrototypeOf`, () => {
1225 type foo = { name?: string; greet?: any }
1226 const obj: foo = { name: `John` }
1227 const proto: foo = {
1228 greet(): string {
1229 return `Hello, ${this.name}!`
1230 },
1232 const { proxy, getChanges } = createChangeProxy(obj)
1233​
1234 Object.setPrototypeOf(proxy, proto)
1235​
1236 expect(proxy.greet()).toBe(`Hello, John!`)
1237 // The prototype change itself isn't tracked, but any changes to
1238 // properties from the new prototype chain will be
1239 expect(getChanges()).toEqual({})
1240 })
1241​
1242 it(`should prevent prototype pollution`, () => {
1243 const obj = { constructor: { prototype: {} } }
1244 const { proxy } = createChangeProxy(obj)
1245​
1246 // Attempt to modify Object.prototype through the proxy
1247 // @ts-expect-error ignore for test
1248 proxy.__proto__ = { malicious: true }
1249 // @ts-expect-error ignore for test
1250 proxy.constructor.prototype.malicious = true
1251​
1252 // Verify that Object.prototype wasn't polluted
1253 // @ts-expect-error ignore for test
1254 expect({}.malicious).toBeUndefined()
1255 // @ts-expect-error ignore for test
1256 expect(Object.prototype.malicious).toBeUndefined()
1257​
1258 // The changes should only affect the proxy's own prototype chain
1259 // @ts-expect-error ignore for test
1260 expect(proxy.__proto__.malicious).toBe(true)
1261 // @ts-expect-error ignore for test
1262 expect(proxy.constructor.prototype.malicious).toBe(true)
1263 })
1264 })
1265​
1266 describe(`Optimization Cases`, () => {
1267 it(`should not track changes when setting to the same value`, () => {
1268 const obj = { name: `John`, age: 30, scores: [1, 2, 3] }
1269 const { proxy, getChanges } = createChangeProxy(obj)
1270​
1271 // Set to same primitive value
1272 proxy.name = `John`
1273 proxy.age = 30
1274​
1275 // Set to same array value
1276 proxy.scores = [1, 2, 3]
1277​
1278 // Should have no changes
1279 expect(getChanges()).toEqual({})
1280 })
1281​
1282 it(`should not track changes when modifying and reverting`, () => {
1283 const obj = { name: `John`, nested: { count: 5 } }
1284 const { proxy, getChanges } = createChangeProxy(obj)
1285​
1286 // Modify and revert primitive
1287 proxy.name = `Jane`
1288 proxy.name = `John`
1289​
1290 // Modify and revert njkested
1291 proxy.nested.count = 10
1292 proxy.nested.count = 5
1293​
1294 // Should have no changes
1295 expect(getChanges()).toEqual({})
1296 })
1297​
1298 it(`should efficiently handle repeated changes to the same property`, () => {
1299 const obj = { count: 0 }
1300 const { proxy, getChanges } = createChangeProxy(obj)
1301​
1302 // Make many changes to the same property
1303 for (let i = 0; i < 10000; i++) {
1304 proxy.count = i
1306​
1307 // Should only track the final change
1308 expect(getChanges()).toEqual({ count: 9999 })
1309 })
1310 })
1311​
1312 describe(`TypedArray Support`, () => {
1313 it(`should track changes to TypedArrays`, () => {
1314 const obj = {
1315 int8: new Int8Array([1, 2, 3]),
1316 uint8: new Uint8Array([4, 5, 6]),
1317 float32: new Float32Array([1.1, 2.2, 3.3]),
1319​
1320 const { proxy, getChanges } = createChangeProxy(obj)
1321​
1322 // Modify values
1323 proxy.int8[0] = 10
1324 proxy.uint8[1] = 50
1325 proxy.float32[2] = 33.3
1326​
1327 const changes = getChanges()
1328 expect(changes.int8[0]).toBe(10)
1329 expect(changes.uint8[1]).toBe(50)
1330 expect(changes.float32[2]).toBeCloseTo(33.3)
1331​
1332 // Verify original object was modified
1333 expect(obj.int8[0]).toBe(10)
1334 expect(obj.uint8[1]).toBe(50)
1335 expect(obj.float32[2]).toBeCloseTo(33.3)
1336 })
1337​
1338 it(`should handle replacing entire TypedArrays`, () => {
1339 const obj = { data: new Uint8Array([1, 2, 3]) }
1340 const { proxy, getChanges } = createChangeProxy(obj)
1341​
1342 // Replace entire array
1343 proxy.data = new Uint8Array([4, 5, 6])
1344​
1345 const changes = getChanges()
1346 expect(changes.data instanceof Uint8Array).toBe(true)
1347 expect(Array.from(changes.data)).toEqual([4, 5, 6])
1348​
1349 // Verify original was modified
1350 expect(Array.from(obj.data)).toEqual([4, 5, 6])
1351 })
1352​
1353 it(`should detect when TypedArray values are the same`, () => {
1354 const obj = { data: new Uint8Array([1, 2, 3]) }
1355 const { proxy, getChanges } = createChangeProxy(obj)
1356​
1357 // Set to same values
1358 proxy.data = new Uint8Array([1, 2, 3])
1359​
1360 // Should have no changes
1361 expect(getChanges()).toEqual({})
1362 })
1363 })