diff --git a/__tests__/patch-set-replay.js b/__tests__/patch-set-replay.js new file mode 100644 index 00000000..7b908318 --- /dev/null +++ b/__tests__/patch-set-replay.js @@ -0,0 +1,546 @@ +import {Immer, enableMapSet, enablePatches, immerable} from "../src/immer" + +enableMapSet() +enablePatches() + +describe.each([false, true])( + "Set patch replay and removal (autoFreeze: %s)", + autoFreeze => { + it("removes cloned object members in concatenated and sequential Set patches (#1367)", () => { + const api = new Immer({autoFreeze}) + const base = {slot: null} + + const [inserted, first, firstInverse] = api.produceWithPatches( + base, + draft => { + draft.slot = new Set([{n: 0}]) + } + ) + const [next, second, secondInverse] = api.produceWithPatches( + inserted, + draft => { + draft.slot.clear() + } + ) + + const combinedReplay = api.applyPatches(base, [...first, ...second]) + expect(next.slot.size).toBe(0) + expect(combinedReplay).toEqual(next) + expect(combinedReplay.slot.size).toBe(0) + // Original patch value must not be mutated + expect(first[0].value.size).toBe(1) + + // Sequential applyPatches calls + const step1 = api.applyPatches(base, first) + const step2 = api.applyPatches(step1, second) + expect(step1.slot.size).toBe(1) + expect(step2.slot.size).toBe(0) + expect(step2).toEqual(next) + + // Reversing back from replayed state + const undoneStep1 = api.applyPatches(step2, secondInverse) + expect(undoneStep1).toEqual(inserted) + const undoneBase = api.applyPatches(undoneStep1, firstInverse) + expect(undoneBase).toEqual(base) + }) + + it("reverses an added object member across separate applyPatches calls", () => { + const api = new Immer({autoFreeze}) + const base = new Set() + + const [next, patches, inverse] = api.produceWithPatches(base, draft => { + draft.add({n: 0}) + }) + + const replay = api.applyPatches(base, patches) + expect(replay).toEqual(next) + + const undone = api.applyPatches(replay, inverse) + expect(undone.size).toBe(0) + expect(undone).toEqual(base) + expect(replay.size).toBe(1) + + // Combined add + inverse remove in one call + const canceled = api.applyPatches(base, [...patches, ...inverse]) + expect(canceled.size).toBe(0) + + // Applying inverse inside a produce draft + const undoneInDraft = api.produce(replay, draft => { + api.applyPatches(draft, inverse) + }) + expect(undoneInDraft.size).toBe(0) + }) + + it("preserves reference identity for structurally equal objects in a Set", () => { + const api = new Immer({autoFreeze}) + const existing = {n: 0} + const added = {n: 0} + const unrelated = {n: 0} + const base = new Set([existing]) + + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.add(added) + }) + const [s2, p2] = api.produceWithPatches(s1, draft => { + draft.delete(added) + }) + + // Removing added must remove only the cloned added entry, keeping existing by reference + const combined = api.applyPatches(base, [...p1, ...p2]) + expect(combined.size).toBe(1) + expect(combined.has(existing)).toBe(true) + + const step1 = api.applyPatches(base, p1) + const step2 = api.applyPatches(step1, p2) + expect(step2.size).toBe(1) + expect(step2.has(existing)).toBe(true) + expect(step2).toEqual(s2) + + // Attempting to remove a structurally equal but unrelated object must be a no-op + const unchanged = api.applyPatches(base, [ + {op: "remove", path: [0], value: unrelated} + ]) + expect(unchanged).toBe(base) + expect(unchanged.size).toBe(1) + expect(unchanged.has(existing)).toBe(true) + }) + + it("distinguishes two structurally equal objects added via patches", () => { + const api = new Immer({autoFreeze}) + const a = {n: 0} + const b = {n: 0} + const base = new Set() + + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.add(a) + draft.add(b) + }) + const [s2, p2] = api.produceWithPatches(s1, draft => { + draft.delete(b) + }) + const [s3, p3] = api.produceWithPatches(s2, draft => { + draft.delete(a) + }) + + const r1 = api.applyPatches(base, p1) + expect(r1.size).toBe(2) + + const r2 = api.applyPatches(r1, p2) + expect(r2.size).toBe(1) + + const r3 = api.applyPatches(r2, p3) + expect(r3.size).toBe(0) + expect(r3).toEqual(s3) + }) + + it("handles repeated in-place mutations of Set object members and full undo", () => { + const api = new Immer({autoFreeze}) + const base = {slot: null} + + const [s1, p1, inv1] = api.produceWithPatches(base, draft => { + draft.slot = new Set([{n: 0}]) + }) + const [s2, p2, inv2] = api.produceWithPatches(s1, draft => { + for (const item of draft.slot) item.n = 1 + }) + const [s3, p3, inv3] = api.produceWithPatches(s2, draft => { + for (const item of draft.slot) item.n = 2 + }) + + const replayedAll = api.applyPatches(base, [...p1, ...p2, ...p3]) + expect(replayedAll.slot.size).toBe(1) + expect([...replayedAll.slot]).toEqual([{n: 2}]) + expect(replayedAll).toEqual(s3) + + const undoneAll = api.applyPatches(replayedAll, [ + ...inv3, + ...inv2, + ...inv1 + ]) + expect(undoneAll).toEqual(base) + + // Step by step + const r1 = api.applyPatches(base, p1) + const r2 = api.applyPatches(r1, p2) + const r3 = api.applyPatches(r2, p3) + expect(r3).toEqual(s3) + const u2 = api.applyPatches(r3, inv3) + expect(u2).toEqual(s2) + const u1 = api.applyPatches(u2, inv2) + expect(u1).toEqual(s1) + const u0 = api.applyPatches(u1, inv1) + expect(u0).toEqual(base) + }) + + it("supports reusing patches across independent base states without sharing clones", () => { + const api = new Immer({autoFreeze}) + const baseA = {tag: "A", slot: null} + const baseB = {tag: "B", slot: null} + + const [s1, p1] = api.produceWithPatches(baseA, draft => { + draft.slot = new Set([{n: 1}]) + }) + const [, p2] = api.produceWithPatches(s1, draft => { + draft.slot.clear() + }) + + const rA1 = api.applyPatches(baseA, p1) + const rB1 = api.applyPatches(baseB, p1) + expect([...rA1.slot][0]).not.toBe([...rB1.slot][0]) + expect([...rA1.slot][0]).not.toBe([...p1[0].value][0]) + + expect(api.applyPatches(rA1, p2).slot.size).toBe(0) + expect(api.applyPatches(rB1, p2).slot.size).toBe(0) + expect(api.applyPatches(baseA, [...p1, ...p2]).slot.size).toBe(0) + expect(api.applyPatches(baseB, [...p1, ...p2]).slot.size).toBe(0) + expect(p1[0].value.size).toBe(1) + }) + + it("handles interleaved add and remove of the same object in a single applyPatches call", () => { + const api = new Immer({autoFreeze}) + const item = {n: 1} + const base = new Set() + + const patches = [ + {op: "add", path: [0], value: item}, + {op: "remove", path: [0], value: item}, + {op: "add", path: [0], value: item}, + {op: "remove", path: [0], value: item} + ] + + const result = api.applyPatches(base, patches) + expect(result.size).toBe(0) + }) + + it("handles nested Sets, Maps, Arrays, immerable classes, null-prototype objects, and primitives", () => { + class Item { + [immerable] = true + constructor(v) { + this.v = v + } + } + + const api = new Immer({autoFreeze}) + const nestedSet = new Set([{nested: true}]) + const nestedMap = new Map([["a", {x: 1}]]) + const nestedArray = [{arr: 1}] + const classItem = new Item(42) + + const base = {root: null} + const [s1, p1, inv1] = api.produceWithPatches(base, draft => { + draft.root = { + items: new Set([ + nestedSet, + nestedMap, + nestedArray, + classItem, + NaN, + "str", + null, + undefined + ]) + } + }) + const [s2, p2, inv2] = api.produceWithPatches(s1, draft => { + draft.root.items.clear() + }) + + const combined = api.applyPatches(base, [...p1, ...p2]) + expect(combined.root.items.size).toBe(0) + + const r1 = api.applyPatches(base, p1) + const r2 = api.applyPatches(r1, p2) + expect(r2.root.items.size).toBe(0) + expect(r2).toEqual(s2) + + const restored = api.applyPatches(r2, inv2) + expect(restored.root.items.size).toBe(8) + expect(api.applyPatches(restored, inv1)).toEqual(base) + + // Null-prototype object added and removed via patches + const nullProto = Object.create(null) + nullProto.k = "v" + const clearedNullProto = api.applyPatches(new Set(), [ + {op: "add", path: [0], value: nullProto}, + {op: "remove", path: [0], value: nullProto} + ]) + expect(clearedNullProto.size).toBe(0) + }) + + it("handles patches generated from a replayed Set applied to original or another replay", () => { + const api = new Immer({autoFreeze}) + const base = new Set() + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.add({n: 1}) + }) + const r1 = api.applyPatches(base, p1) + const r1Alt = api.applyPatches(base, p1) + + const [, p2, inv2] = api.produceWithPatches(r1, draft => { + draft.clear() + }) + + // Apply p2 (carrying cloned value from r1) to s1 (carrying original) and r1Alt (carrying sibling clone) + expect(api.applyPatches(s1, p2).size).toBe(0) + expect(api.applyPatches(r1Alt, p2).size).toBe(0) + + // Undo chain across multiple replay generations + const r2 = api.applyPatches(r1, p2) + const r1Restored = api.applyPatches(r2, inv2) + expect(r1Restored.size).toBe(1) + const [, , inv1] = api.produceWithPatches(base, draft => { + draft.add([...s1][0]) + }) + expect(api.applyPatches(r1Restored, inv1).size).toBe(0) + }) + + it("handles moved DraftSet followed by clearing it", () => { + const api = new Immer({autoFreeze}) + const base = {a: new Set([{n: 0}])} + + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.b = draft.a + delete draft.a + }) + const [s2, p2] = api.produceWithPatches(s1, draft => { + draft.b.clear() + }) + + const combined = api.applyPatches(base, [...p1, ...p2]) + expect(combined).toEqual(s2) + expect(combined.b.size).toBe(0) + }) + + it("does not mutate patch objects when mutating replayed Set elements inside produce", () => { + const api = new Immer({autoFreeze}) + const orig = {n: 0} + const patches = [{op: "add", path: [0], value: orig}] + + const res = api.produce(new Set(), draft => { + api.applyPatches(draft, patches) + for (const item of draft) { + item.n = 99 + } + }) + + expect(orig.n).toBe(0) + expect([...res]).toEqual([{n: 99}]) + }) + + it("scales linearly when clearing a large replayed Set of objects", () => { + const api = new Immer({autoFreeze}) + const base = {slot: null} + const count = 2000 + + const [s1, p1] = api.produceWithPatches(base, draft => { + const set = new Set() + for (let i = 0; i < count; i++) set.add({i}) + draft.slot = set + }) + const [, p2] = api.produceWithPatches(s1, draft => { + draft.slot.clear() + }) + + const combined = api.applyPatches(base, [...p1, ...p2]) + expect(combined.slot.size).toBe(0) + + const r1 = api.applyPatches(base, p1) + const r2 = api.applyPatches(r1, p2) + expect(r2.slot.size).toBe(0) + }) + + it("treats adding an already-present object reference to a Set as a no-op", () => { + const api = new Immer({autoFreeze}) + const item = {n: 1} + const base = new Set([item]) + + const res = api.applyPatches(base, [{op: "add", path: [0], value: item}]) + expect(res).toBe(base) + expect(res.size).toBe(1) + expect(res.has(item)).toBe(true) + }) + + it("deduplicates repeated add patches for the same object in a replayed Set", () => { + const api = new Immer({autoFreeze}) + const item = {n: 1} + const base = new Set() + + // Duplicate add in a single applyPatches call followed by remove + const dedupSingle = api.applyPatches(base, [ + {op: "add", path: [0], value: item}, + {op: "add", path: [0], value: item} + ]) + expect(dedupSingle.size).toBe(1) + + const dedupThenRemove = api.applyPatches(base, [ + {op: "add", path: [0], value: item}, + {op: "add", path: [0], value: item}, + {op: "remove", path: [0], value: item} + ]) + expect(dedupThenRemove.size).toBe(0) + + // Duplicate add in sequential applyPatches calls is a no-op + const r1 = api.applyPatches(base, [{op: "add", path: [0], value: item}]) + const r2 = api.applyPatches(r1, [{op: "add", path: [0], value: item}]) + expect(r2).toBe(r1) + expect(r2.size).toBe(1) + const r3 = api.applyPatches(r2, [{op: "remove", path: [0], value: item}]) + expect(r3.size).toBe(0) + + // Duplicate add after replacing a Set property + const objBase = {slot: null} + const [, pReplace] = api.produceWithPatches(objBase, draft => { + draft.slot = new Set([item]) + }) + const afterReplaceCombined = api.applyPatches(objBase, [ + ...pReplace, + {op: "add", path: ["slot", 0], value: item} + ]) + expect(afterReplaceCombined.slot.size).toBe(1) + + const afterReplaceRemoved = api.applyPatches(objBase, [ + ...pReplace, + {op: "add", path: ["slot", 0], value: item}, + {op: "remove", path: ["slot", 0], value: item} + ]) + expect(afterReplaceRemoved.slot.size).toBe(0) + + const replacedStep = api.applyPatches(objBase, pReplace) + const dupAfterReplace = api.applyPatches(replacedStep, [ + {op: "add", path: ["slot", 0], value: item} + ]) + expect(dupAfterReplace).toBe(replacedStep) + expect(dupAfterReplace.slot.size).toBe(1) + + // add -> remove(direct clone) -> add in one call must ignore stale index entry + const clonedItem = [...r1][0] + const readded = api.applyPatches(r1, [ + {op: "add", path: [0], value: item}, + {op: "remove", path: [0], value: clonedItem}, + {op: "add", path: [0], value: item} + ]) + expect(readded.size).toBe(1) + expect([...readded]).toEqual([{n: 1}]) + expect( + api.applyPatches(readded, [{op: "remove", path: [0], value: item}]).size + ).toBe(0) + }) + + it("handles Draft proxy in Set patch.value inside produce", () => { + const api = new Immer({autoFreeze}) + const item = {n: 1} + + // Direct Set containing original item, removed via Draft proxy reference + const directBase = {ref: item, slot: new Set([item])} + const removedDirect = api.produce(directBase, draft => { + api.applyPatches(draft, [ + {op: "remove", path: ["slot", 0], value: draft.ref} + ]) + }) + expect(removedDirect.slot.size).toBe(0) + + // Replayed Set containing cloned item, removed via unmodified and modified Draft proxy + const base = {ref: item, slot: null} + const [, p1] = api.produceWithPatches(base, draft => { + draft.slot = new Set([item]) + }) + const r1 = api.applyPatches(base, p1) + + const removedWithDraft = api.produce(r1, draft => { + api.applyPatches(draft, [ + {op: "remove", path: ["slot", 0], value: draft.ref} + ]) + }) + expect(removedWithDraft.slot.size).toBe(0) + + const removedWithModifiedDraft = api.produce(r1, draft => { + draft.ref.n = 2 + api.applyPatches(draft, [ + {op: "remove", path: ["slot", 0], value: draft.ref} + ]) + }) + expect(removedWithModifiedDraft.slot.size).toBe(0) + expect(removedWithModifiedDraft.ref.n).toBe(2) + + // Add, dedupe, and remove a modified Draft proxy inside produce + const addRemoveModified = api.produce( + {ref: {n: 1}, slot: new Set()}, + draft => { + draft.ref.n = 2 + api.applyPatches(draft, [ + {op: "add", path: ["slot", 0], value: draft.ref}, + {op: "add", path: ["slot", 0], value: draft.ref}, + {op: "remove", path: ["slot", 0], value: draft.ref} + ]) + } + ) + expect(addRemoveModified.slot.size).toBe(0) + }) + + it("removes mutated element inside DraftSet before applyPatches and handles moved mutated DraftSet clear", () => { + const api = new Immer({autoFreeze}) + + // Mutate cloned element inside DraftSet before applying remove patch + const base = {slot: null} + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.slot = new Set([{n: 0}]) + }) + const [, p2] = api.produceWithPatches(s1, draft => { + draft.slot.clear() + }) + const r1 = api.applyPatches(base, p1) + const r2 = api.produce(r1, draft => { + for (const item of draft.slot) { + item.n = 99 + } + api.applyPatches(draft, p2) + }) + expect(r2.slot.size).toBe(0) + + // Moved mutated DraftSet followed by clear() + const moveBase = {a: new Set([{n: 0}])} + const [ms1, mp1, minv1] = api.produceWithPatches(moveBase, draft => { + for (const item of draft.a) { + item.n = 1 + } + draft.b = draft.a + delete draft.a + }) + const [ms2, mp2, minv2] = api.produceWithPatches(ms1, draft => { + draft.b.clear() + }) + + const combined = api.applyPatches(moveBase, [...mp1, ...mp2]) + expect(combined).toEqual(ms2) + expect(combined.b.size).toBe(0) + + const mr1 = api.applyPatches(moveBase, mp1) + expect([...mr1.b]).toEqual([{n: 1}]) + const mr2 = api.applyPatches(mr1, mp2) + expect(mr2).toEqual(ms2) + expect(mr2.b.size).toBe(0) + + const undone1 = api.applyPatches(mr2, minv2) + expect(undone1).toEqual(ms1) + const undone0 = api.applyPatches(undone1, minv1) + expect(undone0).toEqual(moveBase) + }) + + it("preserves object keys when replaying concatenated Map replace and remove patches", () => { + const api = new Immer({autoFreeze}) + const key = {id: 1} + const base = {slot: null} + + const [s1, p1] = api.produceWithPatches(base, draft => { + draft.slot = new Map([[key, {n: 0}]]) + }) + const [s2, p2] = api.produceWithPatches(s1, draft => { + draft.slot.delete(key) + }) + + const combined = api.applyPatches(base, [...p1, ...p2]) + expect(combined).toEqual(s2) + expect(combined.slot.size).toBe(0) + }) + } +) diff --git a/src/plugins/patches.ts b/src/plugins/patches.ts index c7c254b9..c48b6fa0 100644 --- a/src/plugins/patches.ts +++ b/src/plugins/patches.ts @@ -29,7 +29,9 @@ import { CONSTRUCTOR, PluginPatches, isArray, - PROTOTYPE + PROTOTYPE, + getValue, + latest } from "../internal" export function enablePatches() { @@ -137,6 +139,32 @@ export function enablePatches() { const REPLACE = "replace" const ADD = "add" const REMOVE = "remove" + const cloneOrigins = new WeakMap() + const originsWithClones = new WeakSet() + + function isWeakKey(value: any): value is object { + return !!value && (isObjectish(value) || isFunction(value)) + } + + function unwrapDraftBase(value: any) { + return getProxyDraft(value)?.base_ ?? value + } + + function trackCloneOrigin(cloned: any, original: any) { + if (cloned !== original && isWeakKey(cloned)) { + const raw = getValue(original) + const origin = (isWeakKey(raw) && cloneOrigins.get(raw)) || raw + cloneOrigins.set(cloned, origin) + if (isWeakKey(origin)) originsWithClones.add(origin) + return origin + } + } + + function indexSetOriginEntry(index: Map, origin: any, item: any) { + const list = index.get(origin) + if (list) list.push(item) + else index.set(origin, [item]) + } function generatePatches_( state: ImmerState, @@ -336,6 +364,89 @@ export function enablePatches() { } function applyPatches_(draft: T, patches: readonly Patch[]): T { + let setOriginIndexes: Map> | undefined + + function getSetOriginIndex(set: any): Map { + if (!setOriginIndexes) setOriginIndexes = new Map() + let index = setOriginIndexes.get(set) + if (!index) { + index = new Map() + const state = getProxyDraft(set) as SetState | null + const entries: Set = state ? latest(state) : set + entries.forEach(item => { + const raw = unwrapDraftBase(item) + if (isWeakKey(raw)) { + const origin = cloneOrigins.get(raw) + if (origin !== undefined) { + indexSetOriginEntry(index!, origin, item) + } + } + }) + setOriginIndexes.set(set, index) + } + return index + } + + function hasByOrigin(set: any, rawValue: any, tryDirect: boolean): boolean { + if (tryDirect && set.has(rawValue)) return true + const targetOrigin = cloneOrigins.get(rawValue) ?? rawValue + if (targetOrigin !== rawValue && set.has(targetOrigin)) return true + if (!originsWithClones.has(targetOrigin)) return false + const index = getSetOriginIndex(set) + const list = index.get(targetOrigin) + if (list) { + for (let i = list.length - 1; i >= 0; i--) { + if (set.has(list[i])) return true + list.splice(i, 1) + } + index.delete(targetOrigin) + } + return false + } + + function hasInSet(set: any, value: any): boolean { + if (set.has(value)) return true + if (!isWeakKey(value)) return false + const rawValue = getValue(value) + return hasByOrigin(set, rawValue, rawValue !== value) + } + + function deleteByOrigin( + set: any, + rawValue: any, + tryDirect: boolean + ): boolean { + if (tryDirect && set.delete(rawValue)) return true + const targetOrigin = cloneOrigins.get(rawValue) ?? rawValue + if (targetOrigin !== rawValue && set.delete(targetOrigin)) return true + if (!originsWithClones.has(targetOrigin)) return false + const index = getSetOriginIndex(set) + const list = index.get(targetOrigin) + if (list) { + while (list.length > 0) { + const match = list.pop()! + if (set.delete(match)) { + if (list.length === 0) index.delete(targetOrigin) + return true + } + } + index.delete(targetOrigin) + } + return false + } + + function deleteFromSet(set: any, value: any): boolean { + if (set.delete(value)) return true + if (!isWeakKey(value)) return false + const draftState = getProxyDraft(value) + if (draftState) { + if (draftState.modified_ && deleteByOrigin(set, draftState.copy_, true)) + return true + return deleteByOrigin(set, draftState.base_, true) + } + return deleteByOrigin(set, value, false) + } + patches.forEach(patch => { const {path, op} = patch @@ -364,10 +475,10 @@ export function enablePatches() { } const type = getArchtype(base) - const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411 const key = path[path.length - 1] switch (op) { - case REPLACE: + case REPLACE: { + const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411 switch (type) { case ArchType.Map: return base.set(key, value) @@ -381,7 +492,10 @@ export function enablePatches() { // @ts-ignore return (base[key] = value) } - case ADD: + } + case ADD: { + if (type === ArchType.Set && hasInSet(base, patch.value)) return + const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411 switch (type) { case ArchType.Array: return key === "-" @@ -389,11 +503,19 @@ export function enablePatches() { : base.splice(key as any, 0, value) case ArchType.Map: return base.set(key, value) - case ArchType.Set: - return base.add(value) + case ArchType.Set: { + const origin = trackCloneOrigin(value, patch.value) + base.add(value) + if (origin !== undefined) { + const index = setOriginIndexes?.get(base) + if (index) indexSetOriginEntry(index, origin, value) + } + return base + } default: return (base[key] = value) } + } case REMOVE: switch (type) { case ArchType.Array: @@ -401,7 +523,7 @@ export function enablePatches() { case ArchType.Map: return base.delete(key) case ArchType.Set: - return base.delete(patch.value) + return deleteFromSet(base, patch.value) default: return delete base[key] } @@ -424,7 +546,15 @@ export function enablePatches() { return new Map( Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)]) ) - if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue)) + if (isSet(obj)) { + const cloned = new Set() + obj.forEach(entry => { + const clonedEntry = deepClonePatchValue(entry) + trackCloneOrigin(clonedEntry, entry) + cloned.add(clonedEntry) + }) + return cloned + } const cloned = Object.create(getPrototypeOf(obj)) for (const key in obj) cloned[key] = deepClonePatchValue(obj[key]) if (has(obj, immerable)) cloned[immerable] = obj[immerable]