@earendil-works/chord 0.0.0

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.
Files changed (98) hide show
  1. package/README.md +205 -0
  2. package/dist/api.d.ts +15 -0
  3. package/dist/api.d.ts.map +1 -0
  4. package/dist/api.js +72 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/bundler.d.ts +6 -0
  7. package/dist/bundler.d.ts.map +1 -0
  8. package/dist/bundler.js +3 -0
  9. package/dist/bundler.js.map +1 -0
  10. package/dist/context/index.d.ts +24 -0
  11. package/dist/context/index.d.ts.map +1 -0
  12. package/dist/context/index.js +97 -0
  13. package/dist/context/index.js.map +1 -0
  14. package/dist/delta/index.d.ts +119 -0
  15. package/dist/delta/index.d.ts.map +1 -0
  16. package/dist/delta/index.js +1213 -0
  17. package/dist/delta/index.js.map +1 -0
  18. package/dist/facets/host.d.ts +12 -0
  19. package/dist/facets/host.d.ts.map +1 -0
  20. package/dist/facets/host.js +763 -0
  21. package/dist/facets/host.js.map +1 -0
  22. package/dist/facets/loader.d.ts +3 -0
  23. package/dist/facets/loader.d.ts.map +1 -0
  24. package/dist/facets/loader.js +5 -0
  25. package/dist/facets/loader.js.map +1 -0
  26. package/dist/index.d.ts +11 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +10 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/json.d.ts +4 -0
  31. package/dist/json.d.ts.map +1 -0
  32. package/dist/json.js +57 -0
  33. package/dist/json.js.map +1 -0
  34. package/dist/node/bundle-loader.d.ts +30 -0
  35. package/dist/node/bundle-loader.d.ts.map +1 -0
  36. package/dist/node/bundle-loader.js +377 -0
  37. package/dist/node/bundle-loader.js.map +1 -0
  38. package/dist/node/bundle.d.ts +26 -0
  39. package/dist/node/bundle.d.ts.map +1 -0
  40. package/dist/node/bundle.js +183 -0
  41. package/dist/node/bundle.js.map +1 -0
  42. package/dist/node/manifest.d.ts +36 -0
  43. package/dist/node/manifest.d.ts.map +1 -0
  44. package/dist/node/manifest.js +6 -0
  45. package/dist/node/manifest.js.map +1 -0
  46. package/dist/node/package.d.ts +15 -0
  47. package/dist/node/package.d.ts.map +1 -0
  48. package/dist/node/package.js +199 -0
  49. package/dist/node/package.js.map +1 -0
  50. package/dist/node.d.ts +5 -0
  51. package/dist/node.d.ts.map +1 -0
  52. package/dist/node.js +3 -0
  53. package/dist/node.js.map +1 -0
  54. package/dist/services/consumer.d.ts +11 -0
  55. package/dist/services/consumer.d.ts.map +1 -0
  56. package/dist/services/consumer.js +537 -0
  57. package/dist/services/consumer.js.map +1 -0
  58. package/dist/services/errors.d.ts +8 -0
  59. package/dist/services/errors.d.ts.map +1 -0
  60. package/dist/services/errors.js +22 -0
  61. package/dist/services/errors.js.map +1 -0
  62. package/dist/services/handle.d.ts +15 -0
  63. package/dist/services/handle.d.ts.map +1 -0
  64. package/dist/services/handle.js +99 -0
  65. package/dist/services/handle.js.map +1 -0
  66. package/dist/services/instances.d.ts +25 -0
  67. package/dist/services/instances.d.ts.map +1 -0
  68. package/dist/services/instances.js +137 -0
  69. package/dist/services/instances.js.map +1 -0
  70. package/dist/services/loopback.d.ts +5 -0
  71. package/dist/services/loopback.d.ts.map +1 -0
  72. package/dist/services/loopback.js +15 -0
  73. package/dist/services/loopback.js.map +1 -0
  74. package/dist/services/provider.d.ts +37 -0
  75. package/dist/services/provider.d.ts.map +1 -0
  76. package/dist/services/provider.js +472 -0
  77. package/dist/services/provider.js.map +1 -0
  78. package/dist/services/state-codec.d.ts +15 -0
  79. package/dist/services/state-codec.d.ts.map +1 -0
  80. package/dist/services/state-codec.js +115 -0
  81. package/dist/services/state-codec.js.map +1 -0
  82. package/dist/services/state-internals.d.ts +11 -0
  83. package/dist/services/state-internals.d.ts.map +1 -0
  84. package/dist/services/state-internals.js +10 -0
  85. package/dist/services/state-internals.js.map +1 -0
  86. package/dist/services/state.d.ts +23 -0
  87. package/dist/services/state.d.ts.map +1 -0
  88. package/dist/services/state.js +124 -0
  89. package/dist/services/state.js.map +1 -0
  90. package/dist/services/wire.d.ts +60 -0
  91. package/dist/services/wire.d.ts.map +1 -0
  92. package/dist/services/wire.js +173 -0
  93. package/dist/services/wire.js.map +1 -0
  94. package/dist/types.d.ts +203 -0
  95. package/dist/types.d.ts.map +1 -0
  96. package/dist/types.js +2 -0
  97. package/dist/types.js.map +1 -0
  98. package/package.json +72 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/delta/index.ts"],"names":[],"mappings":"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","sourcesContent":["import type { JsonValue } from \"../types.ts\";\n\nexport type { JsonValue } from \"../types.ts\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// chord/delta — flush-time change tracking over plain JSON.\n//\n// Depends on nothing else in the harness. Session storage, the runtime and the\n// facet host consume it; keep the arrows pointing that way.\n// ─────────────────────────────────────────────────────────────────────────────\n\nexport type Seg = string | number;\nexport type Path = readonly Seg[];\nexport type NonEmptyPath = readonly [Seg, ...Seg[]];\n\n/** A path inline, or an id assigned by the encoder on second use. */\nexport type PathRef<P extends Path = Path> = P | number;\n\n/**\n * Tuples are the form — in memory, on the wire, on disk.\n *\n * `r` is the ONLY op that replaces a whole value. `s`/`d`/`a`/`t` cannot target\n * the root: the type forbids it. `p` may, and only because a tracked value can\n * itself be an array — but a `p` that replaces its entire target is normalised to\n * `r`/`s` at flush time, so a root `p` is always a partial modification.\n *\n * `Op` knows nothing about the path dictionary. Interning, id references and\n * omitted paths live in `WireOp` and exist only between `encode` and `decode`.\n */\nexport type Op =\n\t| readonly [\"r\", JsonValue]\n\t| readonly [\"s\", NonEmptyPath, JsonValue]\n\t| readonly [\"d\", NonEmptyPath]\n\t| readonly [\"a\", NonEmptyPath, string]\n\t| readonly [\"t\", NonEmptyPath, number]\n\t| readonly [\"p\", Path, number, number, JsonValue[]];\n\n/**\n * What crosses a boundary. Adds two compressions and nothing else:\n *\n * [\"#\", id, path] defines an id, emitted on a path's SECOND use\n * a numeric PathRef references a previously defined id\n * a shortened tuple reuses the previous op's path; arity disambiguates\n *\n * [\"r\", value] carries no path, so it encodes to itself — which is why isBase\n * works unchanged on either vocabulary.\n */\nexport type WireOp =\n\t| readonly [\"r\", JsonValue]\n\t| readonly [\"s\", PathRef<NonEmptyPath>, JsonValue]\n\t| readonly [\"s\", JsonValue]\n\t| readonly [\"d\", PathRef<NonEmptyPath>]\n\t| readonly [\"d\"]\n\t| readonly [\"a\", PathRef<NonEmptyPath>, string]\n\t| readonly [\"a\", string]\n\t| readonly [\"t\", PathRef<NonEmptyPath>, number]\n\t| readonly [\"t\", number]\n\t| readonly [\"p\", PathRef, number, number, JsonValue[]]\n\t| readonly [\"p\", number, number, JsonValue[]]\n\t| readonly [\"#\", number, Path];\n\n// ─── Classification ──────────────────────────────────────────────────────────\n\nexport const isReplace = (op: Op | WireOp): boolean => op[0] === \"r\";\n\n/**\n * A batch begins with a replacement. Flush guarantees `r` is at index 0 or absent,\n * so this is exact rather than a heuristic.\n */\nexport const isBase = (ops: readonly (Op | WireOp)[]): boolean => ops.length > 0 && ops[0]![0] === \"r\";\n\n// ─── Overlap ─────────────────────────────────────────────────────────────────\n\n/**\n * Longest suffix of `a` that is a prefix of `b`. Probes with indexOf and verifies\n * exact substring equality, so the hot loops are native. A hand-written KMP is\n * asymptotically equivalent and much slower in practice.\n *\n * Always correct: the returned n satisfies a.slice(a.length - n) === b.slice(0, n).\n */\nexport function overlap(a: string, b: string, scan: number, probe = 64, maxCandidates = 8): number {\n\tif (a.length === 0 || b.length === 0 || scan === 0) return 0;\n\tconst tail = a.length > scan ? a.slice(a.length - scan) : a;\n\n\t// A probe of length h can only find overlaps of at least h — the head must\n\t// actually occur in `a`. So try a long head first (few candidates, and it\n\t// catches the large overlaps a rolling window produces), then fall back to one\n\t// character, which finds any overlap at the cost of more candidates.\n\t//\n\t// Candidates are bounded because repetitive output — a build log, or any run of\n\t// one character — makes a long head match at thousands of positions. Giving up\n\t// returns 0, which emits a set: larger, never wrong.\n\tfor (const h of [Math.min(probe, b.length), 1]) {\n\t\tconst head = b.slice(0, h);\n\t\tlet tried = 0;\n\t\tfor (let k = tail.indexOf(head); k !== -1; k = tail.indexOf(head, k + 1)) {\n\t\t\tif (++tried > maxCandidates) break;\n\t\t\tconst n = tail.length - k;\n\t\t\tif (n <= b.length && tail.slice(k) === b.slice(0, n)) return n;\n\t\t}\n\t\tif (h === 1) break;\n\t}\n\treturn 0;\n}\n\n// ─── Tracker ─────────────────────────────────────────────────────────────────\n\nexport interface TrackerOptions {\n\tmaxOverlapScan?: number;\n}\n\nexport interface Tracker<T extends object> {\n\t/**\n\t * The tracked value. Mutate and read state only through this proxy. Values\n\t * inserted into it are adopted: callers may retain read-only references, but\n\t * must not mutate them outside this proxy.\n\t */\n\tstate: T;\n\t/** The untracked current value. Mutating it bypasses change tracking. */\n\treadonly target: T;\n\tflush(): Op[];\n\t/** Make the next flush a complete base batch without changing the value. */\n\trebase(): void;\n\t/** Accept pending mutations locally without emitting them. */\n\tdiscard(): void;\n\treadonly dirty: boolean;\n}\n\nconst isObj = (value: unknown): value is object => value !== null && typeof value === \"object\";\nconst cloneJson = <T extends JsonValue>(value: T): T => {\n\tif (!isObj(value)) return value;\n\tif (Array.isArray(value)) return value.map((item) => cloneJson(item)) as T;\n\tconst result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype) as Record<\n\t\tstring,\n\t\tJsonValue\n\t>;\n\tfor (const [key, child] of Object.entries(value)) {\n\t\tObject.defineProperty(result, key, {\n\t\t\tvalue: cloneJson(child),\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn result as T;\n};\n\nconst INDEX = /^(?:0|[1-9]\\d*)$/;\nconst norm = (target: object, key: string | symbol): Seg | symbol =>\n\ttypeof key === \"symbol\" ? key : Array.isArray(target) && INDEX.test(key) ? Number(key) : key;\nconst MUTATORS = new Set([\"push\", \"pop\", \"shift\", \"unshift\", \"splice\", \"sort\", \"reverse\", \"fill\", \"copyWithin\"]);\nconst MISSING = Symbol(\"missing\");\ntype MaybeJson = JsonValue | typeof MISSING;\ntype ArrayDirty = { kind: \"append\"; start: number } | { kind: \"diff\" } | { kind: \"replace\" };\ntype DirtyNode = { valueDirty?: true; array?: ArrayDirty; children: Map<Seg, DirtyNode> };\n\nconst dirtyNode = (): DirtyNode => ({ children: new Map() });\n\nconst spliceItems = (target: unknown[], index: number, remove: number, items: JsonValue[]): JsonValue[] => {\n\tconst removed = Reflect.apply(Array.prototype.splice, target, [index, remove]) as JsonValue[];\n\tconst chunkSize = 10_000;\n\tfor (let offset = 0; offset < items.length; offset += chunkSize) {\n\t\tReflect.apply(Array.prototype.splice, target, [index + offset, 0, ...items.slice(offset, offset + chunkSize)]);\n\t}\n\treturn removed;\n};\n\nconst jsonEqual = (left: JsonValue, right: JsonValue): boolean => {\n\tif (left === right) return true;\n\tif (!isObj(left) || !isObj(right) || Array.isArray(left) !== Array.isArray(right)) return false;\n\tif (Array.isArray(left) && Array.isArray(right)) {\n\t\tif (left.length !== right.length) return false;\n\t\tfor (let index = 0; index < left.length; index++) {\n\t\t\tif (!jsonEqual(left[index]!, right[index]!)) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tconst leftObject = left as Record<string, JsonValue>;\n\tconst rightObject = right as Record<string, JsonValue>;\n\tconst leftKeys = Object.keys(leftObject);\n\tconst rightKeys = Object.keys(rightObject);\n\tif (leftKeys.length !== rightKeys.length) return false;\n\tfor (const key of leftKeys) {\n\t\tif (!Object.hasOwn(rightObject, key) || !jsonEqual(leftObject[key]!, rightObject[key]!)) return false;\n\t}\n\treturn true;\n};\n\nconst ownValue = (value: JsonValue, segment: Seg): MaybeJson => {\n\tif (!isObj(value) || !Object.hasOwn(value, segment)) return MISSING;\n\treturn (value as Record<Seg, JsonValue>)[segment]!;\n};\n\nconst emitSet = (path: Path, value: JsonValue, out: Op[]): void => {\n\tconst snapshot = cloneJson(value);\n\tif (path.length === 0) out.push([\"r\", snapshot]);\n\telse out.push([\"s\", [...path] as unknown as NonEmptyPath, snapshot]);\n};\n\nconst emitDelete = (path: Path, out: Op[]): void => {\n\tif (path.length === 0) throw new TypeError(\"the tracked root cannot be deleted\");\n\tout.push([\"d\", [...path] as unknown as NonEmptyPath]);\n};\n\nconst diffString = (before: string, after: string, path: Path, scan: number, out: Op[]): void => {\n\tif (before === after) return;\n\tif (path.length === 0) {\n\t\temitSet(path, after, out);\n\t\treturn;\n\t}\n\tconst at = [...path] as unknown as NonEmptyPath;\n\t// NOT `after.startsWith(before)`. `after` is usually a cons string — the\n\t// producer just did `s += chunk` — and V8's startsWith walks a cons char by\n\t// char. `slice(...) === before` flattens once and compares with memcmp.\n\t// Measured on a 200 KB string growing by 8 bytes per flush: 845 us -> 42 us.\n\tif (after.length > before.length && after.slice(0, before.length) === before) {\n\t\tout.push([\"a\", at, after.slice(before.length)]);\n\t\treturn;\n\t}\n\tconst shared = overlap(before, after, scan);\n\tif (shared === 0) {\n\t\tout.push([\"s\", at, after]);\n\t\treturn;\n\t}\n\tout.push([\"t\", at, before.length - shared]);\n\tif (after.length > shared) out.push([\"a\", at, after.slice(shared)]);\n};\n\nconst diffValue = (before: MaybeJson, after: MaybeJson, path: Path, scan: number, out: Op[]): void => {\n\tif (before === MISSING) {\n\t\tif (after !== MISSING) emitSet(path, after, out);\n\t\treturn;\n\t}\n\tif (after === MISSING) {\n\t\temitDelete(path, out);\n\t\treturn;\n\t}\n\tif (before === after) return;\n\tif (typeof before === \"string\" && typeof after === \"string\") {\n\t\tdiffString(before, after, path, scan, out);\n\t\treturn;\n\t}\n\tif (Array.isArray(before) && Array.isArray(after)) {\n\t\tdiffArray(before, after, path, scan, out);\n\t\treturn;\n\t}\n\tif (isObj(before) && isObj(after) && !Array.isArray(before) && !Array.isArray(after)) {\n\t\tdiffObject(before as Record<string, JsonValue>, after as Record<string, JsonValue>, path, scan, out);\n\t\treturn;\n\t}\n\temitSet(path, after, out);\n};\n\nfunction diffObject(\n\tbefore: Record<string, JsonValue>,\n\tafter: Record<string, JsonValue>,\n\tpath: Path,\n\tscan: number,\n\tout: Op[],\n): void {\n\tif ([...Object.keys(before), ...Object.keys(after)].some((key) => RESERVED_SEGMENTS.has(key))) {\n\t\temitSet(path, after, out);\n\t\treturn;\n\t}\n\tfor (const key of Object.keys(after)) {\n\t\tdiffValue(Object.hasOwn(before, key) ? before[key]! : MISSING, after[key]!, [...path, key], scan, out);\n\t}\n\tfor (const key of Object.keys(before)) {\n\t\tif (!Object.hasOwn(after, key)) emitDelete([...path, key], out);\n\t}\n}\n\nfunction diffArray(before: JsonValue[], after: JsonValue[], path: Path, scan: number, out: Op[]): void {\n\tif (before.length === after.length) {\n\t\tfor (let index = 0; index < after.length; index++) {\n\t\t\tdiffValue(before[index]!, after[index]!, [...path, index], scan, out);\n\t\t}\n\t\treturn;\n\t}\n\n\tlet prefix = 0;\n\twhile (prefix < before.length && prefix < after.length && jsonEqual(before[prefix]!, after[prefix]!)) prefix++;\n\tlet suffix = 0;\n\twhile (\n\t\tsuffix < before.length - prefix &&\n\t\tsuffix < after.length - prefix &&\n\t\tjsonEqual(before[before.length - 1 - suffix]!, after[after.length - 1 - suffix]!)\n\t) {\n\t\tsuffix++;\n\t}\n\tconst shorter = Math.min(before.length, after.length);\n\tif (prefix + suffix === shorter) {\n\t\tconst remove = before.length - prefix - suffix;\n\t\tconst items = after.slice(prefix, after.length - suffix);\n\t\tif (prefix === 0 && remove === before.length) emitSet(path, after, out);\n\t\telse out.push([\"p\", [...path], prefix, remove, cloneJson(items)]);\n\t\treturn;\n\t}\n\n\t// Structural movement combined with retained-index edits has no unique\n\t// alignment. Preserve the retained index deltas and express only the tail\n\t// length change structurally. It may be broader than the producer's intent,\n\t// but never degrades those edits to a whole-array replacement.\n\tfor (let index = 0; index < shorter; index++) {\n\t\tdiffValue(before[index]!, after[index]!, [...path, index], scan, out);\n\t}\n\tif (after.length > before.length) {\n\t\tout.push([\"p\", [...path], before.length, 0, cloneJson(after.slice(before.length))]);\n\t} else if (before.length > after.length) {\n\t\tif (after.length === 0) emitSet(path, after, out);\n\t\telse out.push([\"p\", [...path], after.length, before.length - after.length, []]);\n\t}\n}\n\nconst walkDirty = (before: JsonValue, after: JsonValue, node: DirtyNode, path: Path, scan: number, out: Op[]): void => {\n\tif (node.valueDirty) {\n\t\tdiffValue(before, after, path, scan, out);\n\t\treturn;\n\t}\n\tif (node.array !== undefined) {\n\t\tif (node.array.kind === \"replace\") {\n\t\t\tif (!jsonEqual(before, after)) emitSet(path, after, out);\n\t\t\treturn;\n\t\t}\n\t\tif (!Array.isArray(before) || !Array.isArray(after) || node.array.kind === \"diff\") {\n\t\t\tdiffValue(before, after, path, scan, out);\n\t\t\treturn;\n\t\t}\n\t\tconst start = node.array.start;\n\t\tif (before.length !== start || after.length < start) {\n\t\t\tdiffValue(before, after, path, scan, out);\n\t\t\treturn;\n\t\t}\n\t\tfor (const [segment, child] of node.children) {\n\t\t\tif (typeof segment !== \"number\" || segment >= start) continue;\n\t\t\tconst previous = ownValue(before, segment);\n\t\t\tconst current = ownValue(after, segment);\n\t\t\tif (previous === MISSING || current === MISSING || child.valueDirty) {\n\t\t\t\tdiffValue(previous, current, [...path, segment], scan, out);\n\t\t\t} else if (isObj(previous) && isObj(current)) {\n\t\t\t\twalkDirty(previous as JsonValue, current as JsonValue, child, [...path, segment], scan, out);\n\t\t\t} else {\n\t\t\t\tdiffValue(previous, current, [...path, segment], scan, out);\n\t\t\t}\n\t\t}\n\t\tconst items = after.slice(start);\n\t\tif (items.length > 0) out.push([\"p\", [...path], start, 0, cloneJson(items)]);\n\t\treturn;\n\t}\n\tfor (const [segment, child] of node.children) {\n\t\tconst previous = ownValue(before, segment);\n\t\tconst current = ownValue(after, segment);\n\t\tif (previous === MISSING || current === MISSING || child.valueDirty) {\n\t\t\tdiffValue(previous, current, [...path, segment], scan, out);\n\t\t\tcontinue;\n\t\t}\n\t\tif (!isObj(previous) || !isObj(current)) {\n\t\t\tdiffValue(previous, current, [...path, segment], scan, out);\n\t\t\tcontinue;\n\t\t}\n\t\twalkDirty(previous as JsonValue, current as JsonValue, child, [...path, segment], scan, out);\n\t}\n};\n\n/**\n * Bring `baseline` up to `root` along the dirty paths by sharing references.\n * Returns false — having changed nothing — if any dirty node is an array\n * change other than a pure append, so the caller can replay ops instead.\n * Cloning a whole array there is O(n) per flush; replay is O(changes).\n *\n * Strings are immutable, so root's `after` is shared outright, and sharing it\n * also means the next flush compares against a flat string rather than a cons.\n * Objects are cloned because root keeps mutating them.\n */\nconst syncBaseline = (baseline: JsonValue, root: JsonValue, node: DirtyNode): boolean => {\n\tif (!canSync(node)) return false;\n\tsyncInto(baseline, root, node);\n\treturn true;\n};\n\nconst canSync = (node: DirtyNode): boolean => {\n\tif (node.array !== undefined && node.array.kind !== \"append\") return false;\n\tfor (const child of node.children.values()) if (!canSync(child)) return false;\n\treturn true;\n};\n\nconst syncInto = (baseline: JsonValue, root: JsonValue, node: DirtyNode): void => {\n\tconst parent = baseline as Record<string | number, JsonValue>;\n\tif (node.array?.kind === \"append\" && Array.isArray(baseline) && Array.isArray(root)) {\n\t\tconst start = node.array.start;\n\t\tfor (const [index, child] of node.children) {\n\t\t\tif (typeof index === \"number\" && index < start) syncChild(parent, root, index, child);\n\t\t}\n\t\tfor (let i = start; i < root.length; i++) {\n\t\t\tbaseline.push(isObj(root[i]) ? cloneJson(root[i] as JsonValue) : (root[i] as JsonValue));\n\t\t}\n\t\treturn;\n\t}\n\tfor (const [segment, child] of node.children) syncChild(parent, root, segment, child);\n};\n\nconst syncChild = (\n\tparent: Record<string | number, JsonValue>,\n\troot: JsonValue,\n\tsegment: Seg,\n\tchild: DirtyNode,\n): void => {\n\tconst current = ownValue(root, segment);\n\tconst previous = ownValue(parent as JsonValue, segment);\n\tif (current === MISSING) {\n\t\tif (Array.isArray(parent)) parent.splice(segment as number, 1);\n\t\telse delete parent[segment];\n\t\treturn;\n\t}\n\tif (child.valueDirty || !isObj(current) || !isObj(previous) || Array.isArray(current) !== Array.isArray(previous)) {\n\t\tparent[segment] = isObj(current) ? cloneJson(current as JsonValue) : (current as JsonValue);\n\t\treturn;\n\t}\n\tsyncInto(previous as JsonValue, current as JsonValue, child);\n};\n\nconst cloneOp = (op: Op): Op => {\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\treturn [\"r\", cloneJson(op[1])];\n\t\tcase \"s\":\n\t\t\treturn [\"s\", op[1], cloneJson(op[2])];\n\t\tcase \"p\":\n\t\t\treturn [\"p\", op[1], op[2], op[3], cloneJson(op[4])];\n\t\tdefault:\n\t\t\treturn op;\n\t}\n};\n\nexport function track<T extends object>(root: T, options: TrackerOptions = {}): Tracker<T> {\n\tconst scan = options.maxOverlapScan ?? 65_536;\n\tlet pending = dirtyNode();\n\tlet hasPending = false;\n\tlet baseline: JsonValue | undefined;\n\tlet forceBase = true;\n\n\tconst clearPending = (): void => {\n\t\tpending = dirtyNode();\n\t\thasPending = false;\n\t};\n\n\tconst ensureNode = (path: Path): DirtyNode | undefined => {\n\t\thasPending = true;\n\t\tlet node = pending;\n\t\tfor (const segment of path) {\n\t\t\tif (node.valueDirty || node.array?.kind === \"diff\" || node.array?.kind === \"replace\") return undefined;\n\t\t\tlet child = node.children.get(segment);\n\t\t\tif (child === undefined) child = dirtyNode();\n\t\t\telse node.children.delete(segment);\n\t\t\tnode.children.set(segment, child);\n\t\t\tnode = child;\n\t\t}\n\t\treturn node;\n\t};\n\n\tconst findNode = (path: Path): DirtyNode | undefined => {\n\t\tlet node = pending;\n\t\tfor (const segment of path) {\n\t\t\tconst child = node.children.get(segment);\n\t\t\tif (child === undefined) return undefined;\n\t\t\tnode = child;\n\t\t}\n\t\treturn node;\n\t};\n\n\tconst markValue = (path: Path): void => {\n\t\tconst node = ensureNode(path);\n\t\tif (node === undefined) return;\n\t\tnode.valueDirty = true;\n\t\tnode.array = undefined;\n\t\tnode.children.clear();\n\t};\n\n\tconst markArrayAppend = (path: Path, start: number): void => {\n\t\tconst node = ensureNode(path);\n\t\tif (node === undefined || node.valueDirty || node.array?.kind === \"diff\" || node.array?.kind === \"replace\") {\n\t\t\treturn;\n\t\t}\n\t\tif (node.array === undefined) node.array = { kind: \"append\", start };\n\t};\n\n\tconst markArrayDiff = (path: Path): void => {\n\t\tconst node = ensureNode(path);\n\t\tif (node === undefined || node.valueDirty || node.array?.kind === \"replace\") return;\n\t\tnode.array = { kind: \"diff\" };\n\t\tnode.children.clear();\n\t};\n\n\tconst markArrayReplace = (path: Path): void => {\n\t\tconst node = ensureNode(path);\n\t\tif (node === undefined || node.valueDirty) return;\n\t\tnode.array = { kind: \"replace\" };\n\t\tnode.children.clear();\n\t};\n\n\tconst appendStart = (path: Path): number | undefined => {\n\t\tconst array = findNode(path)?.array;\n\t\treturn array?.kind === \"append\" ? array.start : undefined;\n\t};\n\n\tconst guard = (segment: Seg | symbol): Seg => {\n\t\tif (typeof segment === \"symbol\") throw new UnsafePathError(String(segment));\n\t\tif (typeof segment === \"string\" && RESERVED_SEGMENTS.has(segment)) throw new UnsafePathError(segment);\n\t\treturn segment;\n\t};\n\n\tconst adoptItems = (values: readonly unknown[]): JsonValue[] => values as JsonValue[];\n\n\tconst integer = (value: unknown): number => {\n\t\tconst number = Number(value);\n\t\tif (Number.isNaN(number) || number === 0) return 0;\n\t\treturn Number.isFinite(number) ? Math.trunc(number) : number;\n\t};\n\n\tconst spliceRange = (length: number, args: readonly unknown[]): { index: number; remove: number } => {\n\t\tconst rawStart = args.length === 0 ? 0 : integer(args[0]);\n\t\tconst index = rawStart < 0 ? Math.max(0, length + rawStart) : Math.min(rawStart, length);\n\t\tconst remove =\n\t\t\targs.length === 0\n\t\t\t\t? 0\n\t\t\t\t: args.length === 1\n\t\t\t\t\t? length - index\n\t\t\t\t\t: Math.max(0, Math.min(integer(args[1]), length - index));\n\t\treturn { index, remove };\n\t};\n\n\tconst wrap = <V extends object>(object: V, path: Path, blockedSegment?: Seg): V => {\n\t\tconst childProxies = new Map<string | symbol, { target: object; proxy: object }>();\n\t\tconst proxy = new Proxy(object, {\n\t\t\tget(target, key, receiver) {\n\t\t\t\tif (Array.isArray(target) && typeof key === \"string\" && MUTATORS.has(key)) {\n\t\t\t\t\treturn (...args: unknown[]) => {\n\t\t\t\t\t\tif (blockedSegment !== undefined) throw new UnsafePathError(blockedSegment);\n\t\t\t\t\t\tconst before = target.length;\n\t\t\t\t\t\tlet result: unknown;\n\t\t\t\t\t\tswitch (key) {\n\t\t\t\t\t\t\tcase \"push\": {\n\t\t\t\t\t\t\t\tconst items = adoptItems(args);\n\t\t\t\t\t\t\t\tif (items.length > 0) markArrayAppend(path, before);\n\t\t\t\t\t\t\t\tspliceItems(target, before, 0, items);\n\t\t\t\t\t\t\t\tresult = target.length;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"unshift\": {\n\t\t\t\t\t\t\t\tconst items = adoptItems(args);\n\t\t\t\t\t\t\t\tif (items.length > 0) markArrayDiff(path);\n\t\t\t\t\t\t\t\tspliceItems(target, 0, 0, items);\n\t\t\t\t\t\t\t\tresult = target.length;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcase \"pop\":\n\t\t\t\t\t\t\t\tif (before > 0) {\n\t\t\t\t\t\t\t\t\tconst start = appendStart(path);\n\t\t\t\t\t\t\t\t\tif (start === undefined || before - 1 < start) markArrayDiff(path);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tresult = Reflect.apply(Array.prototype.pop, target, args);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"shift\":\n\t\t\t\t\t\t\t\tif (before > 0) markArrayDiff(path);\n\t\t\t\t\t\t\t\tresult = Reflect.apply(Array.prototype.shift, target, args);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\tcase \"splice\": {\n\t\t\t\t\t\t\t\tconst items = adoptItems(args.slice(2));\n\t\t\t\t\t\t\t\tconst { index, remove } = spliceRange(before, args);\n\t\t\t\t\t\t\t\tif (remove > 0 || items.length > 0) {\n\t\t\t\t\t\t\t\t\tconst start = appendStart(path);\n\t\t\t\t\t\t\t\t\tif (index === 0 && remove === before) markArrayReplace(path);\n\t\t\t\t\t\t\t\t\telse if (start !== undefined && index >= start) {\n\t\t\t\t\t\t\t\t\t\t// The final append payload includes all tail edits.\n\t\t\t\t\t\t\t\t\t} else if (index === before && remove === 0) markArrayAppend(path, before);\n\t\t\t\t\t\t\t\t\telse markArrayDiff(path);\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tresult = spliceItems(target, index, remove, items);\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tdefault:\n\t\t\t\t\t\t\t\tmarkArrayDiff(path);\n\t\t\t\t\t\t\t\tresult = Reflect.apply(Array.prototype[key as \"sort\"], target, args);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (key === \"pop\") childProxies.delete(String(before - 1));\n\t\t\t\t\t\telse if (key !== \"push\") childProxies.clear();\n\t\t\t\t\t\treturn key === \"sort\" || key === \"reverse\" || key === \"fill\" || key === \"copyWithin\" ? proxy : result;\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst value = Reflect.get(target, key, receiver);\n\t\t\t\tif (!isObj(value)) return value;\n\t\t\t\tconst cached = childProxies.get(key);\n\t\t\t\tif (cached?.target === value) return cached.proxy;\n\t\t\t\tconst rawSegment = norm(target, key);\n\t\t\t\tlet segment: Seg;\n\t\t\t\tlet childBlocked = blockedSegment;\n\t\t\t\tif (blockedSegment !== undefined) {\n\t\t\t\t\tif (typeof rawSegment === \"symbol\") throw new UnsafePathError(String(rawSegment));\n\t\t\t\t\tsegment = rawSegment;\n\t\t\t\t} else if (\n\t\t\t\t\ttypeof rawSegment === \"string\" &&\n\t\t\t\t\tRESERVED_SEGMENTS.has(rawSegment) &&\n\t\t\t\t\tObject.hasOwn(target, key)\n\t\t\t\t) {\n\t\t\t\t\tsegment = rawSegment;\n\t\t\t\t\tchildBlocked = rawSegment;\n\t\t\t\t} else segment = guard(rawSegment);\n\t\t\t\tconst child = wrap(value, [...path, segment], childBlocked);\n\t\t\t\tchildProxies.set(key, { target: value, proxy: child });\n\t\t\t\treturn child;\n\t\t\t},\n\n\t\t\tset(target, key, value) {\n\t\t\t\tif (blockedSegment !== undefined) throw new UnsafePathError(blockedSegment);\n\t\t\t\tif (Array.isArray(target) && key === \"length\") {\n\t\t\t\t\tconst before = target.length;\n\t\t\t\t\tconst next = Number(value);\n\t\t\t\t\tif (!Number.isSafeInteger(next) || next < 0 || next > 4_294_967_295) {\n\t\t\t\t\t\treturn Reflect.set(target, key, value);\n\t\t\t\t\t}\n\t\t\t\t\tif (next < before) {\n\t\t\t\t\t\tconst start = appendStart(path);\n\t\t\t\t\t\tif (next === 0) markArrayReplace(path);\n\t\t\t\t\t\telse if (start === undefined || next < start) markArrayDiff(path);\n\t\t\t\t\t\tReflect.set(target, key, next);\n\t\t\t\t\t\tchildProxies.clear();\n\t\t\t\t\t} else if (next > before) {\n\t\t\t\t\t\tmarkArrayAppend(path, before);\n\t\t\t\t\t\ttarget.length = next;\n\t\t\t\t\t\ttarget.fill(null, before);\n\t\t\t\t\t}\n\t\t\t\t\treturn true;\n\t\t\t\t}\n\n\t\t\t\tconst segment = guard(norm(target, key));\n\t\t\t\tif (Array.isArray(target)) {\n\t\t\t\t\tif (typeof segment !== \"number\") throw new UnsafePathError(segment);\n\t\t\t\t\tif (segment > target.length) throw new UnsafePathError(segment);\n\t\t\t\t}\n\t\t\t\tconst at = [...path, segment] as unknown as NonEmptyPath;\n\n\t\t\t\tif (value === undefined) {\n\t\t\t\t\tif (Array.isArray(target)) {\n\t\t\t\t\t\tthrow new TypeError(\"undefined would create a sparse array; use splice instead\");\n\t\t\t\t\t}\n\t\t\t\t\tmarkValue(at);\n\t\t\t\t\tchildProxies.delete(key);\n\t\t\t\t\treturn Reflect.deleteProperty(target, key);\n\t\t\t\t}\n\n\t\t\t\tconst previous = (target as Record<string | symbol, unknown>)[key];\n\t\t\t\tif (previous === value) return true;\n\t\t\t\tconst cached = childProxies.get(key);\n\t\t\t\tif (cached !== undefined && cached.target === previous && cached.proxy === value) return true;\n\t\t\t\tif (Array.isArray(target)) {\n\t\t\t\t\tconst index = segment as number;\n\t\t\t\t\tif (index === target.length) markArrayAppend(path, target.length);\n\t\t\t\t\telse {\n\t\t\t\t\t\tconst start = appendStart(path);\n\t\t\t\t\t\tif (start === undefined || index < start) markValue(at);\n\t\t\t\t\t}\n\t\t\t\t} else markValue(at);\n\t\t\t\tchildProxies.delete(key);\n\t\t\t\treturn Reflect.set(target, key, value);\n\t\t\t},\n\n\t\t\tdeleteProperty(target, key) {\n\t\t\t\tif (blockedSegment !== undefined) throw new UnsafePathError(blockedSegment);\n\t\t\t\tconst segment = guard(norm(target, key));\n\t\t\t\tif (Array.isArray(target)) {\n\t\t\t\t\tif (typeof segment !== \"number\") throw new UnsafePathError(segment);\n\t\t\t\t\tthrow new TypeError(\"delete would create a sparse array; use splice instead\");\n\t\t\t\t}\n\t\t\t\tmarkValue([...path, segment]);\n\t\t\t\tchildProxies.delete(key);\n\t\t\t\treturn Reflect.deleteProperty(target, key);\n\t\t\t},\n\n\t\t\tdefineProperty() {\n\t\t\t\tthrow new TypeError(\"defineProperty is not supported on tracked state; use assignment\");\n\t\t\t},\n\t\t\tsetPrototypeOf() {\n\t\t\t\tthrow new TypeError(\"setPrototypeOf is not supported on tracked state\");\n\t\t\t},\n\t\t\tpreventExtensions() {\n\t\t\t\tthrow new TypeError(\"preventExtensions is not supported on tracked state\");\n\t\t\t},\n\t\t});\n\n\t\treturn proxy as V;\n\t};\n\n\tlet state = wrap(root, []);\n\n\treturn {\n\t\tget state() {\n\t\t\treturn state;\n\t\t},\n\t\tget target() {\n\t\t\treturn root;\n\t\t},\n\t\tset state(next: T) {\n\t\t\tif (next === state) {\n\t\t\t\tclearPending();\n\t\t\t\tforceBase = true;\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tclearPending();\n\t\t\troot = next;\n\t\t\tstate = wrap(root, []);\n\t\t\tbaseline = undefined;\n\t\t\tforceBase = true;\n\t\t},\n\t\trebase() {\n\t\t\tclearPending();\n\t\t\tforceBase = true;\n\t\t},\n\t\tget dirty() {\n\t\t\treturn forceBase || hasPending;\n\t\t},\n\t\tdiscard() {\n\t\t\tbaseline = cloneJson(root as unknown as JsonValue);\n\t\t\tclearPending();\n\t\t},\n\t\tflush() {\n\t\t\tif (forceBase) {\n\t\t\t\tconst value = cloneJson(root as unknown as JsonValue);\n\t\t\t\tbaseline = cloneJson(root as unknown as JsonValue);\n\t\t\t\tforceBase = false;\n\t\t\t\tclearPending();\n\t\t\t\treturn [[\"r\", value]];\n\t\t\t}\n\t\t\tif (!hasPending || baseline === undefined) return [];\n\t\t\tconst out: Op[] = [];\n\t\t\twalkDirty(baseline, root as unknown as JsonValue, pending, [], scan, out);\n\t\t\t// Advance the baseline by SHARING references from root where that is\n\t\t\t// cheap and exact — scalars, strings, and array appends. Replaying the\n\t\t\t// ops rebuilds every touched string via slice + concat: two window-sized\n\t\t\t// allocations per flush and a cons the next flush must flatten. For\n\t\t\t// anything the sync cannot express cheaply (a non-append array change),\n\t\t\t// it declines and the original replay runs unchanged.\n\t\t\tif (!syncBaseline(baseline as JsonValue, root as unknown as JsonValue, pending)) {\n\t\t\t\tif (out.length > 0) baseline = apply(baseline, out.map(cloneOp));\n\t\t\t}\n\t\t\tclearPending();\n\t\t\treturn out;\n\t\t},\n\t};\n}\n\n// ─── Path safety ─────────────────────────────────────────────────────────────\n\n/**\n * Segments that reach the prototype chain.\n *\n * `JSON.parse` is safe on its own — it makes `__proto__` an own property. What is\n * not safe is `parent[key] = value`, which is exactly what an applier does, and\n * paths are data: `[\"s\", [\"__proto__\", \"isAdmin\"], true]` pollutes\n * `Object.prototype` for the whole process.\n *\n * Ops arrive from a facet, a plugin compartment, or a tool whose details may echo\n * model output, so none of it is trusted input.\n */\nexport const RESERVED_SEGMENTS: ReadonlySet<string> = new Set([\"__proto__\", \"constructor\", \"prototype\"]);\n\nexport class UnsafePathError extends Error {\n\t// Not a parameter property: Node's --experimental-strip-types rejects those,\n\t// and these files are meant to run under it directly.\n\treadonly segment: Seg;\n\tconstructor(segment: Seg) {\n\t\tsuper(`unsafe path segment: ${String(segment)}`);\n\t\tthis.segment = segment;\n\t\tthis.name = \"UnsafePathError\";\n\t}\n}\n\n/**\n * Verb, arity and payload shape for a **decoded** op: paths inline, no `#`, no\n * short forms. `apply` uses this.\n *\n * Validating `Op` against the wire grammar would be laxer than the type: a\n * two-element `[\"s\", value]` would pass, and `apply` would then read the value as\n * a path. Each vocabulary gets the validator that matches it.\n */\nexport function assertValidOp(op: unknown): asserts op is Op {\n\tif (!Array.isArray(op) || op.length === 0) throw new TypeError(\"op is not a tuple\");\n\tswitch (op[0]) {\n\t\tcase \"r\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"r arity\");\n\t\t\treturn;\n\t\tcase \"s\":\n\t\t\tif (op.length !== 3) throw new TypeError(\"s arity\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"d\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"d arity\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"a\":\n\t\t\tif (op.length !== 3 || typeof op[2] !== \"string\") throw new TypeError(\"a shape\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"t\":\n\t\t\tif (op.length !== 3 || !Number.isInteger(op[2]) || op[2] < 0) throw new TypeError(\"t shape\");\n\t\t\tassertPathArg(op[1], true);\n\t\t\treturn;\n\t\tcase \"p\": {\n\t\t\tif (op.length !== 5) throw new TypeError(\"p arity\");\n\t\t\tassertPathArg(op[1]);\n\t\t\tif (!Number.isInteger(op[2]) || op[2] < 0) throw new TypeError(\"p index\");\n\t\t\tif (!Number.isInteger(op[3]) || op[3] < 0) throw new TypeError(\"p remove\");\n\t\t\tif (!Array.isArray(op[4])) throw new TypeError(\"p items\");\n\t\t\treturn;\n\t\t}\n\t\t// Silently skipping an unknown verb is how a newer producer's op vanishes.\n\t\tdefault:\n\t\t\tthrow new TypeError(`unknown op verb: ${String(op[0])}`);\n\t}\n}\n\nfunction assertPathArg(p: unknown, nonEmpty = false): void {\n\tif (!Array.isArray(p)) throw new TypeError(\"path is not an array\");\n\tif (nonEmpty && p.length === 0) throw new TypeError(\"path is empty\");\n\tassertSafePath(p as Path);\n}\n\n/** The same, for the wire grammar: ids and short forms are legal here. */\nexport function assertValidWireOp(op: unknown): asserts op is WireOp {\n\tif (!Array.isArray(op) || op.length === 0) throw new TypeError(\"op is not a tuple\");\n\tconst [verb] = op as unknown[];\n\tconst okRef = (r: unknown): void => {\n\t\tif (typeof r === \"number\") {\n\t\t\tif (!Number.isInteger(r) || r < 0) throw new TypeError(\"bad path id\");\n\t\t\treturn;\n\t\t}\n\t\t// A string is not a path. Unchecked, `\"a\".slice(0, -1)` is `\"\"`, so it\n\t\t// resolves to the ROOT and writes there — a path that is not a path, accepted.\n\t\tif (!Array.isArray(r)) throw new TypeError(\"path is not an array\");\n\t\tassertSafePath(r as Path);\n\t};\n\tswitch (verb) {\n\t\tcase \"r\":\n\t\t\tif (op.length !== 2) throw new TypeError(\"r arity\");\n\t\t\treturn;\n\t\tcase \"s\":\n\t\t\tif (op.length === 3) okRef(op[1]);\n\t\t\telse if (op.length !== 2) throw new TypeError(\"s arity\");\n\t\t\treturn;\n\t\tcase \"d\":\n\t\t\tif (op.length === 2) okRef(op[1]);\n\t\t\telse if (op.length !== 1) throw new TypeError(\"d arity\");\n\t\t\treturn;\n\t\tcase \"a\":\n\t\t\tif (op.length === 3) {\n\t\t\t\tokRef(op[1]);\n\t\t\t\tif (typeof op[2] !== \"string\") throw new TypeError(\"a value\");\n\t\t\t} else if (op.length === 2) {\n\t\t\t\tif (typeof op[1] !== \"string\") throw new TypeError(\"a value\");\n\t\t\t} else throw new TypeError(\"a arity\");\n\t\t\treturn;\n\t\tcase \"t\":\n\t\t\tif (op.length === 3) {\n\t\t\t\tokRef(op[1]);\n\t\t\t\tif (!Number.isInteger(op[2]) || (op[2] as number) < 0) throw new TypeError(\"t count\");\n\t\t\t} else if (op.length === 2) {\n\t\t\t\tif (!Number.isInteger(op[1]) || (op[1] as number) < 0) throw new TypeError(\"t count\");\n\t\t\t} else throw new TypeError(\"t arity\");\n\t\t\treturn;\n\t\tcase \"p\": {\n\t\t\tconst [i, r, items] = op.length === 5 ? [op[2], op[3], op[4]] : op.length === 4 ? [op[1], op[2], op[3]] : [];\n\t\t\tif (items === undefined) throw new TypeError(\"p arity\");\n\t\t\tif (op.length === 5) okRef(op[1]);\n\t\t\tif (!Number.isInteger(i) || (i as number) < 0) throw new TypeError(\"p index\");\n\t\t\tif (!Number.isInteger(r) || (r as number) < 0) throw new TypeError(\"p remove\");\n\t\t\tif (!Array.isArray(items)) throw new TypeError(\"p items\");\n\t\t\treturn;\n\t\t}\n\t\tcase \"#\": {\n\t\t\tif (op.length !== 3 || !Number.isInteger(op[1]) || (op[1] as number) < 0 || !Array.isArray(op[2])) {\n\t\t\t\tthrow new TypeError(\"# shape\");\n\t\t\t}\n\t\t\tassertSafePath(op[2] as Path);\n\t\t\treturn;\n\t\t}\n\t\t// Silently skipping an unknown verb is how a newer producer's op vanishes.\n\t\tdefault:\n\t\t\tthrow new TypeError(`unknown op verb: ${String(verb)}`);\n\t}\n}\n\nexport function assertSafePath(path: Path): void {\n\tfor (const seg of path) {\n\t\tif (typeof seg === \"string\") {\n\t\t\tif (RESERVED_SEGMENTS.has(seg)) throw new UnsafePathError(seg);\n\t\t} else if (!Number.isInteger(seg) || seg < 0) {\n\t\t\tthrow new UnsafePathError(seg);\n\t\t}\n\t}\n}\n\n/**\n * An index may address an existing element or append exactly one past the end.\n *\n * This is not an arbitrary cap — it is what keeps the value a `JsonValue`. A\n * sparse array does not survive a JSON round trip: holes serialise to `null` and\n * return as real properties, so `arr[7] = x` on a length-3 array already produces\n * state a replica cannot match. Rejecting the write is more honest than silently\n * diverging.\n *\n * It also removes the denial of service it would otherwise permit:\n * `[\"s\", [\"xs\", 4294967290], 1]` allocates a 4.29-billion-entry array from one op.\n * Growth stays possible and stays proportional — the tracker already emits\n * `arr.length = n` as a splice of explicit nulls, whose op size grows with the\n * gap, so a large growth costs a large op rather than a small one.\n */\nfunction assertIndexInRange(parent: readonly unknown[], index: number): void {\n\tif (index > parent.length) throw new UnsafePathError(index);\n}\n\n// ─── Applier ─────────────────────────────────────────────────────────────────\n\nexport class PathError extends Error {\n\treadonly path: Path | number;\n\tconstructor(path: Path | number) {\n\t\tsuper(`unresolvable path: ${JSON.stringify(path)}`);\n\t\tthis.path = path;\n\t\tthis.name = \"PathError\";\n\t}\n}\n\n/**\n * Apply ops to a plain mutable value. Returns the value, because `r` replaces it\n * outright and cannot be done in place.\n *\n * Takes decoded ops. Path ids and omitted paths are a wire concern — run\n * `decode` first if the ops came from a boundary.\n */\nexport function apply<T>(target: T | undefined, ops: readonly Op[]): T {\n\treturn applyOps(target, ops);\n}\n\nfunction applyOps<T>(target: T | undefined, ops: readonly Op[]): T {\n\tlet root = target as unknown as JsonValue;\n\n\tfor (const op of ops) {\n\t\tassertValidOp(op);\n\t\tif (op[0] === \"r\") {\n\t\t\t// Adopted, not copied. The consumer owns the batch it was handed.\n\t\t\t//\n\t\t\t// Fanning one batch out to several consumers in-process therefore makes\n\t\t\t// their replicas alias each other. That is an ownership rule, not a\n\t\t\t// defect: copy the batch at the fan-out point, or let each consumer\n\t\t\t// decode its own. A batch that crosses a real boundary is already\n\t\t\t// distinct, because serialisation produces fresh objects.\n\t\t\troot = op[1];\n\t\t\tcontinue;\n\t\t}\n\n\t\tconst path = op[1];\n\t\tassertSafePath(path);\n\n\t\tif (op[0] === \"p\") {\n\t\t\tconst target_ = path.length === 0 ? root : resolve(root, path);\n\t\t\tif (!Array.isArray(target_)) throw new PathError(path);\n\t\t\ttarget_.splice(op[2], op[3]);\n\t\t\tconst chunkSize = 10_000;\n\t\t\tfor (let offset = 0; offset < op[4].length; offset += chunkSize) {\n\t\t\t\ttarget_.splice(op[2] + offset, 0, ...op[4].slice(offset, offset + chunkSize));\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\n\t\t// s/d/a/t can never target the root — the type forbids it.\n\t\tconst parent = resolve(root, path.slice(0, -1)) as Record<Seg, JsonValue>;\n\t\tconst key = path[path.length - 1]!;\n\t\tif (Array.isArray(parent)) {\n\t\t\tif (typeof key !== \"number\") throw new UnsafePathError(key);\n\t\t\tassertIndexInRange(parent, key);\n\t\t}\n\t\t// defineProperty rather than assignment: a setter inherited from the prototype\n\t\t// chain would otherwise run on write.\n\t\tconst write = (value: JsonValue) => {\n\t\t\tObject.defineProperty(parent, key, { value, writable: true, enumerable: true, configurable: true });\n\t\t};\n\t\tconst read = (): unknown => (Object.hasOwn(parent, key) ? parent[key] : undefined);\n\t\tswitch (op[0]) {\n\t\t\tcase \"s\":\n\t\t\t\twrite(op[2]);\n\t\t\t\tbreak;\n\t\t\tcase \"d\":\n\t\t\t\tif (Array.isArray(parent)) {\n\t\t\t\t\tif (typeof key !== \"number\" || key >= parent.length) throw new PathError(path);\n\t\t\t\t\t(parent as unknown as JsonValue[]).splice(key, 1);\n\t\t\t\t} else delete parent[key];\n\t\t\t\tbreak;\n\t\t\tcase \"a\": {\n\t\t\t\tconst current = read();\n\t\t\t\tif (typeof current !== \"string\") throw new PathError(path);\n\t\t\t\twrite(`${current}${op[2]}`);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tcase \"t\": {\n\t\t\t\tconst current = read();\n\t\t\t\tif (typeof current !== \"string\") throw new PathError(path);\n\t\t\t\twrite(current.slice(op[2]));\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\treturn root as unknown as T;\n}\n\n/** Apply decoded operations without mutating the previous immutable value. */\nexport function applyImmutable<T>(target: T | undefined, ops: readonly Op[]): T {\n\tlet root = target as unknown as JsonValue;\n\tfor (const op of ops) {\n\t\tif (op[0] === \"r\") {\n\t\t\tassertValidOp(op);\n\t\t\troot = op[1];\n\t\t\tcontinue;\n\t\t}\n\t\troot = copyContainers(root, op[0] === \"p\" ? op[1] : op[1].slice(0, -1));\n\t\troot = applyOps(root, [op]);\n\t}\n\treturn root as unknown as T;\n}\n\nfunction copyContainers(root: JsonValue, path: Path): JsonValue {\n\tconst copy = (value: JsonValue): JsonValue[] | Record<string, JsonValue> => {\n\t\tif (Array.isArray(value)) return value.slice();\n\t\tif (!isObj(value)) throw new PathError(path);\n\t\tconst result = Object.create(Object.getPrototypeOf(value) === null ? null : Object.prototype) as Record<\n\t\t\tstring,\n\t\t\tJsonValue\n\t\t>;\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tObject.defineProperty(result, key, {\n\t\t\t\tvalue: (value as Record<string, JsonValue>)[key],\n\t\t\t\twritable: true,\n\t\t\t\tenumerable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\t}\n\t\treturn result;\n\t};\n\tconst copiedRoot = copy(root);\n\tlet source = root;\n\tlet destination = copiedRoot;\n\tfor (const segment of path) {\n\t\tif (!isObj(source) || !Object.hasOwn(source, segment)) throw new PathError(path);\n\t\tif (Array.isArray(source) && typeof segment !== \"number\") throw new UnsafePathError(segment);\n\t\tconst child = (source as Record<Seg, JsonValue>)[segment]!;\n\t\tconst copiedChild = copy(child);\n\t\tObject.defineProperty(destination, segment, {\n\t\t\tvalue: copiedChild,\n\t\t\twritable: true,\n\t\t\tenumerable: true,\n\t\t\tconfigurable: true,\n\t\t});\n\t\tsource = child;\n\t\tdestination = copiedChild;\n\t}\n\treturn copiedRoot;\n}\n\nfunction resolveValue(root: JsonValue, path: Path): JsonValue {\n\tlet node: JsonValue = root;\n\tfor (const seg of path) {\n\t\tif (!isObj(node)) throw new PathError(path);\n\t\tif (Array.isArray(node) && typeof seg !== \"number\") throw new UnsafePathError(seg);\n\t\t// Own properties only: an inherited getter must not run, and a walk must not\n\t\t// escape the value into the prototype chain.\n\t\tif (!Object.hasOwn(node, seg as PropertyKey)) throw new PathError(path);\n\t\tnode = (node as Record<Seg, JsonValue>)[seg]!;\n\t}\n\treturn node;\n}\n\nfunction resolve(root: JsonValue, path: Path): JsonValue {\n\tconst node = resolveValue(root, path);\n\tif (!isObj(node)) throw new PathError(path);\n\treturn node;\n}\n\n// ─── Codec ───────────────────────────────────────────────────────────────────\n//\n// Path interning and arity omission live between the tracker and a boundary;\n// `Op` and `apply` know nothing about them.\n//\n// ONE PAIR PER INDEPENDENT STATE STREAM. Every decoder must observe exactly the\n// batches encoded by its matching encoder, beginning with that state's base.\n// Sharing a transport connection does not make separately hydrated states one\n// stream.\n\nconst pathKey = (path: Path): string => JSON.stringify(path);\n\nexport interface Encoder {\n\tencode(ops: readonly Op[]): WireOp[];\n}\n\n/**\n * Intern on SECOND use. A definition costs more than the path it replaces, so\n * interning on first use loses on the many paths written exactly once.\n */\nexport function encoder(): Encoder {\n\tconst seen = new Set<string>();\n\tconst ids = new Map<string, number>();\n\tlet nextId = 0;\n\tlet previous: string | undefined; // last path in THIS batch\n\n\treturn {\n\t\tencode(ops) {\n\t\t\t// Arity omission is scoped to a batch. Letting it span batches would make\n\t\t\t// a batch's first op depend on the previous batch's last one, so a reader\n\t\t\t// that skips or reorders a batch decodes into the wrong path. Ids are the\n\t\t\t// only cross-batch state, and the dictionary makes those explicit.\n\t\t\tprevious = undefined;\n\t\t\tconst out: WireOp[] = [];\n\t\t\tfor (const op of ops) {\n\t\t\t\tif (op[0] === \"r\") {\n\t\t\t\t\tout.push(op);\n\t\t\t\t\t// A base batch is a RECOVERY POINT: a reader replays from the last one\n\t\t\t\t\t// with a fresh decoder. So everything after it must be self-contained.\n\t\t\t\t\t// Keeping ids across a replacement emits references to definitions the\n\t\t\t\t\t// reader never saw — recovery fails with an unresolvable path id.\n\t\t\t\t\tseen.clear();\n\t\t\t\t\tids.clear();\n\t\t\t\t\tnextId = 0;\n\t\t\t\t\tprevious = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst path = op[1];\n\t\t\t\tconst key = pathKey(path);\n\n\t\t\t\t// Same path as the previous op: drop the ref entirely.\n\t\t\t\tif (key === previous) {\n\t\t\t\t\tswitch (op[0]) {\n\t\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\t\tout.push([\"s\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\t\tout.push([\"d\"]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\t\tout.push([\"a\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\t\tout.push([\"t\", op[2]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\tcase \"p\":\n\t\t\t\t\t\t\tout.push([\"p\", op[2], op[3], op[4]]);\n\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tlet ref: PathRef = path;\n\t\t\t\tconst existing = ids.get(key);\n\t\t\t\tif (existing !== undefined) {\n\t\t\t\t\tref = existing;\n\t\t\t\t} else if (seen.has(key)) {\n\t\t\t\t\tconst id = nextId++;\n\t\t\t\t\tids.set(key, id);\n\t\t\t\t\tout.push([\"#\", id, path]); // second use: define, then reference\n\t\t\t\t\tref = id;\n\t\t\t\t} else {\n\t\t\t\t\tseen.add(key); // first use: inline\n\t\t\t\t}\n\n\t\t\t\tswitch (op[0]) {\n\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\tout.push([\"s\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\tout.push([\"d\", ref as PathRef<NonEmptyPath>]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tout.push([\"a\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\tout.push([\"t\", ref as PathRef<NonEmptyPath>, op[2]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"p\":\n\t\t\t\t\t\tout.push([\"p\", ref, op[2], op[3], op[4]]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tprevious = key;\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t};\n}\n\nexport interface Decoder {\n\tdecode(wire: readonly WireOp[]): Op[];\n}\n\nexport function decoder(): Decoder {\n\tconst paths = new Map<number, Path>();\n\n\treturn {\n\t\tdecode(wire) {\n\t\t\tlet previous: Path | undefined; // scoped to the batch, as in encode\n\t\t\tconst out: Op[] = [];\n\t\t\tfor (const op of wire) {\n\t\t\t\tassertValidWireOp(op);\n\t\t\t\tif (op[0] === \"#\") {\n\t\t\t\t\tassertSafePath(op[2]);\n\t\t\t\t\tpaths.set(op[1], op[2]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (op[0] === \"r\") {\n\t\t\t\t\tout.push(op);\n\t\t\t\t\tpaths.clear();\n\t\t\t\t\tprevious = undefined;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\t// Arity tells us whether a ref is present: the short forms omit it.\n\t\t\t\tconst short =\n\t\t\t\t\t(op[0] === \"d\" && op.length === 1) ||\n\t\t\t\t\t(op[0] !== \"d\" && op[0] !== \"p\" && op.length === 2) ||\n\t\t\t\t\t(op[0] === \"p\" && op.length === 4);\n\n\t\t\t\tlet path: Path;\n\t\t\t\tif (short) {\n\t\t\t\t\tif (previous === undefined) throw new PathError([]);\n\t\t\t\t\tpath = previous;\n\t\t\t\t} else {\n\t\t\t\t\tconst ref = op[1] as PathRef;\n\t\t\t\t\tif (typeof ref === \"number\") {\n\t\t\t\t\t\tconst resolved = paths.get(ref);\n\t\t\t\t\t\tif (resolved === undefined) throw new PathError(ref);\n\t\t\t\t\t\tpath = resolved;\n\t\t\t\t\t} else {\n\t\t\t\t\t\tpath = ref;\n\t\t\t\t\t}\n\t\t\t\t\tprevious = path;\n\t\t\t\t}\n\n\t\t\t\tif (op[0] !== \"p\" && path.length === 0) throw new PathError(path);\n\t\t\t\tswitch (op[0]) {\n\t\t\t\t\tcase \"s\":\n\t\t\t\t\t\tout.push([\"s\", path as NonEmptyPath, (short ? op[1] : op[2]) as JsonValue]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"d\":\n\t\t\t\t\t\tout.push([\"d\", path as NonEmptyPath]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"a\":\n\t\t\t\t\t\tout.push([\"a\", path as NonEmptyPath, (short ? op[1] : op[2]) as string]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"t\":\n\t\t\t\t\t\tout.push([\"t\", path as NonEmptyPath, (short ? op[1] : op[2]) as number]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"p\": {\n\t\t\t\t\t\tconst [i, r, items] = short\n\t\t\t\t\t\t\t? [op[1] as number, op[2] as number, op[3] as JsonValue[]]\n\t\t\t\t\t\t\t: [op[2] as number, op[3] as number, op[4] as JsonValue[]];\n\t\t\t\t\t\tout.push([\"p\", path, i, r, items]);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn out;\n\t\t},\n\t};\n}\n"]}