Skip to content
Myr

fix: throw proper immer error when applyPatches path traverses null (#1251)

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

typeof null === "object" causes isObjectish(null) to return true, silently bypassing the path-resolution guard inside applyPatches_. Traversal then calls getArchtype(null) which accesses null[DRAFT_STATE] and crashes with a native TypeError instead of immer error 18 ("Cannot apply patch, path doesn't resolve"). Add an explicit null check alongside isObjectish so the guard fires correctly and the caller receives the expected immer error message. Fixes: applyPatches({a: null}, [{op: 'add', path: ['a', 'b'], value: 1}])

authored by JSap0914 · committed by GitHub · parent 8bc4b2d · Browse files · 2 files+11 added−1 removed
This commit

State

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

Trailers

  • Co-authored-by: JSap0914 <JSap0914@users.noreply.github.com>

Diff stats

2 files+11 added−1 removed

  • tests:+9 added−0 removed
  • other:+2 added−1 removed

2 files+11 added−1 removed

modified:__tests__/patch.js+9 added
1594 unmodified lines
15951596 expect(patches[0].path).toEqual(["queries", "queryKey", "data", "items", 1])1597 })1598})1599test("applyPatches throws proper immer error when intermediate path value is null", () => {1600 // isObjectish(null) === true (typeof null === "object"), so the null check1601 // inside applyPatches_ was missing; navigating into null threw a native1602 // TypeError instead of immer's own "path doesn't resolve" error.1603 const isProd = process.env.NODE_ENV === "production"1604 expect(() => {1605 applyPatches({a: null}, [{op: "add", path: ["a", "b"], value: 1}])1606 }).toThrow(isProd ? "18" : "Cannot apply patch, path doesn't resolve: a/b")1607})
modified:src/plugins/patches.ts+2 added-1 removed
343 unmodified lines
344 )345 die(errorOffset + 3)346 if (isFunction(base) && p === PROTOTYPE) die(errorOffset + 3)347 base = get(base, p)348 if (base === null || !isObjectish(base))348 if (!isObjectish(base)) die(errorOffset + 2, path.join("/"))349 die(errorOffset + 2, path.join("/"))350 }351352 const type = getArchtype(base)353 const value = deepClonePatchValue(patch.value) // used to clone patch to ensure original patch is not modified, see #411
79 unmodified lines