From 0e8764c21a9c0cf2b907f2cb6d9bf7335d5f5728 Mon Sep 17 00:00:00 2001 From: Aryan Date: Thu, 12 Nov 2026 01:20:08 +0530 Subject: [PATCH] fix: preserve symbol keys in intermediate patch paths --- __tests__/patch-symbol-paths.js | 51 +++++++++++++++++++++++++++++++++ src/plugins/patches.ts | 6 +++- 2 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 __tests__/patch-symbol-paths.js diff --git a/__tests__/patch-symbol-paths.js b/__tests__/patch-symbol-paths.js new file mode 100644 index 00000000..65f7ce45 --- /dev/null +++ b/__tests__/patch-symbol-paths.js @@ -0,0 +1,51 @@ +import {Immer, enablePatches, immerable} from "../src/immer" + +enablePatches() + +describe.each([false, true])( + "symbol patch paths (autoFreeze: %s)", + autoFreeze => { + it.each(["object", "class"])( + "replays and reverses nested changes through a symbol on an %s", + kind => { + const key = Symbol("constructor") + class Box { + [immerable] = true + constructor() { + Object.defineProperty(this, key, {value: {count: 0}}) + } + } + const api = new Immer({autoFreeze, useStrictShallowCopy: true}) + const base = kind === "class" ? new Box() : {[key]: {count: 0}} + const [next, patches, inverse] = api.produceWithPatches(base, draft => { + draft[key].count = 1 + }) + + expect(patches).toEqual([ + {op: "replace", path: [key, "count"], value: 1} + ]) + const replay = api.applyPatches(base, patches) + expect(replay[key].count).toBe(next[key].count) + expect(api.applyPatches(replay, inverse)[key].count).toBe(0) + expect(base[key].count).toBe(0) + expect(Object.getPrototypeOf(replay)).toBe(Object.getPrototypeOf(base)) + } + ) + + it("preserves distinct symbols with the same description in a nested path", () => { + const first = Symbol("child") + const second = Symbol("child") + const api = new Immer({autoFreeze}) + const base = {nested: {[first]: {count: 0}, [second]: {count: 10}}} + const [next, patches, inverse] = api.produceWithPatches(base, draft => { + draft.nested[first].count = 1 + }) + + const replay = api.applyPatches(base, patches) + expect(replay.nested[first].count).toBe(next.nested[first].count) + expect(replay.nested[second]).toBe(base.nested[second]) + expect(api.applyPatches(replay, inverse).nested[first].count).toBe(0) + expect(base.nested[first].count).toBe(0) + }) + } +) diff --git a/src/plugins/patches.ts b/src/plugins/patches.ts index e2eaea94..9fe077d2 100644 --- a/src/plugins/patches.ts +++ b/src/plugins/patches.ts @@ -342,7 +342,11 @@ export function enablePatches() { for (let i = 0; i < path.length - 1; i++) { const parentType = getArchtype(base) let p = path[i] - if (typeof p !== "string" && typeof p !== "number") { + if ( + typeof p !== "string" && + typeof p !== "number" && + typeof p !== "symbol" + ) { p = "" + p }