patch.js
This file
Path
__tests__/patch.js
1,535 lines · 28.7 KiB · JavaScript
Last changed by
fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)Mark Eriksonbefore adoptionb208d58
History of this fileTake it
1"use strict"2import {vi} from "vitest"3import {4 produce,5 applyPatches,6 produceWithPatches,7 isDraft,8 immerable,9 nothing,10 enablePatches,11 enableMapSet12} from "../src/immer"1314enablePatches()15enableMapSet()1617vi.setConfig({18 testTimeout: 100019})2021const isProd = process.env.NODE_ENV === "production"2223function createPatchTestData(24 base,25 producer,26 expectedPatches,27 expectedInversePatches,28 expectedResult29) {30 let recordedPatches, recordedInversePatches31 const res = produce(base, producer, (p, i) => {32 recordedPatches = p33 recordedInversePatches = i34 })3536 return {37 result: res,38 patches: recordedPatches,39 inversePatches: recordedInversePatches,40 expectedPatches,41 expectedInversePatches,42 expectedResult,43 base44 }45}4647function runPatchTests(48 testName,49 base,50 producer,51 expectedPatches,52 expectedInversePatches,53 expectedResult,54 options = {}55) {56 const {only = false, skip = false} = options5758 // Choose the appropriate describe function59 let describeFn = describe60 if (testName === "") describeFn = (name, fn) => fn()61 if (only) describeFn = describe.only62 if (skip) describeFn = describe.skip6364 let testData = createPatchTestData(65 base,66 producer,67 expectedPatches,68 expectedInversePatches,69 expectedResult70 )7172 describeFn(testName, () => {73 if (expectedResult !== undefined) {74 test("produced the correct result", () => {75 expect(testData.result).toEqual(expectedResult)76 })77 }7879 test("produces the correct patches", () => {80 expect(testData.patches).toEqual(expectedPatches)81 if (expectedInversePatches) {82 expect(testData.inversePatches).toEqual(expectedInversePatches)83 }84 })8586 test("patches are replayable", () => {87 expect(applyPatches(base, testData.patches)).toEqual(testData.result)88 })8990 test("patches can be reversed", () => {91 if (expectedInversePatches) {92 expect(applyPatches(testData.result, testData.inversePatches)).toEqual(93 base94 )95 }96 })97 })9899 return testData100}101102// Convenience functions for common use cases103runPatchTests.only = function(104 testName,105 base,106 producer,107 expectedPatches,108 expectedInversePatches,109 expectedResult110) {111 return runPatchTests(112 testName,113 base,114 producer,115 expectedPatches,116 expectedInversePatches,117 expectedResult,118 {only: true}119 )120}121122runPatchTests.skip = function(123 testName,124 base,125 producer,126 expectedPatches,127 expectedInversePatches,128 expectedResult129) {130 return runPatchTests(131 testName,132 base,133 producer,134 expectedPatches,135 expectedInversePatches,136 expectedResult,137 {skip: true}138 )139}140141describe("applyPatches", () => {142 it("mutates the base state when it is a draft", () => {143 produce({a: 1}, draft => {144 const result = applyPatches(draft, [145 {op: "replace", path: ["a"], value: 2}146 ])147 expect(result).toBe(draft)148 expect(draft.a).toBe(2)149 })150 })151 it("produces a copy of the base state when not a draft", () => {152 const base = {a: 1}153 const result = applyPatches(base, [{op: "replace", path: ["a"], value: 2}])154 expect(result).not.toBe(base)155 expect(result.a).toBe(2)156 expect(base.a).toBe(1)157 })158 it('throws when `op` is not "add", "replace", nor "remove"', () => {159 expect(() => {160 const patch = {op: "copy", from: [0], path: [1]}161 applyPatches([2], [patch])162 }).toThrowErrorMatchingSnapshot()163 })164 it("throws when `path` cannot be resolved", () => {165 // missing parent166 expect(() => {167 const patch = {op: "add", path: ["a", "b"], value: 1}168 applyPatches({}, [patch])169 }).toThrowErrorMatchingSnapshot()170171 // missing grand-parent172 expect(() => {173 const patch = {op: "add", path: ["a", "b", "c"], value: 1}174 applyPatches({}, [patch])175 }).toThrowErrorMatchingSnapshot()176 })177 it("applied patches cannot be modified", () => {178 // see also: https://github.com/immerjs/immer/issues/411179 const s0 = {180 items: [1]181 }182183 const [s1, p1] = produceWithPatches(s0, draft => {184 draft.items = []185 })186187 const replaceValueBefore = p1[0].value.slice()188189 const [s2, p2] = produceWithPatches(s1, draft => {190 draft.items.push(2)191 })192193 applyPatches(s0, [...p1, ...p2])194195 const replaceValueAfter = p1[0].value.slice()196197 expect(replaceValueAfter).toStrictEqual(replaceValueBefore)198 })199})200201// New macro-style test202runPatchTests(203 "simple assignment - 1",204 {x: 3},205 d => {206 d.x++207 },208 [{op: "replace", path: ["x"], value: 4}]209)210211// Original test (commented out for comparison)212// describe("simple assignment - 1", () => {213// runPatchTest(214// {x: 3},215// d => {216// d.x++217// },218// [{op: "replace", path: ["x"], value: 4}]219// )220// })221222// New macro-style tests223runPatchTests(224 "simple assignment - 2",225 {x: {y: 4}},226 d => {227 d.x.y++228 },229 [{op: "replace", path: ["x", "y"], value: 5}]230)231232runPatchTests(233 "simple assignment - 3",234 {x: [{y: 4}]},235 d => {236 d.x[0].y++237 },238 [{op: "replace", path: ["x", 0, "y"], value: 5}]239)240241runPatchTests(242 "simple assignment - 4",243 new Map([["x", {y: 4}]]),244 d => {245 d.get("x").y++246 },247 [{op: "replace", path: ["x", "y"], value: 5}],248 [{op: "replace", path: ["x", "y"], value: 4}]249)250251runPatchTests(252 "simple assignment - 5",253 {x: new Map([["y", 4]])},254 d => {255 d.x.set("y", 5)256 },257 [{op: "replace", path: ["x", "y"], value: 5}],258 [{op: "replace", path: ["x", "y"], value: 4}]259)260261runPatchTests(262 "simple assignment - 6",263 new Map([["x", 1]]),264 d => {265 // Map.prototype.set should return the Map itself266 const res = d.set("x", 2)267 res.set("y", 3)268 },269 [270 {op: "replace", path: ["x"], value: 2},271 {op: "add", path: ["y"], value: 3}272 ],273 [274 {op: "replace", path: ["x"], value: 1},275 {op: "remove", path: ["y"]}276 ]277)278279// Complex test with external variables - keep as individual describe280describe("simple assignment - 7", () => {281 const key1 = {prop: "val1"}282 const key2 = {prop: "val2"}283284 runPatchTests(285 "",286 {x: new Map([[key1, 4]])},287 d => {288 d.x.set(key1, 5)289 d.x.set(key2, 6)290 },291 [292 {op: "replace", path: ["x", key1], value: 5},293 {op: "add", path: ["x", key2], value: 6}294 ],295 [296 {op: "replace", path: ["x", key1], value: 4},297 {op: "remove", path: ["x", key2]}298 ]299 )300})301302runPatchTests(303 "simple assignment - 8",304 new Map([[0, new Map([[1, 4]])]]),305 d => {306 d.get(0).set(1, 5)307 d.get(0).set(2, 6)308 },309 [310 {op: "replace", path: [0, 1], value: 5},311 {op: "add", path: [0, 2], value: 6}312 ],313 [314 {op: "replace", path: [0, 1], value: 4},315 {op: "remove", path: [0, 2]}316 ]317)318319runPatchTests(320 "delete 1",321 {x: {y: 4}},322 d => {323 delete d.x324 },325 [{op: "remove", path: ["x"]}]326)327328runPatchTests(329 "delete 2",330 new Map([["x", 1]]),331 d => {332 d.delete("x")333 },334 [{op: "remove", path: ["x"]}],335 [{op: "add", path: ["x"], value: 1}]336)337338runPatchTests(339 "delete 3",340 {x: new Map([["y", 1]])},341 d => {342 d.x.delete("y")343 },344 [{op: "remove", path: ["x", "y"]}],345 [{op: "add", path: ["x", "y"], value: 1}]346)347348describe("delete 5", () => {349 const key1 = {prop: "val1"}350 const key2 = {prop: "val2"}351352 runPatchTests(353 "",354 {355 x: new Map([356 [key1, 1],357 [key2, 2]358 ])359 },360 d => {361 d.x.delete(key1)362 d.x.delete(key2)363 },364 [365 {op: "remove", path: ["x", key1]},366 {op: "remove", path: ["x", key2]}367 ],368 [369 {op: "add", path: ["x", key1], value: 1},370 {op: "add", path: ["x", key2], value: 2}371 ]372 )373})374375runPatchTests(376 "delete 6",377 new Set(["x", 1]),378 d => {379 d.delete("x")380 },381 [{op: "remove", path: [0], value: "x"}],382 [{op: "add", path: [0], value: "x"}]383)384385runPatchTests(386 "delete 7",387 {x: new Set(["y", 1])},388 d => {389 d.x.delete("y")390 },391 [{op: "remove", path: ["x", 0], value: "y"}],392 [{op: "add", path: ["x", 0], value: "y"}]393)394395describe("renaming properties", () => {396 runPatchTests(397 "nested object (no changes)",398 {a: {b: 1}},399 d => {400 d.x = d.a401 delete d.a402 },403 [404 {op: "add", path: ["x"], value: {b: 1}},405 {op: "remove", path: ["a"]}406 ]407 )408409 runPatchTests(410 "nested change in object",411 {412 a: {b: 1}413 },414 d => {415 d.a.b++416 },417 [{op: "replace", path: ["a", "b"], value: 2}],418 [{op: "replace", path: ["a", "b"], value: 1}]419 )420421 runPatchTests(422 "nested change in map",423 new Map([["a", new Map([["b", 1]])]]),424 d => {425 d.get("a").set("b", 2)426 },427 [{op: "replace", path: ["a", "b"], value: 2}],428 [{op: "replace", path: ["a", "b"], value: 1}]429 )430431 runPatchTests(432 "nested change in array",433 [[{b: 1}]],434 d => {435 d[0][0].b++436 },437 [{op: "replace", path: [0, 0, "b"], value: 2}],438 [{op: "replace", path: [0, 0, "b"], value: 1}]439 )440441 runPatchTests(442 "nested map (no changes)",443 new Map([["a", new Map([["b", 1]])]]),444 d => {445 d.set("x", d.get("a"))446 d.delete("a")447 },448 [449 {op: "add", path: ["x"], value: new Map([["b", 1]])},450 {op: "remove", path: ["a"]}451 ],452 [453 {op: "remove", path: ["x"]},454 {op: "add", path: ["a"], value: new Map([["b", 1]])}455 ]456 )457458 runPatchTests(459 "nested object (with changes)",460 {a: {b: 1, c: 1}},461 d => {462 let a = d.a463 a.b = 2 // change464 delete a.c // delete465 a.y = 2 // add466467 // rename468 d.x = a469 delete d.a470 },471 [472 {op: "add", path: ["x"], value: {b: 2, y: 2}},473 {op: "remove", path: ["a"]}474 ]475 )476477 runPatchTests(478 "nested map (with changes)",479 new Map([480 [481 "a",482 new Map([483 ["b", 1],484 ["c", 1]485 ])486 ]487 ]),488 d => {489 let a = d.get("a")490 a.set("b", 2) // change491 a.delete("c") // delete492 a.set("y", 2) // add493494 // rename495 d.set("x", a)496 d.delete("a")497 },498 [499 {500 op: "add",501 path: ["x"],502 value: new Map([503 ["b", 2],504 ["y", 2]505 ])506 },507 {op: "remove", path: ["a"]}508 ],509 [510 {op: "remove", path: ["x"]},511 {512 op: "add",513 path: ["a"],514 value: new Map([515 ["b", 1],516 ["c", 1]517 ])518 }519 ]520 )521522 runPatchTests(523 "deeply nested object (with changes)",524 {a: {b: {c: 1, d: 1}}},525 d => {526 let b = d.a.b527 b.c = 2 // change528 delete b.d // delete529 b.y = 2 // add530531 // rename532 d.a.x = b533 delete d.a.b534 },535 [536 {op: "add", path: ["a", "x"], value: {c: 2, y: 2}},537 {op: "remove", path: ["a", "b"]}538 ]539 )540541 runPatchTests(542 "deeply nested map (with changes)",543 new Map([544 [545 "a",546 new Map([547 [548 "b",549 new Map([550 ["c", 1],551 ["d", 1]552 ])553 ]554 ])555 ]556 ]),557 d => {558 let b = d.get("a").get("b")559 b.set("c", 2) // change560 b.delete("d") // delete561 b.set("y", 2) // add562563 // rename564 d.get("a").set("x", b)565 d.get("a").delete("b")566 },567 [568 {569 op: "add",570 path: ["a", "x"],571 value: new Map([572 ["c", 2],573 ["y", 2]574 ])575 },576 {op: "remove", path: ["a", "b"]}577 ],578 [579 {op: "remove", path: ["a", "x"]},580 {581 op: "add",582 path: ["a", "b"],583 value: new Map([584 ["c", 1],585 ["d", 1]586 ])587 }588 ]589 )590})591592runPatchTests(593 "minimum amount of changes",594 {x: 3, y: {a: 4}, z: 3},595 d => {596 d.y.a = 4597 d.y.b = 5598 Object.assign(d, {x: 4, y: {a: 2}})599 },600 [601 {op: "replace", path: ["x"], value: 4},602 {op: "replace", path: ["y"], value: {a: 2}}603 ]604)605606runPatchTests(607 "arrays - prepend",608 {x: [1, 2, 3]},609 d => {610 d.x.unshift(4)611 },612 [613 {op: "replace", path: ["x", 0], value: 4},614 {op: "replace", path: ["x", 1], value: 1},615 {op: "replace", path: ["x", 2], value: 2},616 {op: "add", path: ["x", 3], value: 3}617 ]618)619620runPatchTests(621 "arrays - multiple prepend",622 {x: [1, 2, 3]},623 d => {624 d.x.unshift(4)625 d.x.unshift(5)626 // 4,5,1,2,3627 },628 [629 {op: "replace", path: ["x", 0], value: 5},630 {op: "replace", path: ["x", 1], value: 4},631 {op: "replace", path: ["x", 2], value: 1},632 {op: "add", path: ["x", 3], value: 2},633 {op: "add", path: ["x", 4], value: 3}634 ]635)636637runPatchTests(638 "arrays - splice middle",639 {x: [1, 2, 3]},640 d => {641 d.x.splice(1, 1)642 },643 [644 {op: "replace", path: ["x", 1], value: 3},645 {op: "remove", path: ["x", 2]}646 ]647)648649runPatchTests(650 "arrays - multiple splice",651 [0, 1, 2, 3, 4, 5, 0],652 d => {653 d.splice(4, 2, 3)654 // [0,1,2,3,3,0]655 d.splice(1, 2, 3)656 // [0,3,3,3,0]657 expect(d.slice()).toEqual([0, 3, 3, 3, 0])658 },659 [660 {op: "replace", path: [1], value: 3},661 {op: "replace", path: [2], value: 3},662 {op: "replace", path: [4], value: 0},663 {op: "remove", path: [6]},664 {op: "remove", path: [5]}665 ]666)667668runPatchTests(669 "arrays - modify and shrink",670 {x: [1, 2, 3]},671 d => {672 d.x[0] = 4673 d.x.length = 2674 // [0, 2]675 },676 [677 {op: "replace", path: ["x", 0], value: 4},678 {op: "remove", path: ["x", 2]}679 ],680 [681 {op: "replace", path: ["x", 0], value: 1},682 {op: "add", path: ["x", 2], value: 3}683 ]684)685686runPatchTests(687 "arrays - prepend then splice middle",688 {x: [1, 2, 3]},689 d => {690 d.x.unshift(4)691 d.x.splice(2, 1)692 // 4, 1, 3693 },694 [695 {op: "replace", path: ["x", 0], value: 4},696 {op: "replace", path: ["x", 1], value: 1}697 ]698)699700runPatchTests(701 "arrays - splice middle then prepend",702 {x: [1, 2, 3]},703 d => {704 d.x.splice(1, 1)705 d.x.unshift(4)706 // [4, 1, 3]707 },708 [709 {op: "replace", path: ["x", 0], value: 4},710 {op: "replace", path: ["x", 1], value: 1}711 ]712)713714runPatchTests(715 "arrays - truncate",716 {x: [1, 2, 3]},717 d => {718 d.x.length -= 2719 },720 [721 {op: "remove", path: ["x", 2]},722 {op: "remove", path: ["x", 1]}723 ],724 [725 {op: "add", path: ["x", 1], value: 2},726 {op: "add", path: ["x", 2], value: 3}727 ]728)729730runPatchTests(731 "arrays - pop twice",732 {x: [1, 2, 3]},733 d => {734 d.x.pop()735 d.x.pop()736 },737 [738 {op: "remove", path: ["x", 2]},739 {op: "remove", path: ["x", 1]}740 ]741)742743runPatchTests(744 "arrays - push multiple",745 {x: [1, 2, 3]},746 d => {747 d.x.push(4, 5)748 },749 [750 {op: "add", path: ["x", 3], value: 4},751 {op: "add", path: ["x", 4], value: 5}752 ],753 [754 {op: "remove", path: ["x", 4]},755 {op: "remove", path: ["x", 3]}756 ]757)758759runPatchTests(760 "arrays - splice (expand)",761 {x: [1, 2, 3]},762 d => {763 d.x.splice(1, 1, 4, 5, 6) // [1,4,5,6,3]764 },765 [766 {op: "replace", path: ["x", 1], value: 4},767 {op: "replace", path: ["x", 2], value: 5},768 {op: "add", path: ["x", 3], value: 6},769 {op: "add", path: ["x", 4], value: 3}770 ],771 [772 {op: "replace", path: ["x", 1], value: 2},773 {op: "replace", path: ["x", 2], value: 3},774 {op: "remove", path: ["x", 4]},775 {op: "remove", path: ["x", 3]}776 ]777)778779runPatchTests(780 "arrays - splice (shrink)",781 {x: [1, 2, 3, 4, 5]},782 d => {783 d.x.splice(1, 3, 6) // [1, 6, 5]784 },785 [786 {op: "replace", path: ["x", 1], value: 6},787 {op: "replace", path: ["x", 2], value: 5},788 {op: "remove", path: ["x", 4]},789 {op: "remove", path: ["x", 3]}790 ],791 [792 {op: "replace", path: ["x", 1], value: 2},793 {op: "replace", path: ["x", 2], value: 3},794 {op: "add", path: ["x", 3], value: 4},795 {op: "add", path: ["x", 4], value: 5}796 ]797)798799runPatchTests(800 "arrays - delete",801 {802 x: [803 {a: 1, b: 2},804 {c: 3, d: 4}805 ]806 },807 d => {808 delete d.x[1].c809 },810 [{op: "remove", path: ["x", 1, "c"]}]811)812813describe("arrays - append", () => {814 test("appends to array when last part of path is '-'", () => {815 const state = {816 list: [1, 2, 3]817 }818 const patch = {819 op: "add",820 value: 4,821 path: ["list", "-"]822 }823 expect(applyPatches(state, [patch])).toEqual({824 list: [1, 2, 3, 4]825 })826 })827})828829runPatchTests(830 "sets - add - 1",831 new Set([1]),832 d => {833 d.add(2)834 },835 [{op: "add", path: [1], value: 2}],836 [{op: "remove", path: [1], value: 2}]837)838839runPatchTests(840 "sets - add, delete, add - 1",841 new Set([1]),842 d => {843 d.add(2)844 d.delete(2)845 d.add(2)846 },847 [{op: "add", path: [1], value: 2}],848 [{op: "remove", path: [1], value: 2}]849)850851runPatchTests(852 "sets - add, delete, add - 2",853 new Set([2, 1]),854 d => {855 d.add(2)856 d.delete(2)857 d.add(2)858 },859 [],860 []861)862863describe("sets - mutate - 1", () => {864 const findById = (set, id) => {865 for (const item of set) {866 if (item.id === id) return item867 }868 }869 runPatchTests(870 "",871 new Set([872 {id: 1, val: "We"},873 {id: 2, val: "will"}874 ]),875 d => {876 const obj1 = findById(d, 1)877 const obj2 = findById(d, 2)878 obj1.val = "rock"879 obj2.val = "you"880 },881 [882 {op: "remove", path: [0], value: {id: 1, val: "We"}},883 {op: "remove", path: [1], value: {id: 2, val: "will"}},884 {op: "add", path: [0], value: {id: 1, val: "rock"}},885 {op: "add", path: [1], value: {id: 2, val: "you"}}886 ],887 [888 {op: "remove", path: [1], value: {id: 2, val: "you"}},889 {op: "remove", path: [0], value: {id: 1, val: "rock"}},890 {op: "add", path: [1], value: {id: 2, val: "will"}},891 {op: "add", path: [0], value: {id: 1, val: "We"}}892 ]893 )894})895896// These patches were more optimal pre immer 7, but not always correct897runPatchTests(898 "arrays - splice should should result in remove op.",899 [1, 2],900 d => {901 d.splice(1, 1)902 },903 [{op: "remove", path: [1]}],904 [{op: "add", path: [1], value: 2}]905)906907// These patches were more optimal pre immer 7, but not always correct908runPatchTests(909 "arrays - NESTED splice should should result in remove op.",910 {a: {b: {c: [1, 2]}}},911 d => {912 d.a.b.c.splice(1, 1)913 },914 [{op: "remove", path: ["a", "b", "c", 1]}],915 [{op: "add", path: ["a", "b", "c", 1], value: 2}]916)917918runPatchTests("simple replacement", {x: 3}, _d => 4, [919 {op: "replace", path: [], value: 4}920])921922runPatchTests(923 "same value replacement - 1",924 {x: {y: 3}},925 d => {926 const a = d.x927 d.x = a928 },929 []930)931932runPatchTests(933 "same value replacement - 2",934 {x: {y: 3}},935 d => {936 const a = d.x937 d.x = 4938 d.x = a939 },940 []941)942943runPatchTests(944 "same value replacement - 3",945 {x: 3},946 d => {947 d.x = 3948 },949 []950)951952runPatchTests(953 "same value replacement - 4",954 {x: 3},955 d => {956 d.x = 4957 d.x = 3958 },959 []960)961962runPatchTests(963 "same value replacement - 5",964 new Map([["x", 3]]),965 d => {966 d.set("x", 4)967 d.set("x", 3)968 },969 [],970 []971)972973runPatchTests(974 "same value replacement - 6",975 new Set(["x", 3]),976 d => {977 d.delete("x")978 d.add("x")979 },980 [],981 []982)983984runPatchTests(985 "simple delete",986 {x: 2},987 d => {988 delete d.x989 },990 [991 {992 op: "remove",993 path: ["x"]994 }995 ]996)997998describe("patch compressions yields correct results", () => {999 let p1 = [1000 {1001 op: "add",1002 path: ["x"],1003 value: {1004 test: true1005 }1006 }1007 ]1008 let p2 = [1009 {1010 op: "remove",1011 path: ["x"]1012 }1013 ]10141015 runPatchTests(1016 "add only",1017 {},1018 d => {1019 d.x = {test: true}1020 },1021 p11022 )10231024 runPatchTests(1025 "delete only",1026 {x: {test: true}},1027 d => {1028 delete d.x1029 },1030 p21031 )1032 const testData = runPatchTests(1033 "add and delete together cancel",1034 {},1035 d => {1036 applyPatches(d, [...p1, ...p2])1037 },1038 []1039 )10401041 expect(testData.result).toEqual({})1042})10431044runPatchTests(1045 "change then delete property",1046 {1047 x: 11048 },1049 d => {1050 d.x = 21051 delete d.x1052 },1053 [1054 {1055 op: "remove",1056 path: ["x"]1057 }1058 ]1059)10601061test("replaying patches with interweaved replacements should work correctly", () => {1062 const patches = []1063 const s0 = {x: 1}10641065 const s1 = produce(1066 s0,1067 draft => {1068 draft.x = 21069 },1070 p => {1071 patches.push(...p)1072 }1073 )10741075 const s2 = produce(1076 s1,1077 draft => {1078 return {x: 0}1079 },1080 p => {1081 patches.push(...p)1082 }1083 )10841085 const s3 = produce(1086 s2,1087 draft => {1088 draft.x--1089 },1090 p => {1091 patches.push(...p)1092 }1093 )10941095 expect(s3).toEqual({x: -1}) // correct result1096 expect(applyPatches(s0, patches)).toEqual({x: -1}) // correct replay10971098 // manual replay on a draft should also be correct1099 expect(1100 produce(s0, draft => {1101 return applyPatches(draft, patches)1102 })1103 ).toEqual({x: -1})1104})11051106describe("#468", () => {1107 function run() {1108 const item = {id: 1}1109 const state = [item]1110 const [nextState, patches] = produceWithPatches(state, draft => {1111 draft[0].id = 21112 draft[1] = item1113 })11141115 expect(nextState).toEqual([{id: 2}, {id: 1}])1116 expect(patches).toEqual([1117 {1118 op: "replace",1119 path: [0, "id"],1120 value: 21121 },1122 {1123 op: "add",1124 path: [1],1125 value: {1126 id: 11127 }1128 }1129 ])11301131 const final = applyPatches(state, patches)1132 expect(final).toEqual(nextState)1133 }11341135 test("proxy", () => {1136 run()1137 })1138})11391140test("#521", () => {1141 const state = new Map()11421143 const [nextState, patches] = produceWithPatches(state, draft => {1144 draft.set("hello", new Set(["world"]))1145 })11461147 let patchedState = applyPatches(state, patches)1148 expect(patchedState).toEqual(nextState)11491150 const [nextStateV2, patchesV2] = produceWithPatches(nextState, draft => {1151 draft.get("hello").add("immer")1152 })11531154 expect(applyPatches(nextState, patchesV2)).toEqual(1155 new Map([["hello", new Set(["world", "immer"])]])1156 )1157})11581159test("#559 patches works in a nested reducer with proxies", () => {1160 const state = {1161 x: 1,1162 sub: {1163 y: [{a: 0}, {a: 1}]1164 }1165 }11661167 const changes = []1168 const inverseChanges = []11691170 const newState = produce(state, draft => {1171 draft.sub = produce(1172 draft.sub,1173 draft => {1174 draft.y.pop()1175 },1176 (patches, inversePatches) => {1177 expect(isDraft(inversePatches[0].value)).toBeFalsy()1178 expect(inversePatches[0].value).toMatchObject({a: 1})1179 changes.push(...patches)1180 inverseChanges.push(...inversePatches)1181 }1182 )1183 })11841185 const reversedSubState = applyPatches(newState.sub, inverseChanges)11861187 expect(reversedSubState).toMatchObject(state.sub)1188})11891190describe("#588", () => {1191 const reference = {value: {num: 53}}11921193 class Base {1194 [immerable] = true1195 get nested() {1196 return reference.value1197 }1198 set nested(value) {}1199 }12001201 let base = new Base()12021203 runPatchTests(1204 "",1205 base,1206 vdraft => {1207 reference.value = vdraft1208 produce(base, bdraft => {1209 bdraft.nested.num = 421210 })1211 },1212 [{op: "add", path: ["num"], value: 42}]1213 )1214})12151216test("#676 patching Date objects", () => {1217 class Test {1218 constructor() {1219 this.test = true1220 }1221 perform() {1222 return "tested!"1223 }1224 }12251226 const [nextState, patches] = produceWithPatches({}, function(draft) {1227 draft.date = new Date("2020-11-10T08:08:08.003Z")1228 draft.test = new Test()1229 })12301231 expect(nextState.date.toJSON()).toMatchInlineSnapshot(1232 `"2020-11-10T08:08:08.003Z"`1233 )1234 expect(nextState.test.perform()).toBe("tested!")12351236 const rebuilt = applyPatches({}, patches)1237 expect(rebuilt.date).toBeInstanceOf(Date)1238 expect(rebuilt.date.toJSON()).toMatchInlineSnapshot(1239 `"2020-11-10T08:08:08.003Z"`1240 )1241 expect(rebuilt.date).toEqual(new Date("2020-11-10T08:08:08.003Z"))1242})12431244test("do not allow __proto__ polution - 738", () => {1245 const obj = {}12461247 // @ts-ignore1248 expect(obj.polluted).toBe(undefined)1249 expect(() => {1250 applyPatches({}, [1251 {op: "add", path: ["__proto__", "polluted"], value: "yes"}1252 ])1253 }).toThrow(1254 isProd1255 ? "19"1256 : "Patching reserved attributes like __proto__, prototype and constructor is not allowed"1257 )1258 // @ts-ignore1259 expect(obj.polluted).toBe(undefined)1260})12611262test("do not allow __proto__ polution using arrays - 738", () => {1263 const obj = {}1264 const ar = []12651266 // @ts-ignore1267 expect(obj.polluted).toBe(undefined)1268 // @ts-ignore1269 expect(ar.polluted).toBe(undefined)1270 expect(() => {1271 applyPatches(1272 [],1273 [{op: "add", path: ["__proto__", "polluted"], value: "yes"}]1274 )1275 }).toThrow(1276 isProd1277 ? "19"1278 : "Patching reserved attributes like __proto__, prototype and constructor is not allowed"1279 )1280 // @ts-ignore1281 expect(obj.polluted).toBe(undefined)1282 // @ts-ignore1283 expect(ar.polluted).toBe(undefined)1284})12851286test("do not allow prototype polution - 738", () => {1287 const obj = {}12881289 // @ts-ignore1290 expect(obj.polluted).toBe(undefined)1291 expect(() => {1292 applyPatches(Object, [1293 {op: "add", path: ["prototype", "polluted"], value: "yes"}1294 ])1295 }).toThrow(1296 isProd1297 ? "19"1298 : "Patching reserved attributes like __proto__, prototype and constructor is not allowed"1299 )1300 // @ts-ignore1301 expect(obj.polluted).toBe(undefined)1302})13031304test("do not allow constructor polution - 738", () => {1305 const obj = {}13061307 // @ts-ignore1308 expect(obj.polluted).toBe(undefined)1309 const t = {}1310 applyPatches(t, [{op: "replace", path: ["constructor"], value: "yes"}])1311 expect(typeof t.constructor).toBe("function")1312 // @ts-ignore1313 expect(Object.polluted).toBe(undefined)1314})13151316test("do not allow constructor.prototype polution - 738", () => {1317 const obj = {}13181319 // @ts-ignore1320 expect(obj.polluted).toBe(undefined)1321 expect(() => {1322 applyPatches({}, [1323 {op: "add", path: ["constructor", "prototype", "polluted"], value: "yes"}1324 ])1325 }).toThrow(1326 isProd1327 ? "19"1328 : "Patching reserved attributes like __proto__, prototype and constructor is not allowed"1329 )1330 // @ts-ignore1331 expect(Object.polluted).toBe(undefined)1332})13331334test("maps can store __proto__, prototype and constructor props", () => {1335 const obj = {}1336 const map = new Map()1337 map.set("__proto__", {})1338 map.set("constructor", {})1339 map.set("prototype", {})1340 const newMap = applyPatches(map, [1341 {op: "add", path: ["__proto__", "polluted"], value: "yes"},1342 {op: "add", path: ["constructor", "polluted"], value: "yes"},1343 {op: "add", path: ["prototype", "polluted"], value: "yes"}1344 ])1345 expect(newMap.get("__proto__").polluted).toBe("yes")1346 expect(newMap.get("constructor").polluted).toBe("yes")1347 expect(newMap.get("prototype").polluted).toBe("yes")1348 expect(obj.polluted).toBe(undefined)1349})13501351test("CVE-2020-28477 (https://snyk.io/vuln/SNYK-JS-IMMER-1019369) follow up", () => {1352 const obj = {}13531354 // @ts-ignore1355 expect(obj.polluted).toBe(undefined)1356 expect(() => {1357 applyPatches({}, [1358 {op: "add", path: [["__proto__"], "polluted"], value: "yes"}1359 ])1360 }).toThrow(1361 isProd1362 ? "19"1363 : "Patching reserved attributes like __proto__, prototype and constructor is not allowed"1364 )1365 // @ts-ignore1366 expect(obj.polluted).toBe(undefined)1367})13681369test("#648 assigning object to itself should not change patches", () => {1370 const input = {1371 obj: {1372 value: 2001373 }1374 }13751376 const [nextState, patches] = produceWithPatches(input, draft => {1377 draft.obj.value = 11378 draft.obj = draft.obj1379 })13801381 expect(patches).toEqual([1382 {1383 op: "replace",1384 path: ["obj", "value"],1385 value: 11386 }1387 ])1388})13891390test("#791 patch for nothing is stored as undefined", () => {1391 const [newState, patches] = produceWithPatches({abc: 123}, draft => nothing)1392 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])13931394 expect(applyPatches({}, patches)).toEqual(undefined)1395})13961397test("#876 Ensure empty patch set for atomic set+delete on Map", () => {1398 {1399 const [newState, patches] = produceWithPatches(1400 new Map([["foo", "baz"]]),1401 draft => {1402 draft.set("foo", "bar")1403 draft.delete("foo")1404 }1405 )1406 expect(patches).toEqual([{op: "remove", path: ["foo"]}])1407 }14081409 {1410 const [newState, patches] = produceWithPatches(new Map(), draft => {1411 draft.set("foo", "bar")1412 draft.delete("foo")1413 })1414 expect(patches).toEqual([])1415 }1416})14171418test("#888 patch to a primitive produces the primitive", () => {1419 {1420 const [res, patches] = produceWithPatches({abc: 123}, draft => nothing)1421 expect(res).toEqual(undefined)1422 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1423 }1424 {1425 const [res, patches] = produceWithPatches(null, draft => nothing)1426 expect(res).toEqual(undefined)1427 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1428 }1429 {1430 const [res, patches] = produceWithPatches(0, draft => nothing)1431 expect(res).toEqual(undefined)1432 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1433 }1434 {1435 const [res, patches] = produceWithPatches("foobar", draft => nothing)1436 expect(res).toEqual(undefined)1437 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1438 }1439 {1440 const [res, patches] = produceWithPatches([], draft => nothing)1441 expect(res).toEqual(undefined)1442 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1443 }1444 {1445 const [res, patches] = produceWithPatches(false, draft => nothing)1446 expect(res).toEqual(undefined)1447 expect(patches).toEqual([{op: "replace", path: [], value: undefined}])1448 }1449 {1450 const [res, patches] = produceWithPatches(1451 "foobar",1452 draft => "something else"1453 )1454 expect(res).toEqual("something else")1455 expect(patches).toEqual([1456 {op: "replace", path: [], value: "something else"}1457 ])1458 }1459 {1460 const [res, patches] = produceWithPatches(false, draft => true)1461 expect(res).toEqual(true)1462 expect(patches).toEqual([{op: "replace", path: [], value: true}])1463 }1464})14651466runPatchTests(1467 "#879 delete item from array",1468 [1, 2, 3],1469 draft => {1470 delete draft[1]1471 },1472 [{op: "replace", path: [1], value: undefined}],1473 [{op: "replace", path: [1], value: 2}],1474 [1, undefined, 3]1475)14761477runPatchTests(1478 "#879 delete item from array - 2",1479 [1, 2, 3],1480 draft => {1481 delete draft[2]1482 },1483 [{op: "replace", path: [2], value: undefined}],1484 [{op: "replace", path: [2], value: 3}],1485 [1, 2, undefined]1486)14871488test("#897 appendPatch", () => {1489 const state0 = {a: []}1490 const state1 = applyPatches(state0, [{op: "add", path: ["a", "-"], value: 1}])1491 const state2 = applyPatches(state1, [{op: "add", path: ["a", "-"], value: 2}])1492 const state3 = applyPatches(state2, [{op: "add", path: ["a", "-"], value: 3}])1493 expect(state3).toEqual({1494 a: [1, 2, 3]1495 })1496})14971498// Bug reproduction: Patch path truncation in production build1499// This bug is caused by the "key_" in state check failing after minification1500// The patch path should include the full path for nested array modifications1501describe("RTK-5159: Patch path truncation bug", () => {1502 test("patch paths should include full path for nested array modifications", () => {1503 const baseState = {1504 lists: [{items: [{id: 1}]}]1505 }15061507 const [result, patches] = produceWithPatches(baseState, draft => {1508 draft.lists[0].items.push({id: 2})1509 })15101511 // The patch path should be ["lists", 0, "items", 1], not just [1]1512 expect(patches[0].path).toEqual(["lists", 0, "items", 1])1513 expect(patches).toEqual([1514 {op: "add", path: ["lists", 0, "items", 1], value: {id: 2}}1515 ])1516 })15171518 test("patch paths correct for deeply nested object in array", () => {1519 const baseState = {1520 queries: {1521 queryKey: {1522 data: {1523 items: [{name: "item1"}]1524 }1525 }1526 }1527 }15281529 const [result, patches] = produceWithPatches(baseState, draft => {1530 draft.queries.queryKey.data.items.push({name: "item2"})1531 })15321533 expect(patches[0].path).toEqual(["queries", "queryKey", "data", "items", 1])1534 })1535})