Skip to content
Myr

fix: draft relocated base refs after reverse/sort in array-methods plugin (#1255)

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

With enableArrayMethods(), reverse() and sort() run natively on copy_, which still holds raw base references. Reordering relocates an un-drafted base object to an index where it no longer equals base_[prop], so the get trap's positional check misses it and returns the raw base object. Writing to that object mutates the user's base state, violating immer's guarantee that the base state is never modified. Patches and inverse patches are wrong too. Detect a relocated base reference in the get trap (only after a reorder, for indices the user did not explicitly assign) and draft it before exposing it.

authored by spokodev · committed by GitHub · parent cfec5e5 · Browse files · 3 files+58 added−2 removed
This commit

State

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

Diff stats

3 files+58 added−2 removed

  • tests:+33 added−1 removed
  • other:+25 added−1 removed

3 files+58 added−2 removed

modified:__tests__/base.js+33 added-1 removed
6 unmodified lines
7 isDraft,8 immerable,9 enablePatches,10 enableMapSet,11 enableArrayMethods11 enableArrayMethods,12 applyPatches13} from "../src/immer"1415import {16 each,
339 unmodified lines
356 expect(nextState).not.toBe(baseState)357 expect(nextState).toEqual([{value: 1}, {value: 2}, {value: 3}])358 })359360 it("mutating an element after reverse() does not mutate the base", () => {361 const reordered = {id: 3}362 const baseState = [{id: 1}, {id: 2}, reordered]363 const nextState = produce(baseState, s => {364 s.reverse()365 // After reverse, the element at index 0 is the relocated base366 // object. It must be drafted, otherwise writing to it mutates base.367 expect(isDraft(s[0])).toBe(true)368 s[0].id = 99369 })370 expect(baseState).toEqual([{id: 1}, {id: 2}, {id: 3}])371 expect(reordered).toEqual({id: 3})372 expect(nextState).toEqual([{id: 99}, {id: 2}, {id: 1}])373 })374375 it("mutating an element after sort() does not mutate the base", () => {376 const baseState = [{value: 3}, {value: 1}, {value: 2}]377 const [nextState, patches, inverse] = produceWithPatches(378 baseState,379 s => {380 s.sort((a, b) => a.value - b.value)381 expect(isDraft(s[0])).toBe(true)382 s[0].value = 99383 }384 )385 expect(baseState).toEqual([{value: 3}, {value: 1}, {value: 2}])386 expect(nextState).toEqual([{value: 99}, {value: 2}, {value: 3}])387 expect(applyPatches(baseState, patches)).toEqual(nextState)388 expect(applyPatches(nextState, inverse)).toEqual(baseState)389 })390391 describe("push()", () => {392 test("push single item", () => {393 const base = {items: [{id: 1}, {id: 2}]}394 const result = produce(base, draft => {
3818 unmodified lines
modified:src/core/proxy.ts+24 added-1 removed
42 unmodified lines
43 copy_: AnyArray | null44 draft_: Drafted<AnyArray, ProxyArrayState>45 operationMethod?: string46 allIndicesReassigned_?: boolean47 baseRefs_?: Set<any>48}4950type ProxyState = ProxyObjectState | ProxyArrayState51
94 unmodified lines
146 return value147 }148 // Check for existing draft in modified state.149 // Assigned values are never drafted. This catches any drafts we created, too.149 if (value === peek(state.base_, prop)) {150 if (151 value === peek(state.base_, prop) ||152 isRelocatedBaseRef(state, prop, value)153 ) {154 prepareCopy(state)155 // Ensure array keys are always numbers156 const childKey = state.type_ === ArchType.Array ? +(prop as string) : prop157 const childDraft = createProxy(state.scope_, value, state, childKey)
133 unmodified lines
291 const source = state ? latest(state) : draft292 return source[prop]293}294295// Reordering array methods (reverse, sort) from the array-methods plugin run296// natively on `copy_`, which still holds raw base references. This relocates an297// un-drafted base object to a position where it no longer matches `base_[prop]`,298// so the normal positional check above misses it and the get trap would hand back299// the raw base object, breaking the guarantee that the base state is never mutated.300// Detect such a relocated base reference so it is drafted before being exposed.301function isRelocatedBaseRef(state: ImmerState, prop: PropertyKey, value: any) {302 if (303 state.type_ !== ArchType.Array ||304 !(state as ProxyArrayState).allIndicesReassigned_ ||305 state.assigned_?.get(prop) ||306 !isDraftable(value) ||307 value[DRAFT_STATE]308 ) {309 return false310 }311 return (state as ProxyArrayState).baseRefs_!.has(value)312}313314function readPropFromProto(state: ImmerState, source: any, prop: PropertyKey) {315 const desc = getDescriptorFromProto(source, prop)316 return desc317 ? VALUE in desc
42 unmodified lines
modified:src/plugins/arrayMethods.ts+1 added
179 unmodified lines
180 }181182 function markAllIndicesReassigned(state: ProxyArrayState) {183 state.allIndicesReassigned_ = true184 state.baseRefs_ = new Set(state.base_)185 }186187 function normalizeSliceIndex(index: number, length: number): number {188 if (index < 0) {
253 unmodified lines