patches.ts
This file
Path
src/plugins/patches.ts
432 lines · 10.4 KiB · TypeScript
Last changed by
fix: throw proper immer error when applyPatches path traverses null (#1251)JSap0914before adoptione38ad71
History of this fileTake it
1import {immerable} from "../immer"2import {3 ImmerState,4 Patch,5 SetState,6 ProxyArrayState,7 MapState,8 ProxyObjectState,9 PatchPath,10 get,11 each,12 has,13 getArchtype,14 getPrototypeOf,15 isSet,16 isMap,17 loadPlugin,18 ArchType,19 die,20 isDraft,21 isDraftable,22 NOTHING,23 errors,24 DRAFT_STATE,25 getProxyDraft,26 ImmerScope,27 isObjectish,28 isFunction,29 CONSTRUCTOR,30 PluginPatches,31 isArray,32 PROTOTYPE33} from "../internal"3435export function enablePatches() {36 const errorOffset = 1637 if (process.env.NODE_ENV !== "production") {38 errors.push(39 'Sets cannot have "replace" patches.',40 function (op: string) {41 return "Unsupported patch operation: " + op42 },43 function (path: string) {44 return "Cannot apply patch, path doesn't resolve: " + path45 },46 "Patching reserved attributes like __proto__, prototype and constructor is not allowed"47 )48 }4950 function getPath(state: ImmerState, path: PatchPath = []): PatchPath | null {51 // Step 1: Check if state has a stored key52 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_!))57 const valueAtKey = get(parentCopy, state.key_!)5859 if (valueAtKey === undefined) {60 return null61 }6263 // Check if the value at the key is still related to this draft64 // It should be either the draft itself, the base, or the copy65 if (66 valueAtKey !== state.draft_ &&67 valueAtKey !== state.base_ &&68 valueAtKey !== state.copy_69 ) {70 return null // Value was replaced with something else71 }72 if (proxyDraft != null && proxyDraft.base_ !== state.base_) {73 return null // Different draft74 }7576 // Step 3: Handle Set case specially77 const isSet = state.parent_!.type_ === ArchType.Set78 let key: string | number7980 if (isSet) {81 // For Sets, find the index in the drafts_ map82 const setParent = state.parent_ as SetState83 key = Array.from(setParent.drafts_.keys()).indexOf(state.key_)84 } else {85 key = state.key_ as string | number86 }8788 // Step 4: Validate key still exists in parent89 if (!((isSet && parentCopy.size > key) || has(parentCopy, key))) {90 return null // Key deleted91 }9293 // Step 5: Add key to path94 path.push(key)95 }9697 // Step 6: Recurse to parent if exists98 if (state.parent_) {99 return getPath(state.parent_, path)100 }101102 // Step 7: At root - reverse path and validate103 path.reverse()104105 try {106 // Validate path can be resolved from ROOT107 resolvePath(state.copy_, path)108 } catch (e) {109 return null // Path invalid110 }111112 return path113 }114115 // NEW: Add resolvePath helper function116 function resolvePath(base: any, path: PatchPath): any {117 let current = base118 for (let i = 0; i < path.length - 1; i++) {119 const key = path[i]120 current = get(current, key)121 if (!isObjectish(current) || current === null) {122 throw new Error(`Cannot resolve path at '${path.join("/")}'`)123 }124 }125 return current126 }127128 const REPLACE = "replace"129 const ADD = "add"130 const REMOVE = "remove"131132 function generatePatches_(133 state: ImmerState,134 basePath: PatchPath,135 scope: ImmerScope136 ): void {137 if (state.scope_.processedForPatches_.has(state)) {138 return139 }140141 state.scope_.processedForPatches_.add(state)142143 const {patches_, inversePatches_} = scope144145 switch (state.type_) {146 case ArchType.Object:147 case ArchType.Map:148 return generatePatchesFromAssigned(149 state,150 basePath,151 patches_!,152 inversePatches_!153 )154 case ArchType.Array:155 return generateArrayPatches(156 state,157 basePath,158 patches_!,159 inversePatches_!160 )161 case ArchType.Set:162 return generateSetPatches(163 state as any as SetState,164 basePath,165 patches_!,166 inversePatches_!167 )168 }169 }170171 function generateArrayPatches(172 state: ProxyArrayState,173 basePath: PatchPath,174 patches: Patch[],175 inversePatches: Patch[]176 ) {177 let {base_, assigned_} = state178 let copy_ = state.copy_!179180 // Reduce complexity by ensuring `base` is never longer.181 if (copy_.length < base_.length) {182 // @ts-ignore183 ;[base_, copy_] = [copy_, base_]184 ;[patches, inversePatches] = [inversePatches, patches]185 }186187 const allReassigned = state.allIndicesReassigned_ === true188189 // Process replaced indices.190 for (let i = 0; i < base_.length; i++) {191 const copiedItem = copy_[i]192 const baseItem = base_[i]193194 const isAssigned = allReassigned || assigned_?.get(i.toString())195 if (isAssigned && copiedItem !== baseItem) {196 const childState = copiedItem?.[DRAFT_STATE]197 if (childState && childState.modified_) {198 // Skip - let the child generate its own patches199 continue200 }201 const path = basePath.concat([i])202 patches.push({203 op: REPLACE,204 path,205 // Need to maybe clone it, as it can in fact be the original value206 // due to the base/copy inversion at the start of this function207 value: clonePatchValueIfNeeded(copiedItem)208 })209 inversePatches.push({210 op: REPLACE,211 path,212 value: clonePatchValueIfNeeded(baseItem)213 })214 }215 }216217 // Process added indices.218 for (let i = base_.length; i < copy_.length; i++) {219 const path = basePath.concat([i])220 patches.push({221 op: ADD,222 path,223 // Need to maybe clone it, as it can in fact be the original value224 // due to the base/copy inversion at the start of this function225 value: clonePatchValueIfNeeded(copy_[i])226 })227 }228 for (let i = copy_.length - 1; base_.length <= i; --i) {229 const path = basePath.concat([i])230 inversePatches.push({231 op: REMOVE,232 path233 })234 }235 }236237 // This is used for both Map objects and normal objects.238 function generatePatchesFromAssigned(239 state: MapState | ProxyObjectState,240 basePath: PatchPath,241 patches: Patch[],242 inversePatches: Patch[]243 ) {244 const {base_, copy_, type_} = state245 each(state.assigned_!, (key, assignedValue) => {246 const origValue = get(base_, key, type_)247 const value = get(copy_!, key, type_)248 const op = !assignedValue ? REMOVE : has(base_, key) ? REPLACE : ADD249 if (origValue === value && op === REPLACE) return250 const path = basePath.concat(key as any)251 patches.push(252 op === REMOVE253 ? {op, path}254 : {op, path, value: clonePatchValueIfNeeded(value)}255 )256 inversePatches.push(257 op === ADD258 ? {op: REMOVE, path}259 : op === REMOVE260 ? {op: ADD, path, value: clonePatchValueIfNeeded(origValue)}261 : {op: REPLACE, path, value: clonePatchValueIfNeeded(origValue)}262 )263 })264 }265266 function generateSetPatches(267 state: SetState,268 basePath: PatchPath,269 patches: Patch[],270 inversePatches: Patch[]271 ) {272 let {base_, copy_} = state273274 let i = 0275 base_.forEach((value: any) => {276 if (!copy_!.has(value)) {277 const path = basePath.concat([i])278 patches.push({279 op: REMOVE,280 path,281 value282 })283 inversePatches.unshift({284 op: ADD,285 path,286 value287 })288 }289 i++290 })291 i = 0292 copy_!.forEach((value: any) => {293 if (!base_.has(value)) {294 const path = basePath.concat([i])295 patches.push({296 op: ADD,297 path,298 value299 })300 inversePatches.unshift({301 op: REMOVE,302 path,303 value304 })305 }306 i++307 })308 }309310 function generateReplacementPatches_(311 baseValue: any,312 replacement: any,313 scope: ImmerScope314 ): void {315 const {patches_, inversePatches_} = scope316 patches_!.push({317 op: REPLACE,318 path: [],319 value: replacement === NOTHING ? undefined : replacement320 })321 inversePatches_!.push({322 op: REPLACE,323 path: [],324 value: baseValue325 })326 }327328 function applyPatches_<T>(draft: T, patches: readonly Patch[]): T {329 patches.forEach(patch => {330 const {path, op} = patch331332 let base: any = draft333 for (let i = 0; i < path.length - 1; i++) {334 const parentType = getArchtype(base)335 let p = path[i]336 if (typeof p !== "string" && typeof p !== "number") {337 p = "" + p338 }339340 // See #738, avoid prototype pollution341 if (342 (parentType === ArchType.Object || parentType === ArchType.Array) &&343 (p === "__proto__" || p === CONSTRUCTOR)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))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 #411354 const key = path[path.length - 1]355 switch (op) {356 case REPLACE:357 switch (type) {358 case ArchType.Map:359 return base.set(key, value)360 /* istanbul ignore next */361 case ArchType.Set:362 die(errorOffset)363 default:364 // if value is an object, then it's assigned by reference365 // in the following add or remove ops, the value field inside the patch will also be modifyed366 // so we use value from the cloned patch367 // @ts-ignore368 return (base[key] = value)369 }370 case ADD:371 switch (type) {372 case ArchType.Array:373 return key === "-"374 ? base.push(value)375 : base.splice(key as any, 0, value)376 case ArchType.Map:377 return base.set(key, value)378 case ArchType.Set:379 return base.add(value)380 default:381 return (base[key] = value)382 }383 case REMOVE:384 switch (type) {385 case ArchType.Array:386 return base.splice(key as any, 1)387 case ArchType.Map:388 return base.delete(key)389 case ArchType.Set:390 return base.delete(patch.value)391 default:392 return delete base[key]393 }394 default:395 die(errorOffset + 1, op)396 }397 })398399 return draft400 }401402 // optimize: this is quite a performance hit, can we detect intelligently when it is needed?403 // E.g. auto-draft when new objects from outside are assigned and modified?404 // (See failing test when deepClone just returns obj)405 function deepClonePatchValue<T>(obj: T): T406 function deepClonePatchValue(obj: any) {407 if (!isDraftable(obj)) return obj408 if (isArray(obj)) return obj.map(deepClonePatchValue)409 if (isMap(obj))410 return new Map(411 Array.from(obj.entries()).map(([k, v]) => [k, deepClonePatchValue(v)])412 )413 if (isSet(obj)) return new Set(Array.from(obj).map(deepClonePatchValue))414 const cloned = Object.create(getPrototypeOf(obj))415 for (const key in obj) cloned[key] = deepClonePatchValue(obj[key])416 if (has(obj, immerable)) cloned[immerable] = obj[immerable]417 return cloned418 }419420 function clonePatchValueIfNeeded<T>(obj: T): T {421 if (isDraft(obj)) {422 return deepClonePatchValue(obj)423 } else return obj424 }425426 loadPlugin(PluginPatches, {427 applyPatches_,428 generatePatches_,429 generateReplacementPatches_,430 getPath431 })432}