@vielzeug/patchwork 26.11.13 → 26.11.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -1
- package/dist/_equality.cjs +2 -0
- package/dist/_equality.cjs.map +1 -0
- package/dist/_equality.d.ts +9 -0
- package/dist/_equality.d.ts.map +1 -0
- package/dist/_equality.js +16 -0
- package/dist/_equality.js.map +1 -0
- package/dist/errors.cjs +1 -1
- package/dist/errors.cjs.map +1 -1
- package/dist/errors.d.ts +10 -1
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +6 -1
- package/dist/errors.js.map +1 -1
- package/dist/merge.cjs +2 -0
- package/dist/merge.cjs.map +1 -0
- package/dist/merge.d.ts +37 -0
- package/dist/merge.d.ts.map +1 -0
- package/dist/merge.js +57 -0
- package/dist/merge.js.map +1 -0
- package/dist/patch.cjs +1 -1
- package/dist/patch.cjs.map +1 -1
- package/dist/patch.d.ts +6 -3
- package/dist/patch.d.ts.map +1 -1
- package/dist/patch.js +142 -140
- package/dist/patch.js.map +1 -1
- package/dist/patchwork.cjs +1 -1
- package/dist/patchwork.cjs.map +1 -1
- package/dist/patchwork.iife.js +1 -1
- package/dist/patchwork.iife.js.map +1 -1
- package/dist/patchwork.js +49 -30
- package/dist/patchwork.js.map +1 -1
- package/package.json +13 -1
package/dist/patchwork.iife.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var Patchwork=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var PatchError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},PatchPathError=class extends PatchError{},PatchTestError=class extends PatchError{};function parsePointer(e){if(e===``)return[];if(!e.startsWith(`/`))throw new PatchPathError(`pointer "${e}" must start with "/"`);return e.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`))}function formatPointer(e){return e.map(e=>`/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``)}function
|
|
1
|
+
var Patchwork=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var PatchError=class extends Error{constructor(e,t){super(e,t),this.name=new.target.name,Object.setPrototypeOf(this,new.target.prototype)}},PatchPathError=class extends PatchError{pointer;constructor(e,t){super(e,t),this.pointer=t?.pointer}},PatchTestError=class extends PatchError{};function isPlainObject(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function deepEqual(e,t){if(e===t)return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>deepEqual(e,t[n]));if(isPlainObject(e)&&isPlainObject(t)){let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.hasOwn(t,n)&&deepEqual(e[n],t[n]))}return!1}function parsePointer(e){if(e===``)return[];if(!e.startsWith(`/`))throw new PatchPathError(`pointer "${e}" must start with "/"`);return e.slice(1).split(`/`).map(e=>e.replaceAll(`~1`,`/`).replaceAll(`~0`,`~`))}function formatPointer(e){return e.map(e=>`/${e.replaceAll(`~`,`~0`).replaceAll(`/`,`~1`)}`).join(``)}function isArrayIndex(e){if(/^(0|[1-9]\d*)$/.test(e)){let t=Number(e);return t<=2**53-1?t:-1}return-1}function resolve(e,t){let n=e;for(let e of t){if(Array.isArray(n)){let t=isArrayIndex(e);n=t>=0&&t<n.length?n[t]:void 0}else if(isPlainObject(n))n=Object.hasOwn(n,e)?n[e]:void 0;else return{exists:!1};if(n===void 0)return{exists:!1}}return{exists:!0,value:n}}function getIn(e,t){return resolve(e,parsePointer(t)).value}function descendArray(e,t,n){let r=isArrayIndex(t);if(r<0||r>=e.length)throw new PatchPathError(`cannot ${n} at "/${t}": index out of bounds`);return r}function addIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){if(r===`-`){if(i.length>0)throw new PatchPathError(`cannot add "/-": "-" must be the final token`);return[...e,n]}let t=isArrayIndex(r);if(t<0||t>e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);if(i.length>0){if(t===e.length)throw new PatchPathError(`cannot add "/${r}": index out of bounds`);return[...e.slice(0,t),addIn(e[t],i,n),...e.slice(t+1)]}return[...e.slice(0,t),n,...e.slice(t)]}if(isPlainObject(e)){if(i.length>0){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot add "/${r}": member does not exist`);return{...e,[r]:addIn(e[r],i,n)}}return Object.hasOwn(e,r)&&deepEqual(e[r],n)?e:{...e,[r]:n}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function replaceIn(e,t,n){let[r=``,...i]=t;if(t.length===0)return n;if(Array.isArray(e)){let t=descendArray(e,r,`replace`);return i.length===0?deepEqual(e[t],n)?e:[...e.slice(0,t),n,...e.slice(t+1)]:[...e.slice(0,t),replaceIn(e[t],i,n),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,r))throw new PatchPathError(`cannot replace "/${r}": member does not exist`);return i.length===0?deepEqual(e[r],n)?e:{...e,[r]:n}:{...e,[r]:replaceIn(e[r],i,n)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function removeIn(e,t){let[n=``,...r]=t;if(t.length===0)return null;if(Array.isArray(e)){let t=descendArray(e,n,`remove`);return r.length===0?[...e.slice(0,t),...e.slice(t+1)]:[...e.slice(0,t),removeIn(e[t],r),...e.slice(t+1)]}if(isPlainObject(e)){if(!Object.hasOwn(e,n))throw new PatchPathError(`cannot remove "/${n}": member does not exist`);if(r.length===0){let t={...e};return delete t[n],t}return{...e,[n]:removeIn(e[n],r)}}throw new PatchPathError(`cannot descend into a ${typeof e}`)}function requireValue(e,t,n){let r=resolve(e,t);if(!r.exists)throw new PatchPathError(`pointer "${n}" does not resolve`,{pointer:n});return r.value}function at(e,t){try{return t()}catch(t){throw t instanceof PatchPathError&&t.pointer===void 0?new PatchPathError(t.message,{cause:t,pointer:e}):t}}function applyOperation(e,t){switch(t.op){case`add`:return at(t.path,()=>addIn(e,parsePointer(t.path),structuredClone(t.value)));case`remove`:return at(t.path,()=>removeIn(e,parsePointer(t.path)));case`replace`:return at(t.path,()=>replaceIn(e,parsePointer(t.path),structuredClone(t.value)));case`move`:{let n=at(t.from,()=>requireValue(e,parsePointer(t.from),t.from)),r=at(t.from,()=>removeIn(e,parsePointer(t.from)));return at(t.path,()=>addIn(r,parsePointer(t.path),n))}case`copy`:{let n=at(t.from,()=>requireValue(e,parsePointer(t.from),t.from));return at(t.path,()=>addIn(e,parsePointer(t.path),structuredClone(n)))}case`test`:{let n=resolve(e,parsePointer(t.path));if(!n.exists||!deepEqual(n.value,t.value))throw new PatchTestError(`test failed at "${t.path}"`);return e}}}function apply(e,t){let n=e;for(let e of t)n=applyOperation(n,e);return n}function tryApply(e,t){let n=e;for(let e=0;e<t.length;e+=1){let r=t[e];try{n=applyOperation(n,r)}catch(t){let n=t instanceof PatchTestError?`test`:`path`,i=t instanceof PatchPathError?t.pointer??r.path:r.path;return{error:{index:e,message:t.message,path:i,reason:n},ok:!1}}}return{doc:n,ok:!0}}function diffNode(e,t,n,r){if(!deepEqual(t,n)){if(Array.isArray(t)&&Array.isArray(n)){let i=Math.min(t.length,n.length),a=0;for(;a<i&&deepEqual(t[a],n[a]);)a+=1;let o=0;for(;o<i-a&&deepEqual(t[t.length-1-o],n[n.length-1-o]);)o+=1;let s=t.length-o,c=n.length-o,l=Math.min(s,c)-a;for(let i=a;i<a+l;i+=1)diffNode(`${e}/${i}`,t[i],n[i],r);for(let t=s-1;t>=a+l;--t)r.push({op:`remove`,path:`${e}/${t}`});let u=o===0;for(let t=a+l;t<c;t+=1)r.push({op:`add`,path:u?`${e}/-`:`${e}/${t}`,value:n[t]})}else if(isPlainObject(t)&&isPlainObject(n)){for(let i of Object.keys(t))Object.hasOwn(n,i)||r.push({op:`remove`,path:`${e}${formatPointer([i])}`});for(let i of Object.keys(n)){let a=`${e}${formatPointer([i])}`,o=n[i];Object.hasOwn(t,i)?diffNode(a,t[i],o,r):r.push({op:`add`,path:a,value:o})}}else r.push({op:`replace`,path:e,value:n})}}function diff(e,t){let n=[];return diffNode(``,e,t,n),n}return e.PatchError=PatchError,e.PatchPathError=PatchPathError,e.PatchTestError=PatchTestError,e.apply=apply,e.diff=diff,e.formatPointer=formatPointer,e.getIn=getIn,e.parsePointer=parsePointer,e.tryApply=tryApply,e})({});
|
|
2
2
|
//# sourceMappingURL=patchwork.iife.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patchwork.iife.js","names":["exports","message","options","pointer","token","tokens","value","index","current","doc","a","b","item","aKeys","bKeys","key","action","rest","next","found","operation","patch","error","reason","path","from","to","common","headLength","ops","i","childPath","toValue"],"sources":["../src/errors.ts","../src/patch.ts"],"sourcesContent":["/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** The document could not be patched because a pointer did not resolve. */\nexport class PatchPathError extends PatchError {}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","import { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Structural equality (JSON domain: no NaN/undefined/prototype concerns)\n// ---------------------------------------------------------------------------\n\nfunction deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`);\n return found.value as JsonValue;\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return addIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'remove':\n return removeIn(doc, parsePointer(operation.path));\n case 'replace':\n return replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'move': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(removeIn(doc, parsePointer(operation.from)), parsePointer(operation.path), value);\n }\n case 'copy': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(doc, parsePointer(operation.path), structuredClone(value));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = operation.op === 'move' || operation.op === 'copy' ? operation.from : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Trim the common suffix, then walk positionally: equal entries skip,\n // changed entries recurse, surplus tails add or remove in apply-safe order.\n let common = 0;\n while (\n common < Math.min(from.length, to.length) &&\n deepEqual(from[from.length - 1 - common] as JsonValue, to[to.length - 1 - common] as JsonValue)\n ) {\n common += 1;\n }\n const headLength = Math.min(from.length, to.length) - common;\n for (let i = 0; i < headLength; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = from.length - 1 - common; i >= headLength; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n for (let i = headLength; i < to.length - common; i += 1) {\n ops.push({ op: 'add', path: `${path}/-`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays trim\n * their common suffix and emit ordered add/remove tails, so append-only\n * lists stay small. The result applies cleanly via {@link apply}.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":"A,wFACA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAGa,eAAb,cAAoC,UAAW,CAAC,EAGnC,eAAb,cAAoC,UAAW,CAAC,ECLhD,SAAgB,aAAa,EAAgC,CAC3D,GAAIC,IAAY,GAAI,MAAO,CAAC,EAC5B,GAAI,CAACA,EAAQ,WAAW,GAAG,EAAG,MAAM,IAAI,eAAe,YAAYA,EAAQ,sBAAsB,EACjG,OAAOA,EACJ,MAAM,CAAC,CAAC,CACR,MAAM,GAAG,CAAC,CACV,IAAK,GAAUC,EAAM,WAAW,KAAM,GAAG,CAAC,CAAC,WAAW,KAAM,GAAG,CAAC,CACrE,CAGA,SAAgB,cAAc,EAAwC,CACpE,OAAOC,EAAO,IAAK,GAAU,IAAID,EAAM,WAAW,IAAK,IAAI,CAAC,CAAC,WAAW,IAAK,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,CAC/F,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AK,CAAE,GAAI,UAAW,OAAM,MAAOH,CAAG,CAAC,CAhB3C,CAiBF,CAQA,SAAgB,KAAK,EAAiB,EAA0B,CAC9D,IAAMG,EAAwB,CAAC,EAE/B,OADA,SAAS,GAAIJ,EAAMC,EAAIG,CAAG,EACnBA,CACT,C"}
|
|
1
|
+
{"version":3,"file":"patchwork.iife.js","names":["exports","message","options","value","a","b","item","index","aKeys","bKeys","key","pointer","token","tokens","current","doc","action","rest","next","found","run","error","operation","removed","patch","reason","path","from","to","shared","head","tail","fromMiddle","toMiddle","overlap","ops","i","appends","childPath","toValue"],"sources":["../src/errors.ts","../src/_equality.ts","../src/patch.ts"],"sourcesContent":["import type { JsonPointer } from './types';\n\n/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * The document could not be patched because a pointer did not resolve. `pointer` names the\n * offending pointer when the library can attribute one (the failing `path` of a `move` is\n * not its `from`).\n */\nexport class PatchPathError extends PatchError {\n readonly pointer: JsonPointer | undefined;\n\n constructor(message: string, options?: ErrorOptions & { pointer?: JsonPointer }) {\n super(message, options);\n this.pointer = options?.pointer;\n }\n}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","/**\n * Internal JSON-domain helpers shared by the patch engine and the merge module.\n * Never re-exported from the package barrel.\n */\nimport type { JsonObject, JsonValue } from './types';\n\nexport function isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Structural equality over the JSON domain: no NaN/undefined/prototype concerns. */\nexport function deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n","import { deepEqual, isPlainObject } from './_equality';\nimport { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`, { pointer });\n return found.value as JsonValue;\n}\n\n/** Attributes path failures thrown inside `run` to `pointer` (the caller's full pointer). */\nfunction at<T>(pointer: JsonPointer, run: () => T): T {\n try {\n return run();\n } catch (error) {\n if (error instanceof PatchPathError && error.pointer === undefined) {\n throw new PatchPathError(error.message, { cause: error, pointer });\n }\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'remove':\n return at(operation.path, () => removeIn(doc, parsePointer(operation.path)));\n case 'replace':\n return at(operation.path, () => replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'move': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n const removed = at(operation.from, () => removeIn(doc, parsePointer(operation.from)));\n return at(operation.path, () => addIn(removed, parsePointer(operation.path), value));\n }\n case 'copy': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(value)));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = error instanceof PatchPathError ? (error.pointer ?? operation.path) : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Align on the common prefix and (non-overlapping) common suffix, recurse positionally\n // through the middle, then let surplus removals fall off the middle's tail (descending)\n // and surplus inserts land in ascending index order. True appends keep the `-` token.\n const shared = Math.min(from.length, to.length);\n let head = 0;\n while (head < shared && deepEqual(from[head] as JsonValue, to[head] as JsonValue)) head += 1;\n let tail = 0;\n while (\n tail < shared - head &&\n deepEqual(from[from.length - 1 - tail] as JsonValue, to[to.length - 1 - tail] as JsonValue)\n ) {\n tail += 1;\n }\n const fromMiddle = from.length - tail; // exclusive end of from's middle\n const toMiddle = to.length - tail; // exclusive end of to's middle\n const overlap = Math.min(fromMiddle, toMiddle) - head;\n for (let i = head; i < head + overlap; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = fromMiddle - 1; i >= head + overlap; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n const appends = tail === 0; // surplus only ever lands at the end when no tail is shared\n for (let i = head + overlap; i < toMiddle; i += 1) {\n ops.push({ op: 'add', path: appends ? `${path}/-` : `${path}/${i}`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays align\n * on their common prefix and suffix and emit ordered removals and indexed\n * inserts around a positionally diffed middle, so appends, prepends, and\n * middle inserts each stay one operation. Not minimal-edit: a reorder\n * diffs positionally. The result always round-trips:\n * `apply(from, diff(from, to))` deep-equals `to`.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":"A,wFAGA,IAAa,WAAb,cAAgC,KAAM,CACpC,YAAY,EAAiB,EAAwB,CACnD,MAAMC,EAASC,CAAO,EACtB,KAAK,KAAO,WAAW,KACvB,OAAO,eAAe,KAAM,WAAW,SAAS,CAClD,CACF,EAOa,eAAb,cAAoC,UAAW,CAC7C,QAEA,YAAY,EAAiB,EAAoD,CAC/E,MAAMD,EAASC,CAAO,EACtB,KAAK,QAAUA,GAAS,OAC1B,CACF,EAGa,eAAb,cAAoC,UAAW,CAAC,ECpBhD,SAAgB,cAAc,EAAmD,CAC/E,OAAO,OAAOC,GAAU,YAAYA,GAAkB,CAAC,MAAM,QAAQA,CAAK,CAC5E,CAGA,SAAgB,UAAU,EAAc,EAAuB,CAC7D,GAAIC,IAAMC,EAAG,MAAO,GACpB,GAAI,MAAM,QAAQD,CAAC,GAAK,MAAM,QAAQC,CAAC,EACrC,OAAOD,EAAE,SAAWC,EAAE,QAAUD,EAAE,OAAO,EAAM,IAAU,UAAUE,EAAMD,EAAEE,EAAmB,CAAC,EAEjG,GAAI,cAAcH,CAAC,GAAK,cAAcC,CAAC,EAAG,CACxC,IAAMG,EAAQ,OAAO,KAAKJ,CAAC,EACrBK,EAAQ,OAAO,KAAKJ,CAAC,EAC3B,OACEG,EAAM,SAAWC,EAAM,QACvBD,EAAM,MAAO,GAAQ,OAAO,OAAOH,EAAGK,CAAG,GAAK,UAAUN,EAAEM,GAAmBL,EAAEK,EAAiB,CAAC,CAErG,CACA,MAAO,EACT,CChBA,SAAgB,aAAa,EAAgC,CAC3D,GAAIC,IAAY,GAAI,MAAO,CAAC,EAC5B,GAAI,CAACA,EAAQ,WAAW,GAAG,EAAG,MAAM,IAAI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OAAOC,EAAIlB,CAAG,GAAGyB,EAAI,KAAK,CAAE,GAAI,SAAU,KAAM,GAAGT,IAAO,cAAc,CAAChB,CAAG,CAAC,GAAI,CAAC,EAEhG,IAAK,IAAMA,KAAO,OAAO,KAAKkB,CAAE,EAAG,CACjC,IAAMU,EAAY,GAAGZ,IAAO,cAAc,CAAChB,CAAG,CAAC,IACzC6B,EAAUX,EAAGlB,GACd,OAAO,OAAOiB,EAAMjB,CAAG,EAG1B,SAAS4B,EAAWX,EAAKjB,GAAmB6B,EAASJ,CAAG,EAFxDA,EAAI,KAAK,CAAE,GAAI,MAAO,KAAMG,EAAW,MAAOC,CAAQ,CAAC,CAI3D,CAEF,MACAJ,EAAI,KAAK,CAAE,GAAI,UAAW,OAAM,MAAOP,CAAG,CAAC,CAhB3C,CAiBF,CAWA,SAAgB,KAAK,EAAiB,EAA0B,CAC9D,IAAMO,EAAwB,CAAC,EAE/B,OADA,SAAS,GAAIR,EAAMC,EAAIO,CAAG,EACnBA,CACT,C"}
|
package/dist/patchwork.js
CHANGED
|
@@ -3,7 +3,25 @@ var PatchError = class extends Error {
|
|
|
3
3
|
constructor(e, t) {
|
|
4
4
|
super(e, t), this.name = new.target.name, Object.setPrototypeOf(this, new.target.prototype);
|
|
5
5
|
}
|
|
6
|
-
}, PatchPathError = class extends PatchError {
|
|
6
|
+
}, PatchPathError = class extends PatchError {
|
|
7
|
+
pointer;
|
|
8
|
+
constructor(e, t) {
|
|
9
|
+
super(e, t), this.pointer = t?.pointer;
|
|
10
|
+
}
|
|
11
|
+
}, PatchTestError = class extends PatchError {};
|
|
12
|
+
// src/_equality.ts
|
|
13
|
+
function isPlainObject(e) {
|
|
14
|
+
return typeof e == "object" && !!e && !Array.isArray(e);
|
|
15
|
+
}
|
|
16
|
+
function deepEqual(e, t) {
|
|
17
|
+
if (e === t) return !0;
|
|
18
|
+
if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => deepEqual(e, t[n]));
|
|
19
|
+
if (isPlainObject(e) && isPlainObject(t)) {
|
|
20
|
+
let n = Object.keys(e), r = Object.keys(t);
|
|
21
|
+
return n.length === r.length && n.every((n) => Object.hasOwn(t, n) && deepEqual(e[n], t[n]));
|
|
22
|
+
}
|
|
23
|
+
return !1;
|
|
24
|
+
}
|
|
7
25
|
// src/patch.ts
|
|
8
26
|
function parsePointer(e) {
|
|
9
27
|
if (e === "") return [];
|
|
@@ -13,9 +31,6 @@ function parsePointer(e) {
|
|
|
13
31
|
function formatPointer(e) {
|
|
14
32
|
return e.map((e) => `/${e.replaceAll("~", "~0").replaceAll("/", "~1")}`).join("");
|
|
15
33
|
}
|
|
16
|
-
function isPlainObject(e) {
|
|
17
|
-
return typeof e == "object" && !!e && !Array.isArray(e);
|
|
18
|
-
}
|
|
19
34
|
function isArrayIndex(e) {
|
|
20
35
|
if (/^(0|[1-9]\d*)$/.test(e)) {
|
|
21
36
|
let t = Number(e);
|
|
@@ -41,15 +56,6 @@ function resolve(e, t) {
|
|
|
41
56
|
function getIn(e, t) {
|
|
42
57
|
return resolve(e, parsePointer(t)).value;
|
|
43
58
|
}
|
|
44
|
-
function deepEqual(e, t) {
|
|
45
|
-
if (e === t) return !0;
|
|
46
|
-
if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => deepEqual(e, t[n]));
|
|
47
|
-
if (isPlainObject(e) && isPlainObject(t)) {
|
|
48
|
-
let n = Object.keys(e), r = Object.keys(t);
|
|
49
|
-
return n.length === r.length && n.every((n) => Object.hasOwn(t, n) && deepEqual(e[n], t[n]));
|
|
50
|
-
}
|
|
51
|
-
return !1;
|
|
52
|
-
}
|
|
53
59
|
function descendArray(e, t, n) {
|
|
54
60
|
let r = isArrayIndex(t);
|
|
55
61
|
if (r < 0 || r >= e.length) throw new PatchPathError(`cannot ${n} at "/${t}": index out of bounds`);
|
|
@@ -147,21 +153,31 @@ function removeIn(e, t) {
|
|
|
147
153
|
}
|
|
148
154
|
function requireValue(e, t, n) {
|
|
149
155
|
let r = resolve(e, t);
|
|
150
|
-
if (!r.exists) throw new PatchPathError(`pointer "${n}" does not resolve
|
|
156
|
+
if (!r.exists) throw new PatchPathError(`pointer "${n}" does not resolve`, { pointer: n });
|
|
151
157
|
return r.value;
|
|
152
158
|
}
|
|
159
|
+
function at(e, t) {
|
|
160
|
+
try {
|
|
161
|
+
return t();
|
|
162
|
+
} catch (t) {
|
|
163
|
+
throw t instanceof PatchPathError && t.pointer === void 0 ? new PatchPathError(t.message, {
|
|
164
|
+
cause: t,
|
|
165
|
+
pointer: e
|
|
166
|
+
}) : t;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
153
169
|
function applyOperation(e, t) {
|
|
154
170
|
switch (t.op) {
|
|
155
|
-
case "add": return addIn(e, parsePointer(t.path), structuredClone(t.value));
|
|
156
|
-
case "remove": return removeIn(e, parsePointer(t.path));
|
|
157
|
-
case "replace": return replaceIn(e, parsePointer(t.path), structuredClone(t.value));
|
|
171
|
+
case "add": return at(t.path, () => addIn(e, parsePointer(t.path), structuredClone(t.value)));
|
|
172
|
+
case "remove": return at(t.path, () => removeIn(e, parsePointer(t.path)));
|
|
173
|
+
case "replace": return at(t.path, () => replaceIn(e, parsePointer(t.path), structuredClone(t.value)));
|
|
158
174
|
case "move": {
|
|
159
|
-
let n = requireValue(e, parsePointer(t.from), t.from);
|
|
160
|
-
return
|
|
175
|
+
let n = at(t.from, () => requireValue(e, parsePointer(t.from), t.from)), r = at(t.from, () => removeIn(e, parsePointer(t.from)));
|
|
176
|
+
return at(t.path, () => addIn(r, parsePointer(t.path), n));
|
|
161
177
|
}
|
|
162
178
|
case "copy": {
|
|
163
|
-
let n = requireValue(e, parsePointer(t.from), t.from);
|
|
164
|
-
return addIn(e, parsePointer(t.path), structuredClone(n));
|
|
179
|
+
let n = at(t.from, () => requireValue(e, parsePointer(t.from), t.from));
|
|
180
|
+
return at(t.path, () => addIn(e, parsePointer(t.path), structuredClone(n)));
|
|
165
181
|
}
|
|
166
182
|
case "test": {
|
|
167
183
|
let n = resolve(e, parsePointer(t.path));
|
|
@@ -182,7 +198,7 @@ function tryApply(e, t) {
|
|
|
182
198
|
try {
|
|
183
199
|
n = applyOperation(n, r);
|
|
184
200
|
} catch (t) {
|
|
185
|
-
let n = t instanceof PatchTestError ? "test" : "path", i =
|
|
201
|
+
let n = t instanceof PatchTestError ? "test" : "path", i = t instanceof PatchPathError ? t.pointer ?? r.path : r.path;
|
|
186
202
|
return {
|
|
187
203
|
error: {
|
|
188
204
|
index: e,
|
|
@@ -202,17 +218,20 @@ function tryApply(e, t) {
|
|
|
202
218
|
function diffNode(e, t, n, r) {
|
|
203
219
|
if (!deepEqual(t, n)) {
|
|
204
220
|
if (Array.isArray(t) && Array.isArray(n)) {
|
|
205
|
-
let i = 0;
|
|
206
|
-
for (;
|
|
207
|
-
let
|
|
208
|
-
for (
|
|
209
|
-
|
|
221
|
+
let i = Math.min(t.length, n.length), a = 0;
|
|
222
|
+
for (; a < i && deepEqual(t[a], n[a]);) a += 1;
|
|
223
|
+
let o = 0;
|
|
224
|
+
for (; o < i - a && deepEqual(t[t.length - 1 - o], n[n.length - 1 - o]);) o += 1;
|
|
225
|
+
let s = t.length - o, c = n.length - o, l = Math.min(s, c) - a;
|
|
226
|
+
for (let i = a; i < a + l; i += 1) diffNode(`${e}/${i}`, t[i], n[i], r);
|
|
227
|
+
for (let t = s - 1; t >= a + l; --t) r.push({
|
|
210
228
|
op: "remove",
|
|
211
|
-
path: `${e}/${
|
|
229
|
+
path: `${e}/${t}`
|
|
212
230
|
});
|
|
213
|
-
|
|
231
|
+
let u = o === 0;
|
|
232
|
+
for (let t = a + l; t < c; t += 1) r.push({
|
|
214
233
|
op: "add",
|
|
215
|
-
path: `${e}
|
|
234
|
+
path: u ? `${e}/-` : `${e}/${t}`,
|
|
216
235
|
value: n[t]
|
|
217
236
|
});
|
|
218
237
|
} else if (isPlainObject(t) && isPlainObject(n)) {
|
package/dist/patchwork.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"patchwork.js","names":["message","options","pointer","token","tokens","value","index","current","doc","a","b","item","aKeys","bKeys","key","action","rest","next","found","operation","patch","error","reason","path","from","to","common","headLength","ops","i","childPath","toValue"],"sources":["../src/errors.ts","../src/patch.ts"],"sourcesContent":["/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** The document could not be patched because a pointer did not resolve. */\nexport class PatchPathError extends PatchError {}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","import { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Structural equality (JSON domain: no NaN/undefined/prototype concerns)\n// ---------------------------------------------------------------------------\n\nfunction deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`);\n return found.value as JsonValue;\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return addIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'remove':\n return removeIn(doc, parsePointer(operation.path));\n case 'replace':\n return replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value));\n case 'move': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(removeIn(doc, parsePointer(operation.from)), parsePointer(operation.path), value);\n }\n case 'copy': {\n const value = requireValue(doc, parsePointer(operation.from), operation.from);\n return addIn(doc, parsePointer(operation.path), structuredClone(value));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = operation.op === 'move' || operation.op === 'copy' ? operation.from : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Trim the common suffix, then walk positionally: equal entries skip,\n // changed entries recurse, surplus tails add or remove in apply-safe order.\n let common = 0;\n while (\n common < Math.min(from.length, to.length) &&\n deepEqual(from[from.length - 1 - common] as JsonValue, to[to.length - 1 - common] as JsonValue)\n ) {\n common += 1;\n }\n const headLength = Math.min(from.length, to.length) - common;\n for (let i = 0; i < headLength; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = from.length - 1 - common; i >= headLength; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n for (let i = headLength; i < to.length - common; i += 1) {\n ops.push({ op: 'add', path: `${path}/-`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays trim\n * their common suffix and emit ordered add/remove tails, so append-only\n * lists stay small. The result applies cleanly via {@link apply}.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":";AACA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAGnD,AAFA,MAAMA,GAASC,CAAO,GACtB,KAAK,OAAO,WAAW,MACvB,OAAO,eAAe,MAAM,WAAW,SAAS;CAClD;AACF,GAGa,iBAAb,cAAoC,WAAW,CAAC,GAGnC,iBAAb,cAAoC,WAAW,CAAC;;ACLhD,SAAgB,aAAa,GAAgC;CAC3D,IAAIC,MAAY,IAAI,OAAO,CAAC;CAC5B,IAAI,CAACA,EAAQ,WAAW,GAAG,GAAG,MAAM,IAAI,eAAe,YAAYA,EAAQ,sBAAsB;CACjG,OAAOA,EACJ,MAAM,CAAC,CAAC,CACR,MAAM,GAAG,CAAC,CACV,KAAK,MAAUC,EAAM,WAAW,MAAM,GAAG,CAAC,CAAC,WAAW,MAAM,GAAG,CAAC;AACrE;AAGA,SAAgB,cAAc,GAAwC;CACpE,OAAOC,EAAO,KAAK,MAAU,IAAID,EAAM,WAAW,KAAK,IAAI,CAAC,CAAC,WAAW,KAAK,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE;AAC/F;AAEA,SAAS,cAAc,GAAmD;CACxE,OAAO,OAAOE,KAAU,cAAYA,KAAkB,CAAC,MAAM,QAAQA,CAAK;AAC5E;AAEA,SAAS,aAAa,GAAuB;CAC3C,IAAI,iBAAiB,KAAKF,CAAK,GAAG;EAChC,IAAMG,IAAQ,OAAOH,CAAK;EAC1B,OAAOG,mBAAmCA,IAAQ;CACpD;CACA,OAAO;AACT;AAGA,SAAS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key","pointer","token","tokens","current","doc","action","rest","next","found","run","error","operation","removed","patch","reason","path","from","to","shared","head","tail","fromMiddle","toMiddle","overlap","ops","i","appends","childPath","toValue"],"sources":["../src/errors.ts","../src/_equality.ts","../src/patch.ts"],"sourcesContent":["import type { JsonPointer } from './types';\n\n/** Base class for all patchwork errors. */\nexport class PatchError extends Error {\n constructor(message: string, options?: ErrorOptions) {\n super(message, options);\n this.name = new.target.name;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * The document could not be patched because a pointer did not resolve. `pointer` names the\n * offending pointer when the library can attribute one (the failing `path` of a `move` is\n * not its `from`).\n */\nexport class PatchPathError extends PatchError {\n readonly pointer: JsonPointer | undefined;\n\n constructor(message: string, options?: ErrorOptions & { pointer?: JsonPointer }) {\n super(message, options);\n this.pointer = options?.pointer;\n }\n}\n\n/** A `test` operation did not match the document. */\nexport class PatchTestError extends PatchError {}\n","/**\n * Internal JSON-domain helpers shared by the patch engine and the merge module.\n * Never re-exported from the package barrel.\n */\nimport type { JsonObject, JsonValue } from './types';\n\nexport function isPlainObject(value: JsonValue | undefined): value is JsonObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/** Structural equality over the JSON domain: no NaN/undefined/prototype concerns. */\nexport function deepEqual(a: JsonValue, b: JsonValue): boolean {\n if (a === b) return true;\n if (Array.isArray(a) && Array.isArray(b)) {\n return a.length === b.length && a.every((item, index) => deepEqual(item, b[index] as JsonValue));\n }\n if (isPlainObject(a) && isPlainObject(b)) {\n const aKeys = Object.keys(a);\n const bKeys = Object.keys(b);\n return (\n aKeys.length === bKeys.length &&\n aKeys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key] as JsonValue, b[key] as JsonValue))\n );\n }\n return false;\n}\n","import { deepEqual, isPlainObject } from './_equality';\nimport { PatchPathError, PatchTestError } from './errors';\nimport type { ApplyResult, JsonObject, JsonPatch, JsonPointer, JsonValue, PatchOperation } from './types';\n\n// ---------------------------------------------------------------------------\n// RFC 6901 pointers\n// ---------------------------------------------------------------------------\n\n/** Split a JSON Pointer into decoded reference tokens (`~1` → `/`, `~0` → `~`). */\nexport function parsePointer(pointer: JsonPointer): string[] {\n if (pointer === '') return [];\n if (!pointer.startsWith('/')) throw new PatchPathError(`pointer \"${pointer}\" must start with \"/\"`);\n return pointer\n .slice(1)\n .split('/')\n .map((token) => token.replaceAll('~1', '/').replaceAll('~0', '~'));\n}\n\n/** Escape and join reference tokens into a JSON Pointer. */\nexport function formatPointer(tokens: readonly string[]): JsonPointer {\n return tokens.map((token) => `/${token.replaceAll('~', '~0').replaceAll('/', '~1')}`).join('');\n}\n\nfunction isArrayIndex(token: string): number {\n if (/^(0|[1-9]\\d*)$/.test(token)) {\n const index = Number(token);\n return index <= Number.MAX_SAFE_INTEGER ? index : -1;\n }\n return -1;\n}\n\n/** Resolve a pointer, distinguishing \"targets null\" from \"does not exist\". */\nfunction resolve(doc: JsonValue, tokens: readonly string[]): { exists: boolean; value?: JsonValue } {\n let current: JsonValue | undefined = doc;\n for (const token of tokens) {\n if (Array.isArray(current)) {\n const index = isArrayIndex(token);\n current = index >= 0 && index < current.length ? current[index] : undefined;\n } else if (isPlainObject(current)) {\n current = Object.hasOwn(current, token) ? current[token] : undefined;\n } else {\n return { exists: false };\n }\n if (current === undefined) return { exists: false };\n }\n return { exists: true, value: current };\n}\n\n/** Read the value a pointer targets; returns `undefined` when it does not resolve. */\nexport function getIn(doc: JsonValue, pointer: JsonPointer): JsonValue | undefined {\n return resolve(doc, parsePointer(pointer)).value;\n}\n\n// ---------------------------------------------------------------------------\n// Copy-on-write path updates (untouched subtrees keep their identity)\n// ---------------------------------------------------------------------------\n\nfunction descendArray(doc: readonly JsonValue[], token: string, action: string): number {\n const index = isArrayIndex(token);\n if (index < 0 || index >= doc.length) {\n throw new PatchPathError(`cannot ${action} at \"/${token}\": index out of bounds`);\n }\n return index;\n}\n\n/** Insert (arrays) or set (objects); `add` semantics: index may equal the array length. */\nfunction addIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n if (token === '-') {\n if (rest.length > 0) throw new PatchPathError(`cannot add \"/-\": \"-\" must be the final token`);\n return [...doc, value];\n }\n const index = isArrayIndex(token);\n if (index < 0 || index > doc.length) {\n throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n }\n if (rest.length > 0) {\n if (index === doc.length) throw new PatchPathError(`cannot add \"/${token}\": index out of bounds`);\n return [...doc.slice(0, index), addIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), value, ...doc.slice(index)];\n }\n if (isPlainObject(doc)) {\n if (rest.length > 0) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot add \"/${token}\": member does not exist`);\n return { ...doc, [token]: addIn(doc[token] as JsonValue, rest, value) };\n }\n if (Object.hasOwn(doc, token) && deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Replace in place; the target location must already exist (RFC 6902). */\nfunction replaceIn(doc: JsonValue, tokens: readonly string[], value: JsonValue): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return value;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'replace');\n if (rest.length === 0) {\n if (deepEqual(doc[index] as JsonValue, value)) return doc;\n return [...doc.slice(0, index), value, ...doc.slice(index + 1)];\n }\n return [...doc.slice(0, index), replaceIn(doc[index] as JsonValue, rest, value), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot replace \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n if (deepEqual(doc[token] as JsonValue, value)) return doc;\n return { ...doc, [token]: value };\n }\n return { ...doc, [token]: replaceIn(doc[token] as JsonValue, rest, value) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\n/** Remove the member/index the pointer targets; it must exist. */\nfunction removeIn(doc: JsonValue, tokens: readonly string[]): JsonValue {\n const [token = '', ...rest] = tokens;\n if (tokens.length === 0) return null;\n if (Array.isArray(doc)) {\n const index = descendArray(doc, token, 'remove');\n if (rest.length === 0) return [...doc.slice(0, index), ...doc.slice(index + 1)];\n return [...doc.slice(0, index), removeIn(doc[index] as JsonValue, rest), ...doc.slice(index + 1)];\n }\n if (isPlainObject(doc)) {\n if (!Object.hasOwn(doc, token)) throw new PatchPathError(`cannot remove \"/${token}\": member does not exist`);\n if (rest.length === 0) {\n const next: JsonObject = { ...doc };\n delete next[token];\n return next;\n }\n return { ...doc, [token]: removeIn(doc[token] as JsonValue, rest) };\n }\n throw new PatchPathError(`cannot descend into a ${typeof doc}`);\n}\n\nfunction requireValue(doc: JsonValue, tokens: readonly string[], pointer: JsonPointer): JsonValue {\n const found = resolve(doc, tokens);\n if (!found.exists) throw new PatchPathError(`pointer \"${pointer}\" does not resolve`, { pointer });\n return found.value as JsonValue;\n}\n\n/** Attributes path failures thrown inside `run` to `pointer` (the caller's full pointer). */\nfunction at<T>(pointer: JsonPointer, run: () => T): T {\n try {\n return run();\n } catch (error) {\n if (error instanceof PatchPathError && error.pointer === undefined) {\n throw new PatchPathError(error.message, { cause: error, pointer });\n }\n throw error;\n }\n}\n\n// ---------------------------------------------------------------------------\n// RFC 6902 apply / tryApply\n// ---------------------------------------------------------------------------\n\nfunction applyOperation(doc: JsonValue, operation: PatchOperation): JsonValue {\n switch (operation.op) {\n case 'add':\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'remove':\n return at(operation.path, () => removeIn(doc, parsePointer(operation.path)));\n case 'replace':\n return at(operation.path, () => replaceIn(doc, parsePointer(operation.path), structuredClone(operation.value)));\n case 'move': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n const removed = at(operation.from, () => removeIn(doc, parsePointer(operation.from)));\n return at(operation.path, () => addIn(removed, parsePointer(operation.path), value));\n }\n case 'copy': {\n const value = at(operation.from, () => requireValue(doc, parsePointer(operation.from), operation.from));\n return at(operation.path, () => addIn(doc, parsePointer(operation.path), structuredClone(value)));\n }\n case 'test': {\n const found = resolve(doc, parsePointer(operation.path));\n if (!found.exists || !deepEqual(found.value as JsonValue, operation.value)) {\n throw new PatchTestError(`test failed at \"${operation.path}\"`);\n }\n return doc;\n }\n }\n}\n\n/**\n * Apply an RFC 6902 patch immutably: untouched subtrees keep their identity,\n * so consumers can diff by reference afterwards. Throws {@link PatchPathError}\n * when a pointer does not resolve and {@link PatchTestError} when a `test`\n * operation does not match — use {@link tryApply} in protocol code where a\n * rejection is an ordinary answer rather than an exception.\n */\nexport function apply<T extends JsonValue>(doc: T, patch: JsonPatch): T {\n let current: JsonValue = doc;\n for (const operation of patch) current = applyOperation(current, operation);\n return current as T;\n}\n\n/** Non-throwing {@link apply}: returns the patched doc or a structured rejection with the failing index. */\nexport function tryApply(doc: JsonValue, patch: JsonPatch): ApplyResult {\n let current: JsonValue = doc;\n for (let index = 0; index < patch.length; index += 1) {\n const operation = patch[index] as PatchOperation;\n try {\n current = applyOperation(current, operation);\n } catch (error) {\n const reason = error instanceof PatchTestError ? 'test' : 'path';\n const path = error instanceof PatchPathError ? (error.pointer ?? operation.path) : operation.path;\n return { error: { index, message: (error as Error).message, path, reason }, ok: false };\n }\n }\n return { doc: current, ok: true };\n}\n\n// ---------------------------------------------------------------------------\n// diff\n// ---------------------------------------------------------------------------\n\nfunction diffNode(path: string, from: JsonValue, to: JsonValue, ops: PatchOperation[]): void {\n if (deepEqual(from, to)) return;\n if (Array.isArray(from) && Array.isArray(to)) {\n // Align on the common prefix and (non-overlapping) common suffix, recurse positionally\n // through the middle, then let surplus removals fall off the middle's tail (descending)\n // and surplus inserts land in ascending index order. True appends keep the `-` token.\n const shared = Math.min(from.length, to.length);\n let head = 0;\n while (head < shared && deepEqual(from[head] as JsonValue, to[head] as JsonValue)) head += 1;\n let tail = 0;\n while (\n tail < shared - head &&\n deepEqual(from[from.length - 1 - tail] as JsonValue, to[to.length - 1 - tail] as JsonValue)\n ) {\n tail += 1;\n }\n const fromMiddle = from.length - tail; // exclusive end of from's middle\n const toMiddle = to.length - tail; // exclusive end of to's middle\n const overlap = Math.min(fromMiddle, toMiddle) - head;\n for (let i = head; i < head + overlap; i += 1) {\n diffNode(`${path}/${i}`, from[i] as JsonValue, to[i] as JsonValue, ops);\n }\n for (let i = fromMiddle - 1; i >= head + overlap; i -= 1) {\n ops.push({ op: 'remove', path: `${path}/${i}` });\n }\n const appends = tail === 0; // surplus only ever lands at the end when no tail is shared\n for (let i = head + overlap; i < toMiddle; i += 1) {\n ops.push({ op: 'add', path: appends ? `${path}/-` : `${path}/${i}`, value: to[i] as JsonValue });\n }\n return;\n }\n if (isPlainObject(from) && isPlainObject(to)) {\n for (const key of Object.keys(from)) {\n if (!Object.hasOwn(to, key)) ops.push({ op: 'remove', path: `${path}${formatPointer([key])}` });\n }\n for (const key of Object.keys(to)) {\n const childPath = `${path}${formatPointer([key])}`;\n const toValue = to[key] as JsonValue;\n if (!Object.hasOwn(from, key)) {\n ops.push({ op: 'add', path: childPath, value: toValue });\n } else {\n diffNode(childPath, from[key] as JsonValue, toValue, ops);\n }\n }\n return;\n }\n ops.push({ op: 'replace', path, value: to });\n}\n\n/**\n * Compute an RFC 6902 patch that transforms `from` into `to`. Object keys\n * diff field-by-field (the payload win sync protocols want); arrays align\n * on their common prefix and suffix and emit ordered removals and indexed\n * inserts around a positionally diffed middle, so appends, prepends, and\n * middle inserts each stay one operation. Not minimal-edit: a reorder\n * diffs positionally. The result always round-trips:\n * `apply(from, diff(from, to))` deep-equals `to`.\n */\nexport function diff(from: JsonValue, to: JsonValue): JsonPatch {\n const ops: PatchOperation[] = [];\n diffNode('', from, to, ops);\n return ops;\n}\n"],"mappings":";AAGA,IAAa,aAAb,cAAgC,MAAM;CACpC,YAAY,GAAiB,GAAwB;EAGnD,AA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AUX,EAAGlB;IACnB,AAAK,OAAO,OAAOiB,GAAMjB,CAAG,IAG1B,SAAS4B,GAAWX,EAAKjB,IAAmB6B,GAASJ,CAAG,IAFxDA,EAAI,KAAK;KAAE,IAAI;KAAO,MAAMG;KAAW,OAAOC;IAAQ,CAAC;GAI3D;EAEF,OACA,EAAI,KAAK;GAAE,IAAI;GAAW;GAAM,OAAOX;EAAG,CAAC;CAhB3C;AAiBF;AAWA,SAAgB,KAAK,GAAiB,GAA0B;CAC9D,IAAMO,IAAwB,CAAC;CAE/B,OADA,SAAS,IAAIR,GAAMC,GAAIO,CAAG,GACnBA;AACT"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vielzeug/patchwork",
|
|
3
|
-
"version": "26.11.
|
|
3
|
+
"version": "26.11.15",
|
|
4
4
|
"description": "RFC 6902 JSON Patch: structural diff, immutable apply, and guarded tryApply for sync protocols.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -23,6 +23,18 @@
|
|
|
23
23
|
"import": "./dist/index.js",
|
|
24
24
|
"require": "./dist/index.cjs",
|
|
25
25
|
"types": "./dist/index.d.ts"
|
|
26
|
+
},
|
|
27
|
+
"./merge": {
|
|
28
|
+
"import": "./dist/merge.js",
|
|
29
|
+
"require": "./dist/merge.cjs",
|
|
30
|
+
"types": "./dist/merge.d.ts"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"typesVersions": {
|
|
34
|
+
"*": {
|
|
35
|
+
"merge": [
|
|
36
|
+
"dist/merge.d.ts"
|
|
37
|
+
]
|
|
26
38
|
}
|
|
27
39
|
},
|
|
28
40
|
"sideEffects": false,
|