doxum 0.1.7 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -1
- package/dist/{contract-DNZ4D53r.d.ts → contract-CIcftgR3.d.ts} +25 -27
- package/dist/{contract-j3SLGAwh.d.cts → contract-b87yPRDp.d.cts} +25 -27
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +4 -4
- package/dist/index.d.ts +4 -4
- package/dist/index.js.map +1 -1
- package/dist/integration.d.cts +2 -2
- package/dist/integration.d.ts +2 -2
- package/dist/local-sync.cjs.map +1 -1
- package/dist/local-sync.d.cts +1 -1
- package/dist/local-sync.d.ts +1 -1
- package/dist/local-sync.js.map +1 -1
- package/dist/runtime-0mOFbe_H.cjs.map +1 -1
- package/dist/{runtime-BFmhzPpZ.d.ts → runtime-BzxODO9Q.d.ts} +2 -2
- package/dist/{runtime-B22tuj9A.d.cts → runtime-CRVMB9n1.d.cts} +2 -2
- package/dist/runtime-DF1q9Gje.js.map +1 -1
- package/package.json +1 -1
- package/skills/doxum-runtime/references/guide.en.md +7 -0
- package/skills/doxum-runtime/references/guide.zh-CN.md +5 -0
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["overlaps","id","contains","DocumentDisposedError","object","ownAddress","isRecord","rejected","issue.from","cloneValue","transferPayload","rejected","issue.from","ownPayload","sameStructuralValue","cloneValue","has","rejected","sameOrder","ownPayload","sameStructuralValue","isRecord","cloneValue","issue.from","ownPayload","tree.validate","tree.is","tree.replace","tree.insert","tree.set","tree.remove","tree.move","rejected","issue.from","ownPayload","sameStructuralValue","isRecord","cloneValue","hasOwn","issue.from","cloneValue","locate","isRecord","tree.restoreChange","read","sameStructuralValue","tree.changeChanged","ownPayload","tree.is","tree.recordChange","isRecord","issue.input","input","isPlainObject","isStablePayload","snapshotPayload","resolveLocated","operation.decode","operation.normalize","operation.requiresPayloadCopy","operation.publish","inverse","operation.inverse","operation.decodeBatch","tree.invalidDocument","cloneValue","DocumentDisposedError","DocumentReentrancyError","accessOf","documentReader","notify","resolveAddress","readAddress","commandFootprint","issue.at","deepEqual","subscribeRoot","subscribeTargets","createNotification","accessOf","readWith"],"sources":["../core/src/impact.ts","../core/src/history.ts","../core/src/access/writer.ts","../core/src/mutation/issue.ts","../core/src/mutation/execute-entity.ts","../core/src/mutation/execute-list.ts","../core/src/mutation/tree.ts","../core/src/mutation/execute-tree.ts","../core/src/mutation/execute-value.ts","../core/src/mutation/execute.ts","../core/src/mutation/journal.ts","../core/src/mutation/operation.ts","../core/src/mutation/session.ts","../core/src/runtime.ts","../core/src/runtime/readable.ts","../core/src/projection/select.ts"],"sourcesContent":["import type { CollectionSelector, DocumentAddress, DocumentSchema, ImpactTarget } from './schema';\nimport type { DocumentOperation } from './operations';\nimport { contains, overlaps } from './address';\nimport type { MutationCollectionChange } from './mutation/contract';\nimport { profile } from './profile';\nimport * as target from './impact-target';\n\nexport type CollectionImpact<TId> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: ReadonlySet<TId>;\n readonly removed: ReadonlySet<TId>;\n readonly updated: ReadonlySet<TId>;\n readonly orderChanged: boolean;\n };\n\nexport type DocumentImpact<TSchema extends DocumentSchema> = {\n readonly kind: 'incremental' | 'reset';\n readonly affects: (target: ImpactTarget<unknown>) => boolean;\n readonly collection: <TId extends string>(\n selector: CollectionSelector<TId>\n ) => CollectionImpact<TId>;\n readonly operations: readonly DocumentOperation[];\n};\n\nconst emptyCollectionImpact: CollectionImpact<string> = Object.freeze({\n kind: 'incremental',\n added: new Set<string>(),\n removed: new Set<string>(),\n updated: new Set<string>(),\n orderChanged: false,\n});\nconst resetCollectionImpact: CollectionImpact<never> = Object.freeze({\n kind: 'reset',\n});\n\nexport const createImpact = <TSchema extends DocumentSchema>(input: {\n readonly schema: TSchema;\n readonly operations: readonly DocumentOperation[];\n readonly paths?: readonly DocumentAddress[];\n readonly collections?: readonly MutationCollectionChange[];\n readonly reset?: boolean;\n}): DocumentImpact<TSchema> => {\n const kind = input.reset ? 'reset' : 'incremental';\n const paths = input.paths ?? input.operations.map(operation => operation.at);\n let pathBuckets: Map<string | undefined, DocumentAddress[]> | undefined;\n const somePath = (\n address: DocumentAddress,\n test: (changed: DocumentAddress) => boolean\n ): boolean => {\n if (address.length === 0 || paths.length <= 8) return paths.some(test);\n if (!pathBuckets) {\n pathBuckets = new Map();\n for (const changed of paths) {\n const first = changed[0];\n const bucket = pathBuckets.get(first) ?? [];\n bucket.push(changed);\n pathBuckets.set(first, bucket);\n }\n }\n const root = pathBuckets.get(undefined);\n if (root?.some(test)) return true;\n return pathBuckets.get(address[0])?.some(test) ?? false;\n };\n const pathsAffect = (address: DocumentAddress): boolean =>\n address.length === 0\n ? paths.length > 0\n : somePath(address, changed => overlaps(changed, address));\n let collectionCache:\n | {\n readonly address: DocumentAddress;\n readonly value: CollectionImpact<unknown>;\n }[]\n | undefined;\n const findCollection = (address: DocumentAddress) =>\n input.collections?.find(\n entry =>\n entry.address.length === address.length &&\n entry.address.every((segment, index) => segment === address[index])\n );\n return {\n kind,\n operations: input.operations,\n affects: value => {\n profile.impact.affects();\n if (kind === 'reset') return true;\n if (!target.belongs(value, input.schema)) return false;\n const address = target.address(value);\n if (pathsAffect(address)) return true;\n if (value.kind === 'collection') {\n const collectionAddress = target.address(value);\n const collection = findCollection(collectionAddress);\n if (!collection) return false;\n const id = target.id(value);\n if (id !== undefined)\n return (\n collection.added.has(id) || collection.removed.has(id) || collection.updated.has(id)\n );\n return (\n collection.added.size > 0 ||\n collection.removed.size > 0 ||\n collection.updated.size > 0 ||\n collection.orderChanged\n );\n }\n return false;\n },\n collection: <TId extends string>(selector: CollectionSelector<TId>): CollectionImpact<TId> => {\n if (selector.schema !== input.schema)\n throw new Error('Collection selector belongs to another schema.');\n if (kind === 'reset') return resetCollectionImpact as CollectionImpact<TId>;\n const cached = collectionCache?.find(\n entry =>\n entry.address.length === selector.address.length &&\n entry.address.every((segment, index) => segment === selector.address[index])\n )?.value;\n if (cached) return cached as CollectionImpact<TId>;\n const exact = findCollection(selector.address);\n const subtreeReset = somePath(\n selector.address,\n changed => contains(changed, selector.address) && changed.length < selector.address.length\n );\n if (subtreeReset) {\n const reset = { kind: 'reset' } as const;\n (collectionCache ??= []).push({\n address: selector.address,\n value: reset,\n });\n return reset;\n }\n if (!exact) {\n const empty = emptyCollectionImpact as CollectionImpact<TId>;\n (collectionCache ??= []).push({\n address: selector.address,\n value: empty as CollectionImpact<unknown>,\n });\n return empty;\n }\n const incremental = {\n kind: 'incremental' as const,\n added: exact.added as ReadonlySet<TId>,\n removed: exact.removed as ReadonlySet<TId>,\n updated: exact.updated as ReadonlySet<TId>,\n orderChanged: exact.orderChanged,\n };\n (collectionCache ??= []).push({\n address: selector.address,\n value: incremental as CollectionImpact<unknown>,\n });\n return incremental;\n },\n };\n};\n","import type { DocumentOperation } from './operations';\nimport type {\n HistoryState,\n LocalHistory,\n ObserverError,\n OperationResult,\n} from './runtime/contract';\nimport { DocumentDisposedError } from './runtime/contract';\n\ntype Batch = {\n readonly operations: readonly DocumentOperation[];\n readonly inverse: readonly DocumentOperation[];\n};\ntype Entry = { readonly batches: Batch[] };\ntype Group = { entry?: Entry; readonly undos: Entry[]; readonly redos: Entry[] };\n\nexport const createHistory = <TCommit>(input: {\n readonly capacity: number;\n readonly apply: (operations: readonly DocumentOperation[]) => OperationResult<TCommit>;\n readonly revision: () => number;\n readonly assertIdle: () => void;\n readonly notify: (run: () => readonly ObserverError[]) => readonly ObserverError[];\n}) => {\n let undos: Entry[] = [];\n let redos: Entry[] = [];\n const listeners = new Set<() => void>();\n let state: HistoryState = Object.freeze({ undoDepth: 0, redoDepth: 0 });\n let revision = 0;\n let pending = false;\n let disposed = false;\n let group: Group | undefined;\n const unchanged = (): OperationResult<TCommit> => ({\n status: 'unchanged',\n revision: input.revision(),\n });\n const publish = () => {\n if (state.undoDepth === undos.length && state.redoDepth === redos.length) return;\n state = Object.freeze({ undoDepth: undos.length, redoDepth: redos.length });\n revision++;\n pending = true;\n };\n const flush = (): readonly ObserverError[] => {\n if (!pending) return [];\n pending = false;\n const errors: ObserverError[] = [];\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue;\n try {\n listener();\n } catch (error) {\n errors.push({ phase: 'listener', error });\n }\n }\n return errors;\n };\n const clear = () => {\n group = undefined;\n undos.length = redos.length = 0;\n publish();\n };\n const travel = (direction: 'undo' | 'redo' | 'cancel'): OperationResult<TCommit> => {\n input.assertIdle();\n const from = direction === 'redo' ? redos : undos;\n const to = direction === 'redo' ? undos : redos;\n const previousUndos = undos;\n const previousRedos = redos;\n const entry = direction === 'cancel' ? from.at(-1) : from.pop();\n if (!entry) return unchanged();\n if (direction === 'cancel') {\n if (!group || group.entry !== entry)\n throw new Error('History group no longer owns its entry.');\n undos = group.undos;\n redos = group.redos;\n } else to.push(entry);\n let committed = false;\n try {\n const operations =\n direction === 'redo'\n ? entry.batches.flatMap(batch => batch.operations)\n : entry.batches\n .slice()\n .reverse()\n .flatMap(batch => batch.inverse);\n const result = input.apply(operations);\n committed = result.status !== 'rejected';\n if (committed && direction === 'cancel') group = undefined;\n if (result.status === 'unchanged') {\n publish();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n }\n return result;\n } finally {\n if (!committed) {\n if (direction === 'cancel') {\n undos = previousUndos;\n redos = previousRedos;\n } else {\n to.pop();\n from.push(entry);\n }\n }\n }\n };\n const api: LocalHistory<TCommit> = {\n current: () => state,\n revision: () => revision,\n subscribe: listener => {\n if (disposed) throw new DocumentDisposedError();\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n undo: () => {\n input.assertIdle();\n group = undefined;\n return travel('undo');\n },\n redo: () => {\n input.assertIdle();\n group = undefined;\n return travel('redo');\n },\n clear: () => {\n input.assertIdle();\n clear();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n },\n group: () => {\n input.assertIdle();\n if (group) throw new Error('A history group is already active.');\n if (input.capacity <= 0) throw new Error('History is disabled.');\n const scope: Group = { undos: undos.slice(), redos: redos.slice() };\n group = scope;\n return Object.freeze({\n end: () => {\n input.assertIdle();\n if (group === scope) group = undefined;\n },\n cancel: () => {\n input.assertIdle();\n if (group !== scope) return unchanged();\n if (!scope.entry) {\n group = undefined;\n return unchanged();\n }\n const result = travel('cancel');\n if (result.status !== 'rejected') group = undefined;\n return result;\n },\n });\n },\n };\n return {\n api,\n record: (operations: readonly DocumentOperation[], inverse: readonly DocumentOperation[]) => {\n if (input.capacity <= 0) return;\n const batch = { operations, inverse };\n if (group?.entry) group.entry.batches.push(batch);\n else {\n const entry: Entry = { batches: [batch] };\n undos.push(entry);\n if (group) group.entry = entry;\n if (undos.length > input.capacity) undos.shift();\n }\n redos.length = 0;\n publish();\n },\n publish,\n flush,\n endGroup: () => {\n group = undefined;\n },\n invalidate: clear,\n dispose: () => {\n disposed = true;\n listeners.clear();\n clear();\n pending = false;\n },\n };\n};\n","import { object } from '../schema';\nimport type {\n DictNode,\n DocumentAddress,\n DocumentNode,\n DocumentSchema,\n DocumentValueOfNode,\n DocumentTreeValue,\n EntitySchemaNode,\n ListNode,\n MapNode,\n ObjectNode,\n TableNode,\n TreeNode,\n VariantNode,\n} from '../schema';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\n\nexport type FieldWriter<T, Optional extends boolean = false> = {\n readonly set: (value: T) => void;\n} & (Optional extends true ? { readonly clear: () => void } : {});\nexport type DictionaryWriter<TKey extends string, TValue> = {\n readonly set: (key: TKey, value: TValue) => void;\n readonly delete: (key: TKey) => void;\n readonly replace: (value: Readonly<Partial<Record<TKey, TValue>>>) => void;\n};\nexport type CollectionWriter<TId, TNode extends EntitySchemaNode> = {\n readonly create: (\n entry:\n | { readonly id: TId; readonly value: DocumentValueOfNode<TNode> }\n | readonly { readonly id: TId; readonly value: DocumentValueOfNode<TNode> }[],\n anchor?: DocumentAnchor\n ) => void;\n readonly item: (id: TId) => WriterOfNode<TNode>;\n readonly remove: (id: TId | readonly TId[]) => void;\n readonly move: (id: TId, anchor?: DocumentAnchor) => void;\n};\nexport type MapWriter<TId, TNode extends EntitySchemaNode> = {\n readonly create: (\n entry:\n | { readonly id: TId; readonly value: DocumentValueOfNode<TNode> }\n | readonly { readonly id: TId; readonly value: DocumentValueOfNode<TNode> }[]\n ) => void;\n readonly item: (id: TId) => WriterOfNode<TNode>;\n readonly remove: (id: TId | readonly TId[]) => void;\n};\nexport type ListWriter<T> = {\n readonly insert: (value: T, anchor?: DocumentAnchor) => void;\n readonly move: (key: string, anchor?: DocumentAnchor) => void;\n readonly remove: (key: string) => void;\n readonly replace: (value: readonly T[]) => void;\n};\nexport type TreeWriter<T> = {\n readonly insert: (\n id: string,\n value: T,\n position?: { readonly parentId?: string; readonly index?: number }\n ) => void;\n readonly move: (\n id: string,\n position?: { readonly parentId?: string; readonly index?: number }\n ) => void;\n readonly remove: (id: string) => void;\n readonly set: (id: string, value: T) => void;\n readonly replace: (value: DocumentTreeValue<T>) => void;\n};\ntype OptionalClear<TNode extends DocumentNode, TWriter> = TNode extends { readonly optional: true }\n ? TWriter & { readonly clear: () => void }\n : TWriter;\nexport type WriterOfNode<TNode extends DocumentNode> = TNode extends {\n kind: 'field';\n}\n ? TNode extends { readonly optional: true }\n ? FieldWriter<DocumentValueOfNode<TNode>, true>\n : FieldWriter<DocumentValueOfNode<TNode>>\n : TNode extends ObjectNode<infer TShape>\n ? { readonly [K in keyof TShape]: WriterOfNode<TShape[K]> }\n : TNode extends VariantNode<string, infer _TVariants>\n ? OptionalClear<TNode, { readonly replace: (value: DocumentValueOfNode<TNode>) => void }>\n : TNode extends TableNode<infer TValue>\n ? CollectionWriter<string, TValue>\n : TNode extends MapNode<infer TValue>\n ? MapWriter<string, TValue>\n : TNode extends DictNode<infer TKey, infer TValue>\n ? OptionalClear<TNode, DictionaryWriter<TKey, TValue>>\n : TNode extends ListNode<infer TItem>\n ? OptionalClear<TNode, ListWriter<TItem>>\n : TNode extends TreeNode<infer TValue>\n ? OptionalClear<TNode, TreeWriter<TValue>>\n : FieldWriter<DocumentValueOfNode<TNode>>;\nexport type DocumentWriter<TSchema extends DocumentSchema> = WriterOfNode<\n ObjectNode<TSchema['shape']>\n>;\n\nexport type OperationSink = (operation: DocumentOperation) => void;\n\nconst schemaRoot = (schema: DocumentSchema): DocumentNode => object(schema.shape);\n\nconst emit = (sink: OperationSink, operation: DocumentOperation): void => sink(operation);\n\nexport const writerFor = (\n node: DocumentNode,\n inputAddress: DocumentAddress,\n sink: OperationSink\n): unknown => {\n const address = Object.freeze(inputAddress);\n if (node.kind === 'field')\n return {\n set: (value: unknown) => emit(sink, { type: 'field.set', at: address, value }),\n clear: node.optional ? () => emit(sink, { type: 'field.clear', at: address }) : undefined,\n };\n if (node.kind === 'dict')\n return {\n set: (key: string, value: unknown) =>\n emit(sink, { type: 'dict.set', at: address, key, value }),\n delete: (key: string) => emit(sink, { type: 'dict.delete', at: address, key }),\n replace: (value: Readonly<Record<string, unknown>>) =>\n emit(sink, { type: 'dict.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'list')\n return {\n insert: (value: unknown, anchor?: DocumentAnchor) =>\n emit(sink, {\n type: 'list.insert',\n at: address,\n key: node.keyOf(value),\n value,\n anchor,\n }),\n move: (key: string, anchor?: DocumentAnchor) =>\n emit(sink, { type: 'list.move', at: address, key, anchor }),\n remove: (key: string) => emit(sink, { type: 'list.remove', at: address, key }),\n replace: (value: readonly unknown[]) =>\n emit(sink, {\n type: 'list.replace',\n at: address,\n value,\n keys: value.map(node.keyOf),\n }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'tree')\n return {\n insert: (\n treeNodeId: string,\n value: unknown,\n position?: { parentId?: string; index?: number }\n ) =>\n emit(sink, {\n type: 'tree.insert',\n at: address,\n treeNodeId,\n value,\n parentId: position?.parentId,\n index: position?.index,\n }),\n move: (treeNodeId: string, position?: { parentId?: string; index?: number }) =>\n emit(sink, {\n type: 'tree.move',\n at: address,\n treeNodeId,\n parentId: position?.parentId,\n index: position?.index,\n }),\n remove: (treeNodeId: string) => emit(sink, { type: 'tree.remove', at: address, treeNodeId }),\n set: (treeNodeId: string, value: unknown) =>\n emit(sink, {\n type: 'tree.set',\n at: address,\n treeNodeId,\n value,\n }),\n replace: (value: unknown) => emit(sink, { type: 'tree.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'table') {\n let items: Map<string, unknown> | undefined;\n return {\n create: (\n input:\n | { readonly id: string; readonly value: unknown }\n | readonly { readonly id: string; readonly value: unknown }[],\n anchor?: DocumentAnchor\n ) => {\n const entries = Array.isArray(input) ? input : [input];\n emit(sink, {\n type: 'entity.create',\n at: address,\n entries: entries.map(({ id, value }) => ({ id, value })),\n anchor,\n });\n },\n item: (id: string) => {\n const cached = items?.get(id);\n if (cached) return cached;\n const writer = writerFor(node.value, [...address, id], sink);\n (items ??= new Map()).set(id, writer);\n return writer;\n },\n remove: (input: string | readonly string[]) =>\n emit(sink, {\n type: 'entity.remove',\n at: address,\n ids: Array.isArray(input) ? [...input] : [input],\n }),\n move: (id: string, anchor?: DocumentAnchor) =>\n emit(sink, { type: 'entity.move', at: address, id, anchor }),\n };\n }\n if (node.kind === 'map') {\n let items: Map<string, unknown> | undefined;\n return {\n create: (\n input:\n | { readonly id: string; readonly value: unknown }\n | readonly { readonly id: string; readonly value: unknown }[]\n ) => {\n const entries = Array.isArray(input) ? input : [input];\n emit(sink, {\n type: 'entity.create',\n at: address,\n entries: entries.map(({ id, value }) => ({ id, value })),\n });\n },\n item: (id: string) => {\n const cached = items?.get(id);\n if (cached) return cached;\n const writer = writerFor(node.value, [...address, id], sink);\n (items ??= new Map()).set(id, writer);\n return writer;\n },\n remove: (input: string | readonly string[]) =>\n emit(sink, {\n type: 'entity.remove',\n at: address,\n ids: Array.isArray(input) ? [...input] : [input],\n }),\n };\n }\n if (node.kind === 'variant')\n return {\n replace: (value: unknown) => emit(sink, { type: 'variant.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n\n let children: Map<string, unknown> | undefined;\n return new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string' || !node.shape[property]) return undefined;\n const cached = children?.get(property);\n if (cached) return cached;\n const writer = writerFor(node.shape[property], [...address, property], sink);\n (children ??= new Map()).set(property, writer);\n return writer;\n },\n }\n );\n};\n\nexport const documentWriter = <TSchema extends DocumentSchema>(\n schema: TSchema,\n sink: OperationSink\n): DocumentWriter<TSchema> => writerFor(schemaRoot(schema), [], sink) as DocumentWriter<TSchema>;\n","import type { DocumentAddress } from '../schema';\nimport type { DocumentOperation } from '../operations';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-operation'\n | 'unknown-operation'\n | 'required-field'\n | 'invalid-anchor'\n | 'duplicate-entity'\n | 'missing-entity'\n | 'invalid-collection'\n | 'invalid-list-keys'\n | 'invalid-list-key'\n | 'duplicate-list-item'\n | 'missing-list-item'\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\n\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n readonly operation?: DocumentOperation['type'];\n};\n\nconst ownAddress = (address: DocumentAddress): DocumentAddress => Object.freeze(address.slice());\n\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string,\n operation?: DocumentOperation['type']\n): MutationIssue =>\n Object.freeze({\n source: 'mutation',\n code,\n address: ownAddress(address),\n message,\n ...(operation === undefined ? {} : { operation }),\n });\n\nexport const from = (\n operation: DocumentOperation,\n code: MutationIssueCode,\n message: string\n): MutationIssue => at(operation.at, code, message, operation.type);\n\nexport const input = (code: MutationIssueCode, message: string): MutationIssue =>\n at([], code, message);\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation, EntityCreateOperation } from '../operations';\nimport type { DocumentNode } from '../schema';\nimport type { MutationOutcome } from './contract';\nimport * as anchor from './anchor';\nimport type { MutationIssueCode } from './issue';\nimport * as issue from './issue';\nimport { cloneValue, isRecord, transferPayload } from '../value/ownership';\n\ntype EntityOperation = Extract<\n DocumentOperation,\n { type: 'entity.create' | 'entity.remove' | 'entity.move' }\n>;\n\ntype EntityNode = Extract<DocumentNode, { readonly kind: 'table' | 'map' }>;\n\nexport type EntityCollection =\n | {\n readonly kind: 'table';\n readonly ids: string[];\n readonly byId: Record<string, unknown>;\n }\n | {\n readonly kind: 'map';\n readonly byId: Record<string, unknown>;\n };\n\nexport type EntityCollectionResolution =\n | { readonly status: 'resolved'; readonly collection: EntityCollection }\n | { readonly status: 'invalid' };\n\nexport const resolveEntityCollection = (\n node: EntityNode,\n value: unknown\n): EntityCollectionResolution => {\n if (node.kind === 'table') {\n if (!isRecord(value) || !Array.isArray(value.ids) || !isRecord(value.byId))\n return { status: 'invalid' };\n // Table ids are canonical schema data. Validating every existing id for\n // each operation would turn a constant-address mutation into a full\n // collection scan; operation semantics validate the ids they touch.\n const ids = value.ids as string[];\n return {\n status: 'resolved',\n collection: { kind: 'table', ids, byId: value.byId },\n };\n }\n return isRecord(value)\n ? { status: 'resolved', collection: { kind: 'map', byId: value } }\n : { status: 'invalid' };\n};\n\nconst rejected = (\n operation: EntityOperation,\n code: MutationIssueCode,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeEntity = (\n target: ResolvedAddress,\n operation: EntityOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'table' && target.node.kind !== 'map')\n return rejected(operation, 'invalid-address', 'Collection target is invalid.');\n const resolution = resolveEntityCollection(target.node, target.value);\n if (resolution.status === 'invalid')\n return rejected(operation, 'invalid-address', 'Collection target is invalid.');\n const collection = resolution.collection;\n const ids = collection.kind === 'table' ? collection.ids : undefined;\n if (operation.type === 'entity.move' && collection.kind === 'map')\n return rejected(operation, 'invalid-operation', 'Map entries are unordered.');\n const byId = collection.byId;\n\n if (operation.type === 'entity.create') {\n if (operation.entries.length === 0) return { status: 'unchanged' };\n const seen = new Set<string>();\n for (const entry of operation.entries) {\n if (seen.has(entry.id))\n return rejected(operation, 'duplicate-entity', 'Entity ids must be unique within a batch.');\n seen.add(entry.id);\n if (Object.prototype.hasOwnProperty.call(byId, entry.id))\n return rejected(operation, 'duplicate-entity', `Entity '${entry.id}' already exists.`);\n }\n if (collection.kind === 'map' && (operation.anchor || operation.positions))\n return rejected(operation, 'invalid-anchor', 'Map entries do not support ordering metadata.');\n if (ids && operation.positions) {\n if (\n operation.positions.length !== operation.entries.length ||\n !anchor.validPositions(ids.length, operation.positions)\n )\n return rejected(operation, 'invalid-operation', 'Entity restore positions are invalid.');\n } else if (ids && !anchor.valid(ids, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'Collection anchor is invalid.');\n\n for (const entry of operation.entries)\n byId[entry.id] = copyPayload\n ? cloneValue(entry.value, 'canonical')\n : transferPayload(entry.value);\n if (ids) {\n if (operation.positions) {\n anchor.restore(\n ids,\n operation.entries.map(entry => entry.id),\n operation.positions\n );\n } else {\n if (!operation.anchor || ('at' in operation.anchor && operation.anchor.at === 'end')) {\n for (const entry of operation.entries) ids.push(entry.id);\n } else {\n const insertion = anchor.index(ids, operation.anchor);\n const currentLength = ids.length;\n ids.length = currentLength + operation.entries.length;\n for (let index = currentLength - 1; index >= insertion; index -= 1)\n ids[index + operation.entries.length] = ids[index];\n for (let index = 0; index < operation.entries.length; index += 1)\n ids[insertion + index] = operation.entries[index].id;\n }\n }\n }\n return {\n status: 'changed',\n inverse: [\n {\n type: 'entity.remove',\n at: operation.at,\n ids: operation.entries.map(entry => entry.id),\n },\n ],\n };\n }\n\n if (operation.type === 'entity.remove') {\n if (operation.ids.length === 0) return { status: 'unchanged' };\n const seen = new Set<string>();\n for (const id of operation.ids) {\n if (seen.has(id))\n return rejected(operation, 'duplicate-entity', 'Entity ids must be unique within a batch.');\n seen.add(id);\n if (!Object.prototype.hasOwnProperty.call(byId, id))\n return rejected(operation, 'missing-entity', `Entity '${id}' does not exist.`);\n }\n\n const entries: { id: string; value: unknown }[] = [];\n const positions: number[] = [];\n if (ids) {\n const positionsById = new Map<string, number>();\n for (let index = 0; index < ids.length; index += 1) {\n const id = ids[index];\n if (seen.has(id)) positionsById.set(id, index);\n }\n for (const id of operation.ids)\n if (!positionsById.has(id))\n return rejected(operation, 'invalid-collection', `Collection index is missing '${id}'.`);\n\n let writeIndex = 0;\n for (let index = 0; index < ids.length; index += 1) {\n const id = ids[index];\n if (seen.has(id)) {\n entries.push({ id, value: cloneValue(byId[id], 'inverse') });\n positions.push(index);\n delete byId[id];\n } else {\n ids[writeIndex++] = id;\n }\n }\n ids.length = writeIndex;\n } else {\n for (const id of operation.ids) {\n entries.push({ id, value: cloneValue(byId[id], 'inverse') });\n delete byId[id];\n }\n }\n const inverse: EntityCreateOperation = {\n type: 'entity.create',\n at: operation.at,\n entries,\n ...(ids ? { positions } : {}),\n };\n return { status: 'changed', inverse: [inverse] };\n }\n\n const exists = Object.prototype.hasOwnProperty.call(byId, operation.id);\n const position = ids?.indexOf(operation.id) ?? -1;\n if (!exists)\n return rejected(operation, 'missing-entity', `Entity '${operation.id}' does not exist.`);\n if (!ids || position < 0)\n return rejected(\n operation,\n 'invalid-collection',\n `Collection index is missing '${operation.id}'.`\n );\n if (!anchor.valid(ids, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'Collection anchor is invalid.');\n if (\n operation.anchor &&\n (('before' in operation.anchor && operation.anchor.before === operation.id) ||\n ('after' in operation.anchor && operation.anchor.after === operation.id))\n )\n return rejected(operation, 'invalid-anchor', 'An entity cannot be moved relative to itself.');\n const nextIndex = anchor.afterRemove(ids, position, operation.anchor);\n if (nextIndex === position) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'entity.move',\n at: operation.at,\n id: operation.id,\n anchor: anchor.at(ids, position),\n };\n ids.splice(position, 1);\n ids.splice(nextIndex, 0, operation.id);\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as anchor from './anchor';\nimport type { MutationIssueCode } from './issue';\nimport * as issue from './issue';\nimport { cloneValue, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype ListOperation = Extract<\n DocumentOperation,\n { type: 'list.insert' | 'list.move' | 'list.remove' | 'list.replace' }\n>;\n\nconst rejected = (\n operation: ListOperation,\n code: MutationIssueCode,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeList = (\n target: ResolvedAddress,\n operation: ListOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'list')\n return rejected(operation, 'invalid-address', 'List target is invalid.');\n const absent =\n target.value === undefined && 'optional' in target.node && target.node.optional === true;\n if (!Array.isArray(target.value) && !absent)\n return rejected(operation, 'invalid-address', 'List target is invalid.');\n if (absent && operation.type !== 'list.replace')\n return rejected(\n operation,\n 'invalid-address',\n 'Only list replacement can initialize an optional list.'\n );\n const list = (Array.isArray(target.value) ? target.value : []) as unknown[];\n const orderedKeys = anchor.keys(list, target.node.keyOf);\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n\n if (operation.type === 'list.replace') {\n if (operation.keys.length !== operation.value.length)\n return rejected(operation, 'invalid-list-keys', 'List replacement keys are invalid.');\n const seen = new Set<string>();\n for (let index = 0; index < operation.value.length; index += 1) {\n const key = operation.keys[index];\n if (seen.has(key) || target.node.keyOf(operation.value[index]) !== key)\n return rejected(operation, 'invalid-list-keys', 'List replacement keys are invalid.');\n seen.add(key);\n }\n if (!absent && sameStructuralValue(list, operation.value)) return { status: 'unchanged' };\n const keys = list.map(target.node.keyOf);\n const inverse: DocumentOperation = absent\n ? { type: 'value.clear', at: operation.at }\n : {\n type: 'list.replace',\n at: operation.at,\n value: cloneValue(list, 'inverse'),\n keys,\n };\n const owned = own(operation.value) as unknown[];\n if (absent) (target.parent as Record<string | number, unknown>)[target.key] = owned;\n else {\n list.length = owned.length;\n for (let index = 0; index < owned.length; index += 1) list[index] = owned[index];\n }\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'list.insert') {\n if (target.node.keyOf(operation.value) !== operation.key)\n return rejected(operation, 'invalid-list-key', 'List item key does not match schema.');\n if (orderedKeys.index(operation.key) >= 0)\n return rejected(\n operation,\n 'duplicate-list-item',\n `List item '${operation.key}' already exists.`\n );\n if (!anchor.valid(orderedKeys, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'List anchor is invalid.');\n list.splice(anchor.index(orderedKeys, operation.anchor), 0, own(operation.value));\n return {\n status: 'changed',\n inverse: [{ type: 'list.remove', at: operation.at, key: operation.key }],\n };\n }\n\n const position = orderedKeys.index(operation.key);\n if (position < 0)\n return rejected(operation, 'missing-list-item', `List item '${operation.key}' does not exist.`);\n if (operation.type === 'list.remove') {\n const inverse: DocumentOperation = {\n type: 'list.insert',\n at: operation.at,\n key: operation.key,\n value: cloneValue(list[position], 'inverse'),\n anchor: anchor.at(orderedKeys, position),\n };\n list.splice(position, 1);\n return { status: 'changed', inverse: [inverse] };\n }\n if (!anchor.valid(orderedKeys, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'List anchor is invalid.');\n if (\n operation.anchor &&\n (('before' in operation.anchor && operation.anchor.before === operation.key) ||\n ('after' in operation.anchor && operation.anchor.after === operation.key))\n )\n return rejected(operation, 'invalid-anchor', 'A list item cannot be moved relative to itself.');\n const nextIndex = anchor.afterRemove(orderedKeys, position, operation.anchor);\n if (nextIndex === position) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'list.move',\n at: operation.at,\n key: operation.key,\n anchor: anchor.at(orderedKeys, position),\n };\n const [entry] = list.splice(position, 1);\n list.splice(nextIndex, 0, entry);\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { DocumentAddress, DocumentNode, DocumentSchema } from '../schema';\nimport type { DocumentOperation } from '../operations';\nimport { cloneValue, isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype TreeOperation = Extract<\n DocumentOperation,\n {\n type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n>;\n\ntype MutableTreeNode = {\n parentId?: string;\n children: string[];\n value?: unknown;\n};\n\nexport type MutableTree = {\n rootId?: string;\n nodes: Record<string, MutableTreeNode>;\n};\n\nexport type TreeOutcome =\n | {\n readonly status: 'changed';\n readonly inverse: readonly DocumentOperation[];\n }\n | { readonly status: 'unchanged' }\n | {\n readonly status: 'rejected';\n readonly code:\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\n readonly message: string;\n };\n\ntype TreeNodePresence =\n | { readonly status: 'absent' }\n | {\n readonly status: 'present';\n readonly parentId?: string;\n readonly children: readonly string[];\n readonly value: unknown;\n };\n\ntype TreeRootPresence =\n { readonly status: 'absent' } | { readonly status: 'present'; readonly id: string };\n\nexport type TreeChange =\n | {\n readonly mode: 'incremental';\n readonly root: TreeRootPresence;\n readonly nodes: Map<string, TreeNodePresence>;\n }\n | { readonly mode: 'whole'; readonly value: unknown };\n\nconst has = (value: object, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\nconst validIndex = (index: number | undefined): boolean =>\n index === undefined || (Number.isInteger(index) && index >= 0);\nconst rejected = (\n code: Extract<TreeOutcome, { status: 'rejected' }>['code'],\n message: string\n): TreeOutcome => ({ status: 'rejected', code, message });\n\nconst node = (tree: MutableTree, id: string): MutableTreeNode | undefined => tree.nodes[id];\nconst childIndex = (parent: MutableTreeNode, id: string): number => parent.children.indexOf(id);\nconst sameOrder = (left: readonly string[], right: readonly string[]): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst rootPresence = (id: string | undefined): TreeRootPresence =>\n id === undefined ? { status: 'absent' } : { status: 'present', id };\n\nconst capture = (\n change: Extract<TreeChange, { readonly mode: 'incremental' }>,\n id: string,\n presence: TreeNodePresence\n): void => {\n if (!change.nodes.has(id)) change.nodes.set(id, presence);\n};\n\nconst without = (values: readonly string[], id: string): string[] => {\n const result: string[] = [];\n for (const value of values) if (value !== id) result.push(value);\n return result;\n};\n\nconst inserted = (values: readonly string[], id: string, index: number): string[] => {\n const result = [...values];\n result.splice(Math.min(index, result.length), 0, id);\n return result;\n};\n\nconst moved = (values: readonly string[], id: string, index: number): string[] => {\n const result = without(values, id);\n result.splice(Math.min(index, result.length), 0, id);\n return result;\n};\n\nconst parentPresence = (\n tree: MutableTree,\n id: string,\n children: readonly string[]\n): TreeNodePresence => {\n const entry = node(tree, id);\n return entry\n ? {\n status: 'present',\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n children,\n value: entry.value,\n }\n : { status: 'absent' };\n};\n\nconst restoreIncremental = (\n value: unknown,\n change: Extract<TreeChange, { readonly mode: 'incremental' }>\n): unknown => {\n if (!is(value)) return value;\n if (change.root.status === 'absent') delete value.rootId;\n else value.rootId = change.root.id;\n for (const [id, before] of change.nodes) {\n if (before.status === 'absent') {\n delete value.nodes[id];\n continue;\n }\n value.nodes[id] = {\n ...(before.parentId === undefined ? {} : { parentId: before.parentId }),\n children: [...before.children],\n value: before.value,\n };\n }\n return value;\n};\n\nexport const restoreChange = (value: unknown, change: TreeChange): unknown =>\n change.mode === 'whole' ? ownPayload(change.value, 'journal') : restoreIncremental(value, change);\n\nconst wholeChange = (\n inverse: Extract<TreeOperation, { readonly type: 'tree.replace' }>,\n previous?: TreeChange\n): TreeChange => {\n if (!previous) return { mode: 'whole', value: inverse.value };\n if (previous.mode === 'whole') return previous;\n return {\n mode: 'whole',\n value: restoreIncremental(ownPayload(inverse.value, 'journal'), previous),\n };\n};\n\nconst removedNodePresences = (\n inverses: readonly Extract<TreeOperation, { readonly type: 'tree.insert' }>[]\n): Map<string, TreeNodePresence> => {\n const children = new Map<string, Array<{ readonly id: string; readonly index: number }>>();\n for (const inverse of inverses) {\n if (inverse.parentId === undefined) continue;\n const entries = children.get(inverse.parentId);\n const child = { id: inverse.treeNodeId, index: inverse.index ?? Number.MAX_SAFE_INTEGER };\n if (entries) entries.push(child);\n else children.set(inverse.parentId, [child]);\n }\n const result = new Map<string, TreeNodePresence>();\n for (const inverse of inverses) {\n const ordered = children.get(inverse.treeNodeId) ?? [];\n ordered.sort((left, right) => left.index - right.index);\n result.set(inverse.treeNodeId, {\n status: 'present',\n ...(inverse.parentId === undefined ? {} : { parentId: inverse.parentId }),\n children: ordered.map(entry => entry.id),\n value: inverse.value,\n });\n }\n return result;\n};\n\nexport const recordChange = (\n previous: TreeChange | undefined,\n current: MutableTree,\n forward: TreeOperation,\n inverses: readonly TreeOperation[]\n): TreeChange => {\n const replacement = inverses[0];\n if (replacement?.type === 'tree.replace') return wholeChange(replacement, previous);\n if (previous?.mode === 'whole') return previous;\n\n const change: Extract<TreeChange, { readonly mode: 'incremental' }> = previous ?? {\n mode: 'incremental',\n root:\n forward.type === 'tree.insert' && forward.parentId === undefined\n ? { status: 'absent' }\n : forward.type === 'tree.remove' && inverses[0]?.type === 'tree.insert'\n ? rootPresence(\n inverses[0].parentId === undefined ? inverses[0].treeNodeId : current.rootId\n )\n : rootPresence(current.rootId),\n nodes: new Map(),\n };\n\n if (forward.type === 'tree.insert') {\n capture(change, forward.treeNodeId, { status: 'absent' });\n if (forward.parentId !== undefined) {\n const parentNode = node(current, forward.parentId);\n if (parentNode)\n capture(\n change,\n forward.parentId,\n parentPresence(\n current,\n forward.parentId,\n without(parentNode.children, forward.treeNodeId)\n )\n );\n }\n return change;\n }\n\n if (forward.type === 'tree.remove') {\n const inserts = inverses.filter(\n (inverse): inverse is Extract<TreeOperation, { readonly type: 'tree.insert' }> =>\n inverse.type === 'tree.insert'\n );\n const removed = removedNodePresences(inserts);\n for (const [id, presence] of removed) capture(change, id, presence);\n const first = inserts[0];\n if (first?.parentId !== undefined) {\n const parentNode = node(current, first.parentId);\n if (parentNode)\n capture(\n change,\n first.parentId,\n parentPresence(\n current,\n first.parentId,\n inserted(\n parentNode.children,\n first.treeNodeId,\n first.index ?? parentNode.children.length\n )\n )\n );\n }\n return change;\n }\n\n if (forward.type === 'tree.set') {\n const inverse = inverses[0];\n const entry = node(current, forward.treeNodeId);\n if (entry && inverse?.type === 'tree.set')\n capture(change, forward.treeNodeId, {\n status: 'present',\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n children: [...entry.children],\n value: inverse.value,\n });\n return change;\n }\n\n if (forward.type === 'tree.move') {\n const inverse = inverses[0];\n const entry = node(current, forward.treeNodeId);\n if (!entry || inverse?.type !== 'tree.move' || inverse.parentId === undefined) return change;\n capture(change, forward.treeNodeId, {\n status: 'present',\n parentId: inverse.parentId,\n children: [...entry.children],\n value: entry.value,\n });\n const oldParent = node(current, inverse.parentId);\n if (oldParent) {\n const children =\n inverse.parentId === forward.parentId\n ? moved(\n oldParent.children,\n forward.treeNodeId,\n inverse.index ?? oldParent.children.length\n )\n : inserted(\n oldParent.children,\n forward.treeNodeId,\n inverse.index ?? oldParent.children.length\n );\n capture(change, inverse.parentId, parentPresence(current, inverse.parentId, children));\n }\n if (forward.parentId !== undefined && forward.parentId !== inverse.parentId) {\n const nextParent = node(current, forward.parentId);\n if (nextParent)\n capture(\n change,\n forward.parentId,\n parentPresence(\n current,\n forward.parentId,\n without(nextParent.children, forward.treeNodeId)\n )\n );\n }\n }\n return change;\n};\n\nconst sameNodePresence = (\n before: TreeNodePresence,\n value: MutableTreeNode | undefined\n): boolean => {\n if (before.status === 'absent') return value === undefined;\n return (\n value !== undefined &&\n before.parentId === value.parentId &&\n sameOrder(before.children, value.children) &&\n sameStructuralValue(before.value, value.value)\n );\n};\n\nexport const changeChanged = (change: TreeChange, value: unknown): boolean => {\n if (change.mode === 'whole') return !sameStructuralValue(change.value, value);\n if (!is(value)) return true;\n const rootId = change.root.status === 'present' ? change.root.id : undefined;\n if (rootId !== value.rootId) return true;\n for (const [id, before] of change.nodes)\n if (!sameNodePresence(before, node(value, id))) return true;\n return false;\n};\n\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const contains = (tree: MutableTree, id: string): boolean => has(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !has(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!isRecord(entry) || !Array.isArray(entry.children)) return false;\n if (\n entry.children.some(child => typeof child !== 'string') ||\n new Set(entry.children).size !== entry.children.length\n )\n return false;\n if (entry.parentId !== undefined && typeof entry.parentId !== 'string') return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !has(value.nodes, entry.parentId)) return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nconst documentTreeError = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress\n): DocumentAddress | undefined => {\n if ('optional' in node && node.optional && value === undefined) return undefined;\n if (node.kind === 'tree') return validate(value) ? undefined : address;\n if (node.kind === 'object') {\n if (!isRecord(value)) return undefined;\n for (const [key, child] of Object.entries(node.shape)) {\n const error = documentTreeError(child, value[key], [...address, key]);\n if (error) return error;\n }\n return undefined;\n }\n if (node.kind === 'variant') {\n if (!isRecord(value) || typeof value[node.tag] !== 'string') return undefined;\n const variant = node.variants[value[node.tag] as keyof typeof node.variants];\n return variant ? documentTreeError(variant, value, address) : undefined;\n }\n if (node.kind === 'table') {\n if (!isRecord(value) || !isRecord(value.byId)) return undefined;\n for (const [id, entry] of Object.entries(value.byId)) {\n const error = documentTreeError(node.value, entry, [...address, id]);\n if (error) return error;\n }\n return undefined;\n }\n if (node.kind === 'map') {\n if (!isRecord(value)) return undefined;\n for (const [id, entry] of Object.entries(value)) {\n const error = documentTreeError(node.value, entry, [...address, id]);\n if (error) return error;\n }\n }\n return undefined;\n};\n\nexport const invalidDocument = (\n schema: DocumentSchema,\n value: unknown\n): DocumentAddress | undefined =>\n documentTreeError({ kind: 'object', shape: schema.shape }, value, []);\n\nexport const replace = (\n current: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.replace' }>\n): TreeOutcome => {\n if (!validate(operation.value)) return rejected('invalid-tree', 'Tree replacement is malformed.');\n if (sameStructuralValue(current, operation.value)) return { status: 'unchanged' };\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.replace',\n at: operation.at,\n value: cloneValue(current, 'inverse'),\n },\n ],\n };\n};\n\nexport const insert = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.insert' }>,\n value: unknown\n): TreeOutcome => {\n if (contains(tree, operation.treeNodeId))\n return rejected('duplicate-tree-node', `Tree node '${operation.treeNodeId}' already exists.`);\n if (!validIndex(operation.index)) return rejected('invalid-tree-index', 'Tree index is invalid.');\n\n if (tree.rootId === undefined) {\n if (operation.parentId !== undefined)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n tree.nodes[operation.treeNodeId] = { children: [], value };\n tree.rootId = operation.treeNodeId;\n } else {\n if (operation.parentId === undefined)\n return rejected('invalid-tree', 'A non-empty tree has exactly one root.');\n const parentNode = node(tree, operation.parentId);\n if (!parentNode)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n tree.nodes[operation.treeNodeId] = {\n parentId: operation.parentId,\n children: [],\n value,\n };\n parentNode.children.splice(\n Math.min(operation.index ?? parentNode.children.length, parentNode.children.length),\n 0,\n operation.treeNodeId\n );\n }\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.remove',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n },\n ],\n };\n};\n\nexport const set = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.set' }>,\n value: unknown\n): TreeOutcome => {\n const entry = node(tree, operation.treeNodeId);\n if (!entry)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n if (Object.is(entry.value, value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'tree.set',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n value: cloneValue(entry.value, 'inverse'),\n };\n entry.value = value;\n return { status: 'changed', inverse: [inverse] };\n};\n\nexport const remove = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.remove' }>\n): TreeOutcome => {\n const first = node(tree, operation.treeNodeId);\n if (!first)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n const parentId = first.parentId;\n const parentNode = parentId === undefined ? undefined : node(tree, parentId);\n const originalIndex = parentNode ? childIndex(parentNode, operation.treeNodeId) : 0;\n if (\n (parentId !== undefined && (!parentNode || originalIndex < 0)) ||\n (parentId === undefined && tree.rootId !== operation.treeNodeId)\n )\n return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n\n const entries: Array<{\n readonly id: string;\n readonly parentId?: string;\n readonly index: number;\n readonly value: unknown;\n }> = [];\n const seen = new Set<string>();\n const stack: Array<{\n readonly id: string;\n readonly parentId?: string;\n readonly index: number;\n }> = [{ id: operation.treeNodeId, parentId, index: originalIndex }];\n while (stack.length) {\n const frame = stack.pop() as (typeof stack)[number];\n const entry = node(tree, frame.id);\n if (!entry || seen.has(frame.id) || entry.parentId !== frame.parentId)\n return rejected('invalid-tree', 'Tree contains an invalid descendant.');\n seen.add(frame.id);\n entries.push({\n id: frame.id,\n parentId: frame.parentId,\n index: frame.index,\n value: cloneValue(entry.value, 'inverse'),\n });\n for (let index = entry.children.length - 1; index >= 0; index -= 1) {\n const childId = entry.children[index];\n const child = node(tree, childId);\n if (!child || child.parentId !== frame.id)\n return rejected('invalid-tree', 'Tree child links are inconsistent.');\n stack.push({ id: childId, parentId: frame.id, index });\n }\n }\n\n if (parentNode) parentNode.children.splice(originalIndex, 1);\n for (let index = entries.length - 1; index >= 0; index -= 1) delete tree.nodes[entries[index].id];\n if (tree.rootId === operation.treeNodeId) delete tree.rootId;\n return {\n status: 'changed',\n inverse: entries.map(entry => ({\n type: 'tree.insert' as const,\n at: operation.at,\n treeNodeId: entry.id,\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n index: entry.index,\n value: entry.value,\n })),\n };\n};\n\nexport const move = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.move' }>\n): TreeOutcome => {\n const entry = node(tree, operation.treeNodeId);\n if (!entry)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n if (!validIndex(operation.index)) return rejected('invalid-tree-index', 'Tree index is invalid.');\n if (tree.rootId === operation.treeNodeId)\n return rejected('invalid-tree', 'The root cannot be moved.');\n if (operation.parentId === undefined) {\n return rejected('invalid-tree', 'Only the root can have no parent.');\n }\n const nextParent = node(tree, operation.parentId);\n if (!nextParent)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n if (operation.parentId === operation.treeNodeId)\n return rejected('tree-cycle', 'A tree node cannot parent itself.');\n\n const descendants = [operation.treeNodeId];\n const seen = new Set<string>();\n while (descendants.length) {\n const id = descendants.pop() as string;\n if (seen.has(id)) return rejected('invalid-tree', 'Tree contains a cycle.');\n seen.add(id);\n const current = node(tree, id);\n if (!current) return rejected('invalid-tree', 'Tree contains a missing node.');\n for (const childId of current.children) {\n const child = node(tree, childId);\n if (!child || child.parentId !== id)\n return rejected('invalid-tree', 'Tree child links are inconsistent.');\n if (childId === operation.parentId)\n return rejected('tree-cycle', 'Tree move would create a cycle.');\n descendants.push(childId);\n }\n }\n\n const parentId = entry.parentId;\n const currentParent = parentId === undefined ? undefined : node(tree, parentId);\n if (!currentParent || parentId === undefined)\n return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n const originalIndex = childIndex(currentParent, operation.treeNodeId);\n if (originalIndex < 0) return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n currentParent.children.splice(originalIndex, 1);\n const nextIndex = Math.min(\n operation.index ?? nextParent.children.length,\n nextParent.children.length\n );\n if (parentId === operation.parentId && nextIndex === originalIndex) {\n currentParent.children.splice(originalIndex, 0, operation.treeNodeId);\n return { status: 'unchanged' };\n }\n nextParent.children.splice(nextIndex, 0, operation.treeNodeId);\n entry.parentId = operation.parentId;\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.move',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n parentId,\n index: originalIndex,\n },\n ],\n };\n};\n","import { set as setAddress } from '../address';\nimport type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport * as tree from './tree';\nimport { ownPayload } from '../value/ownership';\n\ntype TreeOperation = Extract<\n DocumentOperation,\n {\n type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n>;\n\nconst outcome = (operation: TreeOperation, value: tree.TreeOutcome): MutationOutcome =>\n value.status === 'rejected'\n ? {\n status: 'rejected',\n issue: issue.from(operation, value.code, value.message),\n }\n : value;\n\nexport const executeTree = (\n root: unknown,\n target: ResolvedAddress,\n operation: TreeOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'tree')\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n const absent =\n target.value === undefined && 'optional' in target.node && target.node.optional === true;\n if (operation.type === 'tree.replace') {\n if (absent) {\n if (!tree.validate(operation.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-tree', 'Tree replacement is malformed.'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [{ type: 'value.clear', at: operation.at }] };\n }\n if (!tree.is(target.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n const result = tree.replace(target.value, operation);\n if (result.status === 'changed') setAddress(root, operation.at, ownPayload(operation.value));\n return outcome(operation, result);\n }\n if (!tree.is(target.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n if (operation.type === 'tree.insert')\n return outcome(operation, tree.insert(target.value, operation, own(operation.value)));\n if (operation.type === 'tree.set')\n return outcome(operation, tree.set(target.value, operation, own(operation.value)));\n if (operation.type === 'tree.remove')\n return outcome(operation, tree.remove(target.value, operation));\n return outcome(operation, tree.move(target.value, operation));\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport { cloneValue, isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype ValueOperation = Extract<\n DocumentOperation,\n {\n type:\n 'field.set' | 'field.clear' | 'variant.replace' | 'dict.set' | 'dict.delete' | 'dict.replace';\n }\n>;\n\nconst rejected = (\n operation: ValueOperation,\n code: Extract<import('./issue').MutationIssueCode, 'invalid-address' | 'required-field'>,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeValue = (\n target: ResolvedAddress,\n operation: ValueOperation,\n copyPayload: boolean\n): MutationOutcome => {\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n\n if (operation.type === 'field.set' || operation.type === 'field.clear') {\n const existed = Object.prototype.hasOwnProperty.call(target.parent, target.key);\n if (operation.type === 'field.clear') {\n if (target.node.kind !== 'field' || !target.node.optional)\n return rejected(operation, 'required-field', 'Only optional fields can be cleared.');\n if (!existed) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'field.set',\n at: operation.at,\n value: target.value,\n };\n delete (target.parent as Record<string | number, unknown>)[target.key];\n return { status: 'changed', inverse: [inverse] };\n }\n if (existed && Object.is(target.value, operation.value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = existed\n ? { type: 'field.set', at: operation.at, value: target.value }\n : { type: 'field.clear', at: operation.at };\n (target.parent as Record<string | number, unknown>)[target.key] = operation.value;\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'variant.replace') {\n if (sameStructuralValue(target.value, operation.value)) return { status: 'unchanged' };\n if (target.value === undefined && target.node.optional) {\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [{ type: 'value.clear', at: operation.at }] };\n }\n const inverse: DocumentOperation = {\n type: 'variant.replace',\n at: operation.at,\n value: ownPayload(target.value, 'inverse'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'dict.replace' && target.value === undefined) {\n if (!('optional' in target.node) || !target.node.optional)\n return rejected(operation, 'invalid-address', 'Dictionary target is invalid.');\n const inverse: DocumentOperation = { type: 'value.clear', at: operation.at };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n if (!isRecord(target.value))\n return rejected(operation, 'invalid-address', 'Dictionary target is invalid.');\n if (operation.type === 'dict.replace') {\n if (sameStructuralValue(target.value, operation.value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'dict.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n const existed = Object.prototype.hasOwnProperty.call(target.value, operation.key);\n if (operation.type === 'dict.delete') {\n if (!existed) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'dict.set',\n at: operation.at,\n key: operation.key,\n value: target.value[operation.key],\n };\n delete target.value[operation.key];\n return { status: 'changed', inverse: [inverse] };\n }\n if (existed && Object.is(target.value[operation.key], operation.value))\n return { status: 'unchanged' };\n const inverse: DocumentOperation = existed\n ? {\n type: 'dict.set',\n at: operation.at,\n key: operation.key,\n value: target.value[operation.key],\n }\n : { type: 'dict.delete', at: operation.at, key: operation.key };\n target.value[operation.key] = operation.value;\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport { executeEntity } from './execute-entity';\nimport { executeList } from './execute-list';\nimport { executeTree } from './execute-tree';\nimport { executeValue } from './execute-value';\nimport { cloneValue } from '../value/ownership';\n\nconst hasOwn = (value: object, key: string | number): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst executeClear = (\n target: ResolvedAddress,\n operation: Extract<DocumentOperation, { type: 'value.clear' }>\n): MutationOutcome => {\n if (!('optional' in target.node) || !target.node.optional)\n return {\n status: 'rejected',\n issue: issue.from(operation, 'required-field', 'Only optional values can be cleared.'),\n };\n if (!hasOwn(target.parent, target.key)) return { status: 'unchanged' };\n if (\n target.node.kind !== 'field' &&\n target.node.kind !== 'variant' &&\n target.node.kind !== 'dict' &&\n target.node.kind !== 'list' &&\n target.node.kind !== 'tree'\n )\n return {\n status: 'rejected',\n issue: issue.from(\n operation,\n 'invalid-operation',\n 'This optional value has no clear operation.'\n ),\n };\n\n const inverse: DocumentOperation = (() => {\n switch (target.node.kind) {\n case 'field':\n return { type: 'field.set', at: operation.at, value: target.value };\n case 'variant':\n return {\n type: 'variant.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n case 'dict':\n return {\n type: 'dict.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse') as Record<string, unknown>,\n };\n case 'list': {\n if (!Array.isArray(target.value))\n return { type: 'list.replace', at: operation.at, value: [], keys: [] };\n return {\n type: 'list.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n keys: target.value.map(target.node.keyOf),\n };\n }\n case 'tree':\n return {\n type: 'tree.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n }\n })();\n delete (target.parent as Record<string | number, unknown>)[target.key];\n return { status: 'changed', inverse: [inverse] };\n};\n\nconst invalidTarget = (operation: DocumentOperation): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(\n operation,\n 'invalid-address',\n `Operation '${operation.type}' does not match the schema address.`\n ),\n});\n\n// Operations reach this dispatcher only after operation.decode and\n// operation.normalize. Executors therefore only validate their domain-specific\n// semantics against one resolved schema address.\nexport const execute = (\n root: unknown,\n operation: DocumentOperation,\n target: ResolvedAddress | undefined,\n copyPayload: boolean\n): MutationOutcome => {\n if (operation.type === 'value.clear')\n return !target ? invalidTarget(operation) : executeClear(target, operation);\n\n if (operation.type === 'field.set' || operation.type === 'field.clear')\n return !target || target.node.kind !== 'field'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (operation.type === 'variant.replace')\n return !target || target.node.kind !== 'variant'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (\n operation.type === 'dict.set' ||\n operation.type === 'dict.delete' ||\n operation.type === 'dict.replace'\n )\n return !target || target.node.kind !== 'dict'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (\n operation.type === 'entity.create' ||\n operation.type === 'entity.remove' ||\n operation.type === 'entity.move'\n )\n return !target || (target.node.kind !== 'table' && target.node.kind !== 'map')\n ? invalidTarget(operation)\n : executeEntity(target, operation, copyPayload);\n\n if (\n operation.type === 'list.insert' ||\n operation.type === 'list.move' ||\n operation.type === 'list.remove' ||\n operation.type === 'list.replace'\n )\n return !target || target.node.kind !== 'list'\n ? invalidTarget(operation)\n : executeList(target, operation, copyPayload);\n\n if (\n operation.type === 'tree.insert' ||\n operation.type === 'tree.move' ||\n operation.type === 'tree.remove' ||\n operation.type === 'tree.set' ||\n operation.type === 'tree.replace'\n )\n return !target || target.node.kind !== 'tree'\n ? invalidTarget(operation)\n : executeTree(root, target, operation, copyPayload);\n\n return {\n status: 'rejected',\n issue: issue.from(operation, 'unknown-operation', 'Unknown document operation.'),\n };\n};\n","import { locate, read } from '../address';\nimport type { ResolvedAddress } from '../address';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\nimport type { DocumentAddress, DocumentNode } from '../schema';\nimport { profile } from '../profile';\nimport { isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\nimport * as anchor from './anchor';\nimport type { MutationCollectionChange } from './contract';\nimport {\n resolveEntityCollection,\n type EntityCollection,\n type EntityCollectionResolution,\n} from './execute-entity';\nimport * as tree from './tree';\n\ntype CollectionContext = NonNullable<ResolvedAddress['collection']>;\ntype ListNode = Extract<DocumentNode, { readonly kind: 'list' }>;\ntype EntityNode = Extract<DocumentNode, { readonly kind: 'table' | 'map' }>;\n\ntype Presence =\n { readonly status: 'absent' } | { readonly status: 'present'; readonly value: unknown };\n\ntype SubjectBase = {\n readonly address: DocumentAddress;\n readonly addressHash: number;\n readonly collection?: CollectionContext;\n};\n\ntype ValueSubject = SubjectBase & {\n readonly kind: 'value';\n readonly before: Presence;\n};\n\ntype VariantSubject = SubjectBase & {\n readonly kind: 'variant';\n readonly before: Presence;\n};\n\ntype DictState =\n | { readonly mode: 'incremental'; readonly entries: Map<string, Presence> }\n | { readonly mode: 'whole'; readonly value: Readonly<Record<string, unknown>> };\n\ntype DictSubject = SubjectBase & {\n readonly kind: 'dict';\n state: DictState;\n};\n\ntype EntityOrderInverse =\n | { readonly kind: 'remove'; readonly ids: readonly string[] }\n | {\n readonly kind: 'restore';\n readonly ids: readonly string[];\n readonly positions: readonly number[];\n }\n | { readonly kind: 'move'; readonly id: string; readonly anchor?: DocumentAnchor };\n\ntype EntityOrder =\n | { readonly kind: 'unordered' }\n | { readonly kind: 'stable'; readonly inverses: EntityOrderInverse[] }\n | { readonly kind: 'tracked'; readonly before: readonly string[] };\n\ntype EntitySubject = SubjectBase & {\n readonly kind: 'entity';\n readonly node: EntityNode;\n readonly entries: Map<string, Presence>;\n order: EntityOrder;\n};\n\ntype ListState =\n | {\n readonly mode: 'incremental';\n readonly items: Map<string, Presence>;\n readonly order: readonly string[];\n }\n | { readonly mode: 'whole'; readonly value: unknown };\n\ntype ListSubject = SubjectBase & {\n readonly kind: 'list';\n readonly node: ListNode;\n state: ListState;\n};\n\ntype TreeSubject = SubjectBase & {\n readonly kind: 'tree';\n state: tree.TreeChange;\n};\n\ntype ChangeSubject =\n ValueSubject | VariantSubject | DictSubject | EntitySubject | ListSubject | TreeSubject;\n\ntype EntityAnalysis = {\n readonly changed: boolean;\n readonly added: ReadonlySet<string>;\n readonly removed: ReadonlySet<string>;\n readonly updated: ReadonlySet<string>;\n readonly orderChanged: boolean;\n};\n\ntype JournalFinish =\n | { readonly status: 'unchanged' }\n | {\n readonly status: 'changed';\n readonly paths: readonly DocumentAddress[];\n readonly collections: readonly MutationCollectionChange[];\n };\n\ntype ChangeJournal = {\n readonly record: (\n resolved: ResolvedAddress,\n operation: DocumentOperation,\n inverse: readonly DocumentOperation[]\n ) => void;\n readonly finish: () => JournalFinish;\n};\n\ntype AddressIndexNode = {\n readonly children: Map<string, AddressIndexNode>;\n subject?: ChangeSubject;\n};\n\nconst indexNode = (): AddressIndexNode => ({ children: new Map() });\nconst hasOwn = (value: object, key: string | number): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst sameAddress = (left: DocumentAddress, right: DocumentAddress): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst sameOrder = (left: readonly string[], right: readonly string[]): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst replaceArray = <T>(target: T[], value: readonly T[]): void => {\n target.length = value.length;\n for (let index = 0; index < value.length; index += 1) target[index] = value[index];\n};\n\nconst present = (value: unknown): Presence => ({ status: 'present', value });\nconst absent: Presence = Object.freeze({ status: 'absent' });\nconst inverseMismatch = (operation: DocumentOperation): never => {\n throw new Error(`Mutation inverse does not match '${operation.type}'.`);\n};\n\nconst ownsDescendant = (subject: ChangeSubject, address: DocumentAddress): boolean => {\n if (subject.address.length >= address.length) return false;\n if (subject.kind === 'variant') return true;\n if (subject.kind !== 'entity') return false;\n return subject.entries.has(address[subject.address.length]);\n};\n\nconst nodeAt = (root: AddressIndexNode, address: DocumentAddress): AddressIndexNode | undefined => {\n let node: AddressIndexNode | undefined = root;\n for (const segment of address) {\n node = node.children.get(segment);\n if (!node) return undefined;\n }\n return node;\n};\n\nconst indexedSubjects = (root: AddressIndexNode, address: DocumentAddress): ChangeSubject[] => {\n const start = nodeAt(root, address);\n if (!start) return [];\n const subjects: ChangeSubject[] = [];\n const stack = [start];\n while (stack.length) {\n const node = stack.pop();\n if (!node) break;\n if (node.subject) subjects.push(node.subject);\n for (const child of node.children.values()) stack.push(child);\n }\n return subjects;\n};\n\nconst writePresence = (root: unknown, address: DocumentAddress, before: Presence): void => {\n const target = locate(root, address);\n if (!target) return;\n if (before.status === 'present')\n (target.parent as Record<string | number, unknown>)[target.key] = before.value;\n else if (Array.isArray(target.parent)) target.parent.splice(Number(target.key), 1);\n else delete target.parent[String(target.key)];\n};\n\nconst writeContainer = (root: unknown, address: DocumentAddress, value: unknown): void => {\n const target = locate(root, address);\n if (!target) return;\n (target.parent as Record<string | number, unknown>)[target.key] = value;\n};\n\nconst restoreDict = (value: Record<string, unknown>, state: DictState): void => {\n if (state.mode === 'whole') {\n for (const key of Object.keys(value)) delete value[key];\n for (const [key, entry] of Object.entries(state.value)) value[key] = entry;\n return;\n }\n for (const [key, before] of state.entries) {\n if (before.status === 'present') value[key] = before.value;\n else delete value[key];\n }\n};\n\nconst restoreList = (value: unknown[], subject: ListSubject): void => {\n if (subject.state.mode === 'whole') {\n replaceArray(value, subject.state.value as readonly unknown[]);\n return;\n }\n const entries = new Map<string, unknown>();\n for (const entry of value) entries.set(subject.node.keyOf(entry), entry);\n for (const [key, before] of subject.state.items) {\n if (before.status === 'present') entries.set(key, before.value);\n else entries.delete(key);\n }\n const restored = new Array<unknown>(subject.state.order.length);\n for (let index = 0; index < subject.state.order.length; index += 1)\n restored[index] = entries.get(subject.state.order[index]);\n replaceArray(value, restored);\n};\n\nconst entityCollection = (subject: EntitySubject, value: unknown): EntityCollectionResolution =>\n resolveEntityCollection(subject.node, value);\n\nconst restoreEntity = (value: unknown, subject: EntitySubject): void => {\n const resolution = entityCollection(subject, value);\n if (resolution.status === 'invalid') return;\n const collection = resolution.collection;\n for (const [id, before] of subject.entries) {\n if (before.status === 'present') collection.byId[id] = before.value;\n else delete collection.byId[id];\n }\n if (collection.kind !== 'table') return;\n if (subject.order.kind === 'tracked') {\n replaceArray(collection.ids, subject.order.before);\n return;\n }\n if (subject.order.kind === 'stable') restoreEntityOrder(collection.ids, subject.order.inverses);\n};\n\nconst restoreRootSubject = (value: unknown, subject: ChangeSubject): unknown => {\n if (subject.kind === 'value')\n return subject.before.status === 'present' ? subject.before.value : undefined;\n if (subject.kind === 'variant')\n return subject.before.status === 'present' ? subject.before.value : undefined;\n if (subject.kind === 'dict') {\n if (isRecord(value)) restoreDict(value, subject.state);\n return value;\n }\n if (subject.kind === 'entity') {\n restoreEntity(value, subject);\n return value;\n }\n if (subject.kind === 'list') {\n if (Array.isArray(value)) restoreList(value, subject);\n return value;\n }\n return tree.restoreChange(value, subject.state);\n};\n\nconst restoreSubject = (\n value: unknown,\n prefix: DocumentAddress,\n subject: ChangeSubject\n): unknown => {\n if (sameAddress(prefix, subject.address)) return restoreRootSubject(value, subject);\n const address = subject.address.slice(prefix.length);\n if (subject.kind === 'value') {\n writePresence(value, address, subject.before);\n return value;\n }\n if (subject.kind === 'variant') {\n writePresence(value, address, subject.before);\n return value;\n }\n const current = read(value, address);\n if (subject.kind === 'dict') {\n if (isRecord(current)) restoreDict(current, subject.state);\n return value;\n }\n if (subject.kind === 'entity') {\n restoreEntity(current, subject);\n return value;\n }\n if (subject.kind === 'list') {\n if (Array.isArray(current)) restoreList(current, subject);\n return value;\n }\n const restored = tree.restoreChange(current, subject.state);\n if (restored !== current) writeContainer(value, address, restored);\n return value;\n};\n\nconst valueChanged = (root: unknown, subject: ValueSubject): boolean => {\n const target = locate(root, subject.address);\n const exists = !!target && hasOwn(target.parent, target.key);\n if (subject.before.status === 'absent') return exists;\n return !exists || !Object.is(subject.before.value, target?.value);\n};\n\nconst dictChanged = (root: unknown, subject: DictSubject): boolean => {\n const value = read(root, subject.address);\n if (!isRecord(value)) return true;\n if (subject.state.mode === 'whole') return !sameStructuralValue(subject.state.value, value);\n for (const [key, before] of subject.state.entries) {\n const exists = hasOwn(value, key);\n if (before.status === 'absent' ? exists : !exists || !Object.is(before.value, value[key]))\n return true;\n }\n return false;\n};\n\nconst listChanged = (root: unknown, subject: ListSubject): boolean => {\n const value = read(root, subject.address);\n if (!Array.isArray(value)) return true;\n if (subject.state.mode === 'whole') return !sameStructuralValue(subject.state.value, value);\n const positions = new Map<string, number>();\n const order = new Array<string>(value.length);\n for (let index = 0; index < value.length; index += 1) {\n const key = subject.node.keyOf(value[index]);\n order[index] = key;\n positions.set(key, index);\n }\n if (!sameOrder(subject.state.order, order)) return true;\n for (const [key, before] of subject.state.items) {\n const position = positions.get(key);\n if (before.status === 'absent') {\n if (position !== undefined) return true;\n } else if (position === undefined || !sameStructuralValue(before.value, value[position]))\n return true;\n }\n return false;\n};\n\nconst commonOrderChanged = (before: readonly string[], after: readonly string[]): boolean => {\n const finalPositions = new Map<string, number>();\n for (let index = 0; index < after.length; index += 1) finalPositions.set(after[index], index);\n let previous = -1;\n for (const id of before) {\n const position = finalPositions.get(id);\n if (position === undefined) continue;\n if (position < previous) return true;\n previous = position;\n }\n return false;\n};\n\nconst analyzeEntity = (root: unknown, subject: EntitySubject): EntityAnalysis => {\n const resolution = entityCollection(subject, read(root, subject.address));\n const added = new Set<string>();\n const removed = new Set<string>();\n const updated = new Set<string>();\n if (resolution.status === 'invalid')\n return { changed: true, added, removed, updated, orderChanged: false };\n const collection = resolution.collection;\n for (const [id, before] of subject.entries) {\n const exists = hasOwn(collection.byId, id);\n if (before.status === 'absent') {\n if (exists) added.add(id);\n } else if (!exists) removed.add(id);\n else if (!sameStructuralValue(before.value, collection.byId[id])) updated.add(id);\n }\n const beforeOrder = subject.order.kind === 'tracked' ? subject.order.before : undefined;\n const finalOrder = collection.kind === 'table' ? collection.ids : [];\n const netOrderChanged = beforeOrder !== undefined && !sameOrder(beforeOrder, finalOrder);\n return {\n changed: added.size > 0 || removed.size > 0 || updated.size > 0 || netOrderChanged,\n added,\n removed,\n updated,\n orderChanged: beforeOrder !== undefined && commonOrderChanged(beforeOrder, finalOrder),\n };\n};\n\nconst subjectChanged = (root: unknown, subject: Exclude<ChangeSubject, EntitySubject>): boolean => {\n if (subject.kind === 'value') return valueChanged(root, subject);\n if (subject.kind === 'variant') {\n const target = locate(root, subject.address);\n const exists = !!target && hasOwn(target.parent, target.key);\n return subject.before.status === 'absent'\n ? exists\n : !exists || !sameStructuralValue(subject.before.value, target?.value);\n }\n if (subject.kind === 'dict') return dictChanged(root, subject);\n if (subject.kind === 'list') return listChanged(root, subject);\n return tree.changeChanged(subject.state, read(root, subject.address));\n};\n\nconst listOrderBefore = (\n value: readonly unknown[],\n node: ListNode,\n inverse: DocumentOperation\n): readonly string[] => {\n const order = value.map(node.keyOf);\n if (inverse.type === 'list.remove') return order.filter(key => key !== inverse.key);\n if (inverse.type === 'list.insert') {\n order.splice(anchor.index(order, inverse.anchor), 0, inverse.key);\n return order;\n }\n if (inverse.type === 'list.move') {\n const position = order.indexOf(inverse.key);\n if (position >= 0) order.splice(position, 1);\n order.splice(anchor.index(order, inverse.anchor), 0, inverse.key);\n }\n return order;\n};\n\nconst recordListPresence = (\n state: Extract<ListState, { readonly mode: 'incremental' }>,\n inverse: DocumentOperation\n): void => {\n if (inverse.type === 'list.remove' && !state.items.has(inverse.key))\n state.items.set(inverse.key, absent);\n else if (inverse.type === 'list.insert' && !state.items.has(inverse.key))\n state.items.set(inverse.key, present(inverse.value));\n};\n\nconst entityOrderInverse = (\n operation: DocumentOperation,\n inverse: DocumentOperation\n): EntityOrderInverse => {\n if (inverse.type === 'entity.remove') return { kind: 'remove', ids: inverse.ids };\n if (inverse.type === 'entity.create') {\n if (!inverse.positions || inverse.positions.length !== inverse.entries.length)\n return inverseMismatch(operation);\n return {\n kind: 'restore',\n ids: inverse.entries.map(entry => entry.id),\n positions: inverse.positions,\n };\n }\n if (inverse.type === 'entity.move')\n return {\n kind: 'move',\n id: inverse.id,\n ...(inverse.anchor ? { anchor: inverse.anchor } : {}),\n };\n return inverseMismatch(operation);\n};\n\nconst removeEntityIds = (order: string[], ids: readonly string[]): void => {\n const removed = new Set(ids);\n let writeIndex = 0;\n for (const id of order) if (!removed.has(id)) order[writeIndex++] = id;\n order.length = writeIndex;\n};\n\nconst restoreEntityOrder = (order: string[], inverses: readonly EntityOrderInverse[]): void => {\n for (let index = inverses.length - 1; index >= 0; index -= 1) {\n const inverse = inverses[index];\n if (inverse.kind === 'remove') {\n removeEntityIds(order, inverse.ids);\n continue;\n }\n if (inverse.kind === 'restore') {\n anchor.restore(order, inverse.ids, inverse.positions);\n continue;\n }\n const position = order.indexOf(inverse.id);\n if (position < 0 || !anchor.valid(order, inverse.anchor))\n throw new Error(`Entity order inverse cannot restore '${inverse.id}'.`);\n const nextIndex = anchor.afterRemove(order, position, inverse.anchor);\n order.splice(position, 1);\n order.splice(nextIndex, 0, inverse.id);\n }\n};\n\nconst treeOperation = (\n operation: DocumentOperation\n): operation is Extract<\n DocumentOperation,\n {\n readonly type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n> => operation.type.startsWith('tree.');\n\nexport const createChangeJournal = (root: unknown): ChangeJournal => {\n const active = new Set<ChangeSubject>();\n const index = indexNode();\n const buckets = new Map<number, ChangeSubject[]>();\n\n const add = <TSubject extends ChangeSubject>(subject: TSubject): TSubject => {\n active.add(subject);\n const candidates = buckets.get(subject.addressHash);\n if (candidates) candidates.push(subject);\n else buckets.set(subject.addressHash, [subject]);\n let node = index;\n for (const segment of subject.address) {\n const existing = node.children.get(segment);\n if (existing) node = existing;\n else {\n const created = indexNode();\n node.children.set(segment, created);\n node = created;\n }\n }\n if (node.subject)\n throw new Error(`Change journal already owns '${subject.address.join('.')}'.`);\n node.subject = subject;\n profile.journal.subject();\n return subject;\n };\n\n const remove = (subject: ChangeSubject): void => {\n if (!active.delete(subject)) return;\n const candidates = buckets.get(subject.addressHash);\n if (candidates) {\n const position = candidates.indexOf(subject);\n if (position >= 0) candidates.splice(position, 1);\n if (candidates.length === 0) buckets.delete(subject.addressHash);\n }\n const nodes: AddressIndexNode[] = [index];\n let node = index;\n for (const segment of subject.address) {\n const child = node.children.get(segment);\n if (!child) return;\n nodes.push(child);\n node = child;\n }\n if (node.subject === subject) delete node.subject;\n for (let position = subject.address.length - 1; position >= 0; position -= 1) {\n const child = nodes[position + 1];\n if (child.subject || child.children.size > 0) break;\n nodes[position].children.delete(subject.address[position]);\n }\n };\n\n function find(\n kind: 'value',\n address: DocumentAddress,\n addressHash: number\n ): ValueSubject | undefined;\n function find(\n kind: 'variant',\n address: DocumentAddress,\n addressHash: number\n ): VariantSubject | undefined;\n function find(\n kind: 'dict',\n address: DocumentAddress,\n addressHash: number\n ): DictSubject | undefined;\n function find(\n kind: 'entity',\n address: DocumentAddress,\n addressHash: number\n ): EntitySubject | undefined;\n function find(\n kind: 'list',\n address: DocumentAddress,\n addressHash: number\n ): ListSubject | undefined;\n function find(\n kind: 'tree',\n address: DocumentAddress,\n addressHash: number\n ): TreeSubject | undefined;\n function find(\n kind: ChangeSubject['kind'],\n address: DocumentAddress,\n addressHash: number\n ): ChangeSubject | undefined {\n const candidates = buckets.get(addressHash) ?? [];\n for (const subject of candidates) {\n profile.journal.comparison();\n if (subject.kind === kind && sameAddress(subject.address, address)) return subject;\n }\n return undefined;\n }\n\n const ownerOf = (address: DocumentAddress): ChangeSubject | undefined => {\n let node = index;\n for (let position = 0; position < address.length; position += 1) {\n if (node.subject && ownsDescendant(node.subject, address)) return node.subject;\n const child = node.children.get(address[position]);\n if (!child) return undefined;\n node = child;\n }\n return undefined;\n };\n\n const absorb = (value: unknown, address: DocumentAddress): unknown => {\n const subjects = indexedSubjects(index, address);\n if (subjects.length === 0) return value;\n subjects.sort((left, right) => left.address.length - right.address.length);\n let before = ownPayload(value, 'journal');\n for (const subject of subjects) before = restoreSubject(before, address, subject);\n for (const subject of subjects) {\n remove(subject);\n profile.journal.absorbed();\n }\n return before;\n };\n\n const base = (resolved: ResolvedAddress, operation: DocumentOperation): SubjectBase => ({\n address: operation.at,\n addressHash: resolved.addressHash,\n ...(resolved.collection ? { collection: resolved.collection } : {}),\n });\n\n const recordValue = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'field.set' | 'field.clear' | 'value.clear' | 'dict.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (find('value', operation.at, resolved.addressHash)) return;\n const first = inverse[0];\n if (\n first?.type !== 'field.set' &&\n first?.type !== 'field.clear' &&\n first?.type !== 'value.clear' &&\n !('value' in (first ?? {}))\n )\n return inverseMismatch(operation);\n const before =\n first.type === 'field.clear' || first.type === 'value.clear'\n ? absent\n : 'value' in first\n ? present(first.value)\n : inverseMismatch(operation);\n add<ValueSubject>({\n ...base(resolved, operation),\n kind: 'value',\n before,\n });\n };\n\n const recordVariant = (\n resolved: ResolvedAddress,\n operation: Extract<DocumentOperation, { readonly type: 'variant.replace' | 'value.clear' }>,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (find('variant', operation.at, resolved.addressHash)) return;\n const first = inverse[0];\n if (first?.type !== 'variant.replace' && first?.type !== 'value.clear')\n return inverseMismatch(operation);\n add<VariantSubject>({\n ...base(resolved, operation),\n kind: 'variant',\n before: first.type === 'value.clear' ? absent : present(absorb(first.value, operation.at)),\n });\n };\n\n const recordDict = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'dict.set' | 'dict.delete' | 'dict.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n const subject =\n find('dict', operation.at, resolved.addressHash) ??\n add<DictSubject>({\n ...base(resolved, operation),\n kind: 'dict',\n state: { mode: 'incremental', entries: new Map() },\n });\n if (subject.state.mode === 'whole') return;\n if (first.type === 'dict.replace') {\n const value = ownPayload(first.value, 'journal');\n restoreDict(value, subject.state);\n subject.state = { mode: 'whole', value };\n return;\n }\n if (first.type !== 'dict.set' && first.type !== 'dict.delete')\n return inverseMismatch(operation);\n if (!subject.state.entries.has(first.key))\n subject.state.entries.set(\n first.key,\n first.type === 'dict.set' ? present(first.value) : absent\n );\n };\n\n const recordList = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'list.insert' | 'list.move' | 'list.remove' | 'list.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (resolved.node.kind !== 'list') return inverseMismatch(operation);\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n let subject = find('list', operation.at, resolved.addressHash);\n if (!subject) {\n if (first.type === 'value.clear') {\n add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: { mode: 'whole', value: undefined },\n });\n return;\n }\n if (first.type === 'list.replace') {\n add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: { mode: 'whole', value: first.value },\n });\n return;\n }\n const value = read(root, operation.at);\n if (!Array.isArray(value)) return inverseMismatch(operation);\n subject = add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: {\n mode: 'incremental',\n items: new Map(),\n order: listOrderBefore(value, resolved.node, first),\n },\n });\n }\n if (subject.state.mode === 'whole') return;\n if (first.type === 'list.replace') {\n const value = Array.from(ownPayload(first.value, 'journal'));\n restoreList(value, subject);\n subject.state = { mode: 'whole', value };\n return;\n }\n if (first.type !== 'list.insert' && first.type !== 'list.move' && first.type !== 'list.remove')\n return inverseMismatch(operation);\n recordListPresence(subject.state, first);\n };\n\n const trackEntityOrder = (\n subject: EntitySubject,\n collection: Extract<EntityCollection, { readonly kind: 'table' }>\n ): void => {\n if (subject.order.kind !== 'stable') return;\n profile.journal.orderSnapshot(collection.ids.length);\n const before = [...collection.ids];\n restoreEntityOrder(before, subject.order.inverses);\n subject.order = { kind: 'tracked', before };\n };\n\n const recordEntity = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'entity.create' | 'entity.remove' | 'entity.move' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (resolved.node.kind !== 'table' && resolved.node.kind !== 'map')\n return inverseMismatch(operation);\n const resolution = resolveEntityCollection(resolved.node, read(root, operation.at));\n if (resolution.status === 'invalid') return inverseMismatch(operation);\n const collection = resolution.collection;\n const subject =\n find('entity', operation.at, resolved.addressHash) ??\n add<EntitySubject>({\n ...base(resolved, operation),\n kind: 'entity',\n node: resolved.node,\n entries: new Map(),\n order:\n collection.kind === 'table' ? { kind: 'stable', inverses: [] } : { kind: 'unordered' },\n });\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n\n if (collection.kind === 'table' && subject.order.kind === 'stable')\n subject.order.inverses.push(entityOrderInverse(operation, first));\n\n if (first.type === 'entity.remove') {\n for (const id of first.ids) if (!subject.entries.has(id)) subject.entries.set(id, absent);\n if (\n collection.kind === 'table' &&\n first.ids.some(id => subject.entries.get(id)?.status === 'present')\n )\n trackEntityOrder(subject, collection);\n return;\n }\n\n if (first.type === 'entity.create') {\n for (const entry of first.entries) {\n if (subject.entries.has(entry.id)) continue;\n const address = [...operation.at, entry.id];\n subject.entries.set(entry.id, present(absorb(entry.value, address)));\n }\n return;\n }\n\n if (first.type === 'entity.move') {\n if (collection.kind === 'table' && subject.entries.get(first.id)?.status !== 'absent')\n trackEntityOrder(subject, collection);\n return;\n }\n return inverseMismatch(operation);\n };\n\n const recordTree = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n {\n readonly type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n const current = read(root, operation.at);\n if (\n inverse.length === 1 &&\n inverse[0].type === 'value.clear' &&\n operation.type === 'tree.replace'\n ) {\n const subject = find('tree', operation.at, resolved.addressHash);\n if (subject) subject.state = { mode: 'whole', value: undefined };\n else\n add<TreeSubject>({\n ...base(resolved, operation),\n kind: 'tree',\n state: { mode: 'whole', value: undefined },\n });\n return;\n }\n if (!tree.is(current)) return inverseMismatch(operation);\n const inverses = inverse.filter(treeOperation);\n if (inverses.length === 0 || inverses.length !== inverse.length)\n return inverseMismatch(operation);\n const subject = find('tree', operation.at, resolved.addressHash);\n const state = tree.recordChange(subject?.state, current, operation, inverses);\n if (subject) subject.state = state;\n else add<TreeSubject>({ ...base(resolved, operation), kind: 'tree', state });\n };\n\n return {\n record: (resolved, operation, inverse) => {\n profile.batch.journalRecord();\n if (ownerOf(operation.at)) return;\n if (operation.type === 'value.clear' && resolved.node.kind === 'variant') {\n recordVariant(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'field.set' ||\n operation.type === 'field.clear' ||\n operation.type === 'value.clear'\n ) {\n recordValue(resolved, operation, inverse);\n return;\n }\n if (operation.type === 'variant.replace') {\n recordVariant(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'dict.set' ||\n operation.type === 'dict.delete' ||\n operation.type === 'dict.replace'\n ) {\n if (operation.type === 'dict.replace' && inverse[0]?.type === 'value.clear')\n recordValue(resolved, operation, inverse);\n else recordDict(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'entity.create' ||\n operation.type === 'entity.remove' ||\n operation.type === 'entity.move'\n ) {\n recordEntity(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'list.insert' ||\n operation.type === 'list.move' ||\n operation.type === 'list.remove' ||\n operation.type === 'list.replace'\n ) {\n recordList(resolved, operation, inverse);\n return;\n }\n recordTree(resolved, operation, inverse);\n },\n finish: () => {\n const changed: ChangeSubject[] = [];\n const entityChanges = new Map<EntitySubject, EntityAnalysis>();\n for (const subject of active) {\n profile.journal.comparison();\n if (subject.kind === 'entity') {\n const analysis = analyzeEntity(root, subject);\n if (!analysis.changed) continue;\n entityChanges.set(subject, analysis);\n changed.push(subject);\n } else if (subjectChanged(root, subject)) changed.push(subject);\n }\n if (changed.length === 0) return { status: 'unchanged' };\n\n const collections: Array<{\n address: DocumentAddress;\n added: Set<string>;\n removed: Set<string>;\n updated: Set<string>;\n orderChanged: boolean;\n }> = [];\n const collectionBuckets = new Map<number, (typeof collections)[number][]>();\n const changeAt = (address: DocumentAddress, addressHash: number) => {\n const candidates = collectionBuckets.get(addressHash) ?? [];\n collectionBuckets.set(addressHash, candidates);\n let change = candidates.find(entry => sameAddress(entry.address, address));\n if (!change) {\n change = {\n address,\n added: new Set(),\n removed: new Set(),\n updated: new Set(),\n orderChanged: false,\n };\n candidates.push(change);\n collections.push(change);\n }\n return change;\n };\n\n for (const subject of changed) {\n if (subject.kind === 'entity') {\n const analysis = entityChanges.get(subject);\n if (analysis) {\n const change = changeAt(subject.address, subject.addressHash);\n analysis.added.forEach(id => change.added.add(id));\n analysis.removed.forEach(id => change.removed.add(id));\n analysis.updated.forEach(id => change.updated.add(id));\n if (analysis.orderChanged) change.orderChanged = true;\n }\n }\n for (let collection = subject.collection; collection; collection = collection.parent)\n changeAt(collection.address, collection.addressHash).updated.add(collection.id);\n }\n for (const change of collections) {\n change.added.forEach(id => change.updated.delete(id));\n change.removed.forEach(id => change.updated.delete(id));\n }\n\n return {\n status: 'changed',\n paths: Object.freeze(changed.map(subject => subject.address)),\n collections,\n };\n },\n };\n};\n","import type { DocumentAddress } from '../schema';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\nimport { profile } from '../profile';\nimport { isRecord, isPlainObject, isStablePayload, snapshotPayload } from '../value/ownership';\nimport type { MutationIssue } from './issue';\nimport * as issue from './issue';\n\nexport type OperationDecode =\n | { readonly status: 'decoded'; readonly operation: DocumentOperation }\n | { readonly status: 'rejected'; readonly issue: MutationIssue };\nexport type OperationBatchDecode =\n | { readonly status: 'decoded'; readonly operations: readonly unknown[] }\n | { readonly status: 'rejected'; readonly issue: MutationIssue };\n\nconst has = (value: Record<string, unknown>, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\nconst stringArray = (value: unknown): value is readonly string[] =>\n Array.isArray(value) && value.every(entry => typeof entry === 'string');\nconst positions = (value: unknown): value is readonly number[] =>\n Array.isArray(value) && value.every(entry => Number.isInteger(entry) && entry >= 0);\nconst address = (value: unknown): value is DocumentAddress => stringArray(value);\nconst anchor = (value: unknown): value is DocumentAnchor => {\n if (!isRecord(value)) return false;\n const count =\n Number(has(value, 'at')) + Number(has(value, 'before')) + Number(has(value, 'after'));\n if (count !== 1) return false;\n if (has(value, 'at')) return value.at === 'start' || value.at === 'end';\n return typeof (has(value, 'before') ? value.before : value.after) === 'string';\n};\nconst optionalAnchor = (value: Record<string, unknown>): boolean =>\n !has(value, 'anchor') || value.anchor === undefined || anchor(value.anchor);\nconst optionalParent = (value: Record<string, unknown>): boolean =>\n !has(value, 'parentId') || value.parentId === undefined || typeof value.parentId === 'string';\nconst optionalIndex = (value: Record<string, unknown>): boolean =>\n !has(value, 'index') ||\n value.index === undefined ||\n (Number.isInteger(value.index) && (value.index as number) >= 0);\nconst entries = (value: unknown): boolean =>\n Array.isArray(value) &&\n value.every(entry => isRecord(entry) && typeof entry.id === 'string' && has(entry, 'value'));\n\nconst decoded = (operation: DocumentOperation): OperationDecode => ({\n status: 'decoded',\n operation,\n});\nconst rejected = (code: MutationIssue['code'], message: string): OperationDecode => ({\n status: 'rejected',\n issue: issue.input(code, message),\n});\n\nexport const decode = (input: unknown): OperationDecode => {\n if (!isRecord(input)) return rejected('invalid-operation', 'Operation must be an object.');\n if (!address(input.at)) return rejected('invalid-address', 'Operation address is malformed.');\n if (typeof input.type !== 'string')\n return rejected('invalid-operation', 'Operation type must be a string.');\n\n switch (input.type) {\n case 'field.set':\n case 'variant.replace':\n return has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Operation value is required.');\n case 'field.clear':\n case 'value.clear':\n return decoded(input as DocumentOperation);\n case 'dict.set':\n return typeof input.key === 'string' && has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary set requires a string key and value.');\n case 'dict.delete':\n return typeof input.key === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary delete requires a string key.');\n case 'dict.replace':\n return isRecord(input.value)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary replacement must be an object.');\n case 'entity.create':\n return entries(input.entries) &&\n optionalAnchor(input) &&\n (!has(input, 'positions') || input.positions === undefined || positions(input.positions))\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity create payload is malformed.');\n case 'entity.remove':\n return stringArray(input.ids)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity remove requires string ids.');\n case 'entity.move':\n return typeof input.id === 'string' && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity move payload is malformed.');\n case 'list.insert':\n return typeof input.key === 'string' && has(input, 'value') && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List insert payload is malformed.');\n case 'list.move':\n return typeof input.key === 'string' && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List move payload is malformed.');\n case 'list.remove':\n return typeof input.key === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List remove requires a string key.');\n case 'list.replace':\n return Array.isArray(input.value) && stringArray(input.keys)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List replacement payload is malformed.');\n case 'tree.insert':\n return typeof input.treeNodeId === 'string' && optionalParent(input) && optionalIndex(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree insert payload is malformed.');\n case 'tree.move':\n return typeof input.treeNodeId === 'string' && optionalParent(input) && optionalIndex(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree move payload is malformed.');\n case 'tree.remove':\n return typeof input.treeNodeId === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree remove requires a node id.');\n case 'tree.set':\n return typeof input.treeNodeId === 'string' && has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree set payload is malformed.');\n case 'tree.replace':\n return has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree replacement value is required.');\n default:\n return rejected('unknown-operation', 'Unknown document operation.');\n }\n};\n\nexport const decodeBatch = (input: unknown): OperationBatchDecode =>\n Array.isArray(input)\n ? { status: 'decoded', operations: input }\n : {\n status: 'rejected',\n issue: issue.input('invalid-operation', 'Operation batch must be an array.'),\n };\n\nconst ownAddress = (value: DocumentAddress): DocumentAddress => {\n if (Object.isFrozen(value)) return value;\n profile.address.arrayCopied();\n return Object.freeze(value.slice());\n};\n\nconst structuralPayload = (value: unknown): boolean => Array.isArray(value) || isPlainObject(value);\n\nexport const normalize = (operation: DocumentOperation): DocumentOperation => {\n profile.mutation.normalized();\n const copy = {\n ...operation,\n at: ownAddress(operation.at),\n } as DocumentOperation & {\n anchor?: DocumentAnchor;\n keys?: readonly string[];\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n ids?: readonly string[];\n positions?: readonly number[];\n value?: unknown;\n };\n if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });\n if (copy.keys) copy.keys = Object.freeze([...copy.keys]);\n if (copy.entries)\n copy.entries = Object.freeze(copy.entries.map(entry => Object.freeze({ ...entry })));\n if (copy.ids) copy.ids = Object.freeze([...copy.ids]);\n if (copy.positions) copy.positions = Object.freeze([...copy.positions]);\n return Object.freeze(copy);\n};\n\nexport const publish = (operation: DocumentOperation): DocumentOperation => {\n if (\n operation.type === 'entity.create' &&\n operation.entries.every(\n entry => !structuralPayload(entry.value) || isStablePayload(entry.value)\n )\n )\n return operation;\n if (\n 'value' in operation &&\n (!structuralPayload(operation.value) || isStablePayload(operation.value))\n )\n return operation;\n const copy = { ...operation } as DocumentOperation & {\n value?: unknown;\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n };\n if (copy.entries)\n copy.entries = Object.freeze(\n copy.entries.map(entry =>\n Object.freeze({\n id: entry.id,\n value: structuralPayload(entry.value)\n ? isStablePayload(entry.value)\n ? entry.value\n : snapshotPayload(entry.value, 'commit')\n : entry.value,\n })\n )\n );\n else if ('value' in copy && structuralPayload(copy.value))\n copy.value = isStablePayload(copy.value) ? copy.value : snapshotPayload(copy.value, 'commit');\n return Object.freeze(copy);\n};\n\n// Published operation snapshots are frozen so they can be safely retained by\n// commits, history, or a persistence adapter. Replaying one must clone its\n// structural payload before it becomes canonical mutable document state.\nexport const requiresPayloadCopy = (operation: DocumentOperation): boolean => {\n if (operation.type === 'entity.create')\n return operation.entries.some(entry => isStablePayload(entry.value));\n return 'value' in operation && isStablePayload(operation.value);\n};\n\nexport const inverse = (operation: DocumentOperation): DocumentOperation => {\n const copy = { ...operation } as DocumentOperation & {\n anchor?: DocumentAnchor;\n keys?: readonly string[];\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n ids?: readonly string[];\n positions?: readonly number[];\n };\n if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });\n if (copy.keys) copy.keys = Object.freeze([...copy.keys]);\n if (copy.entries)\n copy.entries = Object.freeze(\n copy.entries.map(entry =>\n Object.freeze({\n id: entry.id,\n value: structuralPayload(entry.value)\n ? isStablePayload(entry.value)\n ? entry.value\n : snapshotPayload(entry.value, 'inverse')\n : entry.value,\n })\n )\n );\n if (copy.ids) copy.ids = Object.freeze([...copy.ids]);\n if (copy.positions) copy.positions = Object.freeze([...copy.positions]);\n if ('value' in copy && structuralPayload(copy.value)) {\n const payload = copy as { value?: unknown };\n payload.value = isStablePayload(payload.value)\n ? payload.value\n : snapshotPayload(payload.value, 'inverse');\n }\n return Object.freeze(copy);\n};\n","import { resolveLocated } from '../address';\nimport type { DocumentSchema } from '../schema';\nimport type { DocumentOperation } from '../operations';\nimport { profile } from '../profile';\nimport type { MutationBatch } from './contract';\nimport type { MutationIssue } from './issue';\nimport { execute } from './execute';\nimport { createChangeJournal } from './journal';\nimport * as operation from './operation';\n\nexport type MutationSession<TSchema extends DocumentSchema> = {\n readonly apply: (input: unknown) => MutationIssue | undefined;\n readonly finish: () => MutationBatch<TSchema>;\n readonly rollback: () => void;\n};\n\ntype AppliedStep = {\n readonly forward: DocumentOperation;\n readonly inverse: readonly DocumentOperation[];\n};\n\nexport const createMutationSession = <TSchema extends DocumentSchema>(\n root: unknown,\n schema: TSchema,\n options: { readonly copyPayload?: boolean } = {}\n): MutationSession<TSchema> => {\n const steps: AppliedStep[] = [];\n const journal = createChangeJournal(root);\n let state: 'active' | 'finished' | 'rolled-back' = 'active';\n\n const rollback = (): void => {\n if (state === 'rolled-back') return;\n for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) {\n for (const inverse of steps[stepIndex].inverse) {\n const target = resolveLocated(schema, root, inverse.at);\n const result = execute(root, inverse, target, true);\n if (result.status === 'rejected')\n throw new Error(`Document rollback failed: ${result.issue.message}`);\n }\n }\n state = 'rolled-back';\n };\n\n return {\n apply: input => {\n if (state !== 'active') throw new Error('Mutation session is closed.');\n profile.batch.operation();\n const decoded = operation.decode(input);\n if (decoded.status === 'rejected') {\n profile.batch.rejected();\n return decoded.issue;\n }\n const normalized = operation.normalize(decoded.operation);\n profile.batch.entry(\n normalized.type === 'entity.create'\n ? normalized.entries.length\n : normalized.type === 'entity.remove'\n ? normalized.ids.length\n : 1\n );\n const resolved = resolveLocated(schema, root, normalized.at);\n if (resolved?.collection) profile.batch.collectionResolved();\n profile.mutation.executed();\n const result = execute(\n root,\n normalized,\n resolved,\n options.copyPayload === true || operation.requiresPayloadCopy(normalized)\n );\n if (result.status === 'rejected') {\n profile.batch.rejected();\n return result.issue;\n }\n if (result.status === 'unchanged') return undefined;\n\n const published = operation.publish(normalized);\n const group: DocumentOperation[] = [];\n for (const rawInverse of result.inverse) {\n const inverse = operation.inverse(rawInverse);\n group.push(inverse);\n profile.mutation.inverse();\n profile.batch.inverse();\n }\n steps.push({ forward: published, inverse: Object.freeze(group) });\n try {\n if (!resolved) throw new Error(`Changed operation '${normalized.type}' was not resolved.`);\n journal.record(resolved, normalized, result.inverse);\n } catch (error) {\n rollback();\n throw error;\n }\n return undefined;\n },\n finish: () => {\n if (state !== 'active') throw new Error('Mutation session is closed.');\n const changes = journal.finish();\n state = 'finished';\n if (changes.status === 'unchanged') return { status: 'unchanged' };\n\n let inverseCount = 0;\n for (const step of steps) inverseCount += step.inverse.length;\n const inverse = new Array<DocumentOperation>(inverseCount);\n let writeIndex = 0;\n for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1)\n for (const entry of steps[stepIndex].inverse) inverse[writeIndex++] = entry;\n return {\n status: 'changed',\n operations: Object.freeze(steps.map(step => step.forward)),\n inverse: Object.freeze(inverse),\n paths: changes.paths,\n collections: changes.collections,\n };\n },\n rollback,\n };\n};\n\nexport const mutateOperations = <TSchema extends DocumentSchema>(\n root: unknown,\n schema: TSchema,\n operations: unknown,\n options: { readonly copyPayload?: boolean } = {}\n): MutationBatch<TSchema> => {\n const decodedBatch = operation.decodeBatch(operations);\n if (decodedBatch.status === 'rejected')\n return { status: 'rejected', issues: Object.freeze([decodedBatch.issue]) };\n const session = createMutationSession(root, schema, options);\n for (const input of decodedBatch.operations) {\n const issue = session.apply(input);\n if (!issue) continue;\n session.rollback();\n return { status: 'rejected', issues: Object.freeze([issue]) };\n }\n return session.finish();\n};\n","import type { DocumentSchema, ImpactTarget, ReadonlyDocument } from './schema';\nimport { contains, debugKey, overlaps, read as readAddress, resolveAddress } from './address';\nimport { createImpact } from './impact';\nimport { createHistory } from './history';\nimport { documentReader } from './access/reader';\nimport { documentWriter } from './access/writer';\nimport { createMutationSession, mutateOperations, type MutationSession } from './mutation/session';\nimport type { MutationBatch } from './mutation/contract';\nimport * as issue from './mutation/issue';\nimport * as tree from './mutation/tree';\nimport { commandFootprint } from './mutation/footprint';\nimport { cloneValue, deepEqual } from './value/ownership';\nimport { profile } from './profile';\nimport { DocumentDisposedError, DocumentReentrancyError } from './runtime/contract';\nimport type {\n CommitListener,\n CommitSource,\n DocumentCommit,\n DocumentDiagnostic,\n DiagnosticInput,\n DocumentProblem,\n DocumentRuntime,\n DocumentTransaction,\n OperationResult,\n PreparedUpdateResult,\n TransactionResult,\n} from './runtime/contract';\nimport { bindRuntimeAccess, accessOf } from './runtime/access';\nimport { assertRuntimeWritable, bindRuntimeDriver, disposeRuntimeDriver } from './runtime/driver';\nimport {\n bindDocumentReadable,\n createNotification,\n disposeNotification,\n notify,\n subscribeRoot,\n subscribeTargets,\n type RuntimeNotification,\n} from './runtime/notification';\n\nclass RejectedUpdate extends Error {\n readonly issues: readonly DocumentProblem[];\n\n constructor(issues: readonly DocumentProblem[]) {\n super('Document update rejected.');\n this.issues = Object.freeze(issues.slice());\n }\n}\n\nconst EMPTY: readonly never[] = Object.freeze([]) as readonly never[];\n\nconst publishDiagnostic = (value: DiagnosticInput): DocumentDiagnostic =>\n Object.freeze({\n ...value,\n source: 'application',\n ...(value.address === undefined ? {} : { address: Object.freeze(value.address.slice()) }),\n });\n\nexport const createDocument = <TSchema extends DocumentSchema>(input: {\n readonly schema: TSchema;\n readonly initial: ReadonlyDocument<TSchema>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<TSchema> => {\n const initialTreeError = tree.invalidDocument(input.schema, input.initial);\n if (initialTreeError)\n throw new TypeError(\n `Initial document contains an invalid tree at '${initialTreeError.join('.')}'.`\n );\n profile.clone.initialDocument();\n const state = {\n schema: input.schema,\n document: cloneValue(input.initial, 'initial'),\n disposed: false,\n };\n let revision = 0;\n let busy = false;\n let runtime!: DocumentRuntime<TSchema>;\n let notification!: RuntimeNotification<TSchema>;\n\n const assertWritable = (intent: Parameters<typeof assertRuntimeWritable>[1]): void => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy) throw new DocumentReentrancyError();\n if (accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n assertRuntimeWritable(runtime, intent);\n };\n\n const runTransaction = <TResult>(\n session: MutationSession<TSchema>,\n run: (transaction: DocumentTransaction<TSchema>) => TResult\n ): { readonly value: TResult; readonly reports: readonly DocumentDiagnostic[] } => {\n let reports: DocumentDiagnostic[] | undefined;\n let active = true;\n const transaction: DocumentTransaction<TSchema> = {\n read: documentReader(\n input.schema,\n () => state.document,\n () => active\n ),\n write: documentWriter(input.schema, operation => {\n if (!active) throw new Error('Document writer is no longer active.');\n const rejected = session.apply(operation);\n if (rejected) throw new RejectedUpdate([rejected]);\n }),\n reject: diagnostic => {\n throw new RejectedUpdate(\n (Array.isArray(diagnostic) ? diagnostic : [diagnostic]).map(entry =>\n publishDiagnostic(entry)\n )\n );\n },\n report: diagnostic => {\n if (!active) throw new Error('Document transaction is no longer active.');\n (reports ??= []).push(publishDiagnostic(diagnostic));\n },\n };\n try {\n const value = run(transaction);\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n throw new TypeError('Document update callback must be synchronous.');\n return {\n value,\n reports: Object.freeze(reports ? reports.slice() : EMPTY),\n };\n } finally {\n active = false;\n }\n };\n\n const impactFor = (\n batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }>,\n kind: 'operations' | 'replace'\n ) =>\n createImpact({\n schema: input.schema,\n operations: batch.operations,\n paths: batch.paths,\n collections: batch.collections,\n reset: kind === 'replace',\n });\n\n const history = createHistory<DocumentCommit<TSchema>>({\n capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),\n revision: () => revision,\n apply: operations => applyBatch(operations, 'history', false),\n assertIdle: () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n },\n notify: run => {\n busy = true;\n try {\n return run();\n } finally {\n busy = false;\n }\n },\n });\n\n const publish = (\n batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }>,\n source: CommitSource,\n kind: 'operations' | 'replace',\n recordHistory: boolean\n ): Extract<OperationResult<DocumentCommit<TSchema>>, { readonly status: 'committed' }> => {\n revision += 1;\n const commit: DocumentCommit<TSchema> = Object.freeze({\n revision,\n kind,\n source,\n operations: batch.operations,\n inverse: batch.inverse,\n impact: impactFor(batch, kind),\n });\n if (kind === 'replace' || source === 'remote') history.invalidate();\n else if (recordHistory && (source === 'local' || source === 'system'))\n history.record(batch.operations, batch.inverse);\n else if (source === 'history') history.publish();\n else history.endGroup();\n busy = true;\n let observerErrors;\n try {\n observerErrors = notify(notification, commit, history.flush);\n } finally {\n busy = false;\n }\n return { status: 'committed', commit, observerErrors };\n };\n\n function applyBatch(\n operations: unknown,\n source: CommitSource,\n recordHistory: boolean\n ): OperationResult<DocumentCommit<TSchema>> {\n assertWritable({ kind: 'apply', source });\n const batch = mutateOperations(state.document, input.schema, operations, {\n copyPayload: source === 'history',\n });\n if (batch.status === 'rejected') return { status: 'rejected', issues: batch.issues, revision };\n if (batch.status === 'unchanged') return { status: 'unchanged', revision };\n return publish(batch, source, 'operations', recordHistory);\n }\n\n runtime = {\n schema: input.schema,\n address: {\n resolve: address => resolveAddress(input.schema, address, state.document),\n read: address => readAddress(state.document, address),\n contains,\n overlaps,\n debugKey,\n },\n revision: () => revision,\n update: <TResult>(\n run: (transaction: DocumentTransaction<TSchema>) => TResult,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<TResult, DocumentCommit<TSchema>> => {\n const source = options?.source ?? 'local';\n assertWritable({ kind: 'update', source });\n busy = true;\n const session = createMutationSession(state.document, input.schema);\n let committed = false;\n try {\n const { value, reports } = runTransaction(session, run);\n const batch = session.finish();\n if (batch.status === 'unchanged')\n return {\n status: 'unchanged',\n value,\n revision,\n reports,\n };\n if (batch.status === 'rejected')\n return { status: 'rejected', issues: batch.issues, revision };\n const result = publish(batch, source, 'operations', options?.history ?? true);\n committed = true;\n return {\n status: 'committed',\n value,\n commit: result.commit,\n reports,\n observerErrors: result.observerErrors,\n };\n } catch (error) {\n try {\n if (!committed) session.rollback();\n } finally {\n busy = false;\n }\n if (error instanceof RejectedUpdate)\n return { status: 'rejected', issues: error.issues, revision };\n throw error;\n } finally {\n busy = false;\n }\n },\n prepare: <TResult>(\n run: (transaction: DocumentTransaction<TSchema>) => TResult\n ): PreparedUpdateResult<TResult, TSchema> => {\n assertWritable({ kind: 'prepare' });\n busy = true;\n const session = createMutationSession(state.document, input.schema);\n try {\n const { value, reports } = runTransaction(session, run);\n const batch = session.finish();\n if (batch.status === 'unchanged') {\n session.rollback();\n return { status: 'unchanged', value, reports };\n }\n if (batch.status === 'rejected') {\n session.rollback();\n return { status: 'rejected', issues: batch.issues };\n }\n const impact = impactFor(batch, 'operations');\n session.rollback();\n return {\n status: 'prepared',\n value,\n operations: batch.operations,\n inverse: batch.inverse,\n impact,\n footprint: commandFootprint(batch.operations),\n reports,\n };\n } catch (error) {\n try {\n session.rollback();\n } finally {\n busy = false;\n }\n if (error instanceof RejectedUpdate) return { status: 'rejected', issues: error.issues };\n throw error;\n } finally {\n busy = false;\n }\n },\n apply: (operations, options) =>\n applyBatch(operations, options?.source ?? 'local', options?.history ?? true),\n replace: (document, options) => {\n const source = options?.source ?? 'system';\n assertWritable({ kind: 'replace', source });\n const invalidTree = tree.invalidDocument(input.schema, document);\n if (invalidTree)\n return {\n status: 'rejected',\n issues: [\n issue.at(invalidTree, 'invalid-tree', 'Document replacement contains an invalid tree.'),\n ],\n revision,\n };\n if (deepEqual(state.document, document)) return { status: 'unchanged', revision };\n state.document = cloneValue(document, 'replace');\n const batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }> = {\n status: 'changed',\n operations: EMPTY,\n inverse: EMPTY,\n paths: EMPTY,\n collections: EMPTY,\n };\n return publish(batch, source, 'replace', false);\n },\n snapshot: () => {\n if (state.disposed) throw new DocumentDisposedError();\n return cloneValue(state.document, 'snapshot');\n },\n subscribe: ((\n targetOrListener:\n ImpactTarget<unknown> | readonly ImpactTarget<unknown>[] | CommitListener<TSchema>,\n listener?: CommitListener<TSchema>\n ) => {\n if (state.disposed) throw new DocumentDisposedError();\n if (typeof targetOrListener === 'function')\n return subscribeRoot(notification, targetOrListener);\n const targets = Array.isArray(targetOrListener)\n ? targetOrListener\n : [targetOrListener as ImpactTarget<unknown>];\n if (targets.length === 0 || !listener)\n throw new TypeError('Filtered subscribe requires at least one target and a listener.');\n return subscribeTargets(notification, targets, listener);\n }) as DocumentRuntime<TSchema>['subscribe'],\n history: history.api,\n dispose: () => {\n if (state.disposed) return;\n if (busy || accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n state.disposed = true;\n try {\n disposeNotification(notification);\n } finally {\n history.dispose();\n disposeRuntimeDriver(runtime);\n }\n },\n };\n\n bindRuntimeAccess(runtime, state);\n bindRuntimeDriver(runtime);\n notification = createNotification(runtime);\n bindDocumentReadable(history.api, runtime);\n return runtime;\n};\n","import type { DocumentSchema } from '../schema';\nimport type { DocumentReadable, DocumentRuntime } from './contract';\nimport { accessOf, bindRuntimeAccess } from './access';\nimport { shareNotification } from './notification';\n\n// A readable capability keeps the canonical runtime behind an explicit\n// mutation funnel while remaining fully compatible with selectors, views, and\n// framework subscriptions.\nexport const asReadable = <TSchema extends DocumentSchema>(\n runtime: DocumentRuntime<TSchema>\n): DocumentReadable<TSchema> => {\n const readable: DocumentReadable<TSchema> = {\n address: runtime.address,\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindRuntimeAccess(readable, accessOf(runtime));\n shareNotification(runtime, readable);\n return Object.freeze(readable);\n};\n","import type { DocumentSchema } from '../schema';\nimport type { DocumentReader } from '../access/reader';\nimport type { DocumentReadable } from '../runtime/contract';\nimport { readWith } from '../runtime/access';\n\nexport type DocumentSelector<TSchema extends DocumentSchema, TResult> = (\n read: DocumentReader<TSchema>\n) => TResult;\n\nexport const select = <TSchema extends DocumentSchema, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(runtime, selector);\n"],"mappings":";;;;;AA0BA,MAAM,wBAAkD,OAAO,OAAO;CACpE,MAAM;CACN,uBAAO,IAAI,KAAa;CACxB,yBAAS,IAAI,KAAa;CAC1B,yBAAS,IAAI,KAAa;CAC1B,cAAc;CACf,CAAC;AACF,MAAM,wBAAiD,OAAO,OAAO,EACnE,MAAM,SACP,CAAC;AAEF,MAAa,gBAAgD,UAM9B;CAC7B,MAAM,OAAO,MAAM,QAAQ,UAAU;CACrC,MAAM,QAAQ,MAAM,SAAS,MAAM,WAAW,KAAI,cAAa,UAAU,GAAG;CAC5E,IAAI;CACJ,MAAM,YACJ,SACA,SACY;AACZ,MAAI,QAAQ,WAAW,KAAK,MAAM,UAAU,EAAG,QAAO,MAAM,KAAK,KAAK;AACtE,MAAI,CAAC,aAAa;AAChB,iCAAc,IAAI,KAAK;AACvB,QAAK,MAAM,WAAW,OAAO;IAC3B,MAAM,QAAQ,QAAQ;IACtB,MAAM,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AACxF,UAAOC,gBAAAA,iBAAiB,cAAc,SAAS,SAAS;;EAE1D,SAAS,QAAQ;EACjB,eAAe;AACb,OAAI,MAAM,SAAU;AACpB,OAAI,QAAQT,gBAAAA,SAAS,QAAQ,CAAC,gBAAiB,OAAM,IAAID,gBAAAA,yBAAyB;AAClF,SAAM,WAAW;AACjB,OAAI;AACF,oBAAA,oBAAoB,aAAa;aACzB;AACR,YAAQ,SAAS;AACjB,mBAAA,qBAAqB,QAAQ;;;EAGlC;AAED,iBAAA,kBAAkB,SAAS,MAAM;AACjC,gBAAA,kBAAkB,QAAQ;AAC1B,gBAAeW,gBAAAA,mBAAmB,QAAQ;AAC1C,iBAAA,qBAAqB,QAAQ,KAAK,QAAQ;AAC1C,QAAO;;;;ACnWT,MAAa,cACX,YAC8B;CAC9B,MAAM,WAAsC;EAC1C,SAAS,QAAQ;EACjB,UAAU,QAAQ;EAClB,WAAW,QAAQ;EACpB;AACD,iBAAA,kBAAkB,UAAUC,gBAAAA,SAAS,QAAQ,CAAC;AAC9C,iBAAA,kBAAkB,SAAS,SAAS;AACpC,QAAO,OAAO,OAAO,SAAS;;;;ACThC,MAAa,UACX,SACA,aACYC,gBAAAA,SAAS,SAAS,SAAS"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["overlaps","id","contains","DocumentDisposedError","object","ownAddress","isRecord","rejected","issue.from","cloneValue","transferPayload","rejected","issue.from","ownPayload","sameStructuralValue","cloneValue","has","rejected","sameOrder","ownPayload","sameStructuralValue","isRecord","cloneValue","issue.from","ownPayload","tree.validate","tree.is","tree.replace","tree.insert","tree.set","tree.remove","tree.move","rejected","issue.from","ownPayload","sameStructuralValue","isRecord","cloneValue","hasOwn","issue.from","cloneValue","locate","isRecord","tree.restoreChange","read","sameStructuralValue","tree.changeChanged","ownPayload","tree.is","tree.recordChange","isRecord","issue.input","input","isPlainObject","isStablePayload","snapshotPayload","resolveLocated","operation.decode","operation.normalize","operation.requiresPayloadCopy","operation.publish","inverse","operation.inverse","operation.decodeBatch","tree.invalidDocument","cloneValue","DocumentDisposedError","DocumentReentrancyError","accessOf","documentReader","notify","resolveAddress","readAddress","commandFootprint","issue.at","deepEqual","subscribeRoot","subscribeTargets","createNotification","accessOf","readWith"],"sources":["../core/src/impact.ts","../core/src/history.ts","../core/src/access/writer.ts","../core/src/mutation/issue.ts","../core/src/mutation/execute-entity.ts","../core/src/mutation/execute-list.ts","../core/src/mutation/tree.ts","../core/src/mutation/execute-tree.ts","../core/src/mutation/execute-value.ts","../core/src/mutation/execute.ts","../core/src/mutation/journal.ts","../core/src/mutation/operation.ts","../core/src/mutation/session.ts","../core/src/runtime.ts","../core/src/runtime/readable.ts","../core/src/projection/select.ts"],"sourcesContent":["import type { CollectionSelector, DocumentAddress, DocumentSchema, ImpactTarget } from './schema';\nimport type { DocumentOperation } from './operations';\nimport { contains, overlaps } from './address';\nimport type { MutationCollectionChange } from './mutation/contract';\nimport { profile } from './profile';\nimport * as target from './impact-target';\n\nexport type CollectionImpact<TId> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: ReadonlySet<TId>;\n readonly removed: ReadonlySet<TId>;\n readonly updated: ReadonlySet<TId>;\n readonly orderChanged: boolean;\n };\n\nexport type DocumentImpact<TSchema extends DocumentSchema> = {\n readonly kind: 'incremental' | 'reset';\n readonly affects: (target: ImpactTarget<unknown>) => boolean;\n readonly collection: <TId extends string>(\n selector: CollectionSelector<TId>\n ) => CollectionImpact<TId>;\n readonly operations: readonly DocumentOperation[];\n};\n\nconst emptyCollectionImpact: CollectionImpact<string> = Object.freeze({\n kind: 'incremental',\n added: new Set<string>(),\n removed: new Set<string>(),\n updated: new Set<string>(),\n orderChanged: false,\n});\nconst resetCollectionImpact: CollectionImpact<never> = Object.freeze({\n kind: 'reset',\n});\n\nexport const createImpact = <TSchema extends DocumentSchema>(input: {\n readonly schema: TSchema;\n readonly operations: readonly DocumentOperation[];\n readonly paths?: readonly DocumentAddress[];\n readonly collections?: readonly MutationCollectionChange[];\n readonly reset?: boolean;\n}): DocumentImpact<TSchema> => {\n const kind = input.reset ? 'reset' : 'incremental';\n const paths = input.paths ?? input.operations.map(operation => operation.at);\n let pathBuckets: Map<string | undefined, DocumentAddress[]> | undefined;\n const somePath = (\n address: DocumentAddress,\n test: (changed: DocumentAddress) => boolean\n ): boolean => {\n if (address.length === 0 || paths.length <= 8) return paths.some(test);\n if (!pathBuckets) {\n pathBuckets = new Map();\n for (const changed of paths) {\n const first = changed[0];\n const bucket = pathBuckets.get(first) ?? [];\n bucket.push(changed);\n pathBuckets.set(first, bucket);\n }\n }\n const root = pathBuckets.get(undefined);\n if (root?.some(test)) return true;\n return pathBuckets.get(address[0])?.some(test) ?? false;\n };\n const pathsAffect = (address: DocumentAddress): boolean =>\n address.length === 0\n ? paths.length > 0\n : somePath(address, changed => overlaps(changed, address));\n let collectionCache:\n | {\n readonly address: DocumentAddress;\n readonly value: CollectionImpact<unknown>;\n }[]\n | undefined;\n const findCollection = (address: DocumentAddress) =>\n input.collections?.find(\n entry =>\n entry.address.length === address.length &&\n entry.address.every((segment, index) => segment === address[index])\n );\n return {\n kind,\n operations: input.operations,\n affects: value => {\n profile.impact.affects();\n if (kind === 'reset') return true;\n if (!target.belongs(value, input.schema)) return false;\n const address = target.address(value);\n if (pathsAffect(address)) return true;\n if (value.kind === 'collection') {\n const collectionAddress = target.address(value);\n const collection = findCollection(collectionAddress);\n if (!collection) return false;\n const id = target.id(value);\n if (id !== undefined)\n return (\n collection.added.has(id) || collection.removed.has(id) || collection.updated.has(id)\n );\n return (\n collection.added.size > 0 ||\n collection.removed.size > 0 ||\n collection.updated.size > 0 ||\n collection.orderChanged\n );\n }\n return false;\n },\n collection: <TId extends string>(selector: CollectionSelector<TId>): CollectionImpact<TId> => {\n if (selector.schema !== input.schema)\n throw new Error('Collection selector belongs to another schema.');\n if (kind === 'reset') return resetCollectionImpact as CollectionImpact<TId>;\n const cached = collectionCache?.find(\n entry =>\n entry.address.length === selector.address.length &&\n entry.address.every((segment, index) => segment === selector.address[index])\n )?.value;\n if (cached) return cached as CollectionImpact<TId>;\n const exact = findCollection(selector.address);\n const subtreeReset = somePath(\n selector.address,\n changed => contains(changed, selector.address) && changed.length < selector.address.length\n );\n if (subtreeReset) {\n const reset = { kind: 'reset' } as const;\n (collectionCache ??= []).push({\n address: selector.address,\n value: reset,\n });\n return reset;\n }\n if (!exact) {\n const empty = emptyCollectionImpact as CollectionImpact<TId>;\n (collectionCache ??= []).push({\n address: selector.address,\n value: empty as CollectionImpact<unknown>,\n });\n return empty;\n }\n const incremental = {\n kind: 'incremental' as const,\n added: exact.added as ReadonlySet<TId>,\n removed: exact.removed as ReadonlySet<TId>,\n updated: exact.updated as ReadonlySet<TId>,\n orderChanged: exact.orderChanged,\n };\n (collectionCache ??= []).push({\n address: selector.address,\n value: incremental as CollectionImpact<unknown>,\n });\n return incremental;\n },\n };\n};\n","import type { DocumentOperation } from './operations';\nimport type {\n HistoryState,\n LocalHistory,\n ObserverError,\n OperationResult,\n} from './runtime/contract';\nimport { DocumentDisposedError } from './runtime/contract';\n\ntype Batch = {\n readonly operations: readonly DocumentOperation[];\n readonly inverse: readonly DocumentOperation[];\n};\ntype Entry = { readonly batches: Batch[] };\ntype Group = { entry?: Entry; readonly undos: Entry[]; readonly redos: Entry[] };\n\nexport const createHistory = <TCommit>(input: {\n readonly capacity: number;\n readonly apply: (operations: readonly DocumentOperation[]) => OperationResult<TCommit>;\n readonly revision: () => number;\n readonly assertIdle: () => void;\n readonly notify: (run: () => readonly ObserverError[]) => readonly ObserverError[];\n}) => {\n let undos: Entry[] = [];\n let redos: Entry[] = [];\n const listeners = new Set<() => void>();\n let state: HistoryState = Object.freeze({ undoDepth: 0, redoDepth: 0 });\n let revision = 0;\n let pending = false;\n let disposed = false;\n let group: Group | undefined;\n const unchanged = (): OperationResult<TCommit> => ({\n status: 'unchanged',\n revision: input.revision(),\n });\n const publish = () => {\n if (state.undoDepth === undos.length && state.redoDepth === redos.length) return;\n state = Object.freeze({ undoDepth: undos.length, redoDepth: redos.length });\n revision++;\n pending = true;\n };\n const flush = (): readonly ObserverError[] => {\n if (!pending) return [];\n pending = false;\n const errors: ObserverError[] = [];\n for (const listener of [...listeners]) {\n if (!listeners.has(listener)) continue;\n try {\n listener();\n } catch (error) {\n errors.push({ phase: 'listener', error });\n }\n }\n return errors;\n };\n const clear = () => {\n group = undefined;\n undos.length = redos.length = 0;\n publish();\n };\n const travel = (direction: 'undo' | 'redo' | 'cancel'): OperationResult<TCommit> => {\n input.assertIdle();\n const from = direction === 'redo' ? redos : undos;\n const to = direction === 'redo' ? undos : redos;\n const previousUndos = undos;\n const previousRedos = redos;\n const entry = direction === 'cancel' ? from.at(-1) : from.pop();\n if (!entry) return unchanged();\n if (direction === 'cancel') {\n if (!group || group.entry !== entry)\n throw new Error('History group no longer owns its entry.');\n undos = group.undos;\n redos = group.redos;\n } else to.push(entry);\n let committed = false;\n try {\n const operations =\n direction === 'redo'\n ? entry.batches.flatMap(batch => batch.operations)\n : entry.batches\n .slice()\n .reverse()\n .flatMap(batch => batch.inverse);\n const result = input.apply(operations);\n committed = result.status !== 'rejected';\n if (committed && direction === 'cancel') group = undefined;\n if (result.status === 'unchanged') {\n publish();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n }\n return result;\n } finally {\n if (!committed) {\n if (direction === 'cancel') {\n undos = previousUndos;\n redos = previousRedos;\n } else {\n to.pop();\n from.push(entry);\n }\n }\n }\n };\n const api: LocalHistory<TCommit> = {\n current: () => state,\n revision: () => revision,\n subscribe: listener => {\n if (disposed) throw new DocumentDisposedError();\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n undo: () => {\n input.assertIdle();\n group = undefined;\n return travel('undo');\n },\n redo: () => {\n input.assertIdle();\n group = undefined;\n return travel('redo');\n },\n clear: () => {\n input.assertIdle();\n clear();\n const errors = input.notify(flush);\n if (errors.length)\n throw new AggregateError(\n errors.map(entry => entry.error),\n 'History listeners failed.'\n );\n },\n group: () => {\n input.assertIdle();\n if (group) throw new Error('A history group is already active.');\n if (input.capacity <= 0) throw new Error('History is disabled.');\n const scope: Group = { undos: undos.slice(), redos: redos.slice() };\n group = scope;\n return Object.freeze({\n end: () => {\n input.assertIdle();\n if (group === scope) group = undefined;\n },\n cancel: () => {\n input.assertIdle();\n if (group !== scope) return unchanged();\n if (!scope.entry) {\n group = undefined;\n return unchanged();\n }\n const result = travel('cancel');\n if (result.status !== 'rejected') group = undefined;\n return result;\n },\n });\n },\n };\n return {\n api,\n record: (operations: readonly DocumentOperation[], inverse: readonly DocumentOperation[]) => {\n if (input.capacity <= 0) return;\n const batch = { operations, inverse };\n if (group?.entry) group.entry.batches.push(batch);\n else {\n const entry: Entry = { batches: [batch] };\n undos.push(entry);\n if (group) group.entry = entry;\n if (undos.length > input.capacity) undos.shift();\n }\n redos.length = 0;\n publish();\n },\n publish,\n flush,\n endGroup: () => {\n group = undefined;\n },\n invalidate: clear,\n dispose: () => {\n disposed = true;\n listeners.clear();\n clear();\n pending = false;\n },\n };\n};\n","import { object } from '../schema';\nimport type {\n DictNode,\n DocumentAddress,\n DocumentNode,\n DocumentSchema,\n Infer,\n DocumentTreeValue,\n EntitySchemaNode,\n ListNode,\n MapNode,\n ObjectNode,\n TableNode,\n TreeNode,\n VariantNode,\n} from '../schema';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\n\nexport type FieldWriter<T, Optional extends boolean = false> = {\n readonly set: (value: T) => void;\n} & (Optional extends true ? { readonly clear: () => void } : {});\nexport type DictionaryWriter<TKey extends string, TValue> = {\n readonly set: (key: TKey, value: TValue) => void;\n readonly delete: (key: TKey) => void;\n readonly replace: (value: Readonly<Partial<Record<TKey, TValue>>>) => void;\n};\nexport type CollectionWriter<TId, TNode extends EntitySchemaNode> = {\n readonly create: (\n entry:\n | { readonly id: TId; readonly value: Exclude<Infer<TNode>, undefined> }\n | readonly { readonly id: TId; readonly value: Exclude<Infer<TNode>, undefined> }[],\n anchor?: DocumentAnchor\n ) => void;\n readonly item: (id: TId) => WriterOfNode<TNode>;\n readonly remove: (id: TId | readonly TId[]) => void;\n readonly move: (id: TId, anchor?: DocumentAnchor) => void;\n};\nexport type MapWriter<TId, TNode extends EntitySchemaNode> = {\n readonly create: (\n entry:\n | { readonly id: TId; readonly value: Exclude<Infer<TNode>, undefined> }\n | readonly { readonly id: TId; readonly value: Exclude<Infer<TNode>, undefined> }[]\n ) => void;\n readonly item: (id: TId) => WriterOfNode<TNode>;\n readonly remove: (id: TId | readonly TId[]) => void;\n};\nexport type ListWriter<T> = {\n readonly insert: (value: T, anchor?: DocumentAnchor) => void;\n readonly move: (key: string, anchor?: DocumentAnchor) => void;\n readonly remove: (key: string) => void;\n readonly replace: (value: readonly T[]) => void;\n};\nexport type TreeWriter<T> = {\n readonly insert: (\n id: string,\n value: T,\n position?: { readonly parentId?: string; readonly index?: number }\n ) => void;\n readonly move: (\n id: string,\n position?: { readonly parentId?: string; readonly index?: number }\n ) => void;\n readonly remove: (id: string) => void;\n readonly set: (id: string, value: T) => void;\n readonly replace: (value: DocumentTreeValue<T>) => void;\n};\ntype OptionalClear<TNode extends DocumentNode, TWriter> = TNode extends { readonly optional: true }\n ? TWriter & { readonly clear: () => void }\n : TWriter;\nexport type WriterOfNode<TNode extends DocumentNode> = TNode extends {\n kind: 'field';\n}\n ? TNode extends { readonly optional: true }\n ? FieldWriter<Infer<TNode>, true>\n : FieldWriter<Infer<TNode>>\n : TNode extends ObjectNode<infer TShape>\n ? { readonly [K in keyof TShape]: WriterOfNode<TShape[K]> }\n : TNode extends VariantNode<string, infer _TVariants>\n ? OptionalClear<\n TNode,\n { readonly replace: (value: Exclude<Infer<TNode>, undefined>) => void }\n >\n : TNode extends TableNode<infer TValue>\n ? CollectionWriter<string, TValue>\n : TNode extends MapNode<infer TValue>\n ? MapWriter<string, TValue>\n : TNode extends DictNode<infer TKey, infer TValue>\n ? OptionalClear<TNode, DictionaryWriter<TKey, TValue>>\n : TNode extends ListNode<infer TItem>\n ? OptionalClear<TNode, ListWriter<TItem>>\n : TNode extends TreeNode<infer TValue>\n ? OptionalClear<TNode, TreeWriter<TValue>>\n : FieldWriter<Infer<TNode>>;\nexport type DocumentWriter<TSchema extends DocumentSchema> = WriterOfNode<\n ObjectNode<TSchema['shape']>\n>;\n\nexport type OperationSink = (operation: DocumentOperation) => void;\n\nconst schemaRoot = (schema: DocumentSchema): DocumentNode => object(schema.shape);\n\nconst emit = (sink: OperationSink, operation: DocumentOperation): void => sink(operation);\n\nexport const writerFor = (\n node: DocumentNode,\n inputAddress: DocumentAddress,\n sink: OperationSink\n): unknown => {\n const address = Object.freeze(inputAddress);\n if (node.kind === 'field')\n return {\n set: (value: unknown) => emit(sink, { type: 'field.set', at: address, value }),\n clear: node.optional ? () => emit(sink, { type: 'field.clear', at: address }) : undefined,\n };\n if (node.kind === 'dict')\n return {\n set: (key: string, value: unknown) =>\n emit(sink, { type: 'dict.set', at: address, key, value }),\n delete: (key: string) => emit(sink, { type: 'dict.delete', at: address, key }),\n replace: (value: Readonly<Record<string, unknown>>) =>\n emit(sink, { type: 'dict.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'list')\n return {\n insert: (value: unknown, anchor?: DocumentAnchor) =>\n emit(sink, {\n type: 'list.insert',\n at: address,\n key: node.keyOf(value),\n value,\n anchor,\n }),\n move: (key: string, anchor?: DocumentAnchor) =>\n emit(sink, { type: 'list.move', at: address, key, anchor }),\n remove: (key: string) => emit(sink, { type: 'list.remove', at: address, key }),\n replace: (value: readonly unknown[]) =>\n emit(sink, {\n type: 'list.replace',\n at: address,\n value,\n keys: value.map(node.keyOf),\n }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'tree')\n return {\n insert: (\n treeNodeId: string,\n value: unknown,\n position?: { parentId?: string; index?: number }\n ) =>\n emit(sink, {\n type: 'tree.insert',\n at: address,\n treeNodeId,\n value,\n parentId: position?.parentId,\n index: position?.index,\n }),\n move: (treeNodeId: string, position?: { parentId?: string; index?: number }) =>\n emit(sink, {\n type: 'tree.move',\n at: address,\n treeNodeId,\n parentId: position?.parentId,\n index: position?.index,\n }),\n remove: (treeNodeId: string) => emit(sink, { type: 'tree.remove', at: address, treeNodeId }),\n set: (treeNodeId: string, value: unknown) =>\n emit(sink, {\n type: 'tree.set',\n at: address,\n treeNodeId,\n value,\n }),\n replace: (value: unknown) => emit(sink, { type: 'tree.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n if (node.kind === 'table') {\n let items: Map<string, unknown> | undefined;\n return {\n create: (\n input:\n | { readonly id: string; readonly value: unknown }\n | readonly { readonly id: string; readonly value: unknown }[],\n anchor?: DocumentAnchor\n ) => {\n const entries = Array.isArray(input) ? input : [input];\n emit(sink, {\n type: 'entity.create',\n at: address,\n entries: entries.map(({ id, value }) => ({ id, value })),\n anchor,\n });\n },\n item: (id: string) => {\n const cached = items?.get(id);\n if (cached) return cached;\n const writer = writerFor(node.value, [...address, id], sink);\n (items ??= new Map()).set(id, writer);\n return writer;\n },\n remove: (input: string | readonly string[]) =>\n emit(sink, {\n type: 'entity.remove',\n at: address,\n ids: Array.isArray(input) ? [...input] : [input],\n }),\n move: (id: string, anchor?: DocumentAnchor) =>\n emit(sink, { type: 'entity.move', at: address, id, anchor }),\n };\n }\n if (node.kind === 'map') {\n let items: Map<string, unknown> | undefined;\n return {\n create: (\n input:\n | { readonly id: string; readonly value: unknown }\n | readonly { readonly id: string; readonly value: unknown }[]\n ) => {\n const entries = Array.isArray(input) ? input : [input];\n emit(sink, {\n type: 'entity.create',\n at: address,\n entries: entries.map(({ id, value }) => ({ id, value })),\n });\n },\n item: (id: string) => {\n const cached = items?.get(id);\n if (cached) return cached;\n const writer = writerFor(node.value, [...address, id], sink);\n (items ??= new Map()).set(id, writer);\n return writer;\n },\n remove: (input: string | readonly string[]) =>\n emit(sink, {\n type: 'entity.remove',\n at: address,\n ids: Array.isArray(input) ? [...input] : [input],\n }),\n };\n }\n if (node.kind === 'variant')\n return {\n replace: (value: unknown) => emit(sink, { type: 'variant.replace', at: address, value }),\n ...(node.optional ? { clear: () => emit(sink, { type: 'value.clear', at: address }) } : {}),\n };\n\n let children: Map<string, unknown> | undefined;\n return new Proxy(\n {},\n {\n get: (_target, property: string | symbol) => {\n if (typeof property !== 'string' || !node.shape[property]) return undefined;\n const cached = children?.get(property);\n if (cached) return cached;\n const writer = writerFor(node.shape[property], [...address, property], sink);\n (children ??= new Map()).set(property, writer);\n return writer;\n },\n }\n );\n};\n\nexport const documentWriter = <TSchema extends DocumentSchema>(\n schema: TSchema,\n sink: OperationSink\n): DocumentWriter<TSchema> => writerFor(schemaRoot(schema), [], sink) as DocumentWriter<TSchema>;\n","import type { DocumentAddress } from '../schema';\nimport type { DocumentOperation } from '../operations';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-operation'\n | 'unknown-operation'\n | 'required-field'\n | 'invalid-anchor'\n | 'duplicate-entity'\n | 'missing-entity'\n | 'invalid-collection'\n | 'invalid-list-keys'\n | 'invalid-list-key'\n | 'duplicate-list-item'\n | 'missing-list-item'\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\n\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n readonly operation?: DocumentOperation['type'];\n};\n\nconst ownAddress = (address: DocumentAddress): DocumentAddress => Object.freeze(address.slice());\n\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string,\n operation?: DocumentOperation['type']\n): MutationIssue =>\n Object.freeze({\n source: 'mutation',\n code,\n address: ownAddress(address),\n message,\n ...(operation === undefined ? {} : { operation }),\n });\n\nexport const from = (\n operation: DocumentOperation,\n code: MutationIssueCode,\n message: string\n): MutationIssue => at(operation.at, code, message, operation.type);\n\nexport const input = (code: MutationIssueCode, message: string): MutationIssue =>\n at([], code, message);\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation, EntityCreateOperation } from '../operations';\nimport type { DocumentNode } from '../schema';\nimport type { MutationOutcome } from './contract';\nimport * as anchor from './anchor';\nimport type { MutationIssueCode } from './issue';\nimport * as issue from './issue';\nimport { cloneValue, isRecord, transferPayload } from '../value/ownership';\n\ntype EntityOperation = Extract<\n DocumentOperation,\n { type: 'entity.create' | 'entity.remove' | 'entity.move' }\n>;\n\ntype EntityNode = Extract<DocumentNode, { readonly kind: 'table' | 'map' }>;\n\nexport type EntityCollection =\n | {\n readonly kind: 'table';\n readonly ids: string[];\n readonly byId: Record<string, unknown>;\n }\n | {\n readonly kind: 'map';\n readonly byId: Record<string, unknown>;\n };\n\nexport type EntityCollectionResolution =\n | { readonly status: 'resolved'; readonly collection: EntityCollection }\n | { readonly status: 'invalid' };\n\nexport const resolveEntityCollection = (\n node: EntityNode,\n value: unknown\n): EntityCollectionResolution => {\n if (node.kind === 'table') {\n if (!isRecord(value) || !Array.isArray(value.ids) || !isRecord(value.byId))\n return { status: 'invalid' };\n // Table ids are canonical schema data. Validating every existing id for\n // each operation would turn a constant-address mutation into a full\n // collection scan; operation semantics validate the ids they touch.\n const ids = value.ids as string[];\n return {\n status: 'resolved',\n collection: { kind: 'table', ids, byId: value.byId },\n };\n }\n return isRecord(value)\n ? { status: 'resolved', collection: { kind: 'map', byId: value } }\n : { status: 'invalid' };\n};\n\nconst rejected = (\n operation: EntityOperation,\n code: MutationIssueCode,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeEntity = (\n target: ResolvedAddress,\n operation: EntityOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'table' && target.node.kind !== 'map')\n return rejected(operation, 'invalid-address', 'Collection target is invalid.');\n const resolution = resolveEntityCollection(target.node, target.value);\n if (resolution.status === 'invalid')\n return rejected(operation, 'invalid-address', 'Collection target is invalid.');\n const collection = resolution.collection;\n const ids = collection.kind === 'table' ? collection.ids : undefined;\n if (operation.type === 'entity.move' && collection.kind === 'map')\n return rejected(operation, 'invalid-operation', 'Map entries are unordered.');\n const byId = collection.byId;\n\n if (operation.type === 'entity.create') {\n if (operation.entries.length === 0) return { status: 'unchanged' };\n const seen = new Set<string>();\n for (const entry of operation.entries) {\n if (seen.has(entry.id))\n return rejected(operation, 'duplicate-entity', 'Entity ids must be unique within a batch.');\n seen.add(entry.id);\n if (Object.prototype.hasOwnProperty.call(byId, entry.id))\n return rejected(operation, 'duplicate-entity', `Entity '${entry.id}' already exists.`);\n }\n if (collection.kind === 'map' && (operation.anchor || operation.positions))\n return rejected(operation, 'invalid-anchor', 'Map entries do not support ordering metadata.');\n if (ids && operation.positions) {\n if (\n operation.positions.length !== operation.entries.length ||\n !anchor.validPositions(ids.length, operation.positions)\n )\n return rejected(operation, 'invalid-operation', 'Entity restore positions are invalid.');\n } else if (ids && !anchor.valid(ids, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'Collection anchor is invalid.');\n\n for (const entry of operation.entries)\n byId[entry.id] = copyPayload\n ? cloneValue(entry.value, 'canonical')\n : transferPayload(entry.value);\n if (ids) {\n if (operation.positions) {\n anchor.restore(\n ids,\n operation.entries.map(entry => entry.id),\n operation.positions\n );\n } else {\n if (!operation.anchor || ('at' in operation.anchor && operation.anchor.at === 'end')) {\n for (const entry of operation.entries) ids.push(entry.id);\n } else {\n const insertion = anchor.index(ids, operation.anchor);\n const currentLength = ids.length;\n ids.length = currentLength + operation.entries.length;\n for (let index = currentLength - 1; index >= insertion; index -= 1)\n ids[index + operation.entries.length] = ids[index];\n for (let index = 0; index < operation.entries.length; index += 1)\n ids[insertion + index] = operation.entries[index].id;\n }\n }\n }\n return {\n status: 'changed',\n inverse: [\n {\n type: 'entity.remove',\n at: operation.at,\n ids: operation.entries.map(entry => entry.id),\n },\n ],\n };\n }\n\n if (operation.type === 'entity.remove') {\n if (operation.ids.length === 0) return { status: 'unchanged' };\n const seen = new Set<string>();\n for (const id of operation.ids) {\n if (seen.has(id))\n return rejected(operation, 'duplicate-entity', 'Entity ids must be unique within a batch.');\n seen.add(id);\n if (!Object.prototype.hasOwnProperty.call(byId, id))\n return rejected(operation, 'missing-entity', `Entity '${id}' does not exist.`);\n }\n\n const entries: { id: string; value: unknown }[] = [];\n const positions: number[] = [];\n if (ids) {\n const positionsById = new Map<string, number>();\n for (let index = 0; index < ids.length; index += 1) {\n const id = ids[index];\n if (seen.has(id)) positionsById.set(id, index);\n }\n for (const id of operation.ids)\n if (!positionsById.has(id))\n return rejected(operation, 'invalid-collection', `Collection index is missing '${id}'.`);\n\n let writeIndex = 0;\n for (let index = 0; index < ids.length; index += 1) {\n const id = ids[index];\n if (seen.has(id)) {\n entries.push({ id, value: cloneValue(byId[id], 'inverse') });\n positions.push(index);\n delete byId[id];\n } else {\n ids[writeIndex++] = id;\n }\n }\n ids.length = writeIndex;\n } else {\n for (const id of operation.ids) {\n entries.push({ id, value: cloneValue(byId[id], 'inverse') });\n delete byId[id];\n }\n }\n const inverse: EntityCreateOperation = {\n type: 'entity.create',\n at: operation.at,\n entries,\n ...(ids ? { positions } : {}),\n };\n return { status: 'changed', inverse: [inverse] };\n }\n\n const exists = Object.prototype.hasOwnProperty.call(byId, operation.id);\n const position = ids?.indexOf(operation.id) ?? -1;\n if (!exists)\n return rejected(operation, 'missing-entity', `Entity '${operation.id}' does not exist.`);\n if (!ids || position < 0)\n return rejected(\n operation,\n 'invalid-collection',\n `Collection index is missing '${operation.id}'.`\n );\n if (!anchor.valid(ids, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'Collection anchor is invalid.');\n if (\n operation.anchor &&\n (('before' in operation.anchor && operation.anchor.before === operation.id) ||\n ('after' in operation.anchor && operation.anchor.after === operation.id))\n )\n return rejected(operation, 'invalid-anchor', 'An entity cannot be moved relative to itself.');\n const nextIndex = anchor.afterRemove(ids, position, operation.anchor);\n if (nextIndex === position) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'entity.move',\n at: operation.at,\n id: operation.id,\n anchor: anchor.at(ids, position),\n };\n ids.splice(position, 1);\n ids.splice(nextIndex, 0, operation.id);\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as anchor from './anchor';\nimport type { MutationIssueCode } from './issue';\nimport * as issue from './issue';\nimport { cloneValue, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype ListOperation = Extract<\n DocumentOperation,\n { type: 'list.insert' | 'list.move' | 'list.remove' | 'list.replace' }\n>;\n\nconst rejected = (\n operation: ListOperation,\n code: MutationIssueCode,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeList = (\n target: ResolvedAddress,\n operation: ListOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'list')\n return rejected(operation, 'invalid-address', 'List target is invalid.');\n const absent =\n target.value === undefined && 'optional' in target.node && target.node.optional === true;\n if (!Array.isArray(target.value) && !absent)\n return rejected(operation, 'invalid-address', 'List target is invalid.');\n if (absent && operation.type !== 'list.replace')\n return rejected(\n operation,\n 'invalid-address',\n 'Only list replacement can initialize an optional list.'\n );\n const list = (Array.isArray(target.value) ? target.value : []) as unknown[];\n const orderedKeys = anchor.keys(list, target.node.keyOf);\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n\n if (operation.type === 'list.replace') {\n if (operation.keys.length !== operation.value.length)\n return rejected(operation, 'invalid-list-keys', 'List replacement keys are invalid.');\n const seen = new Set<string>();\n for (let index = 0; index < operation.value.length; index += 1) {\n const key = operation.keys[index];\n if (seen.has(key) || target.node.keyOf(operation.value[index]) !== key)\n return rejected(operation, 'invalid-list-keys', 'List replacement keys are invalid.');\n seen.add(key);\n }\n if (!absent && sameStructuralValue(list, operation.value)) return { status: 'unchanged' };\n const keys = list.map(target.node.keyOf);\n const inverse: DocumentOperation = absent\n ? { type: 'value.clear', at: operation.at }\n : {\n type: 'list.replace',\n at: operation.at,\n value: cloneValue(list, 'inverse'),\n keys,\n };\n const owned = own(operation.value) as unknown[];\n if (absent) (target.parent as Record<string | number, unknown>)[target.key] = owned;\n else {\n list.length = owned.length;\n for (let index = 0; index < owned.length; index += 1) list[index] = owned[index];\n }\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'list.insert') {\n if (target.node.keyOf(operation.value) !== operation.key)\n return rejected(operation, 'invalid-list-key', 'List item key does not match schema.');\n if (orderedKeys.index(operation.key) >= 0)\n return rejected(\n operation,\n 'duplicate-list-item',\n `List item '${operation.key}' already exists.`\n );\n if (!anchor.valid(orderedKeys, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'List anchor is invalid.');\n list.splice(anchor.index(orderedKeys, operation.anchor), 0, own(operation.value));\n return {\n status: 'changed',\n inverse: [{ type: 'list.remove', at: operation.at, key: operation.key }],\n };\n }\n\n const position = orderedKeys.index(operation.key);\n if (position < 0)\n return rejected(operation, 'missing-list-item', `List item '${operation.key}' does not exist.`);\n if (operation.type === 'list.remove') {\n const inverse: DocumentOperation = {\n type: 'list.insert',\n at: operation.at,\n key: operation.key,\n value: cloneValue(list[position], 'inverse'),\n anchor: anchor.at(orderedKeys, position),\n };\n list.splice(position, 1);\n return { status: 'changed', inverse: [inverse] };\n }\n if (!anchor.valid(orderedKeys, operation.anchor))\n return rejected(operation, 'invalid-anchor', 'List anchor is invalid.');\n if (\n operation.anchor &&\n (('before' in operation.anchor && operation.anchor.before === operation.key) ||\n ('after' in operation.anchor && operation.anchor.after === operation.key))\n )\n return rejected(operation, 'invalid-anchor', 'A list item cannot be moved relative to itself.');\n const nextIndex = anchor.afterRemove(orderedKeys, position, operation.anchor);\n if (nextIndex === position) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'list.move',\n at: operation.at,\n key: operation.key,\n anchor: anchor.at(orderedKeys, position),\n };\n const [entry] = list.splice(position, 1);\n list.splice(nextIndex, 0, entry);\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { DocumentAddress, DocumentNode, DocumentSchema } from '../schema';\nimport type { DocumentOperation } from '../operations';\nimport { cloneValue, isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype TreeOperation = Extract<\n DocumentOperation,\n {\n type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n>;\n\ntype MutableTreeNode = {\n parentId?: string;\n children: string[];\n value?: unknown;\n};\n\nexport type MutableTree = {\n rootId?: string;\n nodes: Record<string, MutableTreeNode>;\n};\n\nexport type TreeOutcome =\n | {\n readonly status: 'changed';\n readonly inverse: readonly DocumentOperation[];\n }\n | { readonly status: 'unchanged' }\n | {\n readonly status: 'rejected';\n readonly code:\n | 'invalid-tree'\n | 'duplicate-tree-node'\n | 'missing-tree-parent'\n | 'invalid-tree-index'\n | 'missing-tree-node'\n | 'tree-cycle';\n readonly message: string;\n };\n\ntype TreeNodePresence =\n | { readonly status: 'absent' }\n | {\n readonly status: 'present';\n readonly parentId?: string;\n readonly children: readonly string[];\n readonly value: unknown;\n };\n\ntype TreeRootPresence =\n { readonly status: 'absent' } | { readonly status: 'present'; readonly id: string };\n\nexport type TreeChange =\n | {\n readonly mode: 'incremental';\n readonly root: TreeRootPresence;\n readonly nodes: Map<string, TreeNodePresence>;\n }\n | { readonly mode: 'whole'; readonly value: unknown };\n\nconst has = (value: object, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\nconst validIndex = (index: number | undefined): boolean =>\n index === undefined || (Number.isInteger(index) && index >= 0);\nconst rejected = (\n code: Extract<TreeOutcome, { status: 'rejected' }>['code'],\n message: string\n): TreeOutcome => ({ status: 'rejected', code, message });\n\nconst node = (tree: MutableTree, id: string): MutableTreeNode | undefined => tree.nodes[id];\nconst childIndex = (parent: MutableTreeNode, id: string): number => parent.children.indexOf(id);\nconst sameOrder = (left: readonly string[], right: readonly string[]): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst rootPresence = (id: string | undefined): TreeRootPresence =>\n id === undefined ? { status: 'absent' } : { status: 'present', id };\n\nconst capture = (\n change: Extract<TreeChange, { readonly mode: 'incremental' }>,\n id: string,\n presence: TreeNodePresence\n): void => {\n if (!change.nodes.has(id)) change.nodes.set(id, presence);\n};\n\nconst without = (values: readonly string[], id: string): string[] => {\n const result: string[] = [];\n for (const value of values) if (value !== id) result.push(value);\n return result;\n};\n\nconst inserted = (values: readonly string[], id: string, index: number): string[] => {\n const result = [...values];\n result.splice(Math.min(index, result.length), 0, id);\n return result;\n};\n\nconst moved = (values: readonly string[], id: string, index: number): string[] => {\n const result = without(values, id);\n result.splice(Math.min(index, result.length), 0, id);\n return result;\n};\n\nconst parentPresence = (\n tree: MutableTree,\n id: string,\n children: readonly string[]\n): TreeNodePresence => {\n const entry = node(tree, id);\n return entry\n ? {\n status: 'present',\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n children,\n value: entry.value,\n }\n : { status: 'absent' };\n};\n\nconst restoreIncremental = (\n value: unknown,\n change: Extract<TreeChange, { readonly mode: 'incremental' }>\n): unknown => {\n if (!is(value)) return value;\n if (change.root.status === 'absent') delete value.rootId;\n else value.rootId = change.root.id;\n for (const [id, before] of change.nodes) {\n if (before.status === 'absent') {\n delete value.nodes[id];\n continue;\n }\n value.nodes[id] = {\n ...(before.parentId === undefined ? {} : { parentId: before.parentId }),\n children: [...before.children],\n value: before.value,\n };\n }\n return value;\n};\n\nexport const restoreChange = (value: unknown, change: TreeChange): unknown =>\n change.mode === 'whole' ? ownPayload(change.value, 'journal') : restoreIncremental(value, change);\n\nconst wholeChange = (\n inverse: Extract<TreeOperation, { readonly type: 'tree.replace' }>,\n previous?: TreeChange\n): TreeChange => {\n if (!previous) return { mode: 'whole', value: inverse.value };\n if (previous.mode === 'whole') return previous;\n return {\n mode: 'whole',\n value: restoreIncremental(ownPayload(inverse.value, 'journal'), previous),\n };\n};\n\nconst removedNodePresences = (\n inverses: readonly Extract<TreeOperation, { readonly type: 'tree.insert' }>[]\n): Map<string, TreeNodePresence> => {\n const children = new Map<string, Array<{ readonly id: string; readonly index: number }>>();\n for (const inverse of inverses) {\n if (inverse.parentId === undefined) continue;\n const entries = children.get(inverse.parentId);\n const child = { id: inverse.treeNodeId, index: inverse.index ?? Number.MAX_SAFE_INTEGER };\n if (entries) entries.push(child);\n else children.set(inverse.parentId, [child]);\n }\n const result = new Map<string, TreeNodePresence>();\n for (const inverse of inverses) {\n const ordered = children.get(inverse.treeNodeId) ?? [];\n ordered.sort((left, right) => left.index - right.index);\n result.set(inverse.treeNodeId, {\n status: 'present',\n ...(inverse.parentId === undefined ? {} : { parentId: inverse.parentId }),\n children: ordered.map(entry => entry.id),\n value: inverse.value,\n });\n }\n return result;\n};\n\nexport const recordChange = (\n previous: TreeChange | undefined,\n current: MutableTree,\n forward: TreeOperation,\n inverses: readonly TreeOperation[]\n): TreeChange => {\n const replacement = inverses[0];\n if (replacement?.type === 'tree.replace') return wholeChange(replacement, previous);\n if (previous?.mode === 'whole') return previous;\n\n const change: Extract<TreeChange, { readonly mode: 'incremental' }> = previous ?? {\n mode: 'incremental',\n root:\n forward.type === 'tree.insert' && forward.parentId === undefined\n ? { status: 'absent' }\n : forward.type === 'tree.remove' && inverses[0]?.type === 'tree.insert'\n ? rootPresence(\n inverses[0].parentId === undefined ? inverses[0].treeNodeId : current.rootId\n )\n : rootPresence(current.rootId),\n nodes: new Map(),\n };\n\n if (forward.type === 'tree.insert') {\n capture(change, forward.treeNodeId, { status: 'absent' });\n if (forward.parentId !== undefined) {\n const parentNode = node(current, forward.parentId);\n if (parentNode)\n capture(\n change,\n forward.parentId,\n parentPresence(\n current,\n forward.parentId,\n without(parentNode.children, forward.treeNodeId)\n )\n );\n }\n return change;\n }\n\n if (forward.type === 'tree.remove') {\n const inserts = inverses.filter(\n (inverse): inverse is Extract<TreeOperation, { readonly type: 'tree.insert' }> =>\n inverse.type === 'tree.insert'\n );\n const removed = removedNodePresences(inserts);\n for (const [id, presence] of removed) capture(change, id, presence);\n const first = inserts[0];\n if (first?.parentId !== undefined) {\n const parentNode = node(current, first.parentId);\n if (parentNode)\n capture(\n change,\n first.parentId,\n parentPresence(\n current,\n first.parentId,\n inserted(\n parentNode.children,\n first.treeNodeId,\n first.index ?? parentNode.children.length\n )\n )\n );\n }\n return change;\n }\n\n if (forward.type === 'tree.set') {\n const inverse = inverses[0];\n const entry = node(current, forward.treeNodeId);\n if (entry && inverse?.type === 'tree.set')\n capture(change, forward.treeNodeId, {\n status: 'present',\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n children: [...entry.children],\n value: inverse.value,\n });\n return change;\n }\n\n if (forward.type === 'tree.move') {\n const inverse = inverses[0];\n const entry = node(current, forward.treeNodeId);\n if (!entry || inverse?.type !== 'tree.move' || inverse.parentId === undefined) return change;\n capture(change, forward.treeNodeId, {\n status: 'present',\n parentId: inverse.parentId,\n children: [...entry.children],\n value: entry.value,\n });\n const oldParent = node(current, inverse.parentId);\n if (oldParent) {\n const children =\n inverse.parentId === forward.parentId\n ? moved(\n oldParent.children,\n forward.treeNodeId,\n inverse.index ?? oldParent.children.length\n )\n : inserted(\n oldParent.children,\n forward.treeNodeId,\n inverse.index ?? oldParent.children.length\n );\n capture(change, inverse.parentId, parentPresence(current, inverse.parentId, children));\n }\n if (forward.parentId !== undefined && forward.parentId !== inverse.parentId) {\n const nextParent = node(current, forward.parentId);\n if (nextParent)\n capture(\n change,\n forward.parentId,\n parentPresence(\n current,\n forward.parentId,\n without(nextParent.children, forward.treeNodeId)\n )\n );\n }\n }\n return change;\n};\n\nconst sameNodePresence = (\n before: TreeNodePresence,\n value: MutableTreeNode | undefined\n): boolean => {\n if (before.status === 'absent') return value === undefined;\n return (\n value !== undefined &&\n before.parentId === value.parentId &&\n sameOrder(before.children, value.children) &&\n sameStructuralValue(before.value, value.value)\n );\n};\n\nexport const changeChanged = (change: TreeChange, value: unknown): boolean => {\n if (change.mode === 'whole') return !sameStructuralValue(change.value, value);\n if (!is(value)) return true;\n const rootId = change.root.status === 'present' ? change.root.id : undefined;\n if (rootId !== value.rootId) return true;\n for (const [id, before] of change.nodes)\n if (!sameNodePresence(before, node(value, id))) return true;\n return false;\n};\n\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const contains = (tree: MutableTree, id: string): boolean => has(tree.nodes, id);\n\nexport const parent = (tree: MutableTree, id: string): string | undefined =>\n node(tree, id)?.parentId;\n\nexport const children = (tree: MutableTree, id: string): readonly string[] | undefined =>\n node(tree, id)?.children;\n\nexport const validate = (value: unknown): value is MutableTree => {\n if (!is(value)) return false;\n const ids = Object.keys(value.nodes);\n if (ids.length === 0) return value.rootId === undefined;\n if (typeof value.rootId !== 'string' || !has(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!isRecord(entry) || !Array.isArray(entry.children)) return false;\n if (\n entry.children.some(child => typeof child !== 'string') ||\n new Set(entry.children).size !== entry.children.length\n )\n return false;\n if (entry.parentId !== undefined && typeof entry.parentId !== 'string') return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !has(value.nodes, entry.parentId)) return false;\n for (const child of entry.children) {\n const childNode = value.nodes[child];\n if (!childNode || childNode.parentId !== id) return false;\n }\n }\n\n const seen = new Set<string>();\n const stack = [value.rootId];\n while (stack.length) {\n const id = stack.pop() as string;\n if (seen.has(id)) return false;\n seen.add(id);\n const entry = value.nodes[id];\n if (!entry) return false;\n for (const child of entry.children) stack.push(child);\n }\n return seen.size === ids.length;\n};\n\nconst documentTreeError = (\n node: DocumentNode,\n value: unknown,\n address: DocumentAddress\n): DocumentAddress | undefined => {\n if ('optional' in node && node.optional && value === undefined) return undefined;\n if (node.kind === 'tree') return validate(value) ? undefined : address;\n if (node.kind === 'object') {\n if (!isRecord(value)) return undefined;\n for (const [key, child] of Object.entries(node.shape)) {\n const error = documentTreeError(child, value[key], [...address, key]);\n if (error) return error;\n }\n return undefined;\n }\n if (node.kind === 'variant') {\n if (!isRecord(value) || typeof value[node.tag] !== 'string') return undefined;\n const variant = node.variants[value[node.tag] as keyof typeof node.variants];\n return variant ? documentTreeError(variant, value, address) : undefined;\n }\n if (node.kind === 'table') {\n if (!isRecord(value) || !isRecord(value.byId)) return undefined;\n for (const [id, entry] of Object.entries(value.byId)) {\n const error = documentTreeError(node.value, entry, [...address, id]);\n if (error) return error;\n }\n return undefined;\n }\n if (node.kind === 'map') {\n if (!isRecord(value)) return undefined;\n for (const [id, entry] of Object.entries(value)) {\n const error = documentTreeError(node.value, entry, [...address, id]);\n if (error) return error;\n }\n }\n return undefined;\n};\n\nexport const invalidDocument = (\n schema: DocumentSchema,\n value: unknown\n): DocumentAddress | undefined =>\n documentTreeError({ kind: 'object', shape: schema.shape }, value, []);\n\nexport const replace = (\n current: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.replace' }>\n): TreeOutcome => {\n if (!validate(operation.value)) return rejected('invalid-tree', 'Tree replacement is malformed.');\n if (sameStructuralValue(current, operation.value)) return { status: 'unchanged' };\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.replace',\n at: operation.at,\n value: cloneValue(current, 'inverse'),\n },\n ],\n };\n};\n\nexport const insert = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.insert' }>,\n value: unknown\n): TreeOutcome => {\n if (contains(tree, operation.treeNodeId))\n return rejected('duplicate-tree-node', `Tree node '${operation.treeNodeId}' already exists.`);\n if (!validIndex(operation.index)) return rejected('invalid-tree-index', 'Tree index is invalid.');\n\n if (tree.rootId === undefined) {\n if (operation.parentId !== undefined)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n tree.nodes[operation.treeNodeId] = { children: [], value };\n tree.rootId = operation.treeNodeId;\n } else {\n if (operation.parentId === undefined)\n return rejected('invalid-tree', 'A non-empty tree has exactly one root.');\n const parentNode = node(tree, operation.parentId);\n if (!parentNode)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n tree.nodes[operation.treeNodeId] = {\n parentId: operation.parentId,\n children: [],\n value,\n };\n parentNode.children.splice(\n Math.min(operation.index ?? parentNode.children.length, parentNode.children.length),\n 0,\n operation.treeNodeId\n );\n }\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.remove',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n },\n ],\n };\n};\n\nexport const set = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.set' }>,\n value: unknown\n): TreeOutcome => {\n const entry = node(tree, operation.treeNodeId);\n if (!entry)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n if (Object.is(entry.value, value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'tree.set',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n value: cloneValue(entry.value, 'inverse'),\n };\n entry.value = value;\n return { status: 'changed', inverse: [inverse] };\n};\n\nexport const remove = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.remove' }>\n): TreeOutcome => {\n const first = node(tree, operation.treeNodeId);\n if (!first)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n const parentId = first.parentId;\n const parentNode = parentId === undefined ? undefined : node(tree, parentId);\n const originalIndex = parentNode ? childIndex(parentNode, operation.treeNodeId) : 0;\n if (\n (parentId !== undefined && (!parentNode || originalIndex < 0)) ||\n (parentId === undefined && tree.rootId !== operation.treeNodeId)\n )\n return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n\n const entries: Array<{\n readonly id: string;\n readonly parentId?: string;\n readonly index: number;\n readonly value: unknown;\n }> = [];\n const seen = new Set<string>();\n const stack: Array<{\n readonly id: string;\n readonly parentId?: string;\n readonly index: number;\n }> = [{ id: operation.treeNodeId, parentId, index: originalIndex }];\n while (stack.length) {\n const frame = stack.pop() as (typeof stack)[number];\n const entry = node(tree, frame.id);\n if (!entry || seen.has(frame.id) || entry.parentId !== frame.parentId)\n return rejected('invalid-tree', 'Tree contains an invalid descendant.');\n seen.add(frame.id);\n entries.push({\n id: frame.id,\n parentId: frame.parentId,\n index: frame.index,\n value: cloneValue(entry.value, 'inverse'),\n });\n for (let index = entry.children.length - 1; index >= 0; index -= 1) {\n const childId = entry.children[index];\n const child = node(tree, childId);\n if (!child || child.parentId !== frame.id)\n return rejected('invalid-tree', 'Tree child links are inconsistent.');\n stack.push({ id: childId, parentId: frame.id, index });\n }\n }\n\n if (parentNode) parentNode.children.splice(originalIndex, 1);\n for (let index = entries.length - 1; index >= 0; index -= 1) delete tree.nodes[entries[index].id];\n if (tree.rootId === operation.treeNodeId) delete tree.rootId;\n return {\n status: 'changed',\n inverse: entries.map(entry => ({\n type: 'tree.insert' as const,\n at: operation.at,\n treeNodeId: entry.id,\n ...(entry.parentId === undefined ? {} : { parentId: entry.parentId }),\n index: entry.index,\n value: entry.value,\n })),\n };\n};\n\nexport const move = (\n tree: MutableTree,\n operation: Extract<TreeOperation, { type: 'tree.move' }>\n): TreeOutcome => {\n const entry = node(tree, operation.treeNodeId);\n if (!entry)\n return rejected('missing-tree-node', `Tree node '${operation.treeNodeId}' does not exist.`);\n if (!validIndex(operation.index)) return rejected('invalid-tree-index', 'Tree index is invalid.');\n if (tree.rootId === operation.treeNodeId)\n return rejected('invalid-tree', 'The root cannot be moved.');\n if (operation.parentId === undefined) {\n return rejected('invalid-tree', 'Only the root can have no parent.');\n }\n const nextParent = node(tree, operation.parentId);\n if (!nextParent)\n return rejected('missing-tree-parent', `Tree parent '${operation.parentId}' does not exist.`);\n if (operation.parentId === operation.treeNodeId)\n return rejected('tree-cycle', 'A tree node cannot parent itself.');\n\n const descendants = [operation.treeNodeId];\n const seen = new Set<string>();\n while (descendants.length) {\n const id = descendants.pop() as string;\n if (seen.has(id)) return rejected('invalid-tree', 'Tree contains a cycle.');\n seen.add(id);\n const current = node(tree, id);\n if (!current) return rejected('invalid-tree', 'Tree contains a missing node.');\n for (const childId of current.children) {\n const child = node(tree, childId);\n if (!child || child.parentId !== id)\n return rejected('invalid-tree', 'Tree child links are inconsistent.');\n if (childId === operation.parentId)\n return rejected('tree-cycle', 'Tree move would create a cycle.');\n descendants.push(childId);\n }\n }\n\n const parentId = entry.parentId;\n const currentParent = parentId === undefined ? undefined : node(tree, parentId);\n if (!currentParent || parentId === undefined)\n return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n const originalIndex = childIndex(currentParent, operation.treeNodeId);\n if (originalIndex < 0) return rejected('invalid-tree', 'Tree parent links are inconsistent.');\n currentParent.children.splice(originalIndex, 1);\n const nextIndex = Math.min(\n operation.index ?? nextParent.children.length,\n nextParent.children.length\n );\n if (parentId === operation.parentId && nextIndex === originalIndex) {\n currentParent.children.splice(originalIndex, 0, operation.treeNodeId);\n return { status: 'unchanged' };\n }\n nextParent.children.splice(nextIndex, 0, operation.treeNodeId);\n entry.parentId = operation.parentId;\n return {\n status: 'changed',\n inverse: [\n {\n type: 'tree.move',\n at: operation.at,\n treeNodeId: operation.treeNodeId,\n parentId,\n index: originalIndex,\n },\n ],\n };\n};\n","import { set as setAddress } from '../address';\nimport type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport * as tree from './tree';\nimport { ownPayload } from '../value/ownership';\n\ntype TreeOperation = Extract<\n DocumentOperation,\n {\n type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n>;\n\nconst outcome = (operation: TreeOperation, value: tree.TreeOutcome): MutationOutcome =>\n value.status === 'rejected'\n ? {\n status: 'rejected',\n issue: issue.from(operation, value.code, value.message),\n }\n : value;\n\nexport const executeTree = (\n root: unknown,\n target: ResolvedAddress,\n operation: TreeOperation,\n copyPayload: boolean\n): MutationOutcome => {\n if (target.node.kind !== 'tree')\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n const absent =\n target.value === undefined && 'optional' in target.node && target.node.optional === true;\n if (operation.type === 'tree.replace') {\n if (absent) {\n if (!tree.validate(operation.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-tree', 'Tree replacement is malformed.'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [{ type: 'value.clear', at: operation.at }] };\n }\n if (!tree.is(target.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n const result = tree.replace(target.value, operation);\n if (result.status === 'changed') setAddress(root, operation.at, ownPayload(operation.value));\n return outcome(operation, result);\n }\n if (!tree.is(target.value))\n return {\n status: 'rejected',\n issue: issue.from(operation, 'invalid-address', 'Tree target is invalid.'),\n };\n if (operation.type === 'tree.insert')\n return outcome(operation, tree.insert(target.value, operation, own(operation.value)));\n if (operation.type === 'tree.set')\n return outcome(operation, tree.set(target.value, operation, own(operation.value)));\n if (operation.type === 'tree.remove')\n return outcome(operation, tree.remove(target.value, operation));\n return outcome(operation, tree.move(target.value, operation));\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport { cloneValue, isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\n\ntype ValueOperation = Extract<\n DocumentOperation,\n {\n type:\n 'field.set' | 'field.clear' | 'variant.replace' | 'dict.set' | 'dict.delete' | 'dict.replace';\n }\n>;\n\nconst rejected = (\n operation: ValueOperation,\n code: Extract<import('./issue').MutationIssueCode, 'invalid-address' | 'required-field'>,\n message: string\n): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(operation, code, message),\n});\n\nexport const executeValue = (\n target: ResolvedAddress,\n operation: ValueOperation,\n copyPayload: boolean\n): MutationOutcome => {\n const own = <T>(value: T): T => (copyPayload ? ownPayload(value) : value);\n\n if (operation.type === 'field.set' || operation.type === 'field.clear') {\n const existed = Object.prototype.hasOwnProperty.call(target.parent, target.key);\n if (operation.type === 'field.clear') {\n if (target.node.kind !== 'field' || !target.node.optional)\n return rejected(operation, 'required-field', 'Only optional fields can be cleared.');\n if (!existed) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'field.set',\n at: operation.at,\n value: target.value,\n };\n delete (target.parent as Record<string | number, unknown>)[target.key];\n return { status: 'changed', inverse: [inverse] };\n }\n if (existed && Object.is(target.value, operation.value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = existed\n ? { type: 'field.set', at: operation.at, value: target.value }\n : { type: 'field.clear', at: operation.at };\n (target.parent as Record<string | number, unknown>)[target.key] = operation.value;\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'variant.replace') {\n if (sameStructuralValue(target.value, operation.value)) return { status: 'unchanged' };\n if (target.value === undefined && target.node.optional) {\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [{ type: 'value.clear', at: operation.at }] };\n }\n const inverse: DocumentOperation = {\n type: 'variant.replace',\n at: operation.at,\n value: ownPayload(target.value, 'inverse'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n\n if (operation.type === 'dict.replace' && target.value === undefined) {\n if (!('optional' in target.node) || !target.node.optional)\n return rejected(operation, 'invalid-address', 'Dictionary target is invalid.');\n const inverse: DocumentOperation = { type: 'value.clear', at: operation.at };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n if (!isRecord(target.value))\n return rejected(operation, 'invalid-address', 'Dictionary target is invalid.');\n if (operation.type === 'dict.replace') {\n if (sameStructuralValue(target.value, operation.value)) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'dict.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n (target.parent as Record<string | number, unknown>)[target.key] = own(operation.value);\n return { status: 'changed', inverse: [inverse] };\n }\n const existed = Object.prototype.hasOwnProperty.call(target.value, operation.key);\n if (operation.type === 'dict.delete') {\n if (!existed) return { status: 'unchanged' };\n const inverse: DocumentOperation = {\n type: 'dict.set',\n at: operation.at,\n key: operation.key,\n value: target.value[operation.key],\n };\n delete target.value[operation.key];\n return { status: 'changed', inverse: [inverse] };\n }\n if (existed && Object.is(target.value[operation.key], operation.value))\n return { status: 'unchanged' };\n const inverse: DocumentOperation = existed\n ? {\n type: 'dict.set',\n at: operation.at,\n key: operation.key,\n value: target.value[operation.key],\n }\n : { type: 'dict.delete', at: operation.at, key: operation.key };\n target.value[operation.key] = operation.value;\n return { status: 'changed', inverse: [inverse] };\n};\n","import type { ResolvedAddress } from '../address';\nimport type { DocumentOperation } from '../operations';\nimport type { MutationOutcome } from './contract';\nimport * as issue from './issue';\nimport { executeEntity } from './execute-entity';\nimport { executeList } from './execute-list';\nimport { executeTree } from './execute-tree';\nimport { executeValue } from './execute-value';\nimport { cloneValue } from '../value/ownership';\n\nconst hasOwn = (value: object, key: string | number): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst executeClear = (\n target: ResolvedAddress,\n operation: Extract<DocumentOperation, { type: 'value.clear' }>\n): MutationOutcome => {\n if (!('optional' in target.node) || !target.node.optional)\n return {\n status: 'rejected',\n issue: issue.from(operation, 'required-field', 'Only optional values can be cleared.'),\n };\n if (!hasOwn(target.parent, target.key)) return { status: 'unchanged' };\n if (\n target.node.kind !== 'field' &&\n target.node.kind !== 'variant' &&\n target.node.kind !== 'dict' &&\n target.node.kind !== 'list' &&\n target.node.kind !== 'tree'\n )\n return {\n status: 'rejected',\n issue: issue.from(\n operation,\n 'invalid-operation',\n 'This optional value has no clear operation.'\n ),\n };\n\n const inverse: DocumentOperation = (() => {\n switch (target.node.kind) {\n case 'field':\n return { type: 'field.set', at: operation.at, value: target.value };\n case 'variant':\n return {\n type: 'variant.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n case 'dict':\n return {\n type: 'dict.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse') as Record<string, unknown>,\n };\n case 'list': {\n if (!Array.isArray(target.value))\n return { type: 'list.replace', at: operation.at, value: [], keys: [] };\n return {\n type: 'list.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n keys: target.value.map(target.node.keyOf),\n };\n }\n case 'tree':\n return {\n type: 'tree.replace',\n at: operation.at,\n value: cloneValue(target.value, 'inverse'),\n };\n }\n })();\n delete (target.parent as Record<string | number, unknown>)[target.key];\n return { status: 'changed', inverse: [inverse] };\n};\n\nconst invalidTarget = (operation: DocumentOperation): MutationOutcome => ({\n status: 'rejected',\n issue: issue.from(\n operation,\n 'invalid-address',\n `Operation '${operation.type}' does not match the schema address.`\n ),\n});\n\n// Operations reach this dispatcher only after operation.decode and\n// operation.normalize. Executors therefore only validate their domain-specific\n// semantics against one resolved schema address.\nexport const execute = (\n root: unknown,\n operation: DocumentOperation,\n target: ResolvedAddress | undefined,\n copyPayload: boolean\n): MutationOutcome => {\n if (operation.type === 'value.clear')\n return !target ? invalidTarget(operation) : executeClear(target, operation);\n\n if (operation.type === 'field.set' || operation.type === 'field.clear')\n return !target || target.node.kind !== 'field'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (operation.type === 'variant.replace')\n return !target || target.node.kind !== 'variant'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (\n operation.type === 'dict.set' ||\n operation.type === 'dict.delete' ||\n operation.type === 'dict.replace'\n )\n return !target || target.node.kind !== 'dict'\n ? invalidTarget(operation)\n : executeValue(target, operation, copyPayload);\n\n if (\n operation.type === 'entity.create' ||\n operation.type === 'entity.remove' ||\n operation.type === 'entity.move'\n )\n return !target || (target.node.kind !== 'table' && target.node.kind !== 'map')\n ? invalidTarget(operation)\n : executeEntity(target, operation, copyPayload);\n\n if (\n operation.type === 'list.insert' ||\n operation.type === 'list.move' ||\n operation.type === 'list.remove' ||\n operation.type === 'list.replace'\n )\n return !target || target.node.kind !== 'list'\n ? invalidTarget(operation)\n : executeList(target, operation, copyPayload);\n\n if (\n operation.type === 'tree.insert' ||\n operation.type === 'tree.move' ||\n operation.type === 'tree.remove' ||\n operation.type === 'tree.set' ||\n operation.type === 'tree.replace'\n )\n return !target || target.node.kind !== 'tree'\n ? invalidTarget(operation)\n : executeTree(root, target, operation, copyPayload);\n\n return {\n status: 'rejected',\n issue: issue.from(operation, 'unknown-operation', 'Unknown document operation.'),\n };\n};\n","import { locate, read } from '../address';\nimport type { ResolvedAddress } from '../address';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\nimport type { DocumentAddress, DocumentNode } from '../schema';\nimport { profile } from '../profile';\nimport { isRecord, ownPayload, sameStructuralValue } from '../value/ownership';\nimport * as anchor from './anchor';\nimport type { MutationCollectionChange } from './contract';\nimport {\n resolveEntityCollection,\n type EntityCollection,\n type EntityCollectionResolution,\n} from './execute-entity';\nimport * as tree from './tree';\n\ntype CollectionContext = NonNullable<ResolvedAddress['collection']>;\ntype ListNode = Extract<DocumentNode, { readonly kind: 'list' }>;\ntype EntityNode = Extract<DocumentNode, { readonly kind: 'table' | 'map' }>;\n\ntype Presence =\n { readonly status: 'absent' } | { readonly status: 'present'; readonly value: unknown };\n\ntype SubjectBase = {\n readonly address: DocumentAddress;\n readonly addressHash: number;\n readonly collection?: CollectionContext;\n};\n\ntype ValueSubject = SubjectBase & {\n readonly kind: 'value';\n readonly before: Presence;\n};\n\ntype VariantSubject = SubjectBase & {\n readonly kind: 'variant';\n readonly before: Presence;\n};\n\ntype DictState =\n | { readonly mode: 'incremental'; readonly entries: Map<string, Presence> }\n | { readonly mode: 'whole'; readonly value: Readonly<Record<string, unknown>> };\n\ntype DictSubject = SubjectBase & {\n readonly kind: 'dict';\n state: DictState;\n};\n\ntype EntityOrderInverse =\n | { readonly kind: 'remove'; readonly ids: readonly string[] }\n | {\n readonly kind: 'restore';\n readonly ids: readonly string[];\n readonly positions: readonly number[];\n }\n | { readonly kind: 'move'; readonly id: string; readonly anchor?: DocumentAnchor };\n\ntype EntityOrder =\n | { readonly kind: 'unordered' }\n | { readonly kind: 'stable'; readonly inverses: EntityOrderInverse[] }\n | { readonly kind: 'tracked'; readonly before: readonly string[] };\n\ntype EntitySubject = SubjectBase & {\n readonly kind: 'entity';\n readonly node: EntityNode;\n readonly entries: Map<string, Presence>;\n order: EntityOrder;\n};\n\ntype ListState =\n | {\n readonly mode: 'incremental';\n readonly items: Map<string, Presence>;\n readonly order: readonly string[];\n }\n | { readonly mode: 'whole'; readonly value: unknown };\n\ntype ListSubject = SubjectBase & {\n readonly kind: 'list';\n readonly node: ListNode;\n state: ListState;\n};\n\ntype TreeSubject = SubjectBase & {\n readonly kind: 'tree';\n state: tree.TreeChange;\n};\n\ntype ChangeSubject =\n ValueSubject | VariantSubject | DictSubject | EntitySubject | ListSubject | TreeSubject;\n\ntype EntityAnalysis = {\n readonly changed: boolean;\n readonly added: ReadonlySet<string>;\n readonly removed: ReadonlySet<string>;\n readonly updated: ReadonlySet<string>;\n readonly orderChanged: boolean;\n};\n\ntype JournalFinish =\n | { readonly status: 'unchanged' }\n | {\n readonly status: 'changed';\n readonly paths: readonly DocumentAddress[];\n readonly collections: readonly MutationCollectionChange[];\n };\n\ntype ChangeJournal = {\n readonly record: (\n resolved: ResolvedAddress,\n operation: DocumentOperation,\n inverse: readonly DocumentOperation[]\n ) => void;\n readonly finish: () => JournalFinish;\n};\n\ntype AddressIndexNode = {\n readonly children: Map<string, AddressIndexNode>;\n subject?: ChangeSubject;\n};\n\nconst indexNode = (): AddressIndexNode => ({ children: new Map() });\nconst hasOwn = (value: object, key: string | number): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\n\nconst sameAddress = (left: DocumentAddress, right: DocumentAddress): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst sameOrder = (left: readonly string[], right: readonly string[]): boolean => {\n if (left.length !== right.length) return false;\n for (let index = 0; index < left.length; index += 1)\n if (left[index] !== right[index]) return false;\n return true;\n};\n\nconst replaceArray = <T>(target: T[], value: readonly T[]): void => {\n target.length = value.length;\n for (let index = 0; index < value.length; index += 1) target[index] = value[index];\n};\n\nconst present = (value: unknown): Presence => ({ status: 'present', value });\nconst absent: Presence = Object.freeze({ status: 'absent' });\nconst inverseMismatch = (operation: DocumentOperation): never => {\n throw new Error(`Mutation inverse does not match '${operation.type}'.`);\n};\n\nconst ownsDescendant = (subject: ChangeSubject, address: DocumentAddress): boolean => {\n if (subject.address.length >= address.length) return false;\n if (subject.kind === 'variant') return true;\n if (subject.kind !== 'entity') return false;\n return subject.entries.has(address[subject.address.length]);\n};\n\nconst nodeAt = (root: AddressIndexNode, address: DocumentAddress): AddressIndexNode | undefined => {\n let node: AddressIndexNode | undefined = root;\n for (const segment of address) {\n node = node.children.get(segment);\n if (!node) return undefined;\n }\n return node;\n};\n\nconst indexedSubjects = (root: AddressIndexNode, address: DocumentAddress): ChangeSubject[] => {\n const start = nodeAt(root, address);\n if (!start) return [];\n const subjects: ChangeSubject[] = [];\n const stack = [start];\n while (stack.length) {\n const node = stack.pop();\n if (!node) break;\n if (node.subject) subjects.push(node.subject);\n for (const child of node.children.values()) stack.push(child);\n }\n return subjects;\n};\n\nconst writePresence = (root: unknown, address: DocumentAddress, before: Presence): void => {\n const target = locate(root, address);\n if (!target) return;\n if (before.status === 'present')\n (target.parent as Record<string | number, unknown>)[target.key] = before.value;\n else if (Array.isArray(target.parent)) target.parent.splice(Number(target.key), 1);\n else delete target.parent[String(target.key)];\n};\n\nconst writeContainer = (root: unknown, address: DocumentAddress, value: unknown): void => {\n const target = locate(root, address);\n if (!target) return;\n (target.parent as Record<string | number, unknown>)[target.key] = value;\n};\n\nconst restoreDict = (value: Record<string, unknown>, state: DictState): void => {\n if (state.mode === 'whole') {\n for (const key of Object.keys(value)) delete value[key];\n for (const [key, entry] of Object.entries(state.value)) value[key] = entry;\n return;\n }\n for (const [key, before] of state.entries) {\n if (before.status === 'present') value[key] = before.value;\n else delete value[key];\n }\n};\n\nconst restoreList = (value: unknown[], subject: ListSubject): void => {\n if (subject.state.mode === 'whole') {\n replaceArray(value, subject.state.value as readonly unknown[]);\n return;\n }\n const entries = new Map<string, unknown>();\n for (const entry of value) entries.set(subject.node.keyOf(entry), entry);\n for (const [key, before] of subject.state.items) {\n if (before.status === 'present') entries.set(key, before.value);\n else entries.delete(key);\n }\n const restored = new Array<unknown>(subject.state.order.length);\n for (let index = 0; index < subject.state.order.length; index += 1)\n restored[index] = entries.get(subject.state.order[index]);\n replaceArray(value, restored);\n};\n\nconst entityCollection = (subject: EntitySubject, value: unknown): EntityCollectionResolution =>\n resolveEntityCollection(subject.node, value);\n\nconst restoreEntity = (value: unknown, subject: EntitySubject): void => {\n const resolution = entityCollection(subject, value);\n if (resolution.status === 'invalid') return;\n const collection = resolution.collection;\n for (const [id, before] of subject.entries) {\n if (before.status === 'present') collection.byId[id] = before.value;\n else delete collection.byId[id];\n }\n if (collection.kind !== 'table') return;\n if (subject.order.kind === 'tracked') {\n replaceArray(collection.ids, subject.order.before);\n return;\n }\n if (subject.order.kind === 'stable') restoreEntityOrder(collection.ids, subject.order.inverses);\n};\n\nconst restoreRootSubject = (value: unknown, subject: ChangeSubject): unknown => {\n if (subject.kind === 'value')\n return subject.before.status === 'present' ? subject.before.value : undefined;\n if (subject.kind === 'variant')\n return subject.before.status === 'present' ? subject.before.value : undefined;\n if (subject.kind === 'dict') {\n if (isRecord(value)) restoreDict(value, subject.state);\n return value;\n }\n if (subject.kind === 'entity') {\n restoreEntity(value, subject);\n return value;\n }\n if (subject.kind === 'list') {\n if (Array.isArray(value)) restoreList(value, subject);\n return value;\n }\n return tree.restoreChange(value, subject.state);\n};\n\nconst restoreSubject = (\n value: unknown,\n prefix: DocumentAddress,\n subject: ChangeSubject\n): unknown => {\n if (sameAddress(prefix, subject.address)) return restoreRootSubject(value, subject);\n const address = subject.address.slice(prefix.length);\n if (subject.kind === 'value') {\n writePresence(value, address, subject.before);\n return value;\n }\n if (subject.kind === 'variant') {\n writePresence(value, address, subject.before);\n return value;\n }\n const current = read(value, address);\n if (subject.kind === 'dict') {\n if (isRecord(current)) restoreDict(current, subject.state);\n return value;\n }\n if (subject.kind === 'entity') {\n restoreEntity(current, subject);\n return value;\n }\n if (subject.kind === 'list') {\n if (Array.isArray(current)) restoreList(current, subject);\n return value;\n }\n const restored = tree.restoreChange(current, subject.state);\n if (restored !== current) writeContainer(value, address, restored);\n return value;\n};\n\nconst valueChanged = (root: unknown, subject: ValueSubject): boolean => {\n const target = locate(root, subject.address);\n const exists = !!target && hasOwn(target.parent, target.key);\n if (subject.before.status === 'absent') return exists;\n return !exists || !Object.is(subject.before.value, target?.value);\n};\n\nconst dictChanged = (root: unknown, subject: DictSubject): boolean => {\n const value = read(root, subject.address);\n if (!isRecord(value)) return true;\n if (subject.state.mode === 'whole') return !sameStructuralValue(subject.state.value, value);\n for (const [key, before] of subject.state.entries) {\n const exists = hasOwn(value, key);\n if (before.status === 'absent' ? exists : !exists || !Object.is(before.value, value[key]))\n return true;\n }\n return false;\n};\n\nconst listChanged = (root: unknown, subject: ListSubject): boolean => {\n const value = read(root, subject.address);\n if (!Array.isArray(value)) return true;\n if (subject.state.mode === 'whole') return !sameStructuralValue(subject.state.value, value);\n const positions = new Map<string, number>();\n const order = new Array<string>(value.length);\n for (let index = 0; index < value.length; index += 1) {\n const key = subject.node.keyOf(value[index]);\n order[index] = key;\n positions.set(key, index);\n }\n if (!sameOrder(subject.state.order, order)) return true;\n for (const [key, before] of subject.state.items) {\n const position = positions.get(key);\n if (before.status === 'absent') {\n if (position !== undefined) return true;\n } else if (position === undefined || !sameStructuralValue(before.value, value[position]))\n return true;\n }\n return false;\n};\n\nconst commonOrderChanged = (before: readonly string[], after: readonly string[]): boolean => {\n const finalPositions = new Map<string, number>();\n for (let index = 0; index < after.length; index += 1) finalPositions.set(after[index], index);\n let previous = -1;\n for (const id of before) {\n const position = finalPositions.get(id);\n if (position === undefined) continue;\n if (position < previous) return true;\n previous = position;\n }\n return false;\n};\n\nconst analyzeEntity = (root: unknown, subject: EntitySubject): EntityAnalysis => {\n const resolution = entityCollection(subject, read(root, subject.address));\n const added = new Set<string>();\n const removed = new Set<string>();\n const updated = new Set<string>();\n if (resolution.status === 'invalid')\n return { changed: true, added, removed, updated, orderChanged: false };\n const collection = resolution.collection;\n for (const [id, before] of subject.entries) {\n const exists = hasOwn(collection.byId, id);\n if (before.status === 'absent') {\n if (exists) added.add(id);\n } else if (!exists) removed.add(id);\n else if (!sameStructuralValue(before.value, collection.byId[id])) updated.add(id);\n }\n const beforeOrder = subject.order.kind === 'tracked' ? subject.order.before : undefined;\n const finalOrder = collection.kind === 'table' ? collection.ids : [];\n const netOrderChanged = beforeOrder !== undefined && !sameOrder(beforeOrder, finalOrder);\n return {\n changed: added.size > 0 || removed.size > 0 || updated.size > 0 || netOrderChanged,\n added,\n removed,\n updated,\n orderChanged: beforeOrder !== undefined && commonOrderChanged(beforeOrder, finalOrder),\n };\n};\n\nconst subjectChanged = (root: unknown, subject: Exclude<ChangeSubject, EntitySubject>): boolean => {\n if (subject.kind === 'value') return valueChanged(root, subject);\n if (subject.kind === 'variant') {\n const target = locate(root, subject.address);\n const exists = !!target && hasOwn(target.parent, target.key);\n return subject.before.status === 'absent'\n ? exists\n : !exists || !sameStructuralValue(subject.before.value, target?.value);\n }\n if (subject.kind === 'dict') return dictChanged(root, subject);\n if (subject.kind === 'list') return listChanged(root, subject);\n return tree.changeChanged(subject.state, read(root, subject.address));\n};\n\nconst listOrderBefore = (\n value: readonly unknown[],\n node: ListNode,\n inverse: DocumentOperation\n): readonly string[] => {\n const order = value.map(node.keyOf);\n if (inverse.type === 'list.remove') return order.filter(key => key !== inverse.key);\n if (inverse.type === 'list.insert') {\n order.splice(anchor.index(order, inverse.anchor), 0, inverse.key);\n return order;\n }\n if (inverse.type === 'list.move') {\n const position = order.indexOf(inverse.key);\n if (position >= 0) order.splice(position, 1);\n order.splice(anchor.index(order, inverse.anchor), 0, inverse.key);\n }\n return order;\n};\n\nconst recordListPresence = (\n state: Extract<ListState, { readonly mode: 'incremental' }>,\n inverse: DocumentOperation\n): void => {\n if (inverse.type === 'list.remove' && !state.items.has(inverse.key))\n state.items.set(inverse.key, absent);\n else if (inverse.type === 'list.insert' && !state.items.has(inverse.key))\n state.items.set(inverse.key, present(inverse.value));\n};\n\nconst entityOrderInverse = (\n operation: DocumentOperation,\n inverse: DocumentOperation\n): EntityOrderInverse => {\n if (inverse.type === 'entity.remove') return { kind: 'remove', ids: inverse.ids };\n if (inverse.type === 'entity.create') {\n if (!inverse.positions || inverse.positions.length !== inverse.entries.length)\n return inverseMismatch(operation);\n return {\n kind: 'restore',\n ids: inverse.entries.map(entry => entry.id),\n positions: inverse.positions,\n };\n }\n if (inverse.type === 'entity.move')\n return {\n kind: 'move',\n id: inverse.id,\n ...(inverse.anchor ? { anchor: inverse.anchor } : {}),\n };\n return inverseMismatch(operation);\n};\n\nconst removeEntityIds = (order: string[], ids: readonly string[]): void => {\n const removed = new Set(ids);\n let writeIndex = 0;\n for (const id of order) if (!removed.has(id)) order[writeIndex++] = id;\n order.length = writeIndex;\n};\n\nconst restoreEntityOrder = (order: string[], inverses: readonly EntityOrderInverse[]): void => {\n for (let index = inverses.length - 1; index >= 0; index -= 1) {\n const inverse = inverses[index];\n if (inverse.kind === 'remove') {\n removeEntityIds(order, inverse.ids);\n continue;\n }\n if (inverse.kind === 'restore') {\n anchor.restore(order, inverse.ids, inverse.positions);\n continue;\n }\n const position = order.indexOf(inverse.id);\n if (position < 0 || !anchor.valid(order, inverse.anchor))\n throw new Error(`Entity order inverse cannot restore '${inverse.id}'.`);\n const nextIndex = anchor.afterRemove(order, position, inverse.anchor);\n order.splice(position, 1);\n order.splice(nextIndex, 0, inverse.id);\n }\n};\n\nconst treeOperation = (\n operation: DocumentOperation\n): operation is Extract<\n DocumentOperation,\n {\n readonly type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n> => operation.type.startsWith('tree.');\n\nexport const createChangeJournal = (root: unknown): ChangeJournal => {\n const active = new Set<ChangeSubject>();\n const index = indexNode();\n const buckets = new Map<number, ChangeSubject[]>();\n\n const add = <TSubject extends ChangeSubject>(subject: TSubject): TSubject => {\n active.add(subject);\n const candidates = buckets.get(subject.addressHash);\n if (candidates) candidates.push(subject);\n else buckets.set(subject.addressHash, [subject]);\n let node = index;\n for (const segment of subject.address) {\n const existing = node.children.get(segment);\n if (existing) node = existing;\n else {\n const created = indexNode();\n node.children.set(segment, created);\n node = created;\n }\n }\n if (node.subject)\n throw new Error(`Change journal already owns '${subject.address.join('.')}'.`);\n node.subject = subject;\n profile.journal.subject();\n return subject;\n };\n\n const remove = (subject: ChangeSubject): void => {\n if (!active.delete(subject)) return;\n const candidates = buckets.get(subject.addressHash);\n if (candidates) {\n const position = candidates.indexOf(subject);\n if (position >= 0) candidates.splice(position, 1);\n if (candidates.length === 0) buckets.delete(subject.addressHash);\n }\n const nodes: AddressIndexNode[] = [index];\n let node = index;\n for (const segment of subject.address) {\n const child = node.children.get(segment);\n if (!child) return;\n nodes.push(child);\n node = child;\n }\n if (node.subject === subject) delete node.subject;\n for (let position = subject.address.length - 1; position >= 0; position -= 1) {\n const child = nodes[position + 1];\n if (child.subject || child.children.size > 0) break;\n nodes[position].children.delete(subject.address[position]);\n }\n };\n\n function find(\n kind: 'value',\n address: DocumentAddress,\n addressHash: number\n ): ValueSubject | undefined;\n function find(\n kind: 'variant',\n address: DocumentAddress,\n addressHash: number\n ): VariantSubject | undefined;\n function find(\n kind: 'dict',\n address: DocumentAddress,\n addressHash: number\n ): DictSubject | undefined;\n function find(\n kind: 'entity',\n address: DocumentAddress,\n addressHash: number\n ): EntitySubject | undefined;\n function find(\n kind: 'list',\n address: DocumentAddress,\n addressHash: number\n ): ListSubject | undefined;\n function find(\n kind: 'tree',\n address: DocumentAddress,\n addressHash: number\n ): TreeSubject | undefined;\n function find(\n kind: ChangeSubject['kind'],\n address: DocumentAddress,\n addressHash: number\n ): ChangeSubject | undefined {\n const candidates = buckets.get(addressHash) ?? [];\n for (const subject of candidates) {\n profile.journal.comparison();\n if (subject.kind === kind && sameAddress(subject.address, address)) return subject;\n }\n return undefined;\n }\n\n const ownerOf = (address: DocumentAddress): ChangeSubject | undefined => {\n let node = index;\n for (let position = 0; position < address.length; position += 1) {\n if (node.subject && ownsDescendant(node.subject, address)) return node.subject;\n const child = node.children.get(address[position]);\n if (!child) return undefined;\n node = child;\n }\n return undefined;\n };\n\n const absorb = (value: unknown, address: DocumentAddress): unknown => {\n const subjects = indexedSubjects(index, address);\n if (subjects.length === 0) return value;\n subjects.sort((left, right) => left.address.length - right.address.length);\n let before = ownPayload(value, 'journal');\n for (const subject of subjects) before = restoreSubject(before, address, subject);\n for (const subject of subjects) {\n remove(subject);\n profile.journal.absorbed();\n }\n return before;\n };\n\n const base = (resolved: ResolvedAddress, operation: DocumentOperation): SubjectBase => ({\n address: operation.at,\n addressHash: resolved.addressHash,\n ...(resolved.collection ? { collection: resolved.collection } : {}),\n });\n\n const recordValue = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'field.set' | 'field.clear' | 'value.clear' | 'dict.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (find('value', operation.at, resolved.addressHash)) return;\n const first = inverse[0];\n if (\n first?.type !== 'field.set' &&\n first?.type !== 'field.clear' &&\n first?.type !== 'value.clear' &&\n !('value' in (first ?? {}))\n )\n return inverseMismatch(operation);\n const before =\n first.type === 'field.clear' || first.type === 'value.clear'\n ? absent\n : 'value' in first\n ? present(first.value)\n : inverseMismatch(operation);\n add<ValueSubject>({\n ...base(resolved, operation),\n kind: 'value',\n before,\n });\n };\n\n const recordVariant = (\n resolved: ResolvedAddress,\n operation: Extract<DocumentOperation, { readonly type: 'variant.replace' | 'value.clear' }>,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (find('variant', operation.at, resolved.addressHash)) return;\n const first = inverse[0];\n if (first?.type !== 'variant.replace' && first?.type !== 'value.clear')\n return inverseMismatch(operation);\n add<VariantSubject>({\n ...base(resolved, operation),\n kind: 'variant',\n before: first.type === 'value.clear' ? absent : present(absorb(first.value, operation.at)),\n });\n };\n\n const recordDict = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'dict.set' | 'dict.delete' | 'dict.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n const subject =\n find('dict', operation.at, resolved.addressHash) ??\n add<DictSubject>({\n ...base(resolved, operation),\n kind: 'dict',\n state: { mode: 'incremental', entries: new Map() },\n });\n if (subject.state.mode === 'whole') return;\n if (first.type === 'dict.replace') {\n const value = ownPayload(first.value, 'journal');\n restoreDict(value, subject.state);\n subject.state = { mode: 'whole', value };\n return;\n }\n if (first.type !== 'dict.set' && first.type !== 'dict.delete')\n return inverseMismatch(operation);\n if (!subject.state.entries.has(first.key))\n subject.state.entries.set(\n first.key,\n first.type === 'dict.set' ? present(first.value) : absent\n );\n };\n\n const recordList = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'list.insert' | 'list.move' | 'list.remove' | 'list.replace' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (resolved.node.kind !== 'list') return inverseMismatch(operation);\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n let subject = find('list', operation.at, resolved.addressHash);\n if (!subject) {\n if (first.type === 'value.clear') {\n add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: { mode: 'whole', value: undefined },\n });\n return;\n }\n if (first.type === 'list.replace') {\n add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: { mode: 'whole', value: first.value },\n });\n return;\n }\n const value = read(root, operation.at);\n if (!Array.isArray(value)) return inverseMismatch(operation);\n subject = add<ListSubject>({\n ...base(resolved, operation),\n kind: 'list',\n node: resolved.node,\n state: {\n mode: 'incremental',\n items: new Map(),\n order: listOrderBefore(value, resolved.node, first),\n },\n });\n }\n if (subject.state.mode === 'whole') return;\n if (first.type === 'list.replace') {\n const value = Array.from(ownPayload(first.value, 'journal'));\n restoreList(value, subject);\n subject.state = { mode: 'whole', value };\n return;\n }\n if (first.type !== 'list.insert' && first.type !== 'list.move' && first.type !== 'list.remove')\n return inverseMismatch(operation);\n recordListPresence(subject.state, first);\n };\n\n const trackEntityOrder = (\n subject: EntitySubject,\n collection: Extract<EntityCollection, { readonly kind: 'table' }>\n ): void => {\n if (subject.order.kind !== 'stable') return;\n profile.journal.orderSnapshot(collection.ids.length);\n const before = [...collection.ids];\n restoreEntityOrder(before, subject.order.inverses);\n subject.order = { kind: 'tracked', before };\n };\n\n const recordEntity = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n { readonly type: 'entity.create' | 'entity.remove' | 'entity.move' }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n if (resolved.node.kind !== 'table' && resolved.node.kind !== 'map')\n return inverseMismatch(operation);\n const resolution = resolveEntityCollection(resolved.node, read(root, operation.at));\n if (resolution.status === 'invalid') return inverseMismatch(operation);\n const collection = resolution.collection;\n const subject =\n find('entity', operation.at, resolved.addressHash) ??\n add<EntitySubject>({\n ...base(resolved, operation),\n kind: 'entity',\n node: resolved.node,\n entries: new Map(),\n order:\n collection.kind === 'table' ? { kind: 'stable', inverses: [] } : { kind: 'unordered' },\n });\n const first = inverse[0];\n if (!first) return inverseMismatch(operation);\n\n if (collection.kind === 'table' && subject.order.kind === 'stable')\n subject.order.inverses.push(entityOrderInverse(operation, first));\n\n if (first.type === 'entity.remove') {\n for (const id of first.ids) if (!subject.entries.has(id)) subject.entries.set(id, absent);\n if (\n collection.kind === 'table' &&\n first.ids.some(id => subject.entries.get(id)?.status === 'present')\n )\n trackEntityOrder(subject, collection);\n return;\n }\n\n if (first.type === 'entity.create') {\n for (const entry of first.entries) {\n if (subject.entries.has(entry.id)) continue;\n const address = [...operation.at, entry.id];\n subject.entries.set(entry.id, present(absorb(entry.value, address)));\n }\n return;\n }\n\n if (first.type === 'entity.move') {\n if (collection.kind === 'table' && subject.entries.get(first.id)?.status !== 'absent')\n trackEntityOrder(subject, collection);\n return;\n }\n return inverseMismatch(operation);\n };\n\n const recordTree = (\n resolved: ResolvedAddress,\n operation: Extract<\n DocumentOperation,\n {\n readonly type: 'tree.insert' | 'tree.move' | 'tree.remove' | 'tree.set' | 'tree.replace';\n }\n >,\n inverse: readonly DocumentOperation[]\n ): void => {\n const current = read(root, operation.at);\n if (\n inverse.length === 1 &&\n inverse[0].type === 'value.clear' &&\n operation.type === 'tree.replace'\n ) {\n const subject = find('tree', operation.at, resolved.addressHash);\n if (subject) subject.state = { mode: 'whole', value: undefined };\n else\n add<TreeSubject>({\n ...base(resolved, operation),\n kind: 'tree',\n state: { mode: 'whole', value: undefined },\n });\n return;\n }\n if (!tree.is(current)) return inverseMismatch(operation);\n const inverses = inverse.filter(treeOperation);\n if (inverses.length === 0 || inverses.length !== inverse.length)\n return inverseMismatch(operation);\n const subject = find('tree', operation.at, resolved.addressHash);\n const state = tree.recordChange(subject?.state, current, operation, inverses);\n if (subject) subject.state = state;\n else add<TreeSubject>({ ...base(resolved, operation), kind: 'tree', state });\n };\n\n return {\n record: (resolved, operation, inverse) => {\n profile.batch.journalRecord();\n if (ownerOf(operation.at)) return;\n if (operation.type === 'value.clear' && resolved.node.kind === 'variant') {\n recordVariant(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'field.set' ||\n operation.type === 'field.clear' ||\n operation.type === 'value.clear'\n ) {\n recordValue(resolved, operation, inverse);\n return;\n }\n if (operation.type === 'variant.replace') {\n recordVariant(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'dict.set' ||\n operation.type === 'dict.delete' ||\n operation.type === 'dict.replace'\n ) {\n if (operation.type === 'dict.replace' && inverse[0]?.type === 'value.clear')\n recordValue(resolved, operation, inverse);\n else recordDict(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'entity.create' ||\n operation.type === 'entity.remove' ||\n operation.type === 'entity.move'\n ) {\n recordEntity(resolved, operation, inverse);\n return;\n }\n if (\n operation.type === 'list.insert' ||\n operation.type === 'list.move' ||\n operation.type === 'list.remove' ||\n operation.type === 'list.replace'\n ) {\n recordList(resolved, operation, inverse);\n return;\n }\n recordTree(resolved, operation, inverse);\n },\n finish: () => {\n const changed: ChangeSubject[] = [];\n const entityChanges = new Map<EntitySubject, EntityAnalysis>();\n for (const subject of active) {\n profile.journal.comparison();\n if (subject.kind === 'entity') {\n const analysis = analyzeEntity(root, subject);\n if (!analysis.changed) continue;\n entityChanges.set(subject, analysis);\n changed.push(subject);\n } else if (subjectChanged(root, subject)) changed.push(subject);\n }\n if (changed.length === 0) return { status: 'unchanged' };\n\n const collections: Array<{\n address: DocumentAddress;\n added: Set<string>;\n removed: Set<string>;\n updated: Set<string>;\n orderChanged: boolean;\n }> = [];\n const collectionBuckets = new Map<number, (typeof collections)[number][]>();\n const changeAt = (address: DocumentAddress, addressHash: number) => {\n const candidates = collectionBuckets.get(addressHash) ?? [];\n collectionBuckets.set(addressHash, candidates);\n let change = candidates.find(entry => sameAddress(entry.address, address));\n if (!change) {\n change = {\n address,\n added: new Set(),\n removed: new Set(),\n updated: new Set(),\n orderChanged: false,\n };\n candidates.push(change);\n collections.push(change);\n }\n return change;\n };\n\n for (const subject of changed) {\n if (subject.kind === 'entity') {\n const analysis = entityChanges.get(subject);\n if (analysis) {\n const change = changeAt(subject.address, subject.addressHash);\n analysis.added.forEach(id => change.added.add(id));\n analysis.removed.forEach(id => change.removed.add(id));\n analysis.updated.forEach(id => change.updated.add(id));\n if (analysis.orderChanged) change.orderChanged = true;\n }\n }\n for (let collection = subject.collection; collection; collection = collection.parent)\n changeAt(collection.address, collection.addressHash).updated.add(collection.id);\n }\n for (const change of collections) {\n change.added.forEach(id => change.updated.delete(id));\n change.removed.forEach(id => change.updated.delete(id));\n }\n\n return {\n status: 'changed',\n paths: Object.freeze(changed.map(subject => subject.address)),\n collections,\n };\n },\n };\n};\n","import type { DocumentAddress } from '../schema';\nimport type { DocumentAnchor, DocumentOperation } from '../operations';\nimport { profile } from '../profile';\nimport { isRecord, isPlainObject, isStablePayload, snapshotPayload } from '../value/ownership';\nimport type { MutationIssue } from './issue';\nimport * as issue from './issue';\n\nexport type OperationDecode =\n | { readonly status: 'decoded'; readonly operation: DocumentOperation }\n | { readonly status: 'rejected'; readonly issue: MutationIssue };\nexport type OperationBatchDecode =\n | { readonly status: 'decoded'; readonly operations: readonly unknown[] }\n | { readonly status: 'rejected'; readonly issue: MutationIssue };\n\nconst has = (value: Record<string, unknown>, key: string): boolean =>\n Object.prototype.hasOwnProperty.call(value, key);\nconst stringArray = (value: unknown): value is readonly string[] =>\n Array.isArray(value) && value.every(entry => typeof entry === 'string');\nconst positions = (value: unknown): value is readonly number[] =>\n Array.isArray(value) && value.every(entry => Number.isInteger(entry) && entry >= 0);\nconst address = (value: unknown): value is DocumentAddress => stringArray(value);\nconst anchor = (value: unknown): value is DocumentAnchor => {\n if (!isRecord(value)) return false;\n const count =\n Number(has(value, 'at')) + Number(has(value, 'before')) + Number(has(value, 'after'));\n if (count !== 1) return false;\n if (has(value, 'at')) return value.at === 'start' || value.at === 'end';\n return typeof (has(value, 'before') ? value.before : value.after) === 'string';\n};\nconst optionalAnchor = (value: Record<string, unknown>): boolean =>\n !has(value, 'anchor') || value.anchor === undefined || anchor(value.anchor);\nconst optionalParent = (value: Record<string, unknown>): boolean =>\n !has(value, 'parentId') || value.parentId === undefined || typeof value.parentId === 'string';\nconst optionalIndex = (value: Record<string, unknown>): boolean =>\n !has(value, 'index') ||\n value.index === undefined ||\n (Number.isInteger(value.index) && (value.index as number) >= 0);\nconst entries = (value: unknown): boolean =>\n Array.isArray(value) &&\n value.every(entry => isRecord(entry) && typeof entry.id === 'string' && has(entry, 'value'));\n\nconst decoded = (operation: DocumentOperation): OperationDecode => ({\n status: 'decoded',\n operation,\n});\nconst rejected = (code: MutationIssue['code'], message: string): OperationDecode => ({\n status: 'rejected',\n issue: issue.input(code, message),\n});\n\nexport const decode = (input: unknown): OperationDecode => {\n if (!isRecord(input)) return rejected('invalid-operation', 'Operation must be an object.');\n if (!address(input.at)) return rejected('invalid-address', 'Operation address is malformed.');\n if (typeof input.type !== 'string')\n return rejected('invalid-operation', 'Operation type must be a string.');\n\n switch (input.type) {\n case 'field.set':\n case 'variant.replace':\n return has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Operation value is required.');\n case 'field.clear':\n case 'value.clear':\n return decoded(input as DocumentOperation);\n case 'dict.set':\n return typeof input.key === 'string' && has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary set requires a string key and value.');\n case 'dict.delete':\n return typeof input.key === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary delete requires a string key.');\n case 'dict.replace':\n return isRecord(input.value)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Dictionary replacement must be an object.');\n case 'entity.create':\n return entries(input.entries) &&\n optionalAnchor(input) &&\n (!has(input, 'positions') || input.positions === undefined || positions(input.positions))\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity create payload is malformed.');\n case 'entity.remove':\n return stringArray(input.ids)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity remove requires string ids.');\n case 'entity.move':\n return typeof input.id === 'string' && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Entity move payload is malformed.');\n case 'list.insert':\n return typeof input.key === 'string' && has(input, 'value') && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List insert payload is malformed.');\n case 'list.move':\n return typeof input.key === 'string' && optionalAnchor(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List move payload is malformed.');\n case 'list.remove':\n return typeof input.key === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List remove requires a string key.');\n case 'list.replace':\n return Array.isArray(input.value) && stringArray(input.keys)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'List replacement payload is malformed.');\n case 'tree.insert':\n return typeof input.treeNodeId === 'string' && optionalParent(input) && optionalIndex(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree insert payload is malformed.');\n case 'tree.move':\n return typeof input.treeNodeId === 'string' && optionalParent(input) && optionalIndex(input)\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree move payload is malformed.');\n case 'tree.remove':\n return typeof input.treeNodeId === 'string'\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree remove requires a node id.');\n case 'tree.set':\n return typeof input.treeNodeId === 'string' && has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree set payload is malformed.');\n case 'tree.replace':\n return has(input, 'value')\n ? decoded(input as DocumentOperation)\n : rejected('invalid-operation', 'Tree replacement value is required.');\n default:\n return rejected('unknown-operation', 'Unknown document operation.');\n }\n};\n\nexport const decodeBatch = (input: unknown): OperationBatchDecode =>\n Array.isArray(input)\n ? { status: 'decoded', operations: input }\n : {\n status: 'rejected',\n issue: issue.input('invalid-operation', 'Operation batch must be an array.'),\n };\n\nconst ownAddress = (value: DocumentAddress): DocumentAddress => {\n if (Object.isFrozen(value)) return value;\n profile.address.arrayCopied();\n return Object.freeze(value.slice());\n};\n\nconst structuralPayload = (value: unknown): boolean => Array.isArray(value) || isPlainObject(value);\n\nexport const normalize = (operation: DocumentOperation): DocumentOperation => {\n profile.mutation.normalized();\n const copy = {\n ...operation,\n at: ownAddress(operation.at),\n } as DocumentOperation & {\n anchor?: DocumentAnchor;\n keys?: readonly string[];\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n ids?: readonly string[];\n positions?: readonly number[];\n value?: unknown;\n };\n if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });\n if (copy.keys) copy.keys = Object.freeze([...copy.keys]);\n if (copy.entries)\n copy.entries = Object.freeze(copy.entries.map(entry => Object.freeze({ ...entry })));\n if (copy.ids) copy.ids = Object.freeze([...copy.ids]);\n if (copy.positions) copy.positions = Object.freeze([...copy.positions]);\n return Object.freeze(copy);\n};\n\nexport const publish = (operation: DocumentOperation): DocumentOperation => {\n if (\n operation.type === 'entity.create' &&\n operation.entries.every(\n entry => !structuralPayload(entry.value) || isStablePayload(entry.value)\n )\n )\n return operation;\n if (\n 'value' in operation &&\n (!structuralPayload(operation.value) || isStablePayload(operation.value))\n )\n return operation;\n const copy = { ...operation } as DocumentOperation & {\n value?: unknown;\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n };\n if (copy.entries)\n copy.entries = Object.freeze(\n copy.entries.map(entry =>\n Object.freeze({\n id: entry.id,\n value: structuralPayload(entry.value)\n ? isStablePayload(entry.value)\n ? entry.value\n : snapshotPayload(entry.value, 'commit')\n : entry.value,\n })\n )\n );\n else if ('value' in copy && structuralPayload(copy.value))\n copy.value = isStablePayload(copy.value) ? copy.value : snapshotPayload(copy.value, 'commit');\n return Object.freeze(copy);\n};\n\n// Published operation snapshots are frozen so they can be safely retained by\n// commits, history, or a persistence adapter. Replaying one must clone its\n// structural payload before it becomes canonical mutable document state.\nexport const requiresPayloadCopy = (operation: DocumentOperation): boolean => {\n if (operation.type === 'entity.create')\n return operation.entries.some(entry => isStablePayload(entry.value));\n return 'value' in operation && isStablePayload(operation.value);\n};\n\nexport const inverse = (operation: DocumentOperation): DocumentOperation => {\n const copy = { ...operation } as DocumentOperation & {\n anchor?: DocumentAnchor;\n keys?: readonly string[];\n entries?: readonly { readonly id: string; readonly value: unknown }[];\n ids?: readonly string[];\n positions?: readonly number[];\n };\n if (copy.anchor) copy.anchor = Object.freeze({ ...copy.anchor });\n if (copy.keys) copy.keys = Object.freeze([...copy.keys]);\n if (copy.entries)\n copy.entries = Object.freeze(\n copy.entries.map(entry =>\n Object.freeze({\n id: entry.id,\n value: structuralPayload(entry.value)\n ? isStablePayload(entry.value)\n ? entry.value\n : snapshotPayload(entry.value, 'inverse')\n : entry.value,\n })\n )\n );\n if (copy.ids) copy.ids = Object.freeze([...copy.ids]);\n if (copy.positions) copy.positions = Object.freeze([...copy.positions]);\n if ('value' in copy && structuralPayload(copy.value)) {\n const payload = copy as { value?: unknown };\n payload.value = isStablePayload(payload.value)\n ? payload.value\n : snapshotPayload(payload.value, 'inverse');\n }\n return Object.freeze(copy);\n};\n","import { resolveLocated } from '../address';\nimport type { DocumentSchema } from '../schema';\nimport type { DocumentOperation } from '../operations';\nimport { profile } from '../profile';\nimport type { MutationBatch } from './contract';\nimport type { MutationIssue } from './issue';\nimport { execute } from './execute';\nimport { createChangeJournal } from './journal';\nimport * as operation from './operation';\n\nexport type MutationSession<TSchema extends DocumentSchema> = {\n readonly apply: (input: unknown) => MutationIssue | undefined;\n readonly finish: () => MutationBatch<TSchema>;\n readonly rollback: () => void;\n};\n\ntype AppliedStep = {\n readonly forward: DocumentOperation;\n readonly inverse: readonly DocumentOperation[];\n};\n\nexport const createMutationSession = <TSchema extends DocumentSchema>(\n root: unknown,\n schema: TSchema,\n options: { readonly copyPayload?: boolean } = {}\n): MutationSession<TSchema> => {\n const steps: AppliedStep[] = [];\n const journal = createChangeJournal(root);\n let state: 'active' | 'finished' | 'rolled-back' = 'active';\n\n const rollback = (): void => {\n if (state === 'rolled-back') return;\n for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1) {\n for (const inverse of steps[stepIndex].inverse) {\n const target = resolveLocated(schema, root, inverse.at);\n const result = execute(root, inverse, target, true);\n if (result.status === 'rejected')\n throw new Error(`Document rollback failed: ${result.issue.message}`);\n }\n }\n state = 'rolled-back';\n };\n\n return {\n apply: input => {\n if (state !== 'active') throw new Error('Mutation session is closed.');\n profile.batch.operation();\n const decoded = operation.decode(input);\n if (decoded.status === 'rejected') {\n profile.batch.rejected();\n return decoded.issue;\n }\n const normalized = operation.normalize(decoded.operation);\n profile.batch.entry(\n normalized.type === 'entity.create'\n ? normalized.entries.length\n : normalized.type === 'entity.remove'\n ? normalized.ids.length\n : 1\n );\n const resolved = resolveLocated(schema, root, normalized.at);\n if (resolved?.collection) profile.batch.collectionResolved();\n profile.mutation.executed();\n const result = execute(\n root,\n normalized,\n resolved,\n options.copyPayload === true || operation.requiresPayloadCopy(normalized)\n );\n if (result.status === 'rejected') {\n profile.batch.rejected();\n return result.issue;\n }\n if (result.status === 'unchanged') return undefined;\n\n const published = operation.publish(normalized);\n const group: DocumentOperation[] = [];\n for (const rawInverse of result.inverse) {\n const inverse = operation.inverse(rawInverse);\n group.push(inverse);\n profile.mutation.inverse();\n profile.batch.inverse();\n }\n steps.push({ forward: published, inverse: Object.freeze(group) });\n try {\n if (!resolved) throw new Error(`Changed operation '${normalized.type}' was not resolved.`);\n journal.record(resolved, normalized, result.inverse);\n } catch (error) {\n rollback();\n throw error;\n }\n return undefined;\n },\n finish: () => {\n if (state !== 'active') throw new Error('Mutation session is closed.');\n const changes = journal.finish();\n state = 'finished';\n if (changes.status === 'unchanged') return { status: 'unchanged' };\n\n let inverseCount = 0;\n for (const step of steps) inverseCount += step.inverse.length;\n const inverse = new Array<DocumentOperation>(inverseCount);\n let writeIndex = 0;\n for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex -= 1)\n for (const entry of steps[stepIndex].inverse) inverse[writeIndex++] = entry;\n return {\n status: 'changed',\n operations: Object.freeze(steps.map(step => step.forward)),\n inverse: Object.freeze(inverse),\n paths: changes.paths,\n collections: changes.collections,\n };\n },\n rollback,\n };\n};\n\nexport const mutateOperations = <TSchema extends DocumentSchema>(\n root: unknown,\n schema: TSchema,\n operations: unknown,\n options: { readonly copyPayload?: boolean } = {}\n): MutationBatch<TSchema> => {\n const decodedBatch = operation.decodeBatch(operations);\n if (decodedBatch.status === 'rejected')\n return { status: 'rejected', issues: Object.freeze([decodedBatch.issue]) };\n const session = createMutationSession(root, schema, options);\n for (const input of decodedBatch.operations) {\n const issue = session.apply(input);\n if (!issue) continue;\n session.rollback();\n return { status: 'rejected', issues: Object.freeze([issue]) };\n }\n return session.finish();\n};\n","import type { DocumentSchema, ImpactTarget, Infer } from './schema';\nimport { contains, debugKey, overlaps, read as readAddress, resolveAddress } from './address';\nimport { createImpact } from './impact';\nimport { createHistory } from './history';\nimport { documentReader } from './access/reader';\nimport { documentWriter } from './access/writer';\nimport { createMutationSession, mutateOperations, type MutationSession } from './mutation/session';\nimport type { MutationBatch } from './mutation/contract';\nimport * as issue from './mutation/issue';\nimport * as tree from './mutation/tree';\nimport { commandFootprint } from './mutation/footprint';\nimport { cloneValue, deepEqual } from './value/ownership';\nimport { profile } from './profile';\nimport { DocumentDisposedError, DocumentReentrancyError } from './runtime/contract';\nimport type {\n CommitListener,\n CommitSource,\n DocumentCommit,\n DocumentDiagnostic,\n DiagnosticInput,\n DocumentProblem,\n DocumentRuntime,\n DocumentTransaction,\n OperationResult,\n PreparedUpdateResult,\n TransactionResult,\n} from './runtime/contract';\nimport { bindRuntimeAccess, accessOf } from './runtime/access';\nimport { assertRuntimeWritable, bindRuntimeDriver, disposeRuntimeDriver } from './runtime/driver';\nimport {\n bindDocumentReadable,\n createNotification,\n disposeNotification,\n notify,\n subscribeRoot,\n subscribeTargets,\n type RuntimeNotification,\n} from './runtime/notification';\n\nclass RejectedUpdate extends Error {\n readonly issues: readonly DocumentProblem[];\n\n constructor(issues: readonly DocumentProblem[]) {\n super('Document update rejected.');\n this.issues = Object.freeze(issues.slice());\n }\n}\n\nconst EMPTY: readonly never[] = Object.freeze([]) as readonly never[];\n\nconst publishDiagnostic = (value: DiagnosticInput): DocumentDiagnostic =>\n Object.freeze({\n ...value,\n source: 'application',\n ...(value.address === undefined ? {} : { address: Object.freeze(value.address.slice()) }),\n });\n\nexport const createDocument = <TSchema extends DocumentSchema>(input: {\n readonly schema: TSchema;\n readonly initial: Infer<TSchema>;\n readonly history?: { readonly capacity?: number } | false;\n}): DocumentRuntime<TSchema> => {\n const initialTreeError = tree.invalidDocument(input.schema, input.initial);\n if (initialTreeError)\n throw new TypeError(\n `Initial document contains an invalid tree at '${initialTreeError.join('.')}'.`\n );\n profile.clone.initialDocument();\n const state = {\n schema: input.schema,\n document: cloneValue(input.initial, 'initial'),\n disposed: false,\n };\n let revision = 0;\n let busy = false;\n let runtime!: DocumentRuntime<TSchema>;\n let notification!: RuntimeNotification<TSchema>;\n\n const assertWritable = (intent: Parameters<typeof assertRuntimeWritable>[1]): void => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy) throw new DocumentReentrancyError();\n if (accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n assertRuntimeWritable(runtime, intent);\n };\n\n const runTransaction = <TResult>(\n session: MutationSession<TSchema>,\n run: (transaction: DocumentTransaction<TSchema>) => TResult\n ): { readonly value: TResult; readonly reports: readonly DocumentDiagnostic[] } => {\n let reports: DocumentDiagnostic[] | undefined;\n let active = true;\n const transaction: DocumentTransaction<TSchema> = {\n read: documentReader(\n input.schema,\n () => state.document,\n () => active\n ),\n write: documentWriter(input.schema, operation => {\n if (!active) throw new Error('Document writer is no longer active.');\n const rejected = session.apply(operation);\n if (rejected) throw new RejectedUpdate([rejected]);\n }),\n reject: diagnostic => {\n throw new RejectedUpdate(\n (Array.isArray(diagnostic) ? diagnostic : [diagnostic]).map(entry =>\n publishDiagnostic(entry)\n )\n );\n },\n report: diagnostic => {\n if (!active) throw new Error('Document transaction is no longer active.');\n (reports ??= []).push(publishDiagnostic(diagnostic));\n },\n };\n try {\n const value = run(transaction);\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { then?: unknown }).then === 'function'\n )\n throw new TypeError('Document update callback must be synchronous.');\n return {\n value,\n reports: Object.freeze(reports ? reports.slice() : EMPTY),\n };\n } finally {\n active = false;\n }\n };\n\n const impactFor = (\n batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }>,\n kind: 'operations' | 'replace'\n ) =>\n createImpact({\n schema: input.schema,\n operations: batch.operations,\n paths: batch.paths,\n collections: batch.collections,\n reset: kind === 'replace',\n });\n\n const history = createHistory<DocumentCommit<TSchema>>({\n capacity: input.history === false ? 0 : Math.max(0, input.history?.capacity ?? 100),\n revision: () => revision,\n apply: operations => applyBatch(operations, 'history', false),\n assertIdle: () => {\n if (state.disposed) throw new DocumentDisposedError();\n if (busy || accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n },\n notify: run => {\n busy = true;\n try {\n return run();\n } finally {\n busy = false;\n }\n },\n });\n\n const publish = (\n batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }>,\n source: CommitSource,\n kind: 'operations' | 'replace',\n recordHistory: boolean\n ): Extract<OperationResult<DocumentCommit<TSchema>>, { readonly status: 'committed' }> => {\n revision += 1;\n const commit: DocumentCommit<TSchema> = Object.freeze({\n revision,\n kind,\n source,\n operations: batch.operations,\n inverse: batch.inverse,\n impact: impactFor(batch, kind),\n });\n if (kind === 'replace' || source === 'remote') history.invalidate();\n else if (recordHistory && (source === 'local' || source === 'system'))\n history.record(batch.operations, batch.inverse);\n else if (source === 'history') history.publish();\n else history.endGroup();\n busy = true;\n let observerErrors;\n try {\n observerErrors = notify(notification, commit, history.flush);\n } finally {\n busy = false;\n }\n return { status: 'committed', commit, observerErrors };\n };\n\n function applyBatch(\n operations: unknown,\n source: CommitSource,\n recordHistory: boolean\n ): OperationResult<DocumentCommit<TSchema>> {\n assertWritable({ kind: 'apply', source });\n const batch = mutateOperations(state.document, input.schema, operations, {\n copyPayload: source === 'history',\n });\n if (batch.status === 'rejected') return { status: 'rejected', issues: batch.issues, revision };\n if (batch.status === 'unchanged') return { status: 'unchanged', revision };\n return publish(batch, source, 'operations', recordHistory);\n }\n\n runtime = {\n schema: input.schema,\n address: {\n resolve: address => resolveAddress(input.schema, address, state.document),\n read: address => readAddress(state.document, address),\n contains,\n overlaps,\n debugKey,\n },\n revision: () => revision,\n update: <TResult>(\n run: (transaction: DocumentTransaction<TSchema>) => TResult,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<TResult, DocumentCommit<TSchema>> => {\n const source = options?.source ?? 'local';\n assertWritable({ kind: 'update', source });\n busy = true;\n const session = createMutationSession(state.document, input.schema);\n let committed = false;\n try {\n const { value, reports } = runTransaction(session, run);\n const batch = session.finish();\n if (batch.status === 'unchanged')\n return {\n status: 'unchanged',\n value,\n revision,\n reports,\n };\n if (batch.status === 'rejected')\n return { status: 'rejected', issues: batch.issues, revision };\n const result = publish(batch, source, 'operations', options?.history ?? true);\n committed = true;\n return {\n status: 'committed',\n value,\n commit: result.commit,\n reports,\n observerErrors: result.observerErrors,\n };\n } catch (error) {\n try {\n if (!committed) session.rollback();\n } finally {\n busy = false;\n }\n if (error instanceof RejectedUpdate)\n return { status: 'rejected', issues: error.issues, revision };\n throw error;\n } finally {\n busy = false;\n }\n },\n prepare: <TResult>(\n run: (transaction: DocumentTransaction<TSchema>) => TResult\n ): PreparedUpdateResult<TResult, TSchema> => {\n assertWritable({ kind: 'prepare' });\n busy = true;\n const session = createMutationSession(state.document, input.schema);\n try {\n const { value, reports } = runTransaction(session, run);\n const batch = session.finish();\n if (batch.status === 'unchanged') {\n session.rollback();\n return { status: 'unchanged', value, reports };\n }\n if (batch.status === 'rejected') {\n session.rollback();\n return { status: 'rejected', issues: batch.issues };\n }\n const impact = impactFor(batch, 'operations');\n session.rollback();\n return {\n status: 'prepared',\n value,\n operations: batch.operations,\n inverse: batch.inverse,\n impact,\n footprint: commandFootprint(batch.operations),\n reports,\n };\n } catch (error) {\n try {\n session.rollback();\n } finally {\n busy = false;\n }\n if (error instanceof RejectedUpdate) return { status: 'rejected', issues: error.issues };\n throw error;\n } finally {\n busy = false;\n }\n },\n apply: (operations, options) =>\n applyBatch(operations, options?.source ?? 'local', options?.history ?? true),\n replace: (document, options) => {\n const source = options?.source ?? 'system';\n assertWritable({ kind: 'replace', source });\n const invalidTree = tree.invalidDocument(input.schema, document);\n if (invalidTree)\n return {\n status: 'rejected',\n issues: [\n issue.at(invalidTree, 'invalid-tree', 'Document replacement contains an invalid tree.'),\n ],\n revision,\n };\n if (deepEqual(state.document, document)) return { status: 'unchanged', revision };\n state.document = cloneValue(document, 'replace');\n const batch: Extract<MutationBatch<TSchema>, { readonly status: 'changed' }> = {\n status: 'changed',\n operations: EMPTY,\n inverse: EMPTY,\n paths: EMPTY,\n collections: EMPTY,\n };\n return publish(batch, source, 'replace', false);\n },\n snapshot: () => {\n if (state.disposed) throw new DocumentDisposedError();\n return cloneValue(state.document, 'snapshot');\n },\n subscribe: ((\n targetOrListener:\n ImpactTarget<unknown> | readonly ImpactTarget<unknown>[] | CommitListener<TSchema>,\n listener?: CommitListener<TSchema>\n ) => {\n if (state.disposed) throw new DocumentDisposedError();\n if (typeof targetOrListener === 'function')\n return subscribeRoot(notification, targetOrListener);\n const targets = Array.isArray(targetOrListener)\n ? targetOrListener\n : [targetOrListener as ImpactTarget<unknown>];\n if (targets.length === 0 || !listener)\n throw new TypeError('Filtered subscribe requires at least one target and a listener.');\n return subscribeTargets(notification, targets, listener);\n }) as DocumentRuntime<TSchema>['subscribe'],\n history: history.api,\n dispose: () => {\n if (state.disposed) return;\n if (busy || accessOf(runtime).projectionLocks) throw new DocumentReentrancyError();\n state.disposed = true;\n try {\n disposeNotification(notification);\n } finally {\n history.dispose();\n disposeRuntimeDriver(runtime);\n }\n },\n };\n\n bindRuntimeAccess(runtime, state);\n bindRuntimeDriver(runtime);\n notification = createNotification(runtime);\n bindDocumentReadable(history.api, runtime);\n return runtime;\n};\n","import type { DocumentSchema } from '../schema';\nimport type { DocumentReadable, DocumentRuntime } from './contract';\nimport { accessOf, bindRuntimeAccess } from './access';\nimport { shareNotification } from './notification';\n\n// A readable capability keeps the canonical runtime behind an explicit\n// mutation funnel while remaining fully compatible with selectors, views, and\n// framework subscriptions.\nexport const asReadable = <TSchema extends DocumentSchema>(\n runtime: DocumentRuntime<TSchema>\n): DocumentReadable<TSchema> => {\n const readable: DocumentReadable<TSchema> = {\n address: runtime.address,\n revision: runtime.revision,\n subscribe: runtime.subscribe,\n };\n bindRuntimeAccess(readable, accessOf(runtime));\n shareNotification(runtime, readable);\n return Object.freeze(readable);\n};\n","import type { DocumentSchema } from '../schema';\nimport type { DocumentReader } from '../access/reader';\nimport type { DocumentReadable } from '../runtime/contract';\nimport { readWith } from '../runtime/access';\n\nexport type DocumentSelector<TSchema extends DocumentSchema, TResult> = (\n read: DocumentReader<TSchema>\n) => TResult;\n\nexport const select = <TSchema extends DocumentSchema, TResult>(\n runtime: DocumentReadable<TSchema>,\n selector: DocumentSelector<TSchema, TResult>\n): TResult => readWith(runtime, selector);\n"],"mappings":";;;;;AA0BA,MAAM,wBAAkD,OAAO,OAAO;CACpE,MAAM;CACN,uBAAO,IAAI,KAAa;CACxB,yBAAS,IAAI,KAAa;CAC1B,yBAAS,IAAI,KAAa;CAC1B,cAAc;CACf,CAAC;AACF,MAAM,wBAAiD,OAAO,OAAO,EACnE,MAAM,SACP,CAAC;AAEF,MAAa,gBAAgD,UAM9B;CAC7B,MAAM,OAAO,MAAM,QAAQ,UAAU;CACrC,MAAM,QAAQ,MAAM,SAAS,MAAM,WAAW,KAAI,cAAa,UAAU,GAAG;CAC5E,IAAI;CACJ,MAAM,YACJ,SACA,SACY;AACZ,MAAI,QAAQ,WAAW,KAAK,MAAM,UAAU,EAAG,QAAO,MAAM,KAAK,KAAK;AACtE,MAAI,CAAC,aAAa;AAChB,iCAAc,IAAI,KAAK;AACvB,QAAK,MAAM,WAAW,OAAO;IAC3B,MAAM,QAAQ,QAAQ;IACtB,MAAM,SAAS,YAAY,IAAI,MAAM,IAAI,EAAE;AAC3C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