Skip to content
Myr

fix: Fix broken array patching and ensure all values in draft Maps/Sets are finalized (#1201)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Remove hardcoded key_ field name check * Only build for `test:build` command * Rewrite Vitest prod build config to ensure prod build is used * Add tests for prod patch paths * Ensure plain values in draft maps/sets get finalized * Work around an error with prod tests Somehow was seeing an error with `each` "not existing" on startup when running the prod build tests * Fix test run

authored by Mark Erikson · committed by GitHub · parent d626513 · Browse files · 8 files+228 added−29 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

8 files+228 added−29 removed

  • tests:+154 added−0 removed
  • other:+74 added−29 removed

8 files+228 added−29 removed

modified:__tests__/map-set.js+115 added
365 unmodified lines
366 expect(Array.from(newSet)).toEqual([objs[0], objs[1]])367 })368 })369}370371// Bug reproduction: DraftSet leakage when placed in new object and set into Map372// This bug occurs when a plain object containing a draft Set is set into a DraftMap373describe("RTK-5159: DraftSet leakage in Map", () => {374 const {produce} = new Immer({autoFreeze: true})375376 test("DraftSet should not leak when placed in new object and set into Map", () => {377 const baseState = {378 map: new Map([["key1", {users: new Set()}]])379 }380381 // First produce: add a user382 const state1 = produce(baseState, draft => {383 const entry = draft.map.get("key1")384 entry.users.add({name: "user1"})385 })386387 // Second produce: create new object with existing Set and set into Map388 const state2 = produce(state1, draft => {389 const existingUsers = draft.map.get("key1")?.users ?? new Set()390 const newEntry = {users: existingUsers} // New plain object with existing draft Set391 draft.map.set("key1", newEntry)392 newEntry.users.add({name: "user2"})393 })394395 // Should not throw "Cannot use a proxy that has been revoked"396 const users = state2.map.get("key1").users397398 expect(users).toBeInstanceOf(Set)399 expect([...users].map(u => u.name)).toEqual(["user1", "user2"])400 })401402 test("DraftSet in new object set into Map should finalize correctly", () => {403 const baseState = {404 map: new Map([["key1", {items: new Set([1, 2, 3])}]])405 }406407 const result = produce(baseState, draft => {408 const existingItems = draft.map.get("key1").items409 // Create a new plain object containing the draft Set410 const newEntry = {items: existingItems, extra: "data"}411 draft.map.set("key1", newEntry)412 newEntry.items.add(4)413 })414415 // Verify the result is properly finalized (not a draft/proxy)416 const items = result.map.get("key1").items417 expect(items).toBeInstanceOf(Set)418 expect([...items]).toEqual([1, 2, 3, 4])419 expect(result.map.get("key1").extra).toBe("data")420 })421422 // Test for DraftSet.add() with non-draft object containing nested draft423 // This covers the handleCrossReference() call in DraftSet.add()424 test("DraftSet.add() should handle non-draft object containing nested draft", () => {425 const baseState = {426 items: [{id: 1, name: "item1"}],427 itemSet: new Set()428 }429430 const result = produce(baseState, draft => {431 // Get a draft of an existing item432 const draftItem = draft.items[0]433 // Create a new plain object that contains the draft434 const wrapper = {item: draftItem, extra: "wrapper data"}435 // Add the non-draft wrapper (containing a draft) to the Set436 draft.itemSet.add(wrapper)437 // Modify the draft item after adding438 draftItem.name = "modified"439 })440441 // The wrapper should be finalized correctly442 const addedItems = [...result.itemSet]443 expect(addedItems).toHaveLength(1)444 expect(addedItems[0].item.id).toBe(1)445 expect(addedItems[0].item.name).toBe("modified")446 expect(addedItems[0].extra).toBe("wrapper data")447 // Verify it's not a proxy448 expect(() => JSON.stringify(result)).not.toThrow()449 })450451 test("DraftSet.add() should handle deeply nested drafts in plain objects", () => {452 const baseState = {453 nested: {454 deep: {455 value: "original"456 }457 },458 mySet: new Set()459 }460461 const result = produce(baseState, draft => {462 // Get a draft of a deeply nested object463 const deepDraft = draft.nested.deep464 // Create a plain object hierarchy containing the draft465 const wrapper = {466 level1: {467 level2: {468 draftRef: deepDraft469 }470 }471 }472 // Add to Set473 draft.mySet.add(wrapper)474 // Modify the draft475 deepDraft.value = "modified"476 })477478 const items = [...result.mySet]479 expect(items).toHaveLength(1)480 expect(items[0].level1.level2.draftRef.value).toBe("modified")481 // Should not throw when accessing482 expect(() => JSON.stringify(result)).not.toThrow()483 })484})
modified:__tests__/patch.js+39 added
1492 unmodified lines
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})
modified:src/core/finalize.ts+23 added-17 removed
238 unmodified lines
239 // Handle non-draft objects that might contain drafts240 target.callbacks_.push(function nestedDraftCleanup() {241 const targetCopy = latest(target)242243 if (get(targetCopy, key, target.type_) === value) {244 // Process the value to replace any nested drafts245 // finalizeAssigned(target, key, target.scope_)246247 if (248 scope_.drafts_.length > 1 &&249 ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??250 false) === true &&251 target.copy_252 ) {253 // This might be a non-draft value that has drafts254 // inside. We do need to recurse here to handle those.255 handleValue(256 get(target.copy_, key, target.type_),257 scope_.handledSet_,258 scope_259 )243 // For Sets, check if value is still in the set244 if (target.type_ === ArchType.Set) {245 if (targetCopy.has(value)) {246 // Process the value to replace any nested drafts247 handleValue(value, scope_.handledSet_, scope_)248 }249 } else {250 // Maps/objects251 if (get(targetCopy, key, target.type_) === value) {252 if (253 scope_.drafts_.length > 1 &&254 ((target as Exclude<ImmerState, SetState>).assigned_!.get(key) ??255 false) === true &&256 target.copy_257 ) {258 // This might be a non-draft value that has drafts259 // inside. We do need to recurse here to handle those.260 handleValue(261 get(target.copy_, key, target.type_),262 scope_.handledSet_,263 scope_264 )265 }266 }267 }268 })269 }270}
48 unmodified lines
modified:src/core/proxy.ts+5 added-4 removed
1import {2 each,2 has,3 is,4 isDraftable,5 shallowCopy,
9 unmodified lines
15 DRAFT_STATE,16 die,17 createProxy,18 ArchType,20 ImmerScope,19 handleCrossReference,20 WRITABLE,21 CONFIGURABLE,22 ENUMERABLE,
230 unmodified lines
253 * Array drafts254 */255256const arrayTraps: ProxyHandler<[ProxyArrayState]> = {}259each(objectTraps, (key, fn) => {257// Use `for..in` instead of `each` to work around a weird258// prod test suite issue259for (let key in objectTraps) {260 let fn = objectTraps[key as keyof typeof objectTraps] as Function261 // @ts-ignore262 arrayTraps[key] = function() {263 const args = arguments264 args[0] = args[0][0]265 return fn.apply(this, args)266 }266})267}268arrayTraps.deleteProperty = function(state, prop) {269 if (process.env.NODE_ENV !== "production" && isNaN(parseInt(prop as any)))270 die(13)271 // @ts-ignore
65 unmodified lines
modified:src/plugins/mapset.ts+4 added-1 removed
14 unmodified lines
15 die,16 ArchType,17 each,18 getValue,19 PluginMapSet19 PluginMapSet,20 handleCrossReference21} from "../internal"2223export function enableMapSet() {24 class DraftMap extends Map {
33 unmodified lines
58 markChanged(state)59 state.assigned_!.set(key, true)60 state.copy_!.set(key, value)61 state.assigned_!.set(key, true)62 handleCrossReference(state, key, value)63 }64 return this65 }66
156 unmodified lines
223 if (!this.has(value)) {224 prepareSetCopy(state)225 markChanged(state)226 state.copy_!.add(value)227 handleCrossReference(state, value, value)228 }229 return this230 }231
101 unmodified lines
modified:src/plugins/patches.ts+1 added-1 removed
47 unmodified lines
48 }4950 function getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {51 // Step 1: Check if state has a stored key52 if ("key_" in state && state.key_ !== undefined) {52 if (state.key_ !== undefined) {53 // Step 2: Validate the key is still valid in parent5455 const parentCopy = state.parent_!.copy_ ?? state.parent_!.base_56 const proxyDraft = getProxyDraft(get(parentCopy, state.key_!))
375 unmodified lines
modified:package.json+1 added-2 removed
modified:vitest.config.build.ts+40 added-4 removed