@sanity/mutator 5.0.1-next.7 → 5.0.1
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/lib/index.js +1 -5
- package/lib/index.js.map +1 -1
- package/package.json +9 -9
package/lib/index.js
CHANGED
|
@@ -1,11 +1,7 @@
|
|
|
1
|
-
import isEqual from "lodash
|
|
1
|
+
import { flatten, compact, max, min, isEqual } from "lodash-es";
|
|
2
2
|
import debugIt from "debug";
|
|
3
|
-
import flatten from "lodash/flatten.js";
|
|
4
3
|
import { parsePatch as parsePatch$1, applyPatches, stringifyPatches, makePatches } from "@sanity/diff-match-patch";
|
|
5
|
-
import max from "lodash/max.js";
|
|
6
|
-
import min from "lodash/min.js";
|
|
7
4
|
import { uuid } from "@sanity/uuid";
|
|
8
|
-
import compact from "lodash/compact.js";
|
|
9
5
|
const debug = debugIt("mutator-document");
|
|
10
6
|
class ImmutableAccessor {
|
|
11
7
|
_value;
|
package/lib/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/document/debug.ts","../src/patch/ImmutableAccessor.ts","../src/util.ts","../src/jsonpath/arrayToJSONMatchPath.ts","../src/jsonpath/descend.ts","../src/jsonpath/tokenize.ts","../src/jsonpath/parse.ts","../src/jsonpath/toPath.ts","../src/jsonpath/Expression.ts","../src/jsonpath/Descender.ts","../src/jsonpath/Matcher.ts","../src/jsonpath/PlainProbe.ts","../src/jsonpath/extractAccessors.ts","../src/jsonpath/extract.ts","../src/jsonpath/extractWithPath.ts","../src/patch/DiffMatchPatch.ts","../src/patch/IncPatch.ts","../src/patch/util.ts","../src/patch/InsertPatch.ts","../src/patch/SetIfMissingPatch.ts","../src/patch/SetPatch.ts","../src/patch/UnsetPatch.ts","../src/patch/parse.ts","../src/patch/Patcher.ts","../src/document/luid.ts","../src/document/Mutation.ts","../src/document/Document.ts","../src/document/SquashingBuffer.ts","../src/document/BufferedDocument.ts"],"sourcesContent":["import debugIt from 'debug'\n\nexport const debug = debugIt('mutator-document')\n","import {type Probe} from '../jsonpath/Probe'\n\n/**\n * An immutable probe/writer for plain JS objects that will never mutate\n * the provided _value in place. Each setter returns a new (wrapped) version\n * of the value.\n */\nexport class ImmutableAccessor implements Probe {\n _value: unknown\n path: (string | number)[]\n\n constructor(value: unknown, path?: (string | number)[]) {\n this._value = value\n this.path = path || []\n }\n\n containerType(): 'array' | 'object' | 'primitive' {\n if (Array.isArray(this._value)) {\n return 'array'\n } else if (this._value !== null && typeof this._value === 'object') {\n return 'object'\n }\n return 'primitive'\n }\n\n // Common reader, supported by all containers\n get(): unknown {\n return this._value\n }\n\n // Array reader\n length(): number {\n if (!Array.isArray(this._value)) {\n throw new Error(\"Won't return length of non-indexable _value\")\n }\n\n return this._value.length\n }\n\n getIndex(i: number): ImmutableAccessor | false | null {\n if (!Array.isArray(this._value)) {\n return false\n }\n\n if (i >= this.length()) {\n return null\n }\n\n return new ImmutableAccessor(this._value[i], this.path.concat(i))\n }\n\n // Object reader\n hasAttribute(key: string): boolean {\n return isRecord(this._value) ? this._value.hasOwnProperty(key) : false\n }\n\n attributeKeys(): string[] {\n return isRecord(this._value) ? Object.keys(this._value) : []\n }\n\n getAttribute(key: string): ImmutableAccessor | null {\n if (!isRecord(this._value)) {\n throw new Error('getAttribute only applies to plain objects')\n }\n\n if (!this.hasAttribute(key)) {\n return null\n }\n\n return new ImmutableAccessor(this._value[key], this.path.concat(key))\n }\n\n // Common writer, supported by all containers\n set(value: unknown): ImmutableAccessor {\n return value === this._value ? this : new ImmutableAccessor(value, this.path)\n }\n\n // array writer interface\n setIndex(i: number, value: unknown): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('setIndex only applies to arrays')\n }\n\n if (Object.is(value, this._value[i])) {\n return this\n }\n\n const nextValue = this._value.slice()\n nextValue[i] = value\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n setIndexAccessor(i: number, accessor: ImmutableAccessor): ImmutableAccessor {\n return this.setIndex(i, accessor.get())\n }\n\n unsetIndices(indices: number[]): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('unsetIndices only applies to arrays')\n }\n\n const length = this._value.length\n const nextValue = []\n // Copy every _value _not_ in the indices array over to the newValue\n for (let i = 0; i < length; i++) {\n if (indices.indexOf(i) === -1) {\n nextValue.push(this._value[i])\n }\n }\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n insertItemsAt(pos: number, items: unknown[]): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('insertItemsAt only applies to arrays')\n }\n\n let nextValue\n if (this._value.length === 0 && pos === 0) {\n nextValue = items\n } else {\n nextValue = this._value.slice(0, pos).concat(items).concat(this._value.slice(pos))\n }\n\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n // Object writer interface\n setAttribute(key: string, value: unknown): ImmutableAccessor {\n if (!isRecord(this._value)) {\n throw new Error('Unable to set attribute of non-object container')\n }\n\n if (Object.is(value, this._value[key])) {\n return this\n }\n\n const nextValue = Object.assign({}, this._value, {[key]: value})\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n setAttributeAccessor(key: string, accessor: ImmutableAccessor): ImmutableAccessor {\n return this.setAttribute(key, accessor.get())\n }\n\n unsetAttribute(key: string): ImmutableAccessor {\n if (!isRecord(this._value)) {\n throw new Error('Unable to unset attribute of non-object container')\n }\n\n const nextValue = Object.assign({}, this._value)\n delete nextValue[key]\n return new ImmutableAccessor(nextValue, this.path)\n }\n}\n\nfunction isRecord(value: unknown): value is {[key: string]: unknown} {\n return value !== null && typeof value === 'object'\n}\n","export function isRecord(value: unknown): value is {[key: string]: unknown} {\n return value !== null && typeof value === 'object'\n}\n","import {type Path, type PathSegment} from '@sanity/types'\n\nimport {isRecord} from '../util'\n\nconst IS_DOTTABLE = /^[a-z_$]+/\n\n/**\n * Converts a path in array form to a JSONPath string\n *\n * @param pathArray - Array of path segments\n * @returns String representation of the path\n * @internal\n */\nexport function arrayToJSONMatchPath(pathArray: Path): string {\n let path = ''\n pathArray.forEach((segment, index) => {\n path += stringifySegment(segment, index === 0)\n })\n return path\n}\n\n// Converts an array of simple values (strings, numbers only) to a jsonmatch path string.\nfunction stringifySegment(\n segment: PathSegment | Record<string, unknown>,\n hasLeading: boolean,\n): string {\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (isRecord(segment)) {\n const seg = segment as Record<string, unknown>\n return Object.keys(segment)\n .map((key) => (isPrimitiveValue(seg[key]) ? `[${key}==\"${seg[key]}\"]` : ''))\n .join('')\n }\n\n if (typeof segment === 'string' && IS_DOTTABLE.test(segment)) {\n return hasLeading ? segment : `.${segment}`\n }\n\n return `['${segment}']`\n}\n\nfunction isPrimitiveValue(val: unknown): val is string | number | boolean {\n switch (typeof val) {\n case 'number':\n case 'string':\n case 'boolean':\n return true\n default:\n return false\n }\n}\n","import {type Expr, type PathExpr} from './types'\n\n/**\n * Splits an expression into a set of heads, tails. A head is the next leaf node to\n * check for matches, and a tail is everything that follows it. Matching is done by\n * matching heads, then proceedint to the matching value, splitting the tail into\n * heads and tails and checking the heads against the new value, and so on.\n */\nexport function descend(tail: Expr): [Expr | null, PathExpr | null][] {\n const [head, newTail] = splitIfPath(tail)\n if (!head) {\n throw new Error('Head cannot be null')\n }\n\n return spreadIfUnionHead(head, newTail)\n}\n\n// Split path in [head, tail]\nfunction splitIfPath(tail: Expr): [Expr | null, PathExpr | null] {\n if (tail.type !== 'path') {\n return [tail, null]\n }\n\n const nodes = tail.nodes\n if (nodes.length === 0) {\n return [null, null]\n }\n\n if (nodes.length === 1) {\n return [nodes[0], null]\n }\n\n return [nodes[0], {type: 'path', nodes: nodes.slice(1)}]\n}\n\nfunction concatPaths(path1: PathExpr | null, path2: PathExpr | null): PathExpr | null {\n if (!path1 && !path2) {\n return null\n }\n\n const nodes1 = path1 ? path1.nodes : []\n const nodes2 = path2 ? path2.nodes : []\n return {\n type: 'path',\n nodes: nodes1.concat(nodes2),\n }\n}\n\n// Spreads a union head into several heads/tails\nfunction spreadIfUnionHead(head: Expr, tail: PathExpr | null): [Expr | null, PathExpr | null][] {\n if (head.type !== 'union') {\n return [[head, tail]]\n }\n\n return head.nodes.map((node) => {\n if (node.type === 'path') {\n const [subHead, subTail] = splitIfPath(node)\n return [subHead, concatPaths(subTail, tail)]\n }\n\n return [node, tail]\n })\n}\n","import {\n type IdentifierToken,\n type NumberToken,\n type QuotedToken,\n type SymbolClass,\n type SymbolToken,\n type Token,\n} from './types'\n\n// TODO: Support '*'\n\nconst digitChar = /[0-9]/\nconst attributeCharMatcher = /^[a-zA-Z0-9_]$/\nconst attributeFirstCharMatcher = /^[a-zA-Z_]$/\n\nconst symbols: Record<SymbolClass, string[]> = {\n // NOTE: These are compared against in order of definition,\n // thus '==' must come before '=', '>=' before '>', etc.\n operator: ['..', '.', ',', ':', '?'],\n comparator: ['>=', '<=', '<', '>', '==', '!='],\n keyword: ['$', '@'],\n boolean: ['true', 'false'],\n paren: ['[', ']'],\n}\n\nconst symbolClasses = Object.keys(symbols) as SymbolClass[]\n\ntype TokenizerFn = () => Token | null\n\n/**\n * Tokenizes a jsonpath2 expression\n */\nclass Tokenizer {\n source: string\n i: number\n length: number\n tokenizers: TokenizerFn[]\n\n constructor(path: string) {\n this.source = path\n this.length = path.length\n this.i = 0\n this.tokenizers = [\n this.tokenizeSymbol,\n this.tokenizeIdentifier,\n this.tokenizeNumber,\n this.tokenizeQuoted,\n ].map((fn) => fn.bind(this))\n }\n\n tokenize(): Token[] {\n const result: Token[] = []\n while (!this.EOF()) {\n this.chompWhitespace()\n let token: Token | null = null\n // @todo refactor into a simpler `.find()`?\n const found = this.tokenizers.some((tokenizer) => {\n token = tokenizer()\n return Boolean(token)\n })\n if (!found || !token) {\n throw new Error(`Invalid tokens in jsonpath '${this.source}' @ ${this.i}`)\n }\n result.push(token)\n }\n return result\n }\n\n takeWhile(fn: (character: string) => string | null): string | null {\n const start = this.i\n let result = ''\n while (!this.EOF()) {\n const nextChar = fn(this.source[this.i])\n if (nextChar === null) {\n break\n }\n result += nextChar\n this.i++\n }\n if (this.i === start) {\n return null\n }\n return result\n }\n\n EOF(): boolean {\n return this.i >= this.length\n }\n\n peek(): string | null {\n if (this.EOF()) {\n return null\n }\n return this.source[this.i]\n }\n\n consume(str: string) {\n if (this.i + str.length > this.length) {\n throw new Error(`Expected ${str} at end of jsonpath`)\n }\n if (str === this.source.slice(this.i, this.i + str.length)) {\n this.i += str.length\n } else {\n throw new Error(`Expected \"${str}\", but source contained \"${this.source.slice()}`)\n }\n }\n\n // Tries to match the upcoming bit of string with the provided string. If it matches, returns\n // the string, then advances the read pointer to the next bit. If not, returns null and nothing\n // happens.\n tryConsume(str: string) {\n if (this.i + str.length > this.length) {\n return null\n }\n if (str === this.source.slice(this.i, this.i + str.length)) {\n // When checking symbols that consist of valid attribute characters, we\n // need to make sure we don't inadvertently treat an attribute as a\n // symbol. For example, an attribute 'trueCustomerField' should not be\n // scanned as the boolean symbol \"true\".\n if (str[0].match(attributeCharMatcher)) {\n // check that char following the symbol match is not also an attribute char\n if (this.length > this.i + str.length) {\n const nextChar = this.source[this.i + str.length]\n if (nextChar && nextChar.match(attributeCharMatcher)) {\n return null\n }\n }\n }\n this.i += str.length\n return str\n }\n return null\n }\n\n chompWhitespace(): void {\n this.takeWhile((char): string | null => {\n return char === ' ' ? '' : null\n })\n }\n\n tokenizeQuoted(): QuotedToken | null {\n const quote = this.peek()\n if (quote === \"'\" || quote === '\"') {\n this.consume(quote)\n let escape = false\n const inner = this.takeWhile((char) => {\n if (escape) {\n escape = false\n return char\n }\n if (char === '\\\\') {\n escape = true\n return ''\n }\n if (char != quote) {\n return char\n }\n return null\n })\n this.consume(quote)\n return {\n type: 'quoted',\n value: inner,\n quote: quote === '\"' ? 'double' : 'single',\n }\n }\n return null\n }\n\n tokenizeIdentifier(): IdentifierToken | null {\n let first = true\n const identifier = this.takeWhile((char) => {\n if (first) {\n first = false\n return char.match(attributeFirstCharMatcher) ? char : null\n }\n return char.match(attributeCharMatcher) ? char : null\n })\n if (identifier !== null) {\n return {\n type: 'identifier',\n name: identifier,\n }\n }\n return null\n }\n\n tokenizeNumber(): NumberToken | null {\n const start = this.i\n let dotSeen = false\n let digitSeen = false\n let negative = false\n if (this.peek() === '-') {\n negative = true\n this.consume('-')\n }\n const number = this.takeWhile((char) => {\n if (char === '.' && !dotSeen && digitSeen) {\n dotSeen = true\n return char\n }\n digitSeen = true\n return char.match(digitChar) ? char : null\n })\n if (number !== null) {\n return {\n type: 'number',\n value: negative ? -Number(number) : +number,\n raw: negative ? `-${number}` : number,\n }\n }\n // No number, rewind\n this.i = start\n return null\n }\n\n tokenizeSymbol(): SymbolToken | null {\n for (const symbolClass of symbolClasses) {\n const patterns = symbols[symbolClass]\n const symbol = patterns.find((pattern) => this.tryConsume(pattern))\n if (symbol) {\n return {\n type: symbolClass,\n symbol,\n }\n }\n }\n\n return null\n }\n}\n\nexport function tokenize(jsonpath: string): Token[] {\n return new Tokenizer(jsonpath).tokenize()\n}\n","// Converts a string into an abstract syntax tree representation\n\nimport {tokenize} from './tokenize'\nimport {\n type AliasExpr,\n type AttributeExpr,\n type BooleanExpr,\n type ConstraintExpr,\n type IndexExpr,\n type NumberExpr,\n type PathExpr,\n type RangeExpr,\n type RecursiveExpr,\n type StringExpr,\n type Token,\n type UnionExpr,\n} from './types'\n\n// TODO: Support '*'\n\nclass Parser {\n tokens: Token[]\n length: number\n i: number\n\n constructor(path: string) {\n this.tokens = tokenize(path)\n this.length = this.tokens.length\n this.i = 0\n }\n\n parse() {\n return this.parsePath()\n }\n\n EOF() {\n return this.i >= this.length\n }\n\n // Look at upcoming token\n peek() {\n if (this.EOF()) {\n return null\n }\n return this.tokens[this.i]\n }\n\n consume() {\n const result = this.peek()\n this.i += 1\n return result\n }\n\n // Return next token if it matches the pattern\n probe(pattern: Record<string, unknown>): Token | null {\n const token = this.peek()\n if (!token) {\n return null\n }\n\n const record = token as unknown as Record<string, unknown>\n const match = Object.keys(pattern).every((key) => {\n return key in token && pattern[key] === record[key]\n })\n\n return match ? token : null\n }\n\n // Return and consume next token if it matches the pattern\n match(pattern: Partial<Token>): Token | null {\n return this.probe(pattern) ? this.consume() : null\n }\n\n parseAttribute(): AttributeExpr | null {\n const token = this.match({type: 'identifier'})\n if (token && token.type === 'identifier') {\n return {\n type: 'attribute',\n name: token.name,\n }\n }\n const quoted = this.match({type: 'quoted', quote: 'single'})\n if (quoted && quoted.type === 'quoted') {\n return {\n type: 'attribute',\n name: quoted.value || '',\n }\n }\n return null\n }\n\n parseAlias(): AliasExpr | null {\n if (this.match({type: 'keyword', symbol: '@'}) || this.match({type: 'keyword', symbol: '$'})) {\n return {\n type: 'alias',\n target: 'self',\n }\n }\n return null\n }\n\n parseNumber(): NumberExpr | null {\n const token = this.match({type: 'number'})\n if (token && token.type === 'number') {\n return {\n type: 'number',\n value: token.value,\n }\n }\n return null\n }\n\n parseNumberValue(): number | null {\n const expr = this.parseNumber()\n if (expr) {\n return expr.value\n }\n return null\n }\n\n parseSliceSelector(): RangeExpr | IndexExpr | null {\n const start = this.i\n const rangeStart = this.parseNumberValue()\n\n const colon1 = this.match({type: 'operator', symbol: ':'})\n if (!colon1) {\n if (rangeStart === null) {\n // Rewind, this was actually nothing\n this.i = start\n return null\n }\n\n // Unwrap, this was just a single index not followed by colon\n return {type: 'index', value: rangeStart}\n }\n\n const result: RangeExpr = {\n type: 'range',\n start: rangeStart,\n end: this.parseNumberValue(),\n }\n\n const colon2 = this.match({type: 'operator', symbol: ':'})\n if (colon2) {\n result.step = this.parseNumberValue()\n }\n\n if (result.start === null && result.end === null) {\n // rewind, this wasnt' a slice selector\n this.i = start\n return null\n }\n\n return result\n }\n\n parseValueReference(): AttributeExpr | RangeExpr | IndexExpr | null {\n return this.parseAttribute() || this.parseSliceSelector()\n }\n\n parseLiteralValue(): StringExpr | BooleanExpr | NumberExpr | null {\n const literalString = this.match({type: 'quoted', quote: 'double'})\n if (literalString && literalString.type === 'quoted') {\n return {\n type: 'string',\n value: literalString.value || '',\n }\n }\n const literalBoolean = this.match({type: 'boolean'})\n if (literalBoolean && literalBoolean.type === 'boolean') {\n return {\n type: 'boolean',\n value: literalBoolean.symbol === 'true',\n }\n }\n return this.parseNumber()\n }\n\n // TODO: Reorder constraints so that literal value is always on rhs, and variable is always\n // on lhs.\n parseFilterExpression(): ConstraintExpr | null {\n const start = this.i\n const expr = this.parseAttribute() || this.parseAlias()\n if (!expr) {\n return null\n }\n\n if (this.match({type: 'operator', symbol: '?'})) {\n return {\n type: 'constraint',\n operator: '?',\n lhs: expr,\n }\n }\n\n const binOp = this.match({type: 'comparator'})\n if (!binOp || binOp.type !== 'comparator') {\n // No expression, rewind!\n this.i = start\n return null\n }\n\n const lhs = expr\n const rhs = this.parseLiteralValue()\n if (!rhs) {\n throw new Error(`Operator ${binOp.symbol} needs a literal value at the right hand side`)\n }\n\n return {\n type: 'constraint',\n operator: binOp.symbol,\n lhs: lhs,\n rhs: rhs,\n }\n }\n\n parseExpression(): ConstraintExpr | AttributeExpr | RangeExpr | IndexExpr | null {\n return this.parseFilterExpression() || this.parseValueReference()\n }\n\n parseUnion(): UnionExpr | null {\n if (!this.match({type: 'paren', symbol: '['})) {\n return null\n }\n\n const terms = []\n let expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n while (expr) {\n terms.push(expr)\n // End of union?\n if (this.match({type: 'paren', symbol: ']'})) {\n break\n }\n\n if (!this.match({type: 'operator', symbol: ','})) {\n throw new Error('Expected ]')\n }\n\n expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n if (!expr) {\n throw new Error(\"Expected expression following ','\")\n }\n }\n\n return {\n type: 'union',\n nodes: terms,\n }\n }\n\n parseRecursive(): RecursiveExpr | null {\n if (!this.match({type: 'operator', symbol: '..'})) {\n return null\n }\n\n const subpath = this.parsePath()\n if (!subpath) {\n throw new Error(\"Expected path following '..' operator\")\n }\n\n return {\n type: 'recursive',\n term: subpath,\n }\n }\n\n parsePath(): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr | null {\n const nodes: (AttributeExpr | UnionExpr | RecursiveExpr)[] = []\n const expr = this.parseAttribute() || this.parseUnion() || this.parseRecursive()\n if (!expr) {\n return null\n }\n\n nodes.push(expr)\n while (!this.EOF()) {\n if (this.match({type: 'operator', symbol: '.'})) {\n const attr = this.parseAttribute()\n if (!attr) {\n throw new Error(\"Expected attribute name following '.\")\n }\n nodes.push(attr)\n continue\n } else if (this.probe({type: 'paren', symbol: '['})) {\n const union = this.parseUnion()\n if (!union) {\n throw new Error(\"Expected union following '['\")\n }\n nodes.push(union)\n } else {\n const recursive = this.parseRecursive()\n if (recursive) {\n nodes.push(recursive)\n }\n break\n }\n }\n\n if (nodes.length === 1) {\n return nodes[0]\n }\n\n return {\n type: 'path',\n nodes: nodes,\n }\n }\n}\n\nexport function parseJsonPath(path: string): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr {\n const parsed = new Parser(path).parse()\n if (!parsed) {\n throw new Error(`Failed to parse JSON path \"${path}\"`)\n }\n return parsed\n}\n","import {type Expr} from './types'\n\n/**\n * Converts a parsed expression back into jsonpath2, roughly -\n * mostly for use with tests.\n *\n * @param expr - Expression to convert to path\n * @returns a string representation of the path\n * @internal\n */\nexport function toPath(expr: Expr): string {\n return toPathInner(expr, false)\n}\n\nfunction toPathInner(expr: Expr, inUnion: boolean): string {\n switch (expr.type) {\n case 'attribute':\n return expr.name\n case 'alias':\n return expr.target === 'self' ? '@' : '$'\n case 'number':\n return `${expr.value}`\n case 'range': {\n const result = []\n if (!inUnion) {\n result.push('[')\n }\n if (expr.start) {\n result.push(`${expr.start}`)\n }\n result.push(':')\n if (expr.end) {\n result.push(`${expr.end}`)\n }\n if (expr.step) {\n result.push(`:${expr.step}`)\n }\n if (!inUnion) {\n result.push(']')\n }\n return result.join('')\n }\n case 'index':\n if (inUnion) {\n return `${expr.value}`\n }\n\n return `[${expr.value}]`\n case 'constraint': {\n const rhs = expr.rhs ? ` ${toPathInner(expr.rhs, false)}` : ''\n const inner = `${toPathInner(expr.lhs, false)} ${expr.operator}${rhs}`\n\n if (inUnion) {\n return inner\n }\n\n return `[${inner}]`\n }\n case 'string':\n return JSON.stringify(expr.value)\n case 'path': {\n const result = []\n const nodes = expr.nodes.slice()\n while (nodes.length > 0) {\n const node = nodes.shift()\n if (node) {\n result.push(toPath(node))\n }\n\n const upcoming = nodes[0]\n if (upcoming && toPathInner(upcoming, false)[0] !== '[') {\n result.push('.')\n }\n }\n return result.join('')\n }\n case 'union':\n return `[${expr.nodes.map((e) => toPathInner(e, true)).join(',')}]`\n default:\n throw new Error(`Unknown node type ${expr.type}`)\n case 'recursive':\n return `..${toPathInner(expr.term, false)}`\n }\n}\n","// A utility wrapper class to process parsed jsonpath expressions\n\nimport {descend} from './descend'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\nimport {toPath} from './toPath'\nimport {type Expr, type HeadTail} from './types'\n\nexport interface Range {\n start: number\n end: number\n step: number\n}\n\nexport class Expression {\n expr: Expr\n\n constructor(expr: Expr | Expression | null) {\n if (!expr) {\n throw new Error('Attempted to create Expression from null-value')\n }\n\n // This is a wrapped expr\n if ('expr' in expr) {\n this.expr = expr.expr\n } else {\n this.expr = expr\n }\n\n if (!('type' in this.expr)) {\n throw new Error('Attempt to create Expression for expression with no type')\n }\n }\n\n isPath(): boolean {\n return this.expr.type === 'path'\n }\n\n isUnion(): boolean {\n return this.expr.type === 'union'\n }\n\n isCollection(): boolean {\n return this.isPath() || this.isUnion()\n }\n\n isConstraint(): boolean {\n return this.expr.type === 'constraint'\n }\n\n isRecursive(): boolean {\n return this.expr.type === 'recursive'\n }\n\n isExistenceConstraint(): boolean {\n return this.expr.type === 'constraint' && this.expr.operator === '?'\n }\n\n isIndex(): boolean {\n return this.expr.type === 'index'\n }\n\n isRange(): boolean {\n return this.expr.type === 'range'\n }\n\n expandRange(probe?: Probe): Range {\n const probeLength = () => {\n if (!probe) {\n throw new Error('expandRange() required a probe that was not passed')\n }\n\n return probe.length()\n }\n\n let start = 'start' in this.expr ? this.expr.start || 0 : 0\n start = interpretNegativeIndex(start, probe)\n let end = 'end' in this.expr ? this.expr.end || probeLength() : probeLength()\n end = interpretNegativeIndex(end, probe)\n const step = 'step' in this.expr ? this.expr.step || 1 : 1\n return {start, end, step}\n }\n\n isAttributeReference(): boolean {\n return this.expr.type === 'attribute'\n }\n\n // Is a range or index -> something referencing indexes\n isIndexReference(): boolean {\n return this.isIndex() || this.isRange()\n }\n\n name(): string {\n return 'name' in this.expr ? this.expr.name : ''\n }\n\n isSelfReference(): boolean {\n return this.expr.type === 'alias' && this.expr.target === 'self'\n }\n\n constraintTargetIsSelf(): boolean {\n return (\n this.expr.type === 'constraint' &&\n this.expr.lhs.type === 'alias' &&\n this.expr.lhs.target === 'self'\n )\n }\n\n constraintTargetIsAttribute(): boolean {\n return this.expr.type === 'constraint' && this.expr.lhs.type === 'attribute'\n }\n\n testConstraint(probe: Probe): boolean {\n const expr = this.expr\n\n if (expr.type === 'constraint' && expr.lhs.type === 'alias' && expr.lhs.target === 'self') {\n if (probe.containerType() !== 'primitive') {\n return false\n }\n\n if (expr.type === 'constraint' && expr.operator === '?') {\n return true\n }\n\n const lhs = probe.get()\n const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n return testBinaryOperator(lhs, expr.operator, rhs)\n }\n\n if (expr.type !== 'constraint') {\n return false\n }\n\n const lhs = expr.lhs\n if (!lhs) {\n throw new Error('No LHS of expression')\n }\n\n if (lhs.type !== 'attribute') {\n throw new Error(`Constraint target ${lhs.type} not supported`)\n }\n\n if (probe.containerType() !== 'object') {\n return false\n }\n\n const lhsValue = probe.getAttribute(lhs.name)\n if (lhsValue === undefined || lhsValue === null || lhsValue.containerType() !== 'primitive') {\n // LHS is void and empty, or it is a collection\n return false\n }\n\n if (this.isExistenceConstraint()) {\n // There is no rhs, and if we're here the key did exist\n return true\n }\n\n const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n return testBinaryOperator(lhsValue.get(), expr.operator, rhs)\n }\n\n pathNodes(): Expr[] {\n return this.expr.type === 'path' ? this.expr.nodes : [this.expr]\n }\n\n prepend(node: Expression): Expression {\n if (!node) {\n return this\n }\n\n return new Expression({\n type: 'path',\n nodes: node.pathNodes().concat(this.pathNodes()),\n })\n }\n\n concat(other: Expression | null): Expression {\n return other ? other.prepend(this) : this\n }\n\n descend(): HeadTail[] {\n return descend(this.expr).map((headTail) => {\n const [head, tail] = headTail\n return {\n head: head ? new Expression(head) : null,\n tail: tail ? new Expression(tail) : null,\n }\n })\n }\n\n unwrapRecursive(): Expression {\n if (this.expr.type !== 'recursive') {\n throw new Error(`Attempt to unwrap recursive on type ${this.expr.type}`)\n }\n\n return new Expression(this.expr.term)\n }\n\n toIndicies(probe?: Probe): number[] {\n if (this.expr.type !== 'index' && this.expr.type !== 'range') {\n throw new Error('Node cannot be converted to indexes')\n }\n\n if (this.expr.type === 'index') {\n return [interpretNegativeIndex(this.expr.value, probe)]\n }\n\n const result: number[] = []\n const range = this.expandRange(probe)\n let {start, end} = range\n if (range.step < 0) {\n ;[start, end] = [end, start]\n }\n\n for (let i = start; i < end; i++) {\n result.push(i)\n }\n\n return result\n }\n\n toFieldReferences(): number[] | string[] {\n if (this.isIndexReference()) {\n return this.toIndicies()\n }\n if (this.expr.type === 'attribute') {\n return [this.expr.name]\n }\n throw new Error(`Can't convert ${this.expr.type} to field references`)\n }\n\n toString(): string {\n return toPath(this.expr)\n }\n\n static fromPath(path: string): Expression {\n const parsed = parseJsonPath(path)\n if (!parsed) {\n throw new Error(`Failed to parse path \"${path}\"`)\n }\n\n return new Expression(parsed)\n }\n\n static attributeReference(name: string): Expression {\n return new Expression({\n type: 'attribute',\n name: name,\n })\n }\n\n static indexReference(i: number): Expression {\n return new Expression({\n type: 'index',\n value: i,\n })\n }\n}\n\n// Tests an operator on two given primitive values\nfunction testBinaryOperator(lhsValue: any, operator: string, rhsValue: any) {\n switch (operator) {\n case '>':\n return lhsValue > rhsValue\n case '>=':\n return lhsValue >= rhsValue\n case '<':\n return lhsValue < rhsValue\n case '<=':\n return lhsValue <= rhsValue\n case '==':\n return lhsValue === rhsValue\n case '!=':\n return lhsValue !== rhsValue\n default:\n throw new Error(`Unsupported binary operator ${operator}`)\n }\n}\n\nfunction interpretNegativeIndex(index: number, probe?: Probe): number {\n if (index >= 0) {\n return index\n }\n\n if (!probe) {\n throw new Error('interpretNegativeIndex() must have a probe when < 0')\n }\n\n return index + probe.length()\n}\n","import {flatten} from 'lodash'\n\nimport {Expression} from './Expression'\nimport {type Probe} from './Probe'\n\n/**\n * Descender models the state of one partial jsonpath evaluation. Head is the\n * next thing to match, tail is the upcoming things once the head is matched.\n */\nexport class Descender {\n head: Expression | null\n tail: Expression | null\n\n constructor(head: Expression | null, tail: Expression | null) {\n this.head = head\n this.tail = tail\n }\n\n // Iterate this descender once processing any constraints that are\n // resolvable on the current value. Returns an array of new descenders\n // that are guaranteed to be without constraints in the head\n iterate(probe: Probe): Descender[] {\n let result: Descender[] = [this]\n if (this.head && this.head.isConstraint()) {\n let anyConstraints = true\n // Keep rewriting constraints until there are none left\n while (anyConstraints) {\n result = flatten(\n result.map((descender) => {\n return descender.iterateConstraints(probe)\n }),\n )\n anyConstraints = result.some((descender) => {\n return descender.head && descender.head.isConstraint()\n })\n }\n }\n return result\n }\n\n isRecursive(): boolean {\n return Boolean(this.head && this.head.isRecursive())\n }\n\n hasArrived(): boolean {\n return this.head === null && this.tail === null\n }\n\n extractRecursives(): Descender[] {\n if (this.head && this.head.isRecursive()) {\n const term = this.head.unwrapRecursive()\n return new Descender(null, term.concat(this.tail)).descend()\n }\n return []\n }\n\n iterateConstraints(probe: Probe): Descender[] {\n const head = this.head\n if (head === null || !head.isConstraint()) {\n // Not a constraint, no rewrite\n return [this]\n }\n\n const result: Descender[] = []\n\n if (probe.containerType() === 'primitive' && head.constraintTargetIsSelf()) {\n if (head.testConstraint(probe)) {\n result.push(...this.descend())\n }\n return result\n }\n\n // The value is an array\n if (probe.containerType() === 'array') {\n const length = probe.length()\n for (let i = 0; i < length; i++) {\n // Push new descenders with constraint translated to literal indices\n // where they match\n const constraint = probe.getIndex(i)\n if (constraint && head.testConstraint(constraint)) {\n result.push(new Descender(new Expression({type: 'index', value: i}), this.tail))\n }\n }\n return result\n }\n\n // The value is an object\n if (probe.containerType() === 'object') {\n if (head.constraintTargetIsSelf()) {\n // There are no matches for target self ('@') on a plain object\n return []\n }\n\n if (head.testConstraint(probe)) {\n return this.descend()\n }\n\n return result\n }\n\n return result\n }\n\n descend(): Descender[] {\n if (!this.tail) {\n return [new Descender(null, null)]\n }\n\n return this.tail.descend().map((ht) => {\n return new Descender(ht.head, ht.tail)\n })\n }\n\n toString(): string {\n const result = ['<']\n if (this.head) {\n result.push(this.head.toString())\n }\n result.push('|')\n if (this.tail) {\n result.push(this.tail.toString())\n }\n result.push('>')\n return result.join('')\n }\n}\n","import {Descender} from './Descender'\nimport {Expression} from './Expression'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\n\ninterface Result<P = unknown> {\n leads: {\n target: Expression\n matcher: Matcher\n }[]\n\n delivery?: {\n targets: Expression[]\n payload: P\n }\n}\n\n/**\n * @internal\n */\nexport class Matcher {\n active: Descender[]\n recursives: Descender[]\n payload: unknown\n\n constructor(active: Descender[], parent?: Matcher) {\n this.active = active || []\n if (parent) {\n this.recursives = parent.recursives\n this.payload = parent.payload\n } else {\n this.recursives = []\n }\n this.extractRecursives()\n }\n\n setPayload(payload: unknown): this {\n this.payload = payload\n return this\n }\n\n // Moves any recursive descenders onto the recursive track, removing them from\n // the active set\n extractRecursives(): void {\n this.active = this.active.filter((descender) => {\n if (descender.isRecursive()) {\n this.recursives.push(...descender.extractRecursives())\n return false\n }\n return true\n })\n }\n\n // Find recursives that are relevant now and should be considered part of the active set\n activeRecursives(probe: Probe): Descender[] {\n return this.recursives.filter((descender) => {\n const head = descender.head\n if (!head) {\n return false\n }\n\n // Constraints are always relevant\n if (head.isConstraint()) {\n return true\n }\n\n // Index references are only relevant for indexable values\n if (probe.containerType() === 'array' && head.isIndexReference()) {\n return true\n }\n\n // Attribute references are relevant for plain objects\n if (probe.containerType() === 'object') {\n return head.isAttributeReference() && probe.hasAttribute(head.name())\n }\n\n return false\n })\n }\n\n match(probe: Probe): Result {\n return this.iterate(probe).extractMatches(probe)\n }\n\n iterate(probe: Probe): Matcher {\n const newActiveSet: Descender[] = []\n this.active.concat(this.activeRecursives(probe)).forEach((descender) => {\n newActiveSet.push(...descender.iterate(probe))\n })\n return new Matcher(newActiveSet, this)\n }\n\n // Returns true if any of the descenders in the active or recursive set\n // consider the current state a final destination\n isDestination(): boolean {\n return this.active.some((descender) => descender.hasArrived())\n }\n\n hasRecursives(): boolean {\n return this.recursives.length > 0\n }\n\n // Returns any payload delivieries and leads that needs to be followed to complete\n // the process.\n extractMatches(probe: Probe): Result {\n const leads: {target: Expression; matcher: Matcher}[] = []\n const targets: Expression[] = []\n this.active.forEach((descender) => {\n if (descender.hasArrived()) {\n // This was already arrived, so matches this value, not descenders\n targets.push(\n new Expression({\n type: 'alias',\n target: 'self',\n }),\n )\n return\n }\n\n const descenderHead = descender.head\n if (!descenderHead) {\n return\n }\n\n if (probe.containerType() === 'array' && !descenderHead.isIndexReference()) {\n // This descender does not match an indexable value\n return\n }\n\n if (probe.containerType() === 'object' && !descenderHead.isAttributeReference()) {\n // This descender never match a plain object\n return\n }\n\n if (descender.tail) {\n // Not arrived yet\n const matcher = new Matcher(descender.descend(), this)\n descenderHead.toFieldReferences().forEach(() => {\n leads.push({\n target: descenderHead,\n matcher: matcher,\n })\n })\n } else {\n // arrived\n targets.push(descenderHead)\n }\n })\n\n // If there are recursive terms, we need to add a lead for every descendant ...\n if (this.hasRecursives()) {\n // The recustives matcher will have no active set, only inherit recursives from this\n const recursivesMatcher = new Matcher([], this)\n if (probe.containerType() === 'array') {\n const length = probe.length()\n for (let i = 0; i < length; i++) {\n leads.push({\n target: Expression.indexReference(i),\n matcher: recursivesMatcher,\n })\n }\n } else if (probe.containerType() === 'object') {\n probe.attributeKeys().forEach((name) => {\n leads.push({\n target: Expression.attributeReference(name),\n matcher: recursivesMatcher,\n })\n })\n }\n }\n\n return targets.length > 0\n ? {leads: leads, delivery: {targets, payload: this.payload}}\n : {leads: leads}\n }\n\n static fromPath(jsonpath: string): Matcher {\n const path = parseJsonPath(jsonpath)\n if (!path) {\n throw new Error(`Failed to parse path from \"${jsonpath}\"`)\n }\n\n const descender = new Descender(null, new Expression(path))\n return new Matcher(descender.descend())\n }\n}\n","import {isRecord} from '../util'\nimport {type Probe} from './Probe'\n\n// A default implementation of a probe for vanilla JS _values\nexport class PlainProbe implements Probe {\n _value: unknown\n path: (string | number)[]\n\n constructor(value: unknown, path?: (string | number)[]) {\n this._value = value\n this.path = path || []\n }\n\n containerType(): 'array' | 'object' | 'primitive' {\n if (Array.isArray(this._value)) {\n return 'array'\n } else if (this._value !== null && typeof this._value === 'object') {\n return 'object'\n }\n return 'primitive'\n }\n\n length(): number {\n if (!Array.isArray(this._value)) {\n throw new Error(\"Won't return length of non-indexable _value\")\n }\n\n return this._value.length\n }\n\n getIndex(i: number): false | null | PlainProbe {\n if (!Array.isArray(this._value)) {\n return false\n }\n\n if (i >= this.length()) {\n return null\n }\n\n return new PlainProbe(this._value[i], this.path.concat(i))\n }\n\n hasAttribute(key: string): boolean {\n if (!isRecord(this._value)) {\n return false\n }\n\n return this._value.hasOwnProperty(key)\n }\n\n attributeKeys(): string[] {\n return isRecord(this._value) ? Object.keys(this._value) : []\n }\n\n getAttribute(key: string): null | PlainProbe {\n if (!isRecord(this._value)) {\n throw new Error('getAttribute only applies to plain objects')\n }\n\n if (!this.hasAttribute(key)) {\n return null\n }\n\n return new PlainProbe(this._value[key], this.path.concat(key))\n }\n\n get(): unknown {\n return this._value\n }\n}\n","import {compact} from 'lodash'\n\nimport {type Expression} from './Expression'\nimport {Matcher} from './Matcher'\nimport {PlainProbe} from './PlainProbe'\nimport {type Probe} from './Probe'\n\nexport function extractAccessors(path: string, value: unknown): Probe[] {\n const result: Probe[] = []\n const matcher = Matcher.fromPath(path).setPayload(function appendResult(values: Probe[]) {\n result.push(...values)\n })\n const accessor = new PlainProbe(value)\n descend(matcher, accessor)\n return result\n}\n\nfunction descend(matcher: Matcher, accessor: Probe) {\n const {leads, delivery} = matcher.match(accessor)\n\n leads.forEach((lead) => {\n accessorsFromTarget(lead.target, accessor).forEach((childAccessor) => {\n descend(lead.matcher, childAccessor)\n })\n })\n\n if (delivery) {\n delivery.targets.forEach((target) => {\n if (typeof delivery.payload === 'function') {\n delivery.payload(accessorsFromTarget(target, accessor))\n }\n })\n }\n}\n\nfunction accessorsFromTarget(target: Expression, accessor: Probe) {\n const result = []\n if (target.isIndexReference()) {\n target.toIndicies(accessor).forEach((i) => {\n result.push(accessor.getIndex(i))\n })\n } else if (target.isAttributeReference()) {\n result.push(accessor.getAttribute(target.name()))\n } else if (target.isSelfReference()) {\n result.push(accessor)\n } else {\n throw new Error(`Unable to derive accessor for target ${target.toString()}`)\n }\n return compact(result)\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts values matching the given JsonPath\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of values matching the given path\n * @public\n */\nexport function extract(path: string, value: unknown): unknown[] {\n const accessors = extractAccessors(path, value)\n return accessors.map((acc) => acc.get())\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts a value for the given JsonPath, and includes the specific path of where it was found\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of objects with `path` and `value` keys\n * @internal\n */\nexport function extractWithPath(\n path: string,\n value: unknown,\n): {path: (string | number)[]; value: unknown}[] {\n const accessors = extractAccessors(path, value)\n return accessors.map((acc) => ({path: acc.path, value: acc.get()}))\n}\n","import {applyPatches, parsePatch, type Patch} from '@sanity/diff-match-patch'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction applyPatch(patch: Patch[], oldValue: unknown) {\n // Silently avoid patching if the value type is not string\n if (typeof oldValue !== 'string') return oldValue\n const [result] = applyPatches(patch, oldValue, {allowExceedingIndices: true})\n return result\n}\n\nexport class DiffMatchPatch {\n path: string\n dmpPatch: Patch[]\n id: string\n\n constructor(id: string, path: string, dmpPatchSrc: string) {\n this.id = id\n this.path = path\n this.dmpPatch = parsePatch(dmpPatchSrc)\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n\n // The target must be a container type\n if (result.containerType() === 'primitive') {\n return result\n }\n\n for (const target of targets) {\n if (target.isIndexReference()) {\n for (const index of target.toIndicies(accessor)) {\n // Skip patching unless the index actually currently exists\n const item = result.getIndex(index)\n if (!item) {\n continue\n }\n\n const oldValue = item.get()\n const nextValue = applyPatch(this.dmpPatch, oldValue)\n result = result.setIndex(index, nextValue)\n }\n\n continue\n }\n\n if (target.isAttributeReference() && result.hasAttribute(target.name())) {\n const attribute = result.getAttribute(target.name())\n if (!attribute) {\n continue\n }\n\n const oldValue = attribute.get()\n const nextValue = applyPatch(this.dmpPatch, oldValue)\n result = result.setAttribute(target.name(), nextValue)\n continue\n }\n\n throw new Error(`Unable to apply diffMatchPatch to target ${target.toString()}`)\n }\n\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction performIncrement(previousValue: unknown, delta: number): number {\n if (typeof previousValue !== 'number' || !Number.isFinite(previousValue)) {\n return previousValue as number\n }\n\n return previousValue + delta\n}\n\nexport class IncPatch {\n path: string\n value: number\n id: string\n\n constructor(id: string, path: string, value: number) {\n this.path = path\n this.value = value\n this.id = id\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n\n // The target must be a container type\n if (result.containerType() === 'primitive') {\n return result\n }\n\n for (const target of targets) {\n if (target.isIndexReference()) {\n for (const index of target.toIndicies(accessor)) {\n // Skip patching unless the index actually currently exists\n const item = result.getIndex(index)\n if (!item) {\n continue\n }\n\n const previousValue = item.get()\n result = result.setIndex(index, performIncrement(previousValue, this.value))\n }\n\n continue\n }\n\n if (target.isAttributeReference()) {\n const attribute = result.getAttribute(target.name())\n if (!attribute) {\n continue\n }\n\n const previousValue = attribute.get()\n result = result.setAttribute(target.name(), performIncrement(previousValue, this.value))\n continue\n }\n\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport function targetsToIndicies(targets: Expression[], accessor: ImmutableAccessor): number[] {\n const result: number[] = []\n targets.forEach((target) => {\n if (target.isIndexReference()) {\n result.push(...target.toIndicies(accessor))\n }\n })\n return result.sort((a, b) => a - b)\n}\n","import {max, min} from 'lodash'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class InsertPatch {\n location: string\n path: string\n items: unknown[]\n id: string\n\n constructor(id: string, location: string, path: string, items: unknown[]) {\n this.id = id\n this.location = location\n this.path = path\n this.items = items\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n if (accessor.containerType() !== 'array') {\n throw new Error('Attempt to apply insert patch to non-array value')\n }\n\n switch (this.location) {\n case 'before': {\n const pos = minIndex(targets, accessor)\n result = result.insertItemsAt(pos, this.items)\n break\n }\n case 'after': {\n const pos = maxIndex(targets, accessor)\n result = result.insertItemsAt(pos + 1, this.items)\n break\n }\n case 'replace': {\n // TODO: Properly implement ranges in compliance with content lake\n // This will only properly support single contiguous ranges\n const indicies = targetsToIndicies(targets, accessor)\n result = result.unsetIndices(indicies)\n result = result.insertItemsAt(indicies[0], this.items)\n break\n }\n default: {\n throw new Error(`Unsupported location atm: ${this.location}`)\n }\n }\n return result\n }\n}\n\nfunction minIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n let result = min(targetsToIndicies(targets, accessor)) || 0\n\n // Ranges may be zero-length and not turn up in indices\n targets.forEach((target) => {\n if (target.isRange()) {\n const {start} = target.expandRange()\n if (start < result) {\n result = start\n }\n }\n })\n return result\n}\n\nfunction maxIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n let result = max(targetsToIndicies(targets, accessor)) || 0\n\n // Ranges may be zero-length and not turn up in indices\n targets.forEach((target) => {\n if (target.isRange()) {\n const {end} = target.expandRange()\n if (end > result) {\n result = end\n }\n }\n })\n return result\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetIfMissingPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string, value: unknown) {\n this.id = id\n this.path = path\n this.value = value\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n targets.forEach((target) => {\n if (target.isIndexReference()) {\n // setIfMissing do not apply to arrays, since Content Lake will reject nulls in arrays\n } else if (target.isAttributeReference()) {\n // setting a subproperty on a primitive value overwrites it, eg\n // `{setIfMissing: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will\n // result in `{address: {street: 'California St'}}`\n if (result.containerType() === 'primitive') {\n result = result.set({[target.name()]: this.value})\n } else if (!result.hasAttribute(target.name())) {\n result = accessor.setAttribute(target.name(), this.value)\n }\n } else {\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n })\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string, value: unknown) {\n this.id = id\n this.path = path\n this.value = value\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n targets.forEach((target) => {\n if (target.isSelfReference()) {\n result = result.set(this.value)\n } else if (target.isIndexReference()) {\n target.toIndicies(accessor).forEach((i) => {\n result = result.setIndex(i, this.value)\n })\n } else if (target.isAttributeReference()) {\n // setting a subproperty on a primitive value overwrites it, eg\n // `{set: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will result in\n // `{address: {street: 'California St'}}`\n if (result.containerType() === 'primitive') {\n result = result.set({[target.name()]: this.value})\n } else {\n result = result.setAttribute(target.name(), this.value)\n }\n } else {\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n })\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class UnsetPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string) {\n this.id = id\n this.path = path\n }\n\n // eslint-disable-next-line class-methods-use-this\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n switch (accessor.containerType()) {\n case 'array':\n result = result.unsetIndices(targetsToIndicies(targets, accessor))\n break\n case 'object':\n targets.forEach((target) => {\n result = result.unsetAttribute(target.name())\n })\n break\n default:\n throw new Error(\n 'Target value is neither indexable or an object. This error should potentially just be silently ignored?',\n )\n }\n return result\n }\n}\n","import {DiffMatchPatch} from './DiffMatchPatch'\nimport {IncPatch} from './IncPatch'\nimport {InsertPatch} from './InsertPatch'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\nimport {UnsetPatch} from './UnsetPatch'\n\n// Parses a content lake patch into our own personal patch implementations\nexport function parsePatch(patch: SingleDocumentPatch | SingleDocumentPatch[]): PatchTypes[] {\n const result: PatchTypes[] = []\n if (Array.isArray(patch)) {\n return patch.reduce((r, p) => r.concat(parsePatch(p)), result)\n }\n\n const {set, setIfMissing, unset, diffMatchPatch, inc, dec, insert} = patch\n if (setIfMissing) {\n Object.keys(setIfMissing).forEach((path) => {\n result.push(new SetIfMissingPatch(patch.id, path, setIfMissing[path]))\n })\n }\n\n if (set) {\n Object.keys(set).forEach((path) => {\n result.push(new SetPatch(patch.id, path, set[path]))\n })\n }\n\n if (unset) {\n unset.forEach((path) => {\n result.push(new UnsetPatch(patch.id, path))\n })\n }\n\n if (diffMatchPatch) {\n Object.keys(diffMatchPatch).forEach((path) => {\n result.push(new DiffMatchPatch(patch.id, path, diffMatchPatch[path]))\n })\n }\n\n if (inc) {\n Object.keys(inc).forEach((path) => {\n result.push(new IncPatch(patch.id, path, inc[path]))\n })\n }\n\n if (dec) {\n Object.keys(dec).forEach((path) => {\n result.push(new IncPatch(patch.id, path, -dec[path]))\n })\n }\n\n if (insert) {\n let location: string\n let path: string\n const spec = insert\n if ('before' in spec) {\n location = 'before'\n path = spec.before\n } else if ('after' in spec) {\n location = 'after'\n path = spec.after\n } else if ('replace' in spec) {\n location = 'replace'\n path = spec.replace\n } else {\n throw new Error('Invalid insert patch')\n }\n\n result.push(new InsertPatch(patch.id, location, path, spec.items))\n }\n\n return result\n}\n","import {type Doc} from '../document/types'\nimport {Matcher} from '../jsonpath'\nimport {ImmutableAccessor} from './ImmutableAccessor'\nimport {parsePatch} from './parse'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\n\nexport interface Patch {\n id: string\n path: string\n}\n\nexport class Patcher {\n patches: PatchTypes[]\n\n constructor(patch: SingleDocumentPatch | SingleDocumentPatch[]) {\n this.patches = parsePatch(patch)\n }\n\n apply(value: Doc | null): unknown {\n // Apply just makes a root accessor around the provided\n // value, then applies the patches. Due to the use of\n // ImmutableAccessor it is guaranteed to return either the\n // exact same object it was provided (in the case of no changes),\n // or a completely new object. It will never mutate the object in place.\n const accessor = new ImmutableAccessor(value)\n return this.applyViaAccessor(accessor).get()\n }\n\n // If you want to use your own accessor implementation, you can use this method\n // to invoke the patcher. Since all subsequent accessors for children of this accessor\n // are obtained through the methods in the accessors, you retain full control of the\n // implementation throguhgout the application. Have a look in ImmutableAccessor\n // to see an example of how accessors are implemented.\n applyViaAccessor(accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n const idAccessor = accessor.getAttribute('_id')\n if (!idAccessor) {\n throw new Error('Cannot apply patch to document with no _id')\n }\n\n const id = idAccessor.get()\n for (const patch of this.patches) {\n if (patch.id !== id) {\n // Ignore patches that are not targetted at this document\n continue\n }\n\n const matcher = Matcher.fromPath(patch.path).setPayload(patch)\n result = process(matcher, result)\n }\n\n return result\n }\n}\n\n// Recursively (depth first) follows any leads generated by the matcher, expecting\n// a patch to be the payload. When matchers report a delivery, the\n// apply(targets, accessor) is called on the patch\nfunction process(matcher: Matcher, accessor: ImmutableAccessor) {\n const isSetPatch =\n matcher.payload instanceof SetPatch || matcher.payload instanceof SetIfMissingPatch\n\n let result = accessor\n // Every time we execute the matcher a new set of leads is generated. Each lead\n // is a target (being an index, an attribute name or a range) in the form of an\n // Expression instance. For each lead target there is also a matcher. Our job is to obtain\n // accessor(s) for each target (there might be more than one, since the targets may\n // be ranges) and run the provided matcher on those accessors.\n const {leads, delivery} = matcher.match(accessor)\n leads.forEach((lead) => {\n if (lead.target.isIndexReference()) {\n lead.target.toIndicies().forEach((i) => {\n const item = result.getIndex(i)\n if (!item) {\n throw new Error('Index out of bounds')\n }\n\n result = result.setIndexAccessor(i, process(lead.matcher, item))\n })\n } else if (lead.target.isAttributeReference()) {\n // `set`/`setIfMissing` on a primitive value overwrites it\n if (isSetPatch && result.containerType() === 'primitive') {\n result = result.set({})\n }\n\n let oldValueAccessor = result.getAttribute(lead.target.name())\n\n // If the patch is a set/setIfMissing patch, we allow deeply setting properties,\n // creating missing segments as we go.\n if (!oldValueAccessor && isSetPatch) {\n result = result.setAttribute(lead.target.name(), {})\n oldValueAccessor = result.getAttribute(lead.target.name())\n }\n\n if (!oldValueAccessor) {\n // Don't follow lead, no such attribute\n return\n }\n\n const newValueAccessor = process(lead.matcher, oldValueAccessor)\n if (oldValueAccessor !== newValueAccessor) {\n result = result.setAttributeAccessor(lead.target.name(), newValueAccessor)\n }\n } else {\n throw new Error(`Unable to handle target ${lead.target.toString()}`)\n }\n })\n\n // Each time we run the matcher, we might also get a delivery. This means that a\n // term in the jsonpath terminated here and the patch should be applied. The delivery\n // arrives in the form of an array of targets and a payload (which in this application\n // is the patch). Conveniently the patches accept an array of targets and an accessor\n // to do its work, so here we just pass those to the patch and we're done.\n if (delivery && isPatcher(delivery.payload)) {\n const patch = delivery.payload\n result = patch.apply(delivery.targets, result)\n }\n\n return result\n}\n\nfunction isPatcher(payload: unknown): payload is PatchTypes {\n return Boolean(\n payload &&\n typeof payload === 'object' &&\n payload !== null &&\n 'apply' in payload &&\n typeof (payload as PatchTypes).apply === 'function',\n )\n}\n","import {uuid} from '@sanity/uuid'\n\n/**\n * Locally unique id's. We use this to generate transaction ids, and they don't have to be\n * cryptographically unique, as the worst that can happen is that they get rejected because\n * of a collision, and then we should just retry with a new id.\n */\nexport const luid: typeof uuid = uuid\n","import {Patcher} from '../patch'\nimport {debug} from './debug'\nimport {luid} from './luid'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Parameters attached to the mutation\n *\n * @internal\n */\nexport interface MutationParams {\n transactionId?: string\n transition?: string\n identity?: string\n previousRev?: string\n resultRev?: string\n mutations: Mut[]\n timestamp?: string\n effects?: {apply: unknown; revert: unknown}\n}\n\n/**\n * A mutation describing a number of operations on a single document.\n * This should be considered an immutable structure. Mutations are compiled\n * on first application, and any changes in properties will not effectively\n * change its behavior after that.\n *\n * @internal\n */\nexport class Mutation {\n params: MutationParams\n\n compiled?: (doc: Doc | null) => Doc | null\n\n _appliesToMissingDocument: boolean | undefined\n\n constructor(options: MutationParams) {\n this.params = options\n }\n\n get transactionId(): string | undefined {\n return this.params.transactionId\n }\n\n get transition(): string | undefined {\n return this.params.transition\n }\n\n get identity(): string | undefined {\n return this.params.identity\n }\n\n get previousRev(): string | undefined {\n return this.params.previousRev\n }\n\n get resultRev(): string | undefined {\n return this.params.resultRev\n }\n\n get mutations(): Mut[] {\n return this.params.mutations\n }\n\n get timestamp(): Date | undefined {\n if (typeof this.params.timestamp === 'string') {\n return new Date(this.params.timestamp)\n }\n\n return undefined\n }\n\n get effects():\n | {\n apply: unknown\n revert: unknown\n }\n | undefined {\n return this.params.effects\n }\n\n assignRandomTransactionId(): void {\n this.params.transactionId = luid()\n this.params.resultRev = this.params.transactionId\n }\n\n appliesToMissingDocument(): boolean {\n if (typeof this._appliesToMissingDocument !== 'undefined') {\n return this._appliesToMissingDocument\n }\n\n // Only mutations starting with a create operation apply to documents that do not exist ...\n const firstMut = this.mutations[0]\n if (firstMut) {\n this._appliesToMissingDocument = Boolean(\n firstMut.create || firstMut.createIfNotExists || firstMut.createOrReplace,\n )\n } else {\n this._appliesToMissingDocument = true\n }\n\n return this._appliesToMissingDocument\n }\n\n // Compiles all mutations into a handy function\n compile(): void {\n const operations: ((doc: Doc | null) => Doc | null)[] = []\n\n // creation requires a _createdAt\n const getGuaranteedCreatedAt = (doc: Doc): string =>\n doc?._createdAt || this.params.timestamp || new Date().toISOString()\n\n this.mutations.forEach((mutation) => {\n if (mutation.create) {\n // TODO: Fail entire patch if document did exist\n const create = (mutation.create || {}) as Doc\n operations.push((doc): Doc => {\n if (doc) {\n return doc\n }\n\n return Object.assign(create, {\n _createdAt: getGuaranteedCreatedAt(create),\n })\n })\n return\n }\n\n if (mutation.createIfNotExists) {\n const createIfNotExists = mutation.createIfNotExists || {}\n operations.push((doc) =>\n doc === null\n ? Object.assign(createIfNotExists, {\n _createdAt: getGuaranteedCreatedAt(createIfNotExists),\n })\n : doc,\n )\n return\n }\n\n if (mutation.createOrReplace) {\n const createOrReplace = mutation.createOrReplace || {}\n operations.push(() =>\n Object.assign(createOrReplace, {\n _createdAt: getGuaranteedCreatedAt(createOrReplace),\n }),\n )\n return\n }\n\n if (mutation.delete) {\n operations.push(() => null)\n return\n }\n\n if (mutation.patch) {\n if ('query' in mutation.patch) {\n // @todo Warn/throw? Investigate if this can ever happen\n return\n }\n\n const patch = new Patcher(mutation.patch)\n operations.push((doc) => patch.apply(doc) as Doc | null)\n return\n }\n\n throw new Error(`Unsupported mutation ${JSON.stringify(mutation, null, 2)}`)\n })\n\n // Assign `_updatedAt` to the timestamp of the mutation if set\n if (typeof this.params.timestamp === 'string') {\n operations.push((doc) => {\n return doc ? Object.assign(doc, {_updatedAt: this.params.timestamp}) : null\n })\n }\n\n const prevRev = this.previousRev\n const rev = this.resultRev || this.transactionId\n this.compiled = (doc: Doc | null) => {\n if (prevRev && doc && prevRev !== doc._rev) {\n throw new Error(\n `Previous revision for this mutation was ${prevRev}, but the document revision is ${doc._rev}`,\n )\n }\n\n let result: Doc | null = doc\n for (const operation of operations) {\n result = operation(result)\n }\n\n // Should update _rev?\n if (result && rev) {\n // Ensure that result is a unique object, even if the operation was a no-op\n if (result === doc) {\n result = Object.assign({}, doc)\n }\n result._rev = rev\n }\n\n return result\n }\n }\n\n apply(document: Doc | null): Doc | null {\n debug('Applying mutation %O to document %O', this.mutations, document)\n if (!this.compiled) {\n this.compile()\n }\n\n const result = this.compiled!(document)\n debug(' => %O', result)\n return result\n }\n\n static applyAll(document: Doc | null, mutations: Mutation[]): Doc | null {\n return mutations.reduce((doc, mutation) => mutation.apply(doc), document)\n }\n\n // Given a number of yet-to-be-committed mutation objects, collects them into one big mutation\n // any metadata like transactionId is ignored and must be submitted by the client. It is assumed\n // that all mutations are on the same document.\n // TOOO: Optimize mutations, eliminating mutations that overwrite themselves!\n static squash(document: Doc | null, mutations: Mutation[]): Mutation {\n const squashed = mutations.reduce(\n (result, mutation) => result.concat(...mutation.mutations),\n [] as Mut[],\n )\n return new Mutation({mutations: squashed})\n }\n}\n","// TODO: When we have timestamps on mutation notifications, we can reject incoming mutations that are older\n// than the document we are seeing.\n\nimport {isEqual} from 'lodash'\n\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc} from './types'\n\n/**\n * @internal\n */\nexport interface SubmissionResponder {\n success: () => void\n failure: () => void\n}\n\n/**\n * Models a document as it is changed by our own local patches and remote patches coming in from\n * the server. Consolidates incoming patches with our own submitted patches and maintains two\n * versions of the document. EDGE is the optimistic document that the user sees that will always\n * immediately reflect whatever she is doing to it, and HEAD which is the confirmed version of the\n * document consistent with the mutations we have received from the server. As long as nothing out of\n * the ordinary happens, we can track all changes by hooking into the onMutation callback, but we\n * must also respect onRebase events that fire when we have to backtrack because one of our optimistically\n * applied patches were rejected, or some bastard was able to slip a mutation in between ours own.\n *\n * @internal\n */\nexport class Document {\n /**\n * Incoming patches from the server waiting to be applied to HEAD\n */\n incoming: Mutation[] = []\n\n /**\n * Patches we know has been subitted to the server, but has not been seen yet in the return channel\n * so we can't be sure about the ordering yet (someone else might have slipped something between them)\n */\n submitted: Mutation[] = []\n\n /**\n * Pending mutations\n */\n pending: Mutation[] = []\n\n /**\n * Our model of the document according to the incoming patches from the server\n */\n HEAD: Doc | null\n\n /**\n * Our optimistic model of what the document will probably look like as soon as all our patches\n * have been processed. Updated every time we stage a new mutation, but also might revert back\n * to previous states if our mutations fail, or could change if unexpected mutations arrive\n * between our own. The `onRebase` callback will be called when EDGE changes in this manner.\n */\n EDGE: Doc | null\n\n /**\n * Called with the EDGE document when that document changes for a reason other than us staging\n * a new patch or receiving a mutation from the server while our EDGE is in sync with HEAD:\n * I.e. when EDGE changes because the order of mutations has changed in relation to our\n * optimistic predictions.\n */\n onRebase?: (edge: Doc | null, incomingMutations: Mutation[], pendingMutations: Mutation[]) => void\n\n /**\n * Called when we receive a patch in the normal order of things, but the mutation is not ours\n */\n onMutation?: (msg: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n /**\n * Called when consistency state changes with the boolean value of the current consistency state\n */\n onConsistencyChanged?: (isConsistent: boolean) => void\n\n /**\n * Called whenever a new incoming mutation comes in. These are always ordered correctly.\n */\n onRemoteMutation?: (mut: Mutation) => void\n\n /**\n * We are consistent when there are no unresolved mutations of our own, and no un-applicable\n * incoming mutations. When this has been going on for too long, and there has been a while\n * since we staged a new mutation, it is time to reset your state.\n */\n inconsistentAt: Date | null = null\n\n /**\n * The last time we staged a patch of our own. If we have been inconsistent for a while, but it\n * hasn't been long since we staged a new mutation, the reason is probably just because the user\n * is typing or something.\n *\n * Should be used as a guard against resetting state for inconsistency reasons.\n */\n lastStagedAt: Date | null = null\n\n constructor(doc: Doc | null) {\n this.reset(doc)\n this.HEAD = doc\n this.EDGE = doc\n }\n\n // Reset the state of the Document, used to recover from unsavory states by reloading the document\n reset(doc: Doc | null): void {\n this.incoming = []\n this.submitted = []\n this.pending = []\n this.inconsistentAt = null\n this.HEAD = doc\n this.EDGE = doc\n this.considerIncoming()\n this.updateConsistencyFlag()\n }\n\n // Call when a mutation arrives from Sanity\n arrive(mutation: Mutation): void {\n this.incoming.push(mutation)\n this.considerIncoming()\n this.updateConsistencyFlag()\n }\n\n // Call to signal that we are submitting a mutation. Returns a callback object with a\n // success and failure handler that must be called according to the outcome of our\n // submission.\n stage(mutation: Mutation, silent?: boolean): SubmissionResponder {\n if (!mutation.transactionId) {\n throw new Error('Mutations _must_ have transactionId when submitted')\n }\n this.lastStagedAt = new Date()\n\n debug('Staging mutation %s (pushed to pending)', mutation.transactionId)\n this.pending.push(mutation)\n this.EDGE = mutation.apply(this.EDGE)\n\n if (this.onMutation && !silent) {\n this.onMutation({\n mutation,\n document: this.EDGE,\n remote: false,\n })\n }\n\n const txnId = mutation.transactionId\n\n this.updateConsistencyFlag()\n\n return {\n success: () => {\n this.pendingSuccessfullySubmitted(txnId)\n this.updateConsistencyFlag()\n },\n failure: () => {\n this.pendingFailed(txnId)\n this.updateConsistencyFlag()\n },\n }\n }\n\n // Call to check if everything is nice and quiet and there are no unresolved mutations.\n // Means this model thinks both HEAD and EDGE is up to date with what the server sees.\n isConsistent(): boolean {\n return !this.inconsistentAt\n }\n\n // Private\n\n // Attempts to apply any resolvable incoming patches to HEAD. Will keep patching as long as there\n // are applicable patches to be applied\n considerIncoming(): void {\n let mustRebase = false\n let nextMut: Mutation | undefined\n const rebaseMutations: Mutation[] = []\n\n // Filter mutations that are older than the document\n if (this.HEAD && this.HEAD._updatedAt) {\n const updatedAt = new Date(this.HEAD._updatedAt)\n if (this.incoming.find((mut) => mut.timestamp && mut.timestamp < updatedAt)) {\n this.incoming = this.incoming.filter((mut) => mut.timestamp && mut.timestamp < updatedAt)\n }\n }\n\n // Keep applying mutations as long as any apply\n let protect = 0\n do {\n // Find next mutation that can be applied to HEAD (if any)\n if (this.HEAD) {\n const HEAD = this.HEAD\n nextMut = HEAD._rev ? this.incoming.find((mut) => mut.previousRev === HEAD._rev) : undefined\n } else {\n // When HEAD is null, that means the document is currently deleted. Only mutations that start with a create\n // operation will be considered.\n nextMut = this.incoming.find((mut) => mut.appliesToMissingDocument())\n }\n\n if (nextMut) {\n const applied = this.applyIncoming(nextMut)\n mustRebase = mustRebase || applied\n if (mustRebase) {\n rebaseMutations.push(nextMut)\n }\n\n if (protect++ > 10) {\n throw new Error(\n `Mutator stuck flushing incoming mutations. Probably stuck here: ${JSON.stringify(\n nextMut,\n )}`,\n )\n }\n }\n } while (nextMut)\n\n if (this.incoming.length > 0 && debug.enabled) {\n debug(\n 'Unable to apply mutations %s',\n this.incoming.map((mut) => mut.transactionId).join(', '),\n )\n }\n\n if (mustRebase) {\n this.rebase(rebaseMutations)\n }\n }\n\n // check current consistency state, update flag and invoke callback if needed\n updateConsistencyFlag(): void {\n const wasConsistent = this.isConsistent()\n const isConsistent =\n this.pending.length === 0 && this.submitted.length === 0 && this.incoming.length === 0\n // Update the consistency state, taking care not to update the timestamp if we were inconsistent and still are\n if (isConsistent) {\n this.inconsistentAt = null\n } else if (!this.inconsistentAt) {\n this.inconsistentAt = new Date()\n }\n // Handle onConsistencyChanged callback\n if (wasConsistent != isConsistent && this.onConsistencyChanged) {\n if (isConsistent) {\n debug('Buffered document is inconsistent')\n } else {\n debug('Buffered document is consistent')\n }\n this.onConsistencyChanged(isConsistent)\n }\n }\n\n // apply an incoming patch that has been prequalified as the next in line for this document\n applyIncoming(mut: Mutation | undefined): boolean {\n if (!mut) {\n return false\n }\n\n if (!mut.transactionId) {\n throw new Error('Received incoming mutation without a transaction ID')\n }\n\n debug(\n 'Applying mutation %s -> %s to rev %s',\n mut.previousRev,\n mut.resultRev,\n this.HEAD && this.HEAD._rev,\n )\n\n this.HEAD = mut.apply(this.HEAD)\n\n if (this.onRemoteMutation) {\n this.onRemoteMutation(mut)\n }\n\n // Eliminate from incoming set\n this.incoming = this.incoming.filter((m) => m.transactionId !== mut.transactionId)\n\n if (this.hasUnresolvedMutations()) {\n const needRebase = this.consumeUnresolved(mut.transactionId)\n if (debug.enabled) {\n debug(\n `Incoming mutation ${mut.transactionId} appeared while there were pending or submitted local mutations`,\n )\n debug(`Submitted txnIds: ${this.submitted.map((m) => m.transactionId).join(', ')}`)\n debug(`Pending txnIds: ${this.pending.map((m) => m.transactionId).join(', ')}`)\n debug(`needRebase === %s`, needRebase)\n }\n return needRebase\n }\n debug(\n `Remote mutation %s arrived w/o any pending or submitted local mutations`,\n mut.transactionId,\n )\n this.EDGE = this.HEAD\n if (this.onMutation) {\n this.onMutation({\n mutation: mut,\n document: this.EDGE,\n remote: true,\n })\n }\n return false\n }\n\n /**\n * Returns true if there are unresolved mutations between HEAD and EDGE, meaning we have\n * mutations that are still waiting to be either submitted, or to be confirmed by the server.\n *\n * @returns true if there are unresolved mutations between HEAD and EDGE, false otherwise\n */\n hasUnresolvedMutations(): boolean {\n return this.submitted.length > 0 || this.pending.length > 0\n }\n\n /**\n * When an incoming mutation is applied to HEAD, this is called to remove the mutation from\n * the unresolved state. If the newly applied patch is the next upcoming unresolved mutation,\n * no rebase is needed, but we might have the wrong idea about the ordering of mutations, so in\n * that case we are given the flag `needRebase` to tell us that this mutation arrived out of\n * order in terms of our optimistic version, so a rebase is needed.\n *\n * @param txnId - Transaction ID of the remote mutation\n * @returns true if rebase is needed, false otherwise\n */\n consumeUnresolved(txnId: string): boolean {\n // If we have nothing queued up, we are in sync and can apply patch with no\n // rebasing\n if (this.submitted.length === 0 && this.pending.length === 0) {\n return false\n }\n\n // If we can consume the directly upcoming mutation, we won't have to rebase\n if (this.submitted.length !== 0) {\n if (this.submitted[0].transactionId === txnId) {\n debug(\n `Remote mutation %s matches upcoming submitted mutation, consumed from 'submitted' buffer`,\n txnId,\n )\n this.submitted.shift()\n return false\n }\n } else if (this.pending.length > 0 && this.pending[0].transactionId === txnId) {\n // There are no submitted, but some are pending so let's check the upcoming pending\n debug(\n `Remote mutation %s matches upcoming pending mutation, consumed from 'pending' buffer`,\n txnId,\n )\n this.pending.shift()\n return false\n }\n\n debug(\n 'The mutation was not the upcoming mutation, scrubbing. Pending: %d, Submitted: %d',\n this.pending.length,\n this.submitted.length,\n )\n\n // The mutation was not the upcoming mutation, so we'll have to check everything to\n // see if we have an out of order situation\n this.submitted = this.submitted.filter((mut) => mut.transactionId !== txnId)\n this.pending = this.pending.filter((mut) => mut.transactionId !== txnId)\n debug(`After scrubbing: Pending: %d, Submitted: %d`, this.pending.length, this.submitted.length)\n\n // Whether we had it or not we have either a reordering, or an unexpected mutation\n // so must rebase\n return true\n }\n\n pendingSuccessfullySubmitted(pendingTxnId: string): void {\n if (this.pending.length === 0) {\n // If there are no pending, it has probably arrived allready\n return\n }\n\n const first = this.pending[0]\n if (first.transactionId === pendingTxnId) {\n // Nice, the pending transaction arrived in order\n this.pending.shift()\n this.submitted.push(first)\n return\n }\n\n // Oh, no. Submitted out of order.\n let justSubmitted: Mutation | undefined\n const stillPending: Mutation[] = []\n this.pending.forEach((mutation) => {\n if (mutation.transactionId === pendingTxnId) {\n justSubmitted = mutation\n return\n }\n\n stillPending.push(mutation)\n })\n\n // Not found? Hopefully it has already arrived. Might have been forgotten by now\n if (justSubmitted) {\n this.submitted.push(justSubmitted)\n }\n\n this.pending = stillPending\n\n // Must rebase since mutation order has changed\n this.rebase([])\n }\n\n pendingFailed(pendingTxnId: string): void {\n this.pending = this.pending.filter((mutation) => mutation.transactionId !== pendingTxnId)\n\n // Rebase to revert document to what it looked like before the failed mutation\n this.rebase([])\n }\n\n rebase(incomingMutations: Mutation[]): void {\n const oldEdge = this.EDGE\n this.EDGE = Mutation.applyAll(this.HEAD, this.submitted.concat(this.pending))\n\n // Copy over rev, since we don't care if it changed, we only care about the content\n if (oldEdge !== null && this.EDGE !== null) {\n oldEdge._rev = this.EDGE._rev\n }\n\n const changed = !isEqual(this.EDGE, oldEdge)\n if (changed && this.onRebase) {\n this.onRebase(this.EDGE, incomingMutations, this.pending)\n }\n }\n}\n","import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'\n\nimport {arrayToJSONMatchPath} from '../jsonpath/arrayToJSONMatchPath'\nimport {extractWithPath} from '../jsonpath/extractWithPath'\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Implements a buffer for mutations that incrementally optimises the mutations by\n * eliminating set-operations that overwrite earlier set-operations, and rewrite\n * set-operations that change strings into other strings into diffMatchPatch operations.\n *\n * @internal\n */\nexport class SquashingBuffer {\n /**\n * The document forming the basis of this squash\n */\n BASIS: Doc | null\n\n /**\n * The document after the out-Mutation has been applied, but before the staged\n * operations are committed.\n */\n PRESTAGE: Doc | null\n\n /**\n * setOperations contain the latest set operation by path. If the set-operations are\n * updating strings to new strings, they are rewritten as diffMatchPatch operations,\n * any new set operations on the same paths overwrites any older set operations.\n * Only set-operations assigning plain values to plain values gets optimized like this.\n */\n setOperations: Record<string, Mut | undefined>\n\n /**\n * `documentPresent` is true whenever we know that the document must be present due\n * to preceeding mutations. `false` implies that it may or may not already exist.\n */\n documentPresent: boolean\n\n /**\n * The operations in the out-Mutation are not able to be optimized any further\n */\n out: Mut[] = []\n\n /**\n * Staged mutation operations\n */\n staged: Mut[]\n\n constructor(doc: Doc | null) {\n if (doc) {\n debug('Reset mutation buffer to rev %s', doc._rev)\n } else {\n debug('Reset mutation buffer state to document being deleted')\n }\n\n this.staged = []\n this.setOperations = {}\n this.documentPresent = false\n\n this.BASIS = doc\n this.PRESTAGE = doc\n }\n\n add(mut: Mutation): void {\n mut.mutations.forEach((op) => this.addOperation(op))\n }\n\n hasChanges(): boolean {\n return this.out.length > 0 || Object.keys(this.setOperations).length > 0\n }\n\n /**\n * Extracts the mutations in this buffer.\n * After this is done, the buffer lifecycle is over and the client should\n * create an new one with the new, updated BASIS.\n *\n * @param txnId - Transaction ID\n * @returns A `Mutation` instance if we had outgoing mutations pending, null otherwise\n */\n purge(txnId?: string): Mutation | null {\n this.stashStagedOperations()\n let result = null\n if (this.out.length > 0) {\n debug('Purged mutation buffer')\n result = new Mutation({\n mutations: this.out,\n resultRev: txnId,\n transactionId: txnId,\n })\n }\n this.out = []\n this.documentPresent = false\n return result\n }\n\n addOperation(op: Mut): void {\n // Is this a set patch, and only a set patch, and does it apply to the document at hand?\n if (\n op.patch &&\n op.patch.set &&\n 'id' in op.patch &&\n op.patch.id === this.PRESTAGE?._id &&\n Object.keys(op.patch).length === 2 // `id` + `set`\n ) {\n const setPatch = op.patch.set\n const unoptimizable: Record<string, unknown> = {}\n // Apply all optimisable keys in the patch\n for (const path of Object.keys(setPatch)) {\n if (setPatch.hasOwnProperty(path)) {\n if (!this.optimiseSetOperation(path, setPatch[path])) {\n // If not optimisable, add to unoptimizable set\n unoptimizable[path] = setPatch[path]\n }\n }\n }\n\n // If any weren't optimisable, add them to an unoptimised set-operation, then\n // stash everything.\n if (Object.keys(unoptimizable).length > 0) {\n debug('Unoptimizable set-operation detected, purging optimization buffer')\n this.staged.push({patch: {id: this.PRESTAGE._id, set: unoptimizable}})\n this.stashStagedOperations()\n }\n\n return\n }\n\n // Is this a createIfNotExists for our document?\n if (op.createIfNotExists && this.PRESTAGE && op.createIfNotExists._id === this.PRESTAGE._id) {\n if (!this.documentPresent) {\n // If we don't know that it's present we'll have to stage and stash.\n this.staged.push(op)\n this.documentPresent = true\n this.stashStagedOperations()\n }\n\n // Otherwise we can fully ignore it.\n return\n }\n\n debug('Unoptimizable mutation detected, purging optimization buffer')\n // console.log(\"Unoptimizable operation, stashing\", JSON.stringify(op))\n // Un-optimisable operations causes everything to be stashed\n this.staged.push(op)\n this.stashStagedOperations()\n }\n\n /**\n * Attempt to perform one single set operation in an optimised manner, return value\n * reflects whether or not the operation could be performed.\n\n * @param path - The JSONPath to the set operation in question\n * @param nextValue - The value to be set\n * @returns True of optimized, false otherwise\n */\n optimiseSetOperation(path: string, nextValue: unknown): boolean {\n // console.log('optimiseSetOperation', path, nextValue)\n // If target value is not a plain value, unable to optimise\n if (typeof nextValue === 'object') {\n // console.log(\"Not optimisable because next value is object\")\n return false\n }\n\n // Check the source values, if there is more than one value being assigned,\n // we won't optimise\n const matches = extractWithPath(path, this.PRESTAGE)\n // If we are not overwriting exactly one key, this cannot be optimised, so we bail\n if (matches.length !== 1) {\n // console.log('Not optimisable because match count is != 1', JSON.stringify(matches))\n return false\n }\n\n // Okay, we are assigning exactly one value to exactly one existing slot, so we might optimise\n const match = matches[0]\n // If the value of the match is an array or object, we cannot safely optimise this since the meaning\n // of pre-existing operations might change (in theory, at least), so we bail\n if (typeof match.value === 'object') {\n // console.log(\"Not optimisable because old value is object\")\n return false\n }\n\n if (!this.PRESTAGE) {\n // Shouldn't happen, but makes typescript happy\n return false\n }\n\n // If the new and old value are the equal, we optimise this operation by discarding it\n // Now, let's build the operation\n let op: Mut | null = null\n if (match.value === nextValue) {\n // If new and old values are equal, we optimise this by deleting the operation\n // console.log(\"Omitting operation\")\n op = null\n } else if (typeof match.value === 'string' && typeof nextValue === 'string') {\n // console.log(\"Rewriting to dmp\")\n // We are updating a string to another string, so we are making a diffMatchPatch\n try {\n const patch = stringifyPatches(makePatches(match.value, nextValue))\n op = {patch: {id: this.PRESTAGE._id, diffMatchPatch: {[path]: patch}}}\n } catch {\n // patch_make failed due to unicode issue https://github.com/google/diff-match-patch/issues/59\n return false\n }\n } else {\n // console.log(\"Not able to rewrite to dmp, making normal set\")\n // We are changing the type of the value, so must make a normal set-operation\n op = {patch: {id: this.PRESTAGE._id, set: {[path]: nextValue}}}\n }\n\n // Let's make a plain, concrete path from the array-path. We use this to keep only the latest set\n // operation touching this path in the buffer.\n const canonicalPath = arrayToJSONMatchPath(match.path)\n\n // Store this operation, overwriting any previous operations touching this same path\n if (op) {\n this.setOperations[canonicalPath] = op\n } else {\n delete this.setOperations[canonicalPath]\n }\n\n // Signal that we succeeded in optimizing this patch\n return true\n }\n\n stashStagedOperations(): void {\n // Short circuit if there are no staged operations\n const nextOps: Mut[] = []\n\n // Extract the existing outgoing operations if any\n Object.keys(this.setOperations).forEach((key) => {\n const op = this.setOperations[key]\n if (op) {\n nextOps.push(op)\n }\n })\n\n nextOps.push(...this.staged)\n if (nextOps.length > 0) {\n this.PRESTAGE = new Mutation({mutations: nextOps}).apply(this.PRESTAGE) as Doc\n this.staged = []\n this.setOperations = {}\n }\n\n this.out.push(...nextOps)\n }\n\n /**\n * Rebases given the new base-document\n *\n * @param newBasis - New base document to rebase on\n * @returns New \"edge\" document with buffered changes integrated\n */\n rebase(newBasis: Doc | null): Doc | null {\n this.stashStagedOperations()\n\n if (newBasis === null) {\n // If document was just deleted, we must throw out local changes\n this.out = []\n this.BASIS = newBasis\n this.PRESTAGE = newBasis\n this.documentPresent = false\n } else {\n this.BASIS = newBasis\n\n // @todo was this supposed to be `this.out.length > 0`?\n // surely this is always `true`?\n if (this.out) {\n this.PRESTAGE = new Mutation({mutations: this.out}).apply(this.BASIS) as Doc\n } else {\n this.PRESTAGE = this.BASIS\n }\n }\n\n return this.PRESTAGE\n }\n}\n","import {isEqual} from 'lodash'\n\nimport {debug} from './debug'\nimport {Document} from './Document'\nimport {Mutation} from './Mutation'\nimport {SquashingBuffer} from './SquashingBuffer'\nimport {type Doc, type Mut} from './types'\n\nconst ONE_MINUTE = 1000 * 60\n\n/**\n * @internal\n */\nexport interface CommitHandlerMessage {\n mutation: Mutation\n success: () => void\n failure: () => void\n cancel: (error: Error) => void\n}\n\n/**\n * A wrapper for Document that allows the client to gather mutations on the\n * client side and commit them when it wants to.\n */\nclass Commit {\n mutations: Mutation[]\n tries: number\n resolve: () => void\n reject: (error: Error) => void\n\n constructor(\n mutations: Mutation[],\n {resolve, reject}: {resolve: () => void; reject: (error: Error) => void},\n ) {\n this.mutations = mutations\n this.tries = 0\n this.resolve = resolve\n this.reject = reject\n }\n\n apply(doc: Doc | null): Doc | null {\n return Mutation.applyAll(doc, this.mutations)\n }\n\n squash(doc: Doc | null) {\n const result = Mutation.squash(doc, this.mutations)\n result.assignRandomTransactionId()\n return result\n }\n}\n\nconst mutReducerFn = (acc: Mut[], mut: Mutation): Mut[] => acc.concat(mut.mutations)\n\n/**\n * @internal\n */\nexport class BufferedDocument {\n private mutations: Mutation[]\n\n /**\n * The Document we are wrapping\n */\n document: Document\n\n /**\n * The Document with local changes applied\n */\n LOCAL: Doc | null\n\n /**\n * Commits that are waiting to be delivered to the server\n */\n private commits: Commit[]\n\n /**\n * Local mutations that are not scheduled to be committed yet\n */\n buffer: SquashingBuffer\n\n /**\n * Assignable event handler for when the buffered document applies a mutation\n */\n onMutation?: (message: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n /**\n * Assignable event handler for when a remote mutation happened\n */\n onRemoteMutation?: Document['onRemoteMutation']\n\n /**\n * Assignable event handler for when the buffered document rebased\n */\n onRebase?: (localDoc: Doc | null, remoteMutations: Mut[], localMutations: Mut[]) => void\n\n /**\n * Assignable event handler for when the document is deleted\n */\n onDelete?: (doc: Doc | null) => void\n\n /**\n * Assignable event handler for when the state of consistency changed\n */\n onConsistencyChanged?: (isConsistent: boolean) => void\n\n /**\n * Assignable event handler for when the buffered document should commit changes\n */\n commitHandler?: (msg: CommitHandlerMessage) => void\n\n /**\n * Whether or not we are currently commiting\n */\n committerRunning = false\n\n constructor(doc: Doc | null) {\n this.buffer = new SquashingBuffer(doc)\n this.document = new Document(doc)\n this.document.onMutation = (msg) => this.handleDocMutation(msg)\n this.document.onRemoteMutation = (mut) => this.onRemoteMutation && this.onRemoteMutation(mut)\n this.document.onRebase = (edge, remoteMutations, localMutations) =>\n this.handleDocRebase(edge, remoteMutations, localMutations)\n this.document.onConsistencyChanged = (msg) => this.handleDocConsistencyChanged(msg)\n this.LOCAL = doc\n this.mutations = []\n this.commits = []\n }\n\n // Used to reset the state of the local document model. If the model has been inconsistent\n // for too long, it has probably missed a notification, and should reload the document from the server\n reset(doc: Doc | null): void {\n if (doc) {\n debug('Document state reset to revision %s', doc._rev)\n } else {\n debug('Document state reset to being deleted')\n }\n this.document.reset(doc)\n this.rebase([], [])\n this.handleDocConsistencyChanged(this.document.isConsistent())\n }\n\n // Add a change to the buffer\n add(mutation: Mutation): void {\n if (this.onConsistencyChanged) {\n this.onConsistencyChanged(false)\n }\n debug('Staged local mutation')\n this.buffer.add(mutation)\n const oldLocal = this.LOCAL\n this.LOCAL = mutation.apply(this.LOCAL)\n if (this.onMutation && oldLocal !== this.LOCAL) {\n debug('onMutation fired')\n this.onMutation({\n mutation,\n document: this.LOCAL,\n remote: false,\n })\n if (this.LOCAL === null && this.onDelete) {\n this.onDelete(this.LOCAL)\n }\n }\n }\n\n // Call when a mutation arrives from Sanity\n arrive(mutation: Mutation): void {\n debug('Remote mutation arrived %s -> %s', mutation.previousRev, mutation.resultRev)\n if (mutation.previousRev === mutation.resultRev) {\n throw new Error(\n `Mutation ${mutation.transactionId} has previousRev === resultRev (${mutation.previousRev})`,\n )\n }\n return this.document.arrive(mutation)\n }\n\n // Submit all mutations in the buffer to be committed\n commit(): Promise<void> {\n return new Promise((resolve, reject) => {\n // Anything to commit?\n if (!this.buffer.hasChanges()) {\n resolve()\n return\n }\n debug('Committing local changes')\n // Collect current staged mutations into a commit and ...\n const pendingMutations = this.buffer.purge()\n this.commits.push(new Commit(pendingMutations ? [pendingMutations] : [], {resolve, reject}))\n // ... clear the table for the next commit.\n this.buffer = new SquashingBuffer(this.LOCAL)\n this.performCommits()\n })\n }\n\n // Starts the committer that will try to committ all staged commits to the database\n // by calling the commitHandler. Will keep running until all commits are successfully\n // committed.\n performCommits(): void {\n if (!this.commitHandler) {\n throw new Error('No commitHandler configured for this BufferedDocument')\n }\n if (this.committerRunning) {\n // We can have only one committer at any given time\n return\n }\n this._cycleCommitter()\n }\n\n // TODO: Error handling, right now retries after every error\n _cycleCommitter(): void {\n const commit = this.commits.shift()\n if (!commit) {\n this.committerRunning = false\n return\n }\n\n this.committerRunning = true\n const squashed = commit.squash(this.LOCAL)\n const docResponder = this.document.stage(squashed, true)\n\n const responder = {\n success: () => {\n debug('Commit succeeded')\n docResponder.success()\n commit.resolve()\n // Keep running the committer until no more commits\n this._cycleCommitter()\n },\n\n failure: () => {\n debug('Commit failed')\n // Re stage commit\n commit.tries += 1\n if (this.LOCAL !== null) {\n // Only schedule this commit for a retry of the document still exist to avoid looping\n // indefinitely when the document was deleted from under our noses\n this.commits.unshift(commit)\n }\n docResponder.failure()\n\n // Todo: Need better error handling (i.e. propagate to user and provide means of retrying)\n if (commit.tries < 200) {\n setTimeout(() => this._cycleCommitter(), Math.min(commit.tries * 1000, ONE_MINUTE))\n }\n },\n\n cancel: (error: Error) => {\n this.commits.forEach((comm) => comm.reject(error))\n\n // Throw away waiting commits\n this.commits = []\n\n // Reset back to last known state from content lake and cause a rebase that will\n // reset the view in the form\n this.reset(this.document.HEAD)\n\n // Clear the buffer of recent mutations\n this.buffer = new SquashingBuffer(this.LOCAL)\n\n // Stop the committer loop\n this.committerRunning = false\n },\n }\n\n debug('Posting commit')\n if (this.commitHandler) {\n this.commitHandler({\n mutation: squashed,\n success: responder.success,\n failure: responder.failure,\n cancel: responder.cancel,\n })\n }\n }\n\n handleDocRebase(edge: Doc | null, remoteMutations: Mutation[], localMutations: Mutation[]): void {\n this.rebase(remoteMutations, localMutations)\n }\n\n handleDocumentDeleted(): void {\n debug('Document deleted')\n // If the document was just deleted, fire the onDelete event with the absolutely latest\n // version of the document before someone deleted it so that the client may revive the\n // document in the last state the user saw it, should they so desire.\n if (this.LOCAL !== null && this.onDelete) {\n this.onDelete(this.LOCAL)\n }\n\n this.commits = []\n this.mutations = []\n }\n\n handleDocMutation(msg: {mutation: Mutation; document: Doc | null; remote: boolean}): void {\n // If we have no local changes, we can just pass this on to the client\n if (this.commits.length === 0 && !this.buffer.hasChanges()) {\n debug('Document mutated from remote with no local changes')\n this.LOCAL = this.document.EDGE\n this.buffer = new SquashingBuffer(this.LOCAL)\n if (this.onMutation) {\n this.onMutation(msg)\n }\n return\n }\n\n debug('Document mutated from remote with local changes')\n\n // If there are local edits, and the document was deleted, we need to purge those local edits now\n if (this.document.EDGE === null) {\n this.handleDocumentDeleted()\n }\n\n // We had local changes, so need to signal rebase\n this.rebase([msg.mutation], [])\n }\n\n rebase(remoteMutations: Mutation[], localMutations: Mutation[]): void {\n debug('Rebasing document')\n if (this.document.EDGE === null) {\n this.handleDocumentDeleted()\n }\n\n const oldLocal = this.LOCAL\n this.LOCAL = this.commits.reduce((doc, commit) => commit.apply(doc), this.document.EDGE)\n this.LOCAL = this.buffer.rebase(this.LOCAL)\n\n // Copy over rev, since we don't care if it changed, we only care about the content\n if (oldLocal !== null && this.LOCAL !== null) {\n oldLocal._rev = this.LOCAL._rev\n }\n\n const changed = !isEqual(this.LOCAL, oldLocal)\n if (changed && this.onRebase) {\n this.onRebase(\n this.LOCAL,\n remoteMutations.reduce(mutReducerFn, []),\n localMutations.reduce(mutReducerFn, []),\n )\n }\n }\n\n handleDocConsistencyChanged(isConsistent: boolean): void {\n if (!this.onConsistencyChanged) {\n return\n }\n\n const hasLocalChanges = this.commits.length > 0 || this.buffer.hasChanges()\n\n if (isConsistent && !hasLocalChanges) {\n this.onConsistencyChanged(true)\n }\n\n if (!isConsistent) {\n this.onConsistencyChanged(false)\n }\n }\n}\n"],"names":["isRecord","descend","lhs","rhs","parsePatch"],"mappings":";;;;;;;;AAEO,MAAM,QAAQ,QAAQ,kBAAkB;ACKxC,MAAM,kBAAmC;AAAA,EAC9C;AAAA,EACA;AAAA,EAEA,YAAY,OAAgB,MAA4B;AACtD,SAAK,SAAS,OACd,KAAK,OAAO,QAAQ,CAAA;AAAA,EACtB;AAAA,EAEA,gBAAkD;AAChD,W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AK,WAAW,GAAG;AAErB;AAAA,IACF;AAEA,UAAM,iDAAiD,GAGnD,KAAK,SAAS,SAAS,QACzB,KAAK,sBAAA,GAIP,KAAK,OAAO,CAAC,IAAI,QAAQ,GAAG,EAAE;AAAA,EAChC;AAAA,EAEA,OAAO,iBAA6B,gBAAkC;AACpE,UAAM,mBAAmB,GACrB,KAAK,SAAS,SAAS,QACzB,KAAK,sBAAA;AAGP,UAAM,WAAW,KAAK;AACtB,SAAK,QAAQ,KAAK,QAAQ,OAAO,CAAC,KAAK,WAAW,OAAO,MAAM,GAAG,GAAG,KAAK,SAAS,IAAI,GACvF,KAAK,QAAQ,KAAK,OAAO,OAAO,KAAK,KAAK,GAGtC,aAAa,QAAQ,KAAK,UAAU,SACtC,SAAS,OAAO,KAAK,MAAM,OAGb,CAAC,QAAQ,KAAK,OAAO,QAAQ,KAC9B,KAAK,YAClB,KAAK;AAAA,MACH,KAAK;AAAA,MACL,gBAAgB,OAAO,cAAc,EAAE;AAAA,MACvC,eAAe,OAAO,cAAc,CAAA,CAAE;AAAA,IAAA;AAAA,EAG5C;AAAA,EAEA,4BAA4B,cAA6B;AACvD,QAAI,CAAC,KAAK;AACR;AAGF,UAAM,kBAAkB,KAAK,QAAQ,SAAS,KAAK,KAAK,OAAO,WAAA;AAE3D,oBAAgB,CAAC,mBACnB,KAAK,qBAAqB,EAAI,GAG3B,gBACH,KAAK,qBAAqB,EAAK;AAAA,EAEnC;AACF;"}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/document/debug.ts","../src/patch/ImmutableAccessor.ts","../src/util.ts","../src/jsonpath/arrayToJSONMatchPath.ts","../src/jsonpath/descend.ts","../src/jsonpath/tokenize.ts","../src/jsonpath/parse.ts","../src/jsonpath/toPath.ts","../src/jsonpath/Expression.ts","../src/jsonpath/Descender.ts","../src/jsonpath/Matcher.ts","../src/jsonpath/PlainProbe.ts","../src/jsonpath/extractAccessors.ts","../src/jsonpath/extract.ts","../src/jsonpath/extractWithPath.ts","../src/patch/DiffMatchPatch.ts","../src/patch/IncPatch.ts","../src/patch/util.ts","../src/patch/InsertPatch.ts","../src/patch/SetIfMissingPatch.ts","../src/patch/SetPatch.ts","../src/patch/UnsetPatch.ts","../src/patch/parse.ts","../src/patch/Patcher.ts","../src/document/luid.ts","../src/document/Mutation.ts","../src/document/Document.ts","../src/document/SquashingBuffer.ts","../src/document/BufferedDocument.ts"],"sourcesContent":["import debugIt from 'debug'\n\nexport const debug = debugIt('mutator-document')\n","import {type Probe} from '../jsonpath/Probe'\n\n/**\n * An immutable probe/writer for plain JS objects that will never mutate\n * the provided _value in place. Each setter returns a new (wrapped) version\n * of the value.\n */\nexport class ImmutableAccessor implements Probe {\n _value: unknown\n path: (string | number)[]\n\n constructor(value: unknown, path?: (string | number)[]) {\n this._value = value\n this.path = path || []\n }\n\n containerType(): 'array' | 'object' | 'primitive' {\n if (Array.isArray(this._value)) {\n return 'array'\n } else if (this._value !== null && typeof this._value === 'object') {\n return 'object'\n }\n return 'primitive'\n }\n\n // Common reader, supported by all containers\n get(): unknown {\n return this._value\n }\n\n // Array reader\n length(): number {\n if (!Array.isArray(this._value)) {\n throw new Error(\"Won't return length of non-indexable _value\")\n }\n\n return this._value.length\n }\n\n getIndex(i: number): ImmutableAccessor | false | null {\n if (!Array.isArray(this._value)) {\n return false\n }\n\n if (i >= this.length()) {\n return null\n }\n\n return new ImmutableAccessor(this._value[i], this.path.concat(i))\n }\n\n // Object reader\n hasAttribute(key: string): boolean {\n return isRecord(this._value) ? this._value.hasOwnProperty(key) : false\n }\n\n attributeKeys(): string[] {\n return isRecord(this._value) ? Object.keys(this._value) : []\n }\n\n getAttribute(key: string): ImmutableAccessor | null {\n if (!isRecord(this._value)) {\n throw new Error('getAttribute only applies to plain objects')\n }\n\n if (!this.hasAttribute(key)) {\n return null\n }\n\n return new ImmutableAccessor(this._value[key], this.path.concat(key))\n }\n\n // Common writer, supported by all containers\n set(value: unknown): ImmutableAccessor {\n return value === this._value ? this : new ImmutableAccessor(value, this.path)\n }\n\n // array writer interface\n setIndex(i: number, value: unknown): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('setIndex only applies to arrays')\n }\n\n if (Object.is(value, this._value[i])) {\n return this\n }\n\n const nextValue = this._value.slice()\n nextValue[i] = value\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n setIndexAccessor(i: number, accessor: ImmutableAccessor): ImmutableAccessor {\n return this.setIndex(i, accessor.get())\n }\n\n unsetIndices(indices: number[]): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('unsetIndices only applies to arrays')\n }\n\n const length = this._value.length\n const nextValue = []\n // Copy every _value _not_ in the indices array over to the newValue\n for (let i = 0; i < length; i++) {\n if (indices.indexOf(i) === -1) {\n nextValue.push(this._value[i])\n }\n }\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n insertItemsAt(pos: number, items: unknown[]): ImmutableAccessor {\n if (!Array.isArray(this._value)) {\n throw new Error('insertItemsAt only applies to arrays')\n }\n\n let nextValue\n if (this._value.length === 0 && pos === 0) {\n nextValue = items\n } else {\n nextValue = this._value.slice(0, pos).concat(items).concat(this._value.slice(pos))\n }\n\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n // Object writer interface\n setAttribute(key: string, value: unknown): ImmutableAccessor {\n if (!isRecord(this._value)) {\n throw new Error('Unable to set attribute of non-object container')\n }\n\n if (Object.is(value, this._value[key])) {\n return this\n }\n\n const nextValue = Object.assign({}, this._value, {[key]: value})\n return new ImmutableAccessor(nextValue, this.path)\n }\n\n setAttributeAccessor(key: string, accessor: ImmutableAccessor): ImmutableAccessor {\n return this.setAttribute(key, accessor.get())\n }\n\n unsetAttribute(key: string): ImmutableAccessor {\n if (!isRecord(this._value)) {\n throw new Error('Unable to unset attribute of non-object container')\n }\n\n const nextValue = Object.assign({}, this._value)\n delete nextValue[key]\n return new ImmutableAccessor(nextValue, this.path)\n }\n}\n\nfunction isRecord(value: unknown): value is {[key: string]: unknown} {\n return value !== null && typeof value === 'object'\n}\n","export function isRecord(value: unknown): value is {[key: string]: unknown} {\n return value !== null && typeof value === 'object'\n}\n","import {type Path, type PathSegment} from '@sanity/types'\n\nimport {isRecord} from '../util'\n\nconst IS_DOTTABLE = /^[a-z_$]+/\n\n/**\n * Converts a path in array form to a JSONPath string\n *\n * @param pathArray - Array of path segments\n * @returns String representation of the path\n * @internal\n */\nexport function arrayToJSONMatchPath(pathArray: Path): string {\n let path = ''\n pathArray.forEach((segment, index) => {\n path += stringifySegment(segment, index === 0)\n })\n return path\n}\n\n// Converts an array of simple values (strings, numbers only) to a jsonmatch path string.\nfunction stringifySegment(\n segment: PathSegment | Record<string, unknown>,\n hasLeading: boolean,\n): string {\n if (typeof segment === 'number') {\n return `[${segment}]`\n }\n\n if (isRecord(segment)) {\n const seg = segment as Record<string, unknown>\n return Object.keys(segment)\n .map((key) => (isPrimitiveValue(seg[key]) ? `[${key}==\"${seg[key]}\"]` : ''))\n .join('')\n }\n\n if (typeof segment === 'string' && IS_DOTTABLE.test(segment)) {\n return hasLeading ? segment : `.${segment}`\n }\n\n return `['${segment}']`\n}\n\nfunction isPrimitiveValue(val: unknown): val is string | number | boolean {\n switch (typeof val) {\n case 'number':\n case 'string':\n case 'boolean':\n return true\n default:\n return false\n }\n}\n","import {type Expr, type PathExpr} from './types'\n\n/**\n * Splits an expression into a set of heads, tails. A head is the next leaf node to\n * check for matches, and a tail is everything that follows it. Matching is done by\n * matching heads, then proceedint to the matching value, splitting the tail into\n * heads and tails and checking the heads against the new value, and so on.\n */\nexport function descend(tail: Expr): [Expr | null, PathExpr | null][] {\n const [head, newTail] = splitIfPath(tail)\n if (!head) {\n throw new Error('Head cannot be null')\n }\n\n return spreadIfUnionHead(head, newTail)\n}\n\n// Split path in [head, tail]\nfunction splitIfPath(tail: Expr): [Expr | null, PathExpr | null] {\n if (tail.type !== 'path') {\n return [tail, null]\n }\n\n const nodes = tail.nodes\n if (nodes.length === 0) {\n return [null, null]\n }\n\n if (nodes.length === 1) {\n return [nodes[0], null]\n }\n\n return [nodes[0], {type: 'path', nodes: nodes.slice(1)}]\n}\n\nfunction concatPaths(path1: PathExpr | null, path2: PathExpr | null): PathExpr | null {\n if (!path1 && !path2) {\n return null\n }\n\n const nodes1 = path1 ? path1.nodes : []\n const nodes2 = path2 ? path2.nodes : []\n return {\n type: 'path',\n nodes: nodes1.concat(nodes2),\n }\n}\n\n// Spreads a union head into several heads/tails\nfunction spreadIfUnionHead(head: Expr, tail: PathExpr | null): [Expr | null, PathExpr | null][] {\n if (head.type !== 'union') {\n return [[head, tail]]\n }\n\n return head.nodes.map((node) => {\n if (node.type === 'path') {\n const [subHead, subTail] = splitIfPath(node)\n return [subHead, concatPaths(subTail, tail)]\n }\n\n return [node, tail]\n })\n}\n","import {\n type IdentifierToken,\n type NumberToken,\n type QuotedToken,\n type SymbolClass,\n type SymbolToken,\n type Token,\n} from './types'\n\n// TODO: Support '*'\n\nconst digitChar = /[0-9]/\nconst attributeCharMatcher = /^[a-zA-Z0-9_]$/\nconst attributeFirstCharMatcher = /^[a-zA-Z_]$/\n\nconst symbols: Record<SymbolClass, string[]> = {\n // NOTE: These are compared against in order of definition,\n // thus '==' must come before '=', '>=' before '>', etc.\n operator: ['..', '.', ',', ':', '?'],\n comparator: ['>=', '<=', '<', '>', '==', '!='],\n keyword: ['$', '@'],\n boolean: ['true', 'false'],\n paren: ['[', ']'],\n}\n\nconst symbolClasses = Object.keys(symbols) as SymbolClass[]\n\ntype TokenizerFn = () => Token | null\n\n/**\n * Tokenizes a jsonpath2 expression\n */\nclass Tokenizer {\n source: string\n i: number\n length: number\n tokenizers: TokenizerFn[]\n\n constructor(path: string) {\n this.source = path\n this.length = path.length\n this.i = 0\n this.tokenizers = [\n this.tokenizeSymbol,\n this.tokenizeIdentifier,\n this.tokenizeNumber,\n this.tokenizeQuoted,\n ].map((fn) => fn.bind(this))\n }\n\n tokenize(): Token[] {\n const result: Token[] = []\n while (!this.EOF()) {\n this.chompWhitespace()\n let token: Token | null = null\n // @todo refactor into a simpler `.find()`?\n const found = this.tokenizers.some((tokenizer) => {\n token = tokenizer()\n return Boolean(token)\n })\n if (!found || !token) {\n throw new Error(`Invalid tokens in jsonpath '${this.source}' @ ${this.i}`)\n }\n result.push(token)\n }\n return result\n }\n\n takeWhile(fn: (character: string) => string | null): string | null {\n const start = this.i\n let result = ''\n while (!this.EOF()) {\n const nextChar = fn(this.source[this.i])\n if (nextChar === null) {\n break\n }\n result += nextChar\n this.i++\n }\n if (this.i === start) {\n return null\n }\n return result\n }\n\n EOF(): boolean {\n return this.i >= this.length\n }\n\n peek(): string | null {\n if (this.EOF()) {\n return null\n }\n return this.source[this.i]\n }\n\n consume(str: string) {\n if (this.i + str.length > this.length) {\n throw new Error(`Expected ${str} at end of jsonpath`)\n }\n if (str === this.source.slice(this.i, this.i + str.length)) {\n this.i += str.length\n } else {\n throw new Error(`Expected \"${str}\", but source contained \"${this.source.slice()}`)\n }\n }\n\n // Tries to match the upcoming bit of string with the provided string. If it matches, returns\n // the string, then advances the read pointer to the next bit. If not, returns null and nothing\n // happens.\n tryConsume(str: string) {\n if (this.i + str.length > this.length) {\n return null\n }\n if (str === this.source.slice(this.i, this.i + str.length)) {\n // When checking symbols that consist of valid attribute characters, we\n // need to make sure we don't inadvertently treat an attribute as a\n // symbol. For example, an attribute 'trueCustomerField' should not be\n // scanned as the boolean symbol \"true\".\n if (str[0].match(attributeCharMatcher)) {\n // check that char following the symbol match is not also an attribute char\n if (this.length > this.i + str.length) {\n const nextChar = this.source[this.i + str.length]\n if (nextChar && nextChar.match(attributeCharMatcher)) {\n return null\n }\n }\n }\n this.i += str.length\n return str\n }\n return null\n }\n\n chompWhitespace(): void {\n this.takeWhile((char): string | null => {\n return char === ' ' ? '' : null\n })\n }\n\n tokenizeQuoted(): QuotedToken | null {\n const quote = this.peek()\n if (quote === \"'\" || quote === '\"') {\n this.consume(quote)\n let escape = false\n const inner = this.takeWhile((char) => {\n if (escape) {\n escape = false\n return char\n }\n if (char === '\\\\') {\n escape = true\n return ''\n }\n if (char != quote) {\n return char\n }\n return null\n })\n this.consume(quote)\n return {\n type: 'quoted',\n value: inner,\n quote: quote === '\"' ? 'double' : 'single',\n }\n }\n return null\n }\n\n tokenizeIdentifier(): IdentifierToken | null {\n let first = true\n const identifier = this.takeWhile((char) => {\n if (first) {\n first = false\n return char.match(attributeFirstCharMatcher) ? char : null\n }\n return char.match(attributeCharMatcher) ? char : null\n })\n if (identifier !== null) {\n return {\n type: 'identifier',\n name: identifier,\n }\n }\n return null\n }\n\n tokenizeNumber(): NumberToken | null {\n const start = this.i\n let dotSeen = false\n let digitSeen = false\n let negative = false\n if (this.peek() === '-') {\n negative = true\n this.consume('-')\n }\n const number = this.takeWhile((char) => {\n if (char === '.' && !dotSeen && digitSeen) {\n dotSeen = true\n return char\n }\n digitSeen = true\n return char.match(digitChar) ? char : null\n })\n if (number !== null) {\n return {\n type: 'number',\n value: negative ? -Number(number) : +number,\n raw: negative ? `-${number}` : number,\n }\n }\n // No number, rewind\n this.i = start\n return null\n }\n\n tokenizeSymbol(): SymbolToken | null {\n for (const symbolClass of symbolClasses) {\n const patterns = symbols[symbolClass]\n const symbol = patterns.find((pattern) => this.tryConsume(pattern))\n if (symbol) {\n return {\n type: symbolClass,\n symbol,\n }\n }\n }\n\n return null\n }\n}\n\nexport function tokenize(jsonpath: string): Token[] {\n return new Tokenizer(jsonpath).tokenize()\n}\n","// Converts a string into an abstract syntax tree representation\n\nimport {tokenize} from './tokenize'\nimport {\n type AliasExpr,\n type AttributeExpr,\n type BooleanExpr,\n type ConstraintExpr,\n type IndexExpr,\n type NumberExpr,\n type PathExpr,\n type RangeExpr,\n type RecursiveExpr,\n type StringExpr,\n type Token,\n type UnionExpr,\n} from './types'\n\n// TODO: Support '*'\n\nclass Parser {\n tokens: Token[]\n length: number\n i: number\n\n constructor(path: string) {\n this.tokens = tokenize(path)\n this.length = this.tokens.length\n this.i = 0\n }\n\n parse() {\n return this.parsePath()\n }\n\n EOF() {\n return this.i >= this.length\n }\n\n // Look at upcoming token\n peek() {\n if (this.EOF()) {\n return null\n }\n return this.tokens[this.i]\n }\n\n consume() {\n const result = this.peek()\n this.i += 1\n return result\n }\n\n // Return next token if it matches the pattern\n probe(pattern: Record<string, unknown>): Token | null {\n const token = this.peek()\n if (!token) {\n return null\n }\n\n const record = token as unknown as Record<string, unknown>\n const match = Object.keys(pattern).every((key) => {\n return key in token && pattern[key] === record[key]\n })\n\n return match ? token : null\n }\n\n // Return and consume next token if it matches the pattern\n match(pattern: Partial<Token>): Token | null {\n return this.probe(pattern) ? this.consume() : null\n }\n\n parseAttribute(): AttributeExpr | null {\n const token = this.match({type: 'identifier'})\n if (token && token.type === 'identifier') {\n return {\n type: 'attribute',\n name: token.name,\n }\n }\n const quoted = this.match({type: 'quoted', quote: 'single'})\n if (quoted && quoted.type === 'quoted') {\n return {\n type: 'attribute',\n name: quoted.value || '',\n }\n }\n return null\n }\n\n parseAlias(): AliasExpr | null {\n if (this.match({type: 'keyword', symbol: '@'}) || this.match({type: 'keyword', symbol: '$'})) {\n return {\n type: 'alias',\n target: 'self',\n }\n }\n return null\n }\n\n parseNumber(): NumberExpr | null {\n const token = this.match({type: 'number'})\n if (token && token.type === 'number') {\n return {\n type: 'number',\n value: token.value,\n }\n }\n return null\n }\n\n parseNumberValue(): number | null {\n const expr = this.parseNumber()\n if (expr) {\n return expr.value\n }\n return null\n }\n\n parseSliceSelector(): RangeExpr | IndexExpr | null {\n const start = this.i\n const rangeStart = this.parseNumberValue()\n\n const colon1 = this.match({type: 'operator', symbol: ':'})\n if (!colon1) {\n if (rangeStart === null) {\n // Rewind, this was actually nothing\n this.i = start\n return null\n }\n\n // Unwrap, this was just a single index not followed by colon\n return {type: 'index', value: rangeStart}\n }\n\n const result: RangeExpr = {\n type: 'range',\n start: rangeStart,\n end: this.parseNumberValue(),\n }\n\n const colon2 = this.match({type: 'operator', symbol: ':'})\n if (colon2) {\n result.step = this.parseNumberValue()\n }\n\n if (result.start === null && result.end === null) {\n // rewind, this wasnt' a slice selector\n this.i = start\n return null\n }\n\n return result\n }\n\n parseValueReference(): AttributeExpr | RangeExpr | IndexExpr | null {\n return this.parseAttribute() || this.parseSliceSelector()\n }\n\n parseLiteralValue(): StringExpr | BooleanExpr | NumberExpr | null {\n const literalString = this.match({type: 'quoted', quote: 'double'})\n if (literalString && literalString.type === 'quoted') {\n return {\n type: 'string',\n value: literalString.value || '',\n }\n }\n const literalBoolean = this.match({type: 'boolean'})\n if (literalBoolean && literalBoolean.type === 'boolean') {\n return {\n type: 'boolean',\n value: literalBoolean.symbol === 'true',\n }\n }\n return this.parseNumber()\n }\n\n // TODO: Reorder constraints so that literal value is always on rhs, and variable is always\n // on lhs.\n parseFilterExpression(): ConstraintExpr | null {\n const start = this.i\n const expr = this.parseAttribute() || this.parseAlias()\n if (!expr) {\n return null\n }\n\n if (this.match({type: 'operator', symbol: '?'})) {\n return {\n type: 'constraint',\n operator: '?',\n lhs: expr,\n }\n }\n\n const binOp = this.match({type: 'comparator'})\n if (!binOp || binOp.type !== 'comparator') {\n // No expression, rewind!\n this.i = start\n return null\n }\n\n const lhs = expr\n const rhs = this.parseLiteralValue()\n if (!rhs) {\n throw new Error(`Operator ${binOp.symbol} needs a literal value at the right hand side`)\n }\n\n return {\n type: 'constraint',\n operator: binOp.symbol,\n lhs: lhs,\n rhs: rhs,\n }\n }\n\n parseExpression(): ConstraintExpr | AttributeExpr | RangeExpr | IndexExpr | null {\n return this.parseFilterExpression() || this.parseValueReference()\n }\n\n parseUnion(): UnionExpr | null {\n if (!this.match({type: 'paren', symbol: '['})) {\n return null\n }\n\n const terms = []\n let expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n while (expr) {\n terms.push(expr)\n // End of union?\n if (this.match({type: 'paren', symbol: ']'})) {\n break\n }\n\n if (!this.match({type: 'operator', symbol: ','})) {\n throw new Error('Expected ]')\n }\n\n expr = this.parseFilterExpression() || this.parsePath() || this.parseValueReference()\n if (!expr) {\n throw new Error(\"Expected expression following ','\")\n }\n }\n\n return {\n type: 'union',\n nodes: terms,\n }\n }\n\n parseRecursive(): RecursiveExpr | null {\n if (!this.match({type: 'operator', symbol: '..'})) {\n return null\n }\n\n const subpath = this.parsePath()\n if (!subpath) {\n throw new Error(\"Expected path following '..' operator\")\n }\n\n return {\n type: 'recursive',\n term: subpath,\n }\n }\n\n parsePath(): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr | null {\n const nodes: (AttributeExpr | UnionExpr | RecursiveExpr)[] = []\n const expr = this.parseAttribute() || this.parseUnion() || this.parseRecursive()\n if (!expr) {\n return null\n }\n\n nodes.push(expr)\n while (!this.EOF()) {\n if (this.match({type: 'operator', symbol: '.'})) {\n const attr = this.parseAttribute()\n if (!attr) {\n throw new Error(\"Expected attribute name following '.\")\n }\n nodes.push(attr)\n continue\n } else if (this.probe({type: 'paren', symbol: '['})) {\n const union = this.parseUnion()\n if (!union) {\n throw new Error(\"Expected union following '['\")\n }\n nodes.push(union)\n } else {\n const recursive = this.parseRecursive()\n if (recursive) {\n nodes.push(recursive)\n }\n break\n }\n }\n\n if (nodes.length === 1) {\n return nodes[0]\n }\n\n return {\n type: 'path',\n nodes: nodes,\n }\n }\n}\n\nexport function parseJsonPath(path: string): PathExpr | AttributeExpr | UnionExpr | RecursiveExpr {\n const parsed = new Parser(path).parse()\n if (!parsed) {\n throw new Error(`Failed to parse JSON path \"${path}\"`)\n }\n return parsed\n}\n","import {type Expr} from './types'\n\n/**\n * Converts a parsed expression back into jsonpath2, roughly -\n * mostly for use with tests.\n *\n * @param expr - Expression to convert to path\n * @returns a string representation of the path\n * @internal\n */\nexport function toPath(expr: Expr): string {\n return toPathInner(expr, false)\n}\n\nfunction toPathInner(expr: Expr, inUnion: boolean): string {\n switch (expr.type) {\n case 'attribute':\n return expr.name\n case 'alias':\n return expr.target === 'self' ? '@' : '$'\n case 'number':\n return `${expr.value}`\n case 'range': {\n const result = []\n if (!inUnion) {\n result.push('[')\n }\n if (expr.start) {\n result.push(`${expr.start}`)\n }\n result.push(':')\n if (expr.end) {\n result.push(`${expr.end}`)\n }\n if (expr.step) {\n result.push(`:${expr.step}`)\n }\n if (!inUnion) {\n result.push(']')\n }\n return result.join('')\n }\n case 'index':\n if (inUnion) {\n return `${expr.value}`\n }\n\n return `[${expr.value}]`\n case 'constraint': {\n const rhs = expr.rhs ? ` ${toPathInner(expr.rhs, false)}` : ''\n const inner = `${toPathInner(expr.lhs, false)} ${expr.operator}${rhs}`\n\n if (inUnion) {\n return inner\n }\n\n return `[${inner}]`\n }\n case 'string':\n return JSON.stringify(expr.value)\n case 'path': {\n const result = []\n const nodes = expr.nodes.slice()\n while (nodes.length > 0) {\n const node = nodes.shift()\n if (node) {\n result.push(toPath(node))\n }\n\n const upcoming = nodes[0]\n if (upcoming && toPathInner(upcoming, false)[0] !== '[') {\n result.push('.')\n }\n }\n return result.join('')\n }\n case 'union':\n return `[${expr.nodes.map((e) => toPathInner(e, true)).join(',')}]`\n default:\n throw new Error(`Unknown node type ${expr.type}`)\n case 'recursive':\n return `..${toPathInner(expr.term, false)}`\n }\n}\n","// A utility wrapper class to process parsed jsonpath expressions\n\nimport {descend} from './descend'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\nimport {toPath} from './toPath'\nimport {type Expr, type HeadTail} from './types'\n\nexport interface Range {\n start: number\n end: number\n step: number\n}\n\nexport class Expression {\n expr: Expr\n\n constructor(expr: Expr | Expression | null) {\n if (!expr) {\n throw new Error('Attempted to create Expression from null-value')\n }\n\n // This is a wrapped expr\n if ('expr' in expr) {\n this.expr = expr.expr\n } else {\n this.expr = expr\n }\n\n if (!('type' in this.expr)) {\n throw new Error('Attempt to create Expression for expression with no type')\n }\n }\n\n isPath(): boolean {\n return this.expr.type === 'path'\n }\n\n isUnion(): boolean {\n return this.expr.type === 'union'\n }\n\n isCollection(): boolean {\n return this.isPath() || this.isUnion()\n }\n\n isConstraint(): boolean {\n return this.expr.type === 'constraint'\n }\n\n isRecursive(): boolean {\n return this.expr.type === 'recursive'\n }\n\n isExistenceConstraint(): boolean {\n return this.expr.type === 'constraint' && this.expr.operator === '?'\n }\n\n isIndex(): boolean {\n return this.expr.type === 'index'\n }\n\n isRange(): boolean {\n return this.expr.type === 'range'\n }\n\n expandRange(probe?: Probe): Range {\n const probeLength = () => {\n if (!probe) {\n throw new Error('expandRange() required a probe that was not passed')\n }\n\n return probe.length()\n }\n\n let start = 'start' in this.expr ? this.expr.start || 0 : 0\n start = interpretNegativeIndex(start, probe)\n let end = 'end' in this.expr ? this.expr.end || probeLength() : probeLength()\n end = interpretNegativeIndex(end, probe)\n const step = 'step' in this.expr ? this.expr.step || 1 : 1\n return {start, end, step}\n }\n\n isAttributeReference(): boolean {\n return this.expr.type === 'attribute'\n }\n\n // Is a range or index -> something referencing indexes\n isIndexReference(): boolean {\n return this.isIndex() || this.isRange()\n }\n\n name(): string {\n return 'name' in this.expr ? this.expr.name : ''\n }\n\n isSelfReference(): boolean {\n return this.expr.type === 'alias' && this.expr.target === 'self'\n }\n\n constraintTargetIsSelf(): boolean {\n return (\n this.expr.type === 'constraint' &&\n this.expr.lhs.type === 'alias' &&\n this.expr.lhs.target === 'self'\n )\n }\n\n constraintTargetIsAttribute(): boolean {\n return this.expr.type === 'constraint' && this.expr.lhs.type === 'attribute'\n }\n\n testConstraint(probe: Probe): boolean {\n const expr = this.expr\n\n if (expr.type === 'constraint' && expr.lhs.type === 'alias' && expr.lhs.target === 'self') {\n if (probe.containerType() !== 'primitive') {\n return false\n }\n\n if (expr.type === 'constraint' && expr.operator === '?') {\n return true\n }\n\n const lhs = probe.get()\n const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n return testBinaryOperator(lhs, expr.operator, rhs)\n }\n\n if (expr.type !== 'constraint') {\n return false\n }\n\n const lhs = expr.lhs\n if (!lhs) {\n throw new Error('No LHS of expression')\n }\n\n if (lhs.type !== 'attribute') {\n throw new Error(`Constraint target ${lhs.type} not supported`)\n }\n\n if (probe.containerType() !== 'object') {\n return false\n }\n\n const lhsValue = probe.getAttribute(lhs.name)\n if (lhsValue === undefined || lhsValue === null || lhsValue.containerType() !== 'primitive') {\n // LHS is void and empty, or it is a collection\n return false\n }\n\n if (this.isExistenceConstraint()) {\n // There is no rhs, and if we're here the key did exist\n return true\n }\n\n const rhs = expr.rhs && 'value' in expr.rhs ? expr.rhs.value : undefined\n return testBinaryOperator(lhsValue.get(), expr.operator, rhs)\n }\n\n pathNodes(): Expr[] {\n return this.expr.type === 'path' ? this.expr.nodes : [this.expr]\n }\n\n prepend(node: Expression): Expression {\n if (!node) {\n return this\n }\n\n return new Expression({\n type: 'path',\n nodes: node.pathNodes().concat(this.pathNodes()),\n })\n }\n\n concat(other: Expression | null): Expression {\n return other ? other.prepend(this) : this\n }\n\n descend(): HeadTail[] {\n return descend(this.expr).map((headTail) => {\n const [head, tail] = headTail\n return {\n head: head ? new Expression(head) : null,\n tail: tail ? new Expression(tail) : null,\n }\n })\n }\n\n unwrapRecursive(): Expression {\n if (this.expr.type !== 'recursive') {\n throw new Error(`Attempt to unwrap recursive on type ${this.expr.type}`)\n }\n\n return new Expression(this.expr.term)\n }\n\n toIndicies(probe?: Probe): number[] {\n if (this.expr.type !== 'index' && this.expr.type !== 'range') {\n throw new Error('Node cannot be converted to indexes')\n }\n\n if (this.expr.type === 'index') {\n return [interpretNegativeIndex(this.expr.value, probe)]\n }\n\n const result: number[] = []\n const range = this.expandRange(probe)\n let {start, end} = range\n if (range.step < 0) {\n ;[start, end] = [end, start]\n }\n\n for (let i = start; i < end; i++) {\n result.push(i)\n }\n\n return result\n }\n\n toFieldReferences(): number[] | string[] {\n if (this.isIndexReference()) {\n return this.toIndicies()\n }\n if (this.expr.type === 'attribute') {\n return [this.expr.name]\n }\n throw new Error(`Can't convert ${this.expr.type} to field references`)\n }\n\n toString(): string {\n return toPath(this.expr)\n }\n\n static fromPath(path: string): Expression {\n const parsed = parseJsonPath(path)\n if (!parsed) {\n throw new Error(`Failed to parse path \"${path}\"`)\n }\n\n return new Expression(parsed)\n }\n\n static attributeReference(name: string): Expression {\n return new Expression({\n type: 'attribute',\n name: name,\n })\n }\n\n static indexReference(i: number): Expression {\n return new Expression({\n type: 'index',\n value: i,\n })\n }\n}\n\n// Tests an operator on two given primitive values\nfunction testBinaryOperator(lhsValue: any, operator: string, rhsValue: any) {\n switch (operator) {\n case '>':\n return lhsValue > rhsValue\n case '>=':\n return lhsValue >= rhsValue\n case '<':\n return lhsValue < rhsValue\n case '<=':\n return lhsValue <= rhsValue\n case '==':\n return lhsValue === rhsValue\n case '!=':\n return lhsValue !== rhsValue\n default:\n throw new Error(`Unsupported binary operator ${operator}`)\n }\n}\n\nfunction interpretNegativeIndex(index: number, probe?: Probe): number {\n if (index >= 0) {\n return index\n }\n\n if (!probe) {\n throw new Error('interpretNegativeIndex() must have a probe when < 0')\n }\n\n return index + probe.length()\n}\n","import {flatten} from 'lodash-es'\n\nimport {Expression} from './Expression'\nimport {type Probe} from './Probe'\n\n/**\n * Descender models the state of one partial jsonpath evaluation. Head is the\n * next thing to match, tail is the upcoming things once the head is matched.\n */\nexport class Descender {\n head: Expression | null\n tail: Expression | null\n\n constructor(head: Expression | null, tail: Expression | null) {\n this.head = head\n this.tail = tail\n }\n\n // Iterate this descender once processing any constraints that are\n // resolvable on the current value. Returns an array of new descenders\n // that are guaranteed to be without constraints in the head\n iterate(probe: Probe): Descender[] {\n let result: Descender[] = [this]\n if (this.head && this.head.isConstraint()) {\n let anyConstraints = true\n // Keep rewriting constraints until there are none left\n while (anyConstraints) {\n result = flatten(\n result.map((descender) => {\n return descender.iterateConstraints(probe)\n }),\n )\n anyConstraints = result.some((descender) => {\n return descender.head && descender.head.isConstraint()\n })\n }\n }\n return result\n }\n\n isRecursive(): boolean {\n return Boolean(this.head && this.head.isRecursive())\n }\n\n hasArrived(): boolean {\n return this.head === null && this.tail === null\n }\n\n extractRecursives(): Descender[] {\n if (this.head && this.head.isRecursive()) {\n const term = this.head.unwrapRecursive()\n return new Descender(null, term.concat(this.tail)).descend()\n }\n return []\n }\n\n iterateConstraints(probe: Probe): Descender[] {\n const head = this.head\n if (head === null || !head.isConstraint()) {\n // Not a constraint, no rewrite\n return [this]\n }\n\n const result: Descender[] = []\n\n if (probe.containerType() === 'primitive' && head.constraintTargetIsSelf()) {\n if (head.testConstraint(probe)) {\n result.push(...this.descend())\n }\n return result\n }\n\n // The value is an array\n if (probe.containerType() === 'array') {\n const length = probe.length()\n for (let i = 0; i < length; i++) {\n // Push new descenders with constraint translated to literal indices\n // where they match\n const constraint = probe.getIndex(i)\n if (constraint && head.testConstraint(constraint)) {\n result.push(new Descender(new Expression({type: 'index', value: i}), this.tail))\n }\n }\n return result\n }\n\n // The value is an object\n if (probe.containerType() === 'object') {\n if (head.constraintTargetIsSelf()) {\n // There are no matches for target self ('@') on a plain object\n return []\n }\n\n if (head.testConstraint(probe)) {\n return this.descend()\n }\n\n return result\n }\n\n return result\n }\n\n descend(): Descender[] {\n if (!this.tail) {\n return [new Descender(null, null)]\n }\n\n return this.tail.descend().map((ht) => {\n return new Descender(ht.head, ht.tail)\n })\n }\n\n toString(): string {\n const result = ['<']\n if (this.head) {\n result.push(this.head.toString())\n }\n result.push('|')\n if (this.tail) {\n result.push(this.tail.toString())\n }\n result.push('>')\n return result.join('')\n }\n}\n","import {Descender} from './Descender'\nimport {Expression} from './Expression'\nimport {parseJsonPath} from './parse'\nimport {type Probe} from './Probe'\n\ninterface Result<P = unknown> {\n leads: {\n target: Expression\n matcher: Matcher\n }[]\n\n delivery?: {\n targets: Expression[]\n payload: P\n }\n}\n\n/**\n * @internal\n */\nexport class Matcher {\n active: Descender[]\n recursives: Descender[]\n payload: unknown\n\n constructor(active: Descender[], parent?: Matcher) {\n this.active = active || []\n if (parent) {\n this.recursives = parent.recursives\n this.payload = parent.payload\n } else {\n this.recursives = []\n }\n this.extractRecursives()\n }\n\n setPayload(payload: unknown): this {\n this.payload = payload\n return this\n }\n\n // Moves any recursive descenders onto the recursive track, removing them from\n // the active set\n extractRecursives(): void {\n this.active = this.active.filter((descender) => {\n if (descender.isRecursive()) {\n this.recursives.push(...descender.extractRecursives())\n return false\n }\n return true\n })\n }\n\n // Find recursives that are relevant now and should be considered part of the active set\n activeRecursives(probe: Probe): Descender[] {\n return this.recursives.filter((descender) => {\n const head = descender.head\n if (!head) {\n return false\n }\n\n // Constraints are always relevant\n if (head.isConstraint()) {\n return true\n }\n\n // Index references are only relevant for indexable values\n if (probe.containerType() === 'array' && head.isIndexReference()) {\n return true\n }\n\n // Attribute references are relevant for plain objects\n if (probe.containerType() === 'object') {\n return head.isAttributeReference() && probe.hasAttribute(head.name())\n }\n\n return false\n })\n }\n\n match(probe: Probe): Result {\n return this.iterate(probe).extractMatches(probe)\n }\n\n iterate(probe: Probe): Matcher {\n const newActiveSet: Descender[] = []\n this.active.concat(this.activeRecursives(probe)).forEach((descender) => {\n newActiveSet.push(...descender.iterate(probe))\n })\n return new Matcher(newActiveSet, this)\n }\n\n // Returns true if any of the descenders in the active or recursive set\n // consider the current state a final destination\n isDestination(): boolean {\n return this.active.some((descender) => descender.hasArrived())\n }\n\n hasRecursives(): boolean {\n return this.recursives.length > 0\n }\n\n // Returns any payload delivieries and leads that needs to be followed to complete\n // the process.\n extractMatches(probe: Probe): Result {\n const leads: {target: Expression; matcher: Matcher}[] = []\n const targets: Expression[] = []\n this.active.forEach((descender) => {\n if (descender.hasArrived()) {\n // This was already arrived, so matches this value, not descenders\n targets.push(\n new Expression({\n type: 'alias',\n target: 'self',\n }),\n )\n return\n }\n\n const descenderHead = descender.head\n if (!descenderHead) {\n return\n }\n\n if (probe.containerType() === 'array' && !descenderHead.isIndexReference()) {\n // This descender does not match an indexable value\n return\n }\n\n if (probe.containerType() === 'object' && !descenderHead.isAttributeReference()) {\n // This descender never match a plain object\n return\n }\n\n if (descender.tail) {\n // Not arrived yet\n const matcher = new Matcher(descender.descend(), this)\n descenderHead.toFieldReferences().forEach(() => {\n leads.push({\n target: descenderHead,\n matcher: matcher,\n })\n })\n } else {\n // arrived\n targets.push(descenderHead)\n }\n })\n\n // If there are recursive terms, we need to add a lead for every descendant ...\n if (this.hasRecursives()) {\n // The recustives matcher will have no active set, only inherit recursives from this\n const recursivesMatcher = new Matcher([], this)\n if (probe.containerType() === 'array') {\n const length = probe.length()\n for (let i = 0; i < length; i++) {\n leads.push({\n target: Expression.indexReference(i),\n matcher: recursivesMatcher,\n })\n }\n } else if (probe.containerType() === 'object') {\n probe.attributeKeys().forEach((name) => {\n leads.push({\n target: Expression.attributeReference(name),\n matcher: recursivesMatcher,\n })\n })\n }\n }\n\n return targets.length > 0\n ? {leads: leads, delivery: {targets, payload: this.payload}}\n : {leads: leads}\n }\n\n static fromPath(jsonpath: string): Matcher {\n const path = parseJsonPath(jsonpath)\n if (!path) {\n throw new Error(`Failed to parse path from \"${jsonpath}\"`)\n }\n\n const descender = new Descender(null, new Expression(path))\n return new Matcher(descender.descend())\n }\n}\n","import {isRecord} from '../util'\nimport {type Probe} from './Probe'\n\n// A default implementation of a probe for vanilla JS _values\nexport class PlainProbe implements Probe {\n _value: unknown\n path: (string | number)[]\n\n constructor(value: unknown, path?: (string | number)[]) {\n this._value = value\n this.path = path || []\n }\n\n containerType(): 'array' | 'object' | 'primitive' {\n if (Array.isArray(this._value)) {\n return 'array'\n } else if (this._value !== null && typeof this._value === 'object') {\n return 'object'\n }\n return 'primitive'\n }\n\n length(): number {\n if (!Array.isArray(this._value)) {\n throw new Error(\"Won't return length of non-indexable _value\")\n }\n\n return this._value.length\n }\n\n getIndex(i: number): false | null | PlainProbe {\n if (!Array.isArray(this._value)) {\n return false\n }\n\n if (i >= this.length()) {\n return null\n }\n\n return new PlainProbe(this._value[i], this.path.concat(i))\n }\n\n hasAttribute(key: string): boolean {\n if (!isRecord(this._value)) {\n return false\n }\n\n return this._value.hasOwnProperty(key)\n }\n\n attributeKeys(): string[] {\n return isRecord(this._value) ? Object.keys(this._value) : []\n }\n\n getAttribute(key: string): null | PlainProbe {\n if (!isRecord(this._value)) {\n throw new Error('getAttribute only applies to plain objects')\n }\n\n if (!this.hasAttribute(key)) {\n return null\n }\n\n return new PlainProbe(this._value[key], this.path.concat(key))\n }\n\n get(): unknown {\n return this._value\n }\n}\n","import {compact} from 'lodash-es'\n\nimport {type Expression} from './Expression'\nimport {Matcher} from './Matcher'\nimport {PlainProbe} from './PlainProbe'\nimport {type Probe} from './Probe'\n\nexport function extractAccessors(path: string, value: unknown): Probe[] {\n const result: Probe[] = []\n const matcher = Matcher.fromPath(path).setPayload(function appendResult(values: Probe[]) {\n result.push(...values)\n })\n const accessor = new PlainProbe(value)\n descend(matcher, accessor)\n return result\n}\n\nfunction descend(matcher: Matcher, accessor: Probe) {\n const {leads, delivery} = matcher.match(accessor)\n\n leads.forEach((lead) => {\n accessorsFromTarget(lead.target, accessor).forEach((childAccessor) => {\n descend(lead.matcher, childAccessor)\n })\n })\n\n if (delivery) {\n delivery.targets.forEach((target) => {\n if (typeof delivery.payload === 'function') {\n delivery.payload(accessorsFromTarget(target, accessor))\n }\n })\n }\n}\n\nfunction accessorsFromTarget(target: Expression, accessor: Probe) {\n const result = []\n if (target.isIndexReference()) {\n target.toIndicies(accessor).forEach((i) => {\n result.push(accessor.getIndex(i))\n })\n } else if (target.isAttributeReference()) {\n result.push(accessor.getAttribute(target.name()))\n } else if (target.isSelfReference()) {\n result.push(accessor)\n } else {\n throw new Error(`Unable to derive accessor for target ${target.toString()}`)\n }\n return compact(result)\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts values matching the given JsonPath\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of values matching the given path\n * @public\n */\nexport function extract(path: string, value: unknown): unknown[] {\n const accessors = extractAccessors(path, value)\n return accessors.map((acc) => acc.get())\n}\n","import {extractAccessors} from './extractAccessors'\n\n/**\n * Extracts a value for the given JsonPath, and includes the specific path of where it was found\n *\n * @param path - Path to extract\n * @param value - Value to extract from\n * @returns An array of objects with `path` and `value` keys\n * @internal\n */\nexport function extractWithPath(\n path: string,\n value: unknown,\n): {path: (string | number)[]; value: unknown}[] {\n const accessors = extractAccessors(path, value)\n return accessors.map((acc) => ({path: acc.path, value: acc.get()}))\n}\n","import {applyPatches, parsePatch, type Patch} from '@sanity/diff-match-patch'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction applyPatch(patch: Patch[], oldValue: unknown) {\n // Silently avoid patching if the value type is not string\n if (typeof oldValue !== 'string') return oldValue\n const [result] = applyPatches(patch, oldValue, {allowExceedingIndices: true})\n return result\n}\n\nexport class DiffMatchPatch {\n path: string\n dmpPatch: Patch[]\n id: string\n\n constructor(id: string, path: string, dmpPatchSrc: string) {\n this.id = id\n this.path = path\n this.dmpPatch = parsePatch(dmpPatchSrc)\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n\n // The target must be a container type\n if (result.containerType() === 'primitive') {\n return result\n }\n\n for (const target of targets) {\n if (target.isIndexReference()) {\n for (const index of target.toIndicies(accessor)) {\n // Skip patching unless the index actually currently exists\n const item = result.getIndex(index)\n if (!item) {\n continue\n }\n\n const oldValue = item.get()\n const nextValue = applyPatch(this.dmpPatch, oldValue)\n result = result.setIndex(index, nextValue)\n }\n\n continue\n }\n\n if (target.isAttributeReference() && result.hasAttribute(target.name())) {\n const attribute = result.getAttribute(target.name())\n if (!attribute) {\n continue\n }\n\n const oldValue = attribute.get()\n const nextValue = applyPatch(this.dmpPatch, oldValue)\n result = result.setAttribute(target.name(), nextValue)\n continue\n }\n\n throw new Error(`Unable to apply diffMatchPatch to target ${target.toString()}`)\n }\n\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nfunction performIncrement(previousValue: unknown, delta: number): number {\n if (typeof previousValue !== 'number' || !Number.isFinite(previousValue)) {\n return previousValue as number\n }\n\n return previousValue + delta\n}\n\nexport class IncPatch {\n path: string\n value: number\n id: string\n\n constructor(id: string, path: string, value: number) {\n this.path = path\n this.value = value\n this.id = id\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n\n // The target must be a container type\n if (result.containerType() === 'primitive') {\n return result\n }\n\n for (const target of targets) {\n if (target.isIndexReference()) {\n for (const index of target.toIndicies(accessor)) {\n // Skip patching unless the index actually currently exists\n const item = result.getIndex(index)\n if (!item) {\n continue\n }\n\n const previousValue = item.get()\n result = result.setIndex(index, performIncrement(previousValue, this.value))\n }\n\n continue\n }\n\n if (target.isAttributeReference()) {\n const attribute = result.getAttribute(target.name())\n if (!attribute) {\n continue\n }\n\n const previousValue = attribute.get()\n result = result.setAttribute(target.name(), performIncrement(previousValue, this.value))\n continue\n }\n\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport function targetsToIndicies(targets: Expression[], accessor: ImmutableAccessor): number[] {\n const result: number[] = []\n targets.forEach((target) => {\n if (target.isIndexReference()) {\n result.push(...target.toIndicies(accessor))\n }\n })\n return result.sort((a, b) => a - b)\n}\n","import {max, min} from 'lodash-es'\n\nimport {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class InsertPatch {\n location: string\n path: string\n items: unknown[]\n id: string\n\n constructor(id: string, location: string, path: string, items: unknown[]) {\n this.id = id\n this.location = location\n this.path = path\n this.items = items\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n if (accessor.containerType() !== 'array') {\n throw new Error('Attempt to apply insert patch to non-array value')\n }\n\n switch (this.location) {\n case 'before': {\n const pos = minIndex(targets, accessor)\n result = result.insertItemsAt(pos, this.items)\n break\n }\n case 'after': {\n const pos = maxIndex(targets, accessor)\n result = result.insertItemsAt(pos + 1, this.items)\n break\n }\n case 'replace': {\n // TODO: Properly implement ranges in compliance with content lake\n // This will only properly support single contiguous ranges\n const indicies = targetsToIndicies(targets, accessor)\n result = result.unsetIndices(indicies)\n result = result.insertItemsAt(indicies[0], this.items)\n break\n }\n default: {\n throw new Error(`Unsupported location atm: ${this.location}`)\n }\n }\n return result\n }\n}\n\nfunction minIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n let result = min(targetsToIndicies(targets, accessor)) || 0\n\n // Ranges may be zero-length and not turn up in indices\n targets.forEach((target) => {\n if (target.isRange()) {\n const {start} = target.expandRange()\n if (start < result) {\n result = start\n }\n }\n })\n return result\n}\n\nfunction maxIndex(targets: Expression[], accessor: ImmutableAccessor): number {\n let result = max(targetsToIndicies(targets, accessor)) || 0\n\n // Ranges may be zero-length and not turn up in indices\n targets.forEach((target) => {\n if (target.isRange()) {\n const {end} = target.expandRange()\n if (end > result) {\n result = end\n }\n }\n })\n return result\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetIfMissingPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string, value: unknown) {\n this.id = id\n this.path = path\n this.value = value\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n targets.forEach((target) => {\n if (target.isIndexReference()) {\n // setIfMissing do not apply to arrays, since Content Lake will reject nulls in arrays\n } else if (target.isAttributeReference()) {\n // setting a subproperty on a primitive value overwrites it, eg\n // `{setIfMissing: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will\n // result in `{address: {street: 'California St'}}`\n if (result.containerType() === 'primitive') {\n result = result.set({[target.name()]: this.value})\n } else if (!result.hasAttribute(target.name())) {\n result = accessor.setAttribute(target.name(), this.value)\n }\n } else {\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n })\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\n\nexport class SetPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string, value: unknown) {\n this.id = id\n this.path = path\n this.value = value\n }\n\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n targets.forEach((target) => {\n if (target.isSelfReference()) {\n result = result.set(this.value)\n } else if (target.isIndexReference()) {\n target.toIndicies(accessor).forEach((i) => {\n result = result.setIndex(i, this.value)\n })\n } else if (target.isAttributeReference()) {\n // setting a subproperty on a primitive value overwrites it, eg\n // `{set: {'address.street': 'California St'}}` on `{address: 'Fiction St'}` will result in\n // `{address: {street: 'California St'}}`\n if (result.containerType() === 'primitive') {\n result = result.set({[target.name()]: this.value})\n } else {\n result = result.setAttribute(target.name(), this.value)\n }\n } else {\n throw new Error(`Unable to apply to target ${target.toString()}`)\n }\n })\n return result\n }\n}\n","import {type Expression} from '../jsonpath'\nimport {type ImmutableAccessor} from './ImmutableAccessor'\nimport {targetsToIndicies} from './util'\n\nexport class UnsetPatch {\n id: string\n path: string\n value: unknown\n\n constructor(id: string, path: string) {\n this.id = id\n this.path = path\n }\n\n // eslint-disable-next-line class-methods-use-this\n apply(targets: Expression[], accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n switch (accessor.containerType()) {\n case 'array':\n result = result.unsetIndices(targetsToIndicies(targets, accessor))\n break\n case 'object':\n targets.forEach((target) => {\n result = result.unsetAttribute(target.name())\n })\n break\n default:\n throw new Error(\n 'Target value is neither indexable or an object. This error should potentially just be silently ignored?',\n )\n }\n return result\n }\n}\n","import {DiffMatchPatch} from './DiffMatchPatch'\nimport {IncPatch} from './IncPatch'\nimport {InsertPatch} from './InsertPatch'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\nimport {UnsetPatch} from './UnsetPatch'\n\n// Parses a content lake patch into our own personal patch implementations\nexport function parsePatch(patch: SingleDocumentPatch | SingleDocumentPatch[]): PatchTypes[] {\n const result: PatchTypes[] = []\n if (Array.isArray(patch)) {\n return patch.reduce((r, p) => r.concat(parsePatch(p)), result)\n }\n\n const {set, setIfMissing, unset, diffMatchPatch, inc, dec, insert} = patch\n if (setIfMissing) {\n Object.keys(setIfMissing).forEach((path) => {\n result.push(new SetIfMissingPatch(patch.id, path, setIfMissing[path]))\n })\n }\n\n if (set) {\n Object.keys(set).forEach((path) => {\n result.push(new SetPatch(patch.id, path, set[path]))\n })\n }\n\n if (unset) {\n unset.forEach((path) => {\n result.push(new UnsetPatch(patch.id, path))\n })\n }\n\n if (diffMatchPatch) {\n Object.keys(diffMatchPatch).forEach((path) => {\n result.push(new DiffMatchPatch(patch.id, path, diffMatchPatch[path]))\n })\n }\n\n if (inc) {\n Object.keys(inc).forEach((path) => {\n result.push(new IncPatch(patch.id, path, inc[path]))\n })\n }\n\n if (dec) {\n Object.keys(dec).forEach((path) => {\n result.push(new IncPatch(patch.id, path, -dec[path]))\n })\n }\n\n if (insert) {\n let location: string\n let path: string\n const spec = insert\n if ('before' in spec) {\n location = 'before'\n path = spec.before\n } else if ('after' in spec) {\n location = 'after'\n path = spec.after\n } else if ('replace' in spec) {\n location = 'replace'\n path = spec.replace\n } else {\n throw new Error('Invalid insert patch')\n }\n\n result.push(new InsertPatch(patch.id, location, path, spec.items))\n }\n\n return result\n}\n","import {type Doc} from '../document/types'\nimport {Matcher} from '../jsonpath'\nimport {ImmutableAccessor} from './ImmutableAccessor'\nimport {parsePatch} from './parse'\nimport {SetIfMissingPatch} from './SetIfMissingPatch'\nimport {SetPatch} from './SetPatch'\nimport {type PatchTypes, type SingleDocumentPatch} from './types'\n\nexport interface Patch {\n id: string\n path: string\n}\n\nexport class Patcher {\n patches: PatchTypes[]\n\n constructor(patch: SingleDocumentPatch | SingleDocumentPatch[]) {\n this.patches = parsePatch(patch)\n }\n\n apply(value: Doc | null): unknown {\n // Apply just makes a root accessor around the provided\n // value, then applies the patches. Due to the use of\n // ImmutableAccessor it is guaranteed to return either the\n // exact same object it was provided (in the case of no changes),\n // or a completely new object. It will never mutate the object in place.\n const accessor = new ImmutableAccessor(value)\n return this.applyViaAccessor(accessor).get()\n }\n\n // If you want to use your own accessor implementation, you can use this method\n // to invoke the patcher. Since all subsequent accessors for children of this accessor\n // are obtained through the methods in the accessors, you retain full control of the\n // implementation throguhgout the application. Have a look in ImmutableAccessor\n // to see an example of how accessors are implemented.\n applyViaAccessor(accessor: ImmutableAccessor): ImmutableAccessor {\n let result = accessor\n const idAccessor = accessor.getAttribute('_id')\n if (!idAccessor) {\n throw new Error('Cannot apply patch to document with no _id')\n }\n\n const id = idAccessor.get()\n for (const patch of this.patches) {\n if (patch.id !== id) {\n // Ignore patches that are not targetted at this document\n continue\n }\n\n const matcher = Matcher.fromPath(patch.path).setPayload(patch)\n result = process(matcher, result)\n }\n\n return result\n }\n}\n\n// Recursively (depth first) follows any leads generated by the matcher, expecting\n// a patch to be the payload. When matchers report a delivery, the\n// apply(targets, accessor) is called on the patch\nfunction process(matcher: Matcher, accessor: ImmutableAccessor) {\n const isSetPatch =\n matcher.payload instanceof SetPatch || matcher.payload instanceof SetIfMissingPatch\n\n let result = accessor\n // Every time we execute the matcher a new set of leads is generated. Each lead\n // is a target (being an index, an attribute name or a range) in the form of an\n // Expression instance. For each lead target there is also a matcher. Our job is to obtain\n // accessor(s) for each target (there might be more than one, since the targets may\n // be ranges) and run the provided matcher on those accessors.\n const {leads, delivery} = matcher.match(accessor)\n leads.forEach((lead) => {\n if (lead.target.isIndexReference()) {\n lead.target.toIndicies().forEach((i) => {\n const item = result.getIndex(i)\n if (!item) {\n throw new Error('Index out of bounds')\n }\n\n result = result.setIndexAccessor(i, process(lead.matcher, item))\n })\n } else if (lead.target.isAttributeReference()) {\n // `set`/`setIfMissing` on a primitive value overwrites it\n if (isSetPatch && result.containerType() === 'primitive') {\n result = result.set({})\n }\n\n let oldValueAccessor = result.getAttribute(lead.target.name())\n\n // If the patch is a set/setIfMissing patch, we allow deeply setting properties,\n // creating missing segments as we go.\n if (!oldValueAccessor && isSetPatch) {\n result = result.setAttribute(lead.target.name(), {})\n oldValueAccessor = result.getAttribute(lead.target.name())\n }\n\n if (!oldValueAccessor) {\n // Don't follow lead, no such attribute\n return\n }\n\n const newValueAccessor = process(lead.matcher, oldValueAccessor)\n if (oldValueAccessor !== newValueAccessor) {\n result = result.setAttributeAccessor(lead.target.name(), newValueAccessor)\n }\n } else {\n throw new Error(`Unable to handle target ${lead.target.toString()}`)\n }\n })\n\n // Each time we run the matcher, we might also get a delivery. This means that a\n // term in the jsonpath terminated here and the patch should be applied. The delivery\n // arrives in the form of an array of targets and a payload (which in this application\n // is the patch). Conveniently the patches accept an array of targets and an accessor\n // to do its work, so here we just pass those to the patch and we're done.\n if (delivery && isPatcher(delivery.payload)) {\n const patch = delivery.payload\n result = patch.apply(delivery.targets, result)\n }\n\n return result\n}\n\nfunction isPatcher(payload: unknown): payload is PatchTypes {\n return Boolean(\n payload &&\n typeof payload === 'object' &&\n payload !== null &&\n 'apply' in payload &&\n typeof (payload as PatchTypes).apply === 'function',\n )\n}\n","import {uuid} from '@sanity/uuid'\n\n/**\n * Locally unique id's. We use this to generate transaction ids, and they don't have to be\n * cryptographically unique, as the worst that can happen is that they get rejected because\n * of a collision, and then we should just retry with a new id.\n */\nexport const luid: typeof uuid = uuid\n","import {Patcher} from '../patch'\nimport {debug} from './debug'\nimport {luid} from './luid'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Parameters attached to the mutation\n *\n * @internal\n */\nexport interface MutationParams {\n transactionId?: string\n transition?: string\n identity?: string\n previousRev?: string\n resultRev?: string\n mutations: Mut[]\n timestamp?: string\n effects?: {apply: unknown; revert: unknown}\n}\n\n/**\n * A mutation describing a number of operations on a single document.\n * This should be considered an immutable structure. Mutations are compiled\n * on first application, and any changes in properties will not effectively\n * change its behavior after that.\n *\n * @internal\n */\nexport class Mutation {\n params: MutationParams\n\n compiled?: (doc: Doc | null) => Doc | null\n\n _appliesToMissingDocument: boolean | undefined\n\n constructor(options: MutationParams) {\n this.params = options\n }\n\n get transactionId(): string | undefined {\n return this.params.transactionId\n }\n\n get transition(): string | undefined {\n return this.params.transition\n }\n\n get identity(): string | undefined {\n return this.params.identity\n }\n\n get previousRev(): string | undefined {\n return this.params.previousRev\n }\n\n get resultRev(): string | undefined {\n return this.params.resultRev\n }\n\n get mutations(): Mut[] {\n return this.params.mutations\n }\n\n get timestamp(): Date | undefined {\n if (typeof this.params.timestamp === 'string') {\n return new Date(this.params.timestamp)\n }\n\n return undefined\n }\n\n get effects():\n | {\n apply: unknown\n revert: unknown\n }\n | undefined {\n return this.params.effects\n }\n\n assignRandomTransactionId(): void {\n this.params.transactionId = luid()\n this.params.resultRev = this.params.transactionId\n }\n\n appliesToMissingDocument(): boolean {\n if (typeof this._appliesToMissingDocument !== 'undefined') {\n return this._appliesToMissingDocument\n }\n\n // Only mutations starting with a create operation apply to documents that do not exist ...\n const firstMut = this.mutations[0]\n if (firstMut) {\n this._appliesToMissingDocument = Boolean(\n firstMut.create || firstMut.createIfNotExists || firstMut.createOrReplace,\n )\n } else {\n this._appliesToMissingDocument = true\n }\n\n return this._appliesToMissingDocument\n }\n\n // Compiles all mutations into a handy function\n compile(): void {\n const operations: ((doc: Doc | null) => Doc | null)[] = []\n\n // creation requires a _createdAt\n const getGuaranteedCreatedAt = (doc: Doc): string =>\n doc?._createdAt || this.params.timestamp || new Date().toISOString()\n\n this.mutations.forEach((mutation) => {\n if (mutation.create) {\n // TODO: Fail entire patch if document did exist\n const create = (mutation.create || {}) as Doc\n operations.push((doc): Doc => {\n if (doc) {\n return doc\n }\n\n return Object.assign(create, {\n _createdAt: getGuaranteedCreatedAt(create),\n })\n })\n return\n }\n\n if (mutation.createIfNotExists) {\n const createIfNotExists = mutation.createIfNotExists || {}\n operations.push((doc) =>\n doc === null\n ? Object.assign(createIfNotExists, {\n _createdAt: getGuaranteedCreatedAt(createIfNotExists),\n })\n : doc,\n )\n return\n }\n\n if (mutation.createOrReplace) {\n const createOrReplace = mutation.createOrReplace || {}\n operations.push(() =>\n Object.assign(createOrReplace, {\n _createdAt: getGuaranteedCreatedAt(createOrReplace),\n }),\n )\n return\n }\n\n if (mutation.delete) {\n operations.push(() => null)\n return\n }\n\n if (mutation.patch) {\n if ('query' in mutation.patch) {\n // @todo Warn/throw? Investigate if this can ever happen\n return\n }\n\n const patch = new Patcher(mutation.patch)\n operations.push((doc) => patch.apply(doc) as Doc | null)\n return\n }\n\n throw new Error(`Unsupported mutation ${JSON.stringify(mutation, null, 2)}`)\n })\n\n // Assign `_updatedAt` to the timestamp of the mutation if set\n if (typeof this.params.timestamp === 'string') {\n operations.push((doc) => {\n return doc ? Object.assign(doc, {_updatedAt: this.params.timestamp}) : null\n })\n }\n\n const prevRev = this.previousRev\n const rev = this.resultRev || this.transactionId\n this.compiled = (doc: Doc | null) => {\n if (prevRev && doc && prevRev !== doc._rev) {\n throw new Error(\n `Previous revision for this mutation was ${prevRev}, but the document revision is ${doc._rev}`,\n )\n }\n\n let result: Doc | null = doc\n for (const operation of operations) {\n result = operation(result)\n }\n\n // Should update _rev?\n if (result && rev) {\n // Ensure that result is a unique object, even if the operation was a no-op\n if (result === doc) {\n result = Object.assign({}, doc)\n }\n result._rev = rev\n }\n\n return result\n }\n }\n\n apply(document: Doc | null): Doc | null {\n debug('Applying mutation %O to document %O', this.mutations, document)\n if (!this.compiled) {\n this.compile()\n }\n\n const result = this.compiled!(document)\n debug(' => %O', result)\n return result\n }\n\n static applyAll(document: Doc | null, mutations: Mutation[]): Doc | null {\n return mutations.reduce((doc, mutation) => mutation.apply(doc), document)\n }\n\n // Given a number of yet-to-be-committed mutation objects, collects them into one big mutation\n // any metadata like transactionId is ignored and must be submitted by the client. It is assumed\n // that all mutations are on the same document.\n // TOOO: Optimize mutations, eliminating mutations that overwrite themselves!\n static squash(document: Doc | null, mutations: Mutation[]): Mutation {\n const squashed = mutations.reduce(\n (result, mutation) => result.concat(...mutation.mutations),\n [] as Mut[],\n )\n return new Mutation({mutations: squashed})\n }\n}\n","// TODO: When we have timestamps on mutation notifications, we can reject incoming mutations that are older\n// than the document we are seeing.\n\nimport {isEqual} from 'lodash-es'\n\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc} from './types'\n\n/**\n * @internal\n */\nexport interface SubmissionResponder {\n success: () => void\n failure: () => void\n}\n\n/**\n * Models a document as it is changed by our own local patches and remote patches coming in from\n * the server. Consolidates incoming patches with our own submitted patches and maintains two\n * versions of the document. EDGE is the optimistic document that the user sees that will always\n * immediately reflect whatever she is doing to it, and HEAD which is the confirmed version of the\n * document consistent with the mutations we have received from the server. As long as nothing out of\n * the ordinary happens, we can track all changes by hooking into the onMutation callback, but we\n * must also respect onRebase events that fire when we have to backtrack because one of our optimistically\n * applied patches were rejected, or some bastard was able to slip a mutation in between ours own.\n *\n * @internal\n */\nexport class Document {\n /**\n * Incoming patches from the server waiting to be applied to HEAD\n */\n incoming: Mutation[] = []\n\n /**\n * Patches we know has been subitted to the server, but has not been seen yet in the return channel\n * so we can't be sure about the ordering yet (someone else might have slipped something between them)\n */\n submitted: Mutation[] = []\n\n /**\n * Pending mutations\n */\n pending: Mutation[] = []\n\n /**\n * Our model of the document according to the incoming patches from the server\n */\n HEAD: Doc | null\n\n /**\n * Our optimistic model of what the document will probably look like as soon as all our patches\n * have been processed. Updated every time we stage a new mutation, but also might revert back\n * to previous states if our mutations fail, or could change if unexpected mutations arrive\n * between our own. The `onRebase` callback will be called when EDGE changes in this manner.\n */\n EDGE: Doc | null\n\n /**\n * Called with the EDGE document when that document changes for a reason other than us staging\n * a new patch or receiving a mutation from the server while our EDGE is in sync with HEAD:\n * I.e. when EDGE changes because the order of mutations has changed in relation to our\n * optimistic predictions.\n */\n onRebase?: (edge: Doc | null, incomingMutations: Mutation[], pendingMutations: Mutation[]) => void\n\n /**\n * Called when we receive a patch in the normal order of things, but the mutation is not ours\n */\n onMutation?: (msg: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n /**\n * Called when consistency state changes with the boolean value of the current consistency state\n */\n onConsistencyChanged?: (isConsistent: boolean) => void\n\n /**\n * Called whenever a new incoming mutation comes in. These are always ordered correctly.\n */\n onRemoteMutation?: (mut: Mutation) => void\n\n /**\n * We are consistent when there are no unresolved mutations of our own, and no un-applicable\n * incoming mutations. When this has been going on for too long, and there has been a while\n * since we staged a new mutation, it is time to reset your state.\n */\n inconsistentAt: Date | null = null\n\n /**\n * The last time we staged a patch of our own. If we have been inconsistent for a while, but it\n * hasn't been long since we staged a new mutation, the reason is probably just because the user\n * is typing or something.\n *\n * Should be used as a guard against resetting state for inconsistency reasons.\n */\n lastStagedAt: Date | null = null\n\n constructor(doc: Doc | null) {\n this.reset(doc)\n this.HEAD = doc\n this.EDGE = doc\n }\n\n // Reset the state of the Document, used to recover from unsavory states by reloading the document\n reset(doc: Doc | null): void {\n this.incoming = []\n this.submitted = []\n this.pending = []\n this.inconsistentAt = null\n this.HEAD = doc\n this.EDGE = doc\n this.considerIncoming()\n this.updateConsistencyFlag()\n }\n\n // Call when a mutation arrives from Sanity\n arrive(mutation: Mutation): void {\n this.incoming.push(mutation)\n this.considerIncoming()\n this.updateConsistencyFlag()\n }\n\n // Call to signal that we are submitting a mutation. Returns a callback object with a\n // success and failure handler that must be called according to the outcome of our\n // submission.\n stage(mutation: Mutation, silent?: boolean): SubmissionResponder {\n if (!mutation.transactionId) {\n throw new Error('Mutations _must_ have transactionId when submitted')\n }\n this.lastStagedAt = new Date()\n\n debug('Staging mutation %s (pushed to pending)', mutation.transactionId)\n this.pending.push(mutation)\n this.EDGE = mutation.apply(this.EDGE)\n\n if (this.onMutation && !silent) {\n this.onMutation({\n mutation,\n document: this.EDGE,\n remote: false,\n })\n }\n\n const txnId = mutation.transactionId\n\n this.updateConsistencyFlag()\n\n return {\n success: () => {\n this.pendingSuccessfullySubmitted(txnId)\n this.updateConsistencyFlag()\n },\n failure: () => {\n this.pendingFailed(txnId)\n this.updateConsistencyFlag()\n },\n }\n }\n\n // Call to check if everything is nice and quiet and there are no unresolved mutations.\n // Means this model thinks both HEAD and EDGE is up to date with what the server sees.\n isConsistent(): boolean {\n return !this.inconsistentAt\n }\n\n // Private\n\n // Attempts to apply any resolvable incoming patches to HEAD. Will keep patching as long as there\n // are applicable patches to be applied\n considerIncoming(): void {\n let mustRebase = false\n let nextMut: Mutation | undefined\n const rebaseMutations: Mutation[] = []\n\n // Filter mutations that are older than the document\n if (this.HEAD && this.HEAD._updatedAt) {\n const updatedAt = new Date(this.HEAD._updatedAt)\n if (this.incoming.find((mut) => mut.timestamp && mut.timestamp < updatedAt)) {\n this.incoming = this.incoming.filter((mut) => mut.timestamp && mut.timestamp < updatedAt)\n }\n }\n\n // Keep applying mutations as long as any apply\n let protect = 0\n do {\n // Find next mutation that can be applied to HEAD (if any)\n if (this.HEAD) {\n const HEAD = this.HEAD\n nextMut = HEAD._rev ? this.incoming.find((mut) => mut.previousRev === HEAD._rev) : undefined\n } else {\n // When HEAD is null, that means the document is currently deleted. Only mutations that start with a create\n // operation will be considered.\n nextMut = this.incoming.find((mut) => mut.appliesToMissingDocument())\n }\n\n if (nextMut) {\n const applied = this.applyIncoming(nextMut)\n mustRebase = mustRebase || applied\n if (mustRebase) {\n rebaseMutations.push(nextMut)\n }\n\n if (protect++ > 10) {\n throw new Error(\n `Mutator stuck flushing incoming mutations. Probably stuck here: ${JSON.stringify(\n nextMut,\n )}`,\n )\n }\n }\n } while (nextMut)\n\n if (this.incoming.length > 0 && debug.enabled) {\n debug(\n 'Unable to apply mutations %s',\n this.incoming.map((mut) => mut.transactionId).join(', '),\n )\n }\n\n if (mustRebase) {\n this.rebase(rebaseMutations)\n }\n }\n\n // check current consistency state, update flag and invoke callback if needed\n updateConsistencyFlag(): void {\n const wasConsistent = this.isConsistent()\n const isConsistent =\n this.pending.length === 0 && this.submitted.length === 0 && this.incoming.length === 0\n // Update the consistency state, taking care not to update the timestamp if we were inconsistent and still are\n if (isConsistent) {\n this.inconsistentAt = null\n } else if (!this.inconsistentAt) {\n this.inconsistentAt = new Date()\n }\n // Handle onConsistencyChanged callback\n if (wasConsistent != isConsistent && this.onConsistencyChanged) {\n if (isConsistent) {\n debug('Buffered document is inconsistent')\n } else {\n debug('Buffered document is consistent')\n }\n this.onConsistencyChanged(isConsistent)\n }\n }\n\n // apply an incoming patch that has been prequalified as the next in line for this document\n applyIncoming(mut: Mutation | undefined): boolean {\n if (!mut) {\n return false\n }\n\n if (!mut.transactionId) {\n throw new Error('Received incoming mutation without a transaction ID')\n }\n\n debug(\n 'Applying mutation %s -> %s to rev %s',\n mut.previousRev,\n mut.resultRev,\n this.HEAD && this.HEAD._rev,\n )\n\n this.HEAD = mut.apply(this.HEAD)\n\n if (this.onRemoteMutation) {\n this.onRemoteMutation(mut)\n }\n\n // Eliminate from incoming set\n this.incoming = this.incoming.filter((m) => m.transactionId !== mut.transactionId)\n\n if (this.hasUnresolvedMutations()) {\n const needRebase = this.consumeUnresolved(mut.transactionId)\n if (debug.enabled) {\n debug(\n `Incoming mutation ${mut.transactionId} appeared while there were pending or submitted local mutations`,\n )\n debug(`Submitted txnIds: ${this.submitted.map((m) => m.transactionId).join(', ')}`)\n debug(`Pending txnIds: ${this.pending.map((m) => m.transactionId).join(', ')}`)\n debug(`needRebase === %s`, needRebase)\n }\n return needRebase\n }\n debug(\n `Remote mutation %s arrived w/o any pending or submitted local mutations`,\n mut.transactionId,\n )\n this.EDGE = this.HEAD\n if (this.onMutation) {\n this.onMutation({\n mutation: mut,\n document: this.EDGE,\n remote: true,\n })\n }\n return false\n }\n\n /**\n * Returns true if there are unresolved mutations between HEAD and EDGE, meaning we have\n * mutations that are still waiting to be either submitted, or to be confirmed by the server.\n *\n * @returns true if there are unresolved mutations between HEAD and EDGE, false otherwise\n */\n hasUnresolvedMutations(): boolean {\n return this.submitted.length > 0 || this.pending.length > 0\n }\n\n /**\n * When an incoming mutation is applied to HEAD, this is called to remove the mutation from\n * the unresolved state. If the newly applied patch is the next upcoming unresolved mutation,\n * no rebase is needed, but we might have the wrong idea about the ordering of mutations, so in\n * that case we are given the flag `needRebase` to tell us that this mutation arrived out of\n * order in terms of our optimistic version, so a rebase is needed.\n *\n * @param txnId - Transaction ID of the remote mutation\n * @returns true if rebase is needed, false otherwise\n */\n consumeUnresolved(txnId: string): boolean {\n // If we have nothing queued up, we are in sync and can apply patch with no\n // rebasing\n if (this.submitted.length === 0 && this.pending.length === 0) {\n return false\n }\n\n // If we can consume the directly upcoming mutation, we won't have to rebase\n if (this.submitted.length !== 0) {\n if (this.submitted[0].transactionId === txnId) {\n debug(\n `Remote mutation %s matches upcoming submitted mutation, consumed from 'submitted' buffer`,\n txnId,\n )\n this.submitted.shift()\n return false\n }\n } else if (this.pending.length > 0 && this.pending[0].transactionId === txnId) {\n // There are no submitted, but some are pending so let's check the upcoming pending\n debug(\n `Remote mutation %s matches upcoming pending mutation, consumed from 'pending' buffer`,\n txnId,\n )\n this.pending.shift()\n return false\n }\n\n debug(\n 'The mutation was not the upcoming mutation, scrubbing. Pending: %d, Submitted: %d',\n this.pending.length,\n this.submitted.length,\n )\n\n // The mutation was not the upcoming mutation, so we'll have to check everything to\n // see if we have an out of order situation\n this.submitted = this.submitted.filter((mut) => mut.transactionId !== txnId)\n this.pending = this.pending.filter((mut) => mut.transactionId !== txnId)\n debug(`After scrubbing: Pending: %d, Submitted: %d`, this.pending.length, this.submitted.length)\n\n // Whether we had it or not we have either a reordering, or an unexpected mutation\n // so must rebase\n return true\n }\n\n pendingSuccessfullySubmitted(pendingTxnId: string): void {\n if (this.pending.length === 0) {\n // If there are no pending, it has probably arrived allready\n return\n }\n\n const first = this.pending[0]\n if (first.transactionId === pendingTxnId) {\n // Nice, the pending transaction arrived in order\n this.pending.shift()\n this.submitted.push(first)\n return\n }\n\n // Oh, no. Submitted out of order.\n let justSubmitted: Mutation | undefined\n const stillPending: Mutation[] = []\n this.pending.forEach((mutation) => {\n if (mutation.transactionId === pendingTxnId) {\n justSubmitted = mutation\n return\n }\n\n stillPending.push(mutation)\n })\n\n // Not found? Hopefully it has already arrived. Might have been forgotten by now\n if (justSubmitted) {\n this.submitted.push(justSubmitted)\n }\n\n this.pending = stillPending\n\n // Must rebase since mutation order has changed\n this.rebase([])\n }\n\n pendingFailed(pendingTxnId: string): void {\n this.pending = this.pending.filter((mutation) => mutation.transactionId !== pendingTxnId)\n\n // Rebase to revert document to what it looked like before the failed mutation\n this.rebase([])\n }\n\n rebase(incomingMutations: Mutation[]): void {\n const oldEdge = this.EDGE\n this.EDGE = Mutation.applyAll(this.HEAD, this.submitted.concat(this.pending))\n\n // Copy over rev, since we don't care if it changed, we only care about the content\n if (oldEdge !== null && this.EDGE !== null) {\n oldEdge._rev = this.EDGE._rev\n }\n\n const changed = !isEqual(this.EDGE, oldEdge)\n if (changed && this.onRebase) {\n this.onRebase(this.EDGE, incomingMutations, this.pending)\n }\n }\n}\n","import {makePatches, stringifyPatches} from '@sanity/diff-match-patch'\n\nimport {arrayToJSONMatchPath} from '../jsonpath/arrayToJSONMatchPath'\nimport {extractWithPath} from '../jsonpath/extractWithPath'\nimport {debug} from './debug'\nimport {Mutation} from './Mutation'\nimport {type Doc, type Mut} from './types'\n\n/**\n * Implements a buffer for mutations that incrementally optimises the mutations by\n * eliminating set-operations that overwrite earlier set-operations, and rewrite\n * set-operations that change strings into other strings into diffMatchPatch operations.\n *\n * @internal\n */\nexport class SquashingBuffer {\n /**\n * The document forming the basis of this squash\n */\n BASIS: Doc | null\n\n /**\n * The document after the out-Mutation has been applied, but before the staged\n * operations are committed.\n */\n PRESTAGE: Doc | null\n\n /**\n * setOperations contain the latest set operation by path. If the set-operations are\n * updating strings to new strings, they are rewritten as diffMatchPatch operations,\n * any new set operations on the same paths overwrites any older set operations.\n * Only set-operations assigning plain values to plain values gets optimized like this.\n */\n setOperations: Record<string, Mut | undefined>\n\n /**\n * `documentPresent` is true whenever we know that the document must be present due\n * to preceeding mutations. `false` implies that it may or may not already exist.\n */\n documentPresent: boolean\n\n /**\n * The operations in the out-Mutation are not able to be optimized any further\n */\n out: Mut[] = []\n\n /**\n * Staged mutation operations\n */\n staged: Mut[]\n\n constructor(doc: Doc | null) {\n if (doc) {\n debug('Reset mutation buffer to rev %s', doc._rev)\n } else {\n debug('Reset mutation buffer state to document being deleted')\n }\n\n this.staged = []\n this.setOperations = {}\n this.documentPresent = false\n\n this.BASIS = doc\n this.PRESTAGE = doc\n }\n\n add(mut: Mutation): void {\n mut.mutations.forEach((op) => this.addOperation(op))\n }\n\n hasChanges(): boolean {\n return this.out.length > 0 || Object.keys(this.setOperations).length > 0\n }\n\n /**\n * Extracts the mutations in this buffer.\n * After this is done, the buffer lifecycle is over and the client should\n * create an new one with the new, updated BASIS.\n *\n * @param txnId - Transaction ID\n * @returns A `Mutation` instance if we had outgoing mutations pending, null otherwise\n */\n purge(txnId?: string): Mutation | null {\n this.stashStagedOperations()\n let result = null\n if (this.out.length > 0) {\n debug('Purged mutation buffer')\n result = new Mutation({\n mutations: this.out,\n resultRev: txnId,\n transactionId: txnId,\n })\n }\n this.out = []\n this.documentPresent = false\n return result\n }\n\n addOperation(op: Mut): void {\n // Is this a set patch, and only a set patch, and does it apply to the document at hand?\n if (\n op.patch &&\n op.patch.set &&\n 'id' in op.patch &&\n op.patch.id === this.PRESTAGE?._id &&\n Object.keys(op.patch).length === 2 // `id` + `set`\n ) {\n const setPatch = op.patch.set\n const unoptimizable: Record<string, unknown> = {}\n // Apply all optimisable keys in the patch\n for (const path of Object.keys(setPatch)) {\n if (setPatch.hasOwnProperty(path)) {\n if (!this.optimiseSetOperation(path, setPatch[path])) {\n // If not optimisable, add to unoptimizable set\n unoptimizable[path] = setPatch[path]\n }\n }\n }\n\n // If any weren't optimisable, add them to an unoptimised set-operation, then\n // stash everything.\n if (Object.keys(unoptimizable).length > 0) {\n debug('Unoptimizable set-operation detected, purging optimization buffer')\n this.staged.push({patch: {id: this.PRESTAGE._id, set: unoptimizable}})\n this.stashStagedOperations()\n }\n\n return\n }\n\n // Is this a createIfNotExists for our document?\n if (op.createIfNotExists && this.PRESTAGE && op.createIfNotExists._id === this.PRESTAGE._id) {\n if (!this.documentPresent) {\n // If we don't know that it's present we'll have to stage and stash.\n this.staged.push(op)\n this.documentPresent = true\n this.stashStagedOperations()\n }\n\n // Otherwise we can fully ignore it.\n return\n }\n\n debug('Unoptimizable mutation detected, purging optimization buffer')\n // console.log(\"Unoptimizable operation, stashing\", JSON.stringify(op))\n // Un-optimisable operations causes everything to be stashed\n this.staged.push(op)\n this.stashStagedOperations()\n }\n\n /**\n * Attempt to perform one single set operation in an optimised manner, return value\n * reflects whether or not the operation could be performed.\n\n * @param path - The JSONPath to the set operation in question\n * @param nextValue - The value to be set\n * @returns True of optimized, false otherwise\n */\n optimiseSetOperation(path: string, nextValue: unknown): boolean {\n // console.log('optimiseSetOperation', path, nextValue)\n // If target value is not a plain value, unable to optimise\n if (typeof nextValue === 'object') {\n // console.log(\"Not optimisable because next value is object\")\n return false\n }\n\n // Check the source values, if there is more than one value being assigned,\n // we won't optimise\n const matches = extractWithPath(path, this.PRESTAGE)\n // If we are not overwriting exactly one key, this cannot be optimised, so we bail\n if (matches.length !== 1) {\n // console.log('Not optimisable because match count is != 1', JSON.stringify(matches))\n return false\n }\n\n // Okay, we are assigning exactly one value to exactly one existing slot, so we might optimise\n const match = matches[0]\n // If the value of the match is an array or object, we cannot safely optimise this since the meaning\n // of pre-existing operations might change (in theory, at least), so we bail\n if (typeof match.value === 'object') {\n // console.log(\"Not optimisable because old value is object\")\n return false\n }\n\n if (!this.PRESTAGE) {\n // Shouldn't happen, but makes typescript happy\n return false\n }\n\n // If the new and old value are the equal, we optimise this operation by discarding it\n // Now, let's build the operation\n let op: Mut | null = null\n if (match.value === nextValue) {\n // If new and old values are equal, we optimise this by deleting the operation\n // console.log(\"Omitting operation\")\n op = null\n } else if (typeof match.value === 'string' && typeof nextValue === 'string') {\n // console.log(\"Rewriting to dmp\")\n // We are updating a string to another string, so we are making a diffMatchPatch\n try {\n const patch = stringifyPatches(makePatches(match.value, nextValue))\n op = {patch: {id: this.PRESTAGE._id, diffMatchPatch: {[path]: patch}}}\n } catch {\n // patch_make failed due to unicode issue https://github.com/google/diff-match-patch/issues/59\n return false\n }\n } else {\n // console.log(\"Not able to rewrite to dmp, making normal set\")\n // We are changing the type of the value, so must make a normal set-operation\n op = {patch: {id: this.PRESTAGE._id, set: {[path]: nextValue}}}\n }\n\n // Let's make a plain, concrete path from the array-path. We use this to keep only the latest set\n // operation touching this path in the buffer.\n const canonicalPath = arrayToJSONMatchPath(match.path)\n\n // Store this operation, overwriting any previous operations touching this same path\n if (op) {\n this.setOperations[canonicalPath] = op\n } else {\n delete this.setOperations[canonicalPath]\n }\n\n // Signal that we succeeded in optimizing this patch\n return true\n }\n\n stashStagedOperations(): void {\n // Short circuit if there are no staged operations\n const nextOps: Mut[] = []\n\n // Extract the existing outgoing operations if any\n Object.keys(this.setOperations).forEach((key) => {\n const op = this.setOperations[key]\n if (op) {\n nextOps.push(op)\n }\n })\n\n nextOps.push(...this.staged)\n if (nextOps.length > 0) {\n this.PRESTAGE = new Mutation({mutations: nextOps}).apply(this.PRESTAGE) as Doc\n this.staged = []\n this.setOperations = {}\n }\n\n this.out.push(...nextOps)\n }\n\n /**\n * Rebases given the new base-document\n *\n * @param newBasis - New base document to rebase on\n * @returns New \"edge\" document with buffered changes integrated\n */\n rebase(newBasis: Doc | null): Doc | null {\n this.stashStagedOperations()\n\n if (newBasis === null) {\n // If document was just deleted, we must throw out local changes\n this.out = []\n this.BASIS = newBasis\n this.PRESTAGE = newBasis\n this.documentPresent = false\n } else {\n this.BASIS = newBasis\n\n // @todo was this supposed to be `this.out.length > 0`?\n // surely this is always `true`?\n if (this.out) {\n this.PRESTAGE = new Mutation({mutations: this.out}).apply(this.BASIS) as Doc\n } else {\n this.PRESTAGE = this.BASIS\n }\n }\n\n return this.PRESTAGE\n }\n}\n","import {isEqual} from 'lodash-es'\n\nimport {debug} from './debug'\nimport {Document} from './Document'\nimport {Mutation} from './Mutation'\nimport {SquashingBuffer} from './SquashingBuffer'\nimport {type Doc, type Mut} from './types'\n\nconst ONE_MINUTE = 1000 * 60\n\n/**\n * @internal\n */\nexport interface CommitHandlerMessage {\n mutation: Mutation\n success: () => void\n failure: () => void\n cancel: (error: Error) => void\n}\n\n/**\n * A wrapper for Document that allows the client to gather mutations on the\n * client side and commit them when it wants to.\n */\nclass Commit {\n mutations: Mutation[]\n tries: number\n resolve: () => void\n reject: (error: Error) => void\n\n constructor(\n mutations: Mutation[],\n {resolve, reject}: {resolve: () => void; reject: (error: Error) => void},\n ) {\n this.mutations = mutations\n this.tries = 0\n this.resolve = resolve\n this.reject = reject\n }\n\n apply(doc: Doc | null): Doc | null {\n return Mutation.applyAll(doc, this.mutations)\n }\n\n squash(doc: Doc | null) {\n const result = Mutation.squash(doc, this.mutations)\n result.assignRandomTransactionId()\n return result\n }\n}\n\nconst mutReducerFn = (acc: Mut[], mut: Mutation): Mut[] => acc.concat(mut.mutations)\n\n/**\n * @internal\n */\nexport class BufferedDocument {\n private mutations: Mutation[]\n\n /**\n * The Document we are wrapping\n */\n document: Document\n\n /**\n * The Document with local changes applied\n */\n LOCAL: Doc | null\n\n /**\n * Commits that are waiting to be delivered to the server\n */\n private commits: Commit[]\n\n /**\n * Local mutations that are not scheduled to be committed yet\n */\n buffer: SquashingBuffer\n\n /**\n * Assignable event handler for when the buffered document applies a mutation\n */\n onMutation?: (message: {mutation: Mutation; document: Doc | null; remote: boolean}) => void\n\n /**\n * Assignable event handler for when a remote mutation happened\n */\n onRemoteMutation?: Document['onRemoteMutation']\n\n /**\n * Assignable event handler for when the buffered document rebased\n */\n onRebase?: (localDoc: Doc | null, remoteMutations: Mut[], localMutations: Mut[]) => void\n\n /**\n * Assignable event handler for when the document is deleted\n */\n onDelete?: (doc: Doc | null) => void\n\n /**\n * Assignable event handler for when the state of consistency changed\n */\n onConsistencyChanged?: (isConsistent: boolean) => void\n\n /**\n * Assignable event handler for when the buffered document should commit changes\n */\n commitHandler?: (msg: CommitHandlerMessage) => void\n\n /**\n * Whether or not we are currently commiting\n */\n committerRunning = false\n\n constructor(doc: Doc | null) {\n this.buffer = new SquashingBuffer(doc)\n this.document = new Document(doc)\n this.document.onMutation = (msg) => this.handleDocMutation(msg)\n this.document.onRemoteMutation = (mut) => this.onRemoteMutation && this.onRemoteMutation(mut)\n this.document.onRebase = (edge, remoteMutations, localMutations) =>\n this.handleDocRebase(edge, remoteMutations, localMutations)\n this.document.onConsistencyChanged = (msg) => this.handleDocConsistencyChanged(msg)\n this.LOCAL = doc\n this.mutations = []\n this.commits = []\n }\n\n // Used to reset the state of the local document model. If the model has been inconsistent\n // for too long, it has probably missed a notification, and should reload the document from the server\n reset(doc: Doc | null): void {\n if (doc) {\n debug('Document state reset to revision %s', doc._rev)\n } else {\n debug('Document state reset to being deleted')\n }\n this.document.reset(doc)\n this.rebase([], [])\n this.handleDocConsistencyChanged(this.document.isConsistent())\n }\n\n // Add a change to the buffer\n add(mutation: Mutation): void {\n if (this.onConsistencyChanged) {\n this.onConsistencyChanged(false)\n }\n debug('Staged local mutation')\n this.buffer.add(mutation)\n const oldLocal = this.LOCAL\n this.LOCAL = mutation.apply(this.LOCAL)\n if (this.onMutation && oldLocal !== this.LOCAL) {\n debug('onMutation fired')\n this.onMutation({\n mutation,\n document: this.LOCAL,\n remote: false,\n })\n if (this.LOCAL === null && this.onDelete) {\n this.onDelete(this.LOCAL)\n }\n }\n }\n\n // Call when a mutation arrives from Sanity\n arrive(mutation: Mutation): void {\n debug('Remote mutation arrived %s -> %s', mutation.previousRev, mutation.resultRev)\n if (mutation.previousRev === mutation.resultRev) {\n throw new Error(\n `Mutation ${mutation.transactionId} has previousRev === resultRev (${mutation.previousRev})`,\n )\n }\n return this.document.arrive(mutation)\n }\n\n // Submit all mutations in the buffer to be committed\n commit(): Promise<void> {\n return new Promise((resolve, reject) => {\n // Anything to commit?\n if (!this.buffer.hasChanges()) {\n resolve()\n return\n }\n debug('Committing local changes')\n // Collect current staged mutations into a commit and ...\n const pendingMutations = this.buffer.purge()\n this.commits.push(new Commit(pendingMutations ? [pendingMutations] : [], {resolve, reject}))\n // ... clear the table for the next commit.\n this.buffer = new SquashingBuffer(this.LOCAL)\n this.performCommits()\n })\n }\n\n // Starts the committer that will try to committ all staged commits to the database\n // by calling the commitHandler. Will keep running until all commits are successfully\n // committed.\n performCommits(): void {\n if (!this.commitHandler) {\n throw new Error('No commitHandler configured for this BufferedDocument')\n }\n if (this.committerRunning) {\n // We can have only one committer at any given time\n return\n }\n this._cycleCommitter()\n }\n\n // TODO: Error handling, right now retries after every error\n _cycleCommitter(): void {\n const commit = this.commits.shift()\n if (!commit) {\n this.committerRunning = false\n return\n }\n\n this.committerRunning = true\n const squashed = commit.squash(this.LOCAL)\n const docResponder = this.document.stage(squashed, true)\n\n const responder = {\n success: () => {\n debug('Commit succeeded')\n docResponder.success()\n commit.resolve()\n // Keep running the committer until no more commits\n this._cycleCommitter()\n },\n\n failure: () => {\n debug('Commit failed')\n // Re stage commit\n commit.tries += 1\n if (this.LOCAL !== null) {\n // Only schedule this commit for a retry of the document still exist to avoid looping\n // indefinitely when the document was deleted from under our noses\n this.commits.unshift(commit)\n }\n docResponder.failure()\n\n // Todo: Need better error handling (i.e. propagate to user and provide means of retrying)\n if (commit.tries < 200) {\n setTimeout(() => this._cycleCommitter(), Math.min(commit.tries * 1000, ONE_MINUTE))\n }\n },\n\n cancel: (error: Error) => {\n this.commits.forEach((comm) => comm.reject(error))\n\n // Throw away waiting commits\n this.commits = []\n\n // Reset back to last known state from content lake and cause a rebase that will\n // reset the view in the form\n this.reset(this.document.HEAD)\n\n // Clear the buffer of recent mutations\n this.buffer = new SquashingBuffer(this.LOCAL)\n\n // Stop the committer loop\n this.committerRunning = false\n },\n }\n\n debug('Posting commit')\n if (this.commitHandler) {\n this.commitHandler({\n mutation: squashed,\n success: responder.success,\n failure: responder.failure,\n cancel: responder.cancel,\n })\n }\n }\n\n handleDocRebase(edge: Doc | null, remoteMutations: Mutation[], localMutations: Mutation[]): void {\n this.rebase(remoteMutations, localMutations)\n }\n\n handleDocumentDeleted(): void {\n debug('Document deleted')\n // If the document was just deleted, fire the onDelete event with the absolutely latest\n // version of the document before someone deleted it so that the client may revive the\n // document in the last state the user saw it, should they so desire.\n if (this.LOCAL !== null && this.onDelete) {\n this.onDelete(this.LOCAL)\n }\n\n this.commits = []\n this.mutations = []\n }\n\n handleDocMutation(msg: {mutation: Mutation; document: Doc | null; remote: boolean}): void {\n // If we have no local changes, we can just pass this on to the client\n if (this.commits.length === 0 && !this.buffer.hasChanges()) {\n debug('Document mutated from remote with no local changes')\n this.LOCAL = this.document.EDGE\n this.buffer = new SquashingBuffer(this.LOCAL)\n if (this.onMutation) {\n this.onMutation(msg)\n }\n return\n }\n\n debug('Document mutated from remote with local changes')\n\n // If there are local edits, and the document was deleted, we need to purge those local edits now\n if (this.document.EDGE === null) {\n this.handleDocumentDeleted()\n }\n\n // We had local changes, so need to signal rebase\n this.rebase([msg.mutation], [])\n }\n\n rebase(remoteMutations: Mutation[], localMutations: Mutation[]): void {\n debug('Rebasing document')\n if (this.document.EDGE === null) {\n this.handleDocumentDeleted()\n }\n\n const oldLocal = this.LOCAL\n this.LOCAL = this.commits.reduce((doc, commit) => commit.apply(doc), this.document.EDGE)\n this.LOCAL = this.buffer.rebase(this.LOCAL)\n\n // Copy over rev, since we don't care if it changed, we only care about the content\n if (oldLocal !== null && this.LOCAL !== null) {\n oldLocal._rev = this.LOCAL._rev\n }\n\n const changed = !isEqual(this.LOCAL, oldLocal)\n if (changed && this.onRebase) {\n this.onRebase(\n this.LOCAL,\n remoteMutations.reduce(mutReducerFn, []),\n localMutations.reduce(mutReducerFn, []),\n )\n }\n }\n\n handleDocConsistencyChanged(isConsistent: boolean): void {\n if (!this.onConsistencyChanged) {\n return\n }\n\n const hasLocalChanges = this.commits.length > 0 || this.buffer.hasChanges()\n\n if (isConsistent && !hasLocalChanges) {\n this.onConsistencyChanged(true)\n }\n\n if (!isConsistent) {\n this.onConsistencyChanged(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"name": "@sanity/mutator",
|
|
3
|
-
"version": "5.0.1
|
|
3
|
+
"version": "5.0.1",
|
|
4
4
|
"description": "A set of models to make it easier to utilize the powerful real time collaborative features of Sanity",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"sanity",
|
|
@@ -39,22 +39,22 @@
|
|
|
39
39
|
"@sanity/diff-match-patch": "^3.2.0",
|
|
40
40
|
"@sanity/uuid": "^3.0.2",
|
|
41
41
|
"debug": "^4.4.3",
|
|
42
|
-
"lodash": "^4.17.21",
|
|
43
|
-
"@sanity/types": "5.0.
|
|
42
|
+
"lodash-es": "^4.17.21",
|
|
43
|
+
"@sanity/types": "5.0.1"
|
|
44
44
|
},
|
|
45
45
|
"devDependencies": {
|
|
46
46
|
"@sanity/pkg-utils": "^10.2.1",
|
|
47
47
|
"@types/debug": "^4.1.12",
|
|
48
|
-
"@types/lodash": "^4.17.
|
|
48
|
+
"@types/lodash-es": "^4.17.12",
|
|
49
49
|
"@types/node": "^24.3.0",
|
|
50
50
|
"@typescript/native-preview": "7.0.0-dev.20251128.1",
|
|
51
|
-
"eslint": "^9.39.
|
|
51
|
+
"eslint": "^9.39.2",
|
|
52
52
|
"rimraf": "^5.0.10",
|
|
53
53
|
"vitest": "^3.2.4",
|
|
54
|
-
"@repo/
|
|
55
|
-
"@repo/package.config": "5.0.1
|
|
56
|
-
"@repo/
|
|
57
|
-
"@repo/tsconfig": "5.0.1
|
|
54
|
+
"@repo/eslint-config": "5.0.1",
|
|
55
|
+
"@repo/package.config": "5.0.1",
|
|
56
|
+
"@repo/test-config": "5.0.1",
|
|
57
|
+
"@repo/tsconfig": "5.0.1"
|
|
58
58
|
},
|
|
59
59
|
"scripts": {
|
|
60
60
|
"build": "pkg-utils build --strict --check --clean",
|