doxum 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +30 -11
  2. package/dist/{scope-d-L87NeC.js → access-BeSV5ve-.js} +114 -20
  3. package/dist/access-BeSV5ve-.js.map +1 -0
  4. package/dist/{scope-Ezs-Y3TY.cjs → access-Bienf28h.cjs} +149 -19
  5. package/dist/access-Bienf28h.cjs.map +1 -0
  6. package/dist/advanced-BRL5pN0y.cjs +1361 -0
  7. package/dist/advanced-BRL5pN0y.cjs.map +1 -0
  8. package/dist/advanced-COFJtWMT.js +1188 -0
  9. package/dist/advanced-COFJtWMT.js.map +1 -0
  10. package/dist/{advanced-C2fpjbK3.d.ts → advanced-DfKc7TZR.d.cts} +27 -22
  11. package/dist/{advanced-DlOYk1vi.d.cts → advanced-FgdTwu5b.d.ts} +27 -22
  12. package/dist/advanced.cjs +1 -1
  13. package/dist/advanced.d.cts +2 -2
  14. package/dist/advanced.d.ts +2 -2
  15. package/dist/advanced.js +1 -1
  16. package/dist/{contract-XmKnroJq.d.cts → contract-CdmDHRUq.d.cts} +8 -6
  17. package/dist/{contract-CATCCVu5.d.ts → contract-KG5XnQZt.d.ts} +8 -6
  18. package/dist/{driver-CSnhMjbP.js → driver-CLYJOGDQ.js} +2 -2
  19. package/dist/{driver-CSnhMjbP.js.map → driver-CLYJOGDQ.js.map} +1 -1
  20. package/dist/{driver-BCyfqxsl.cjs → driver-Djr3BVvo.cjs} +2 -2
  21. package/dist/{driver-BCyfqxsl.cjs.map → driver-Djr3BVvo.cjs.map} +1 -1
  22. package/dist/index.cjs +1150 -1993
  23. package/dist/index.cjs.map +1 -1
  24. package/dist/index.d.cts +2 -2
  25. package/dist/index.d.ts +2 -2
  26. package/dist/index.js +1105 -1948
  27. package/dist/index.js.map +1 -1
  28. package/dist/{integration-CxVhq-KD.js → integration-C4Isp8lJ.js} +3 -2
  29. package/dist/{integration-CxVhq-KD.js.map → integration-C4Isp8lJ.js.map} +1 -1
  30. package/dist/{integration-B7VDgAOJ.cjs → integration-Z6MsfFI7.cjs} +4 -3
  31. package/dist/{integration-B7VDgAOJ.cjs.map → integration-Z6MsfFI7.cjs.map} +1 -1
  32. package/dist/integration.cjs +3 -3
  33. package/dist/integration.d.cts +1 -1
  34. package/dist/integration.d.ts +1 -1
  35. package/dist/integration.js +3 -3
  36. package/dist/{issue-DhrNdQNg.cjs → issue-DjK1xp5K.cjs} +106 -22
  37. package/dist/issue-DjK1xp5K.cjs.map +1 -0
  38. package/dist/{issue-DVaGQGeP.js → issue-W0hT8u8D.js} +81 -15
  39. package/dist/issue-W0hT8u8D.js.map +1 -0
  40. package/dist/local-sync.cjs +2 -2
  41. package/dist/local-sync.d.cts +1 -1
  42. package/dist/local-sync.d.ts +1 -1
  43. package/dist/local-sync.js +2 -2
  44. package/dist/{notification-IQIJyH3Q.js → notification-Bkjau6B6.js} +3 -56
  45. package/dist/notification-Bkjau6B6.js.map +1 -0
  46. package/dist/{notification-CDSUfiip.cjs → notification-DJfouMEb.cjs} +2 -91
  47. package/dist/notification-DJfouMEb.cjs.map +1 -0
  48. package/dist/react.cjs +2 -2
  49. package/dist/react.js +2 -2
  50. package/package.json +1 -1
  51. package/skills/doxum-runtime/SKILL.md +4 -1
  52. package/skills/doxum-runtime/references/guide.en.md +5 -2
  53. package/skills/doxum-runtime/references/guide.zh-CN.md +5 -2
  54. package/skills/doxum-runtime/references/projections.en.md +23 -9
  55. package/skills/doxum-runtime/references/projections.zh-CN.md +18 -6
  56. package/dist/advanced-BYZCjNWL.js +0 -680
  57. package/dist/advanced-BYZCjNWL.js.map +0 -1
  58. package/dist/advanced-CMMNk49G.cjs +0 -763
  59. package/dist/advanced-CMMNk49G.cjs.map +0 -1
  60. package/dist/issue-DVaGQGeP.js.map +0 -1
  61. package/dist/issue-DhrNdQNg.cjs.map +0 -1
  62. package/dist/notification-CDSUfiip.cjs.map +0 -1
  63. package/dist/notification-IQIJyH3Q.js.map +0 -1
  64. package/dist/scope-Ezs-Y3TY.cjs.map +0 -1
  65. package/dist/scope-d-L87NeC.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"advanced-CMMNk49G.cjs","names":["snapshot"],"sources":["../core/src/projection/definition.ts","../core/src/projection/contract.ts","../core/src/projection/scheduler.ts","../core/src/projection/advanced.ts"],"sourcesContent":["import type { DocumentReadable, Synchronous } from '../runtime/contract';\nimport type {\n CollectionId,\n CollectionPath,\n CollectionNode as SchemaCollectionNode,\n Infer,\n ObjectNode,\n ReadonlyValue,\n SchemaPath,\n PathValueOf,\n} from '../schema';\nimport type { Readable } from './readable';\nimport type {\n CollectionChange,\n ExternalCollectionSource,\n ExternalValueSource,\n GraphSources,\n} from './contract';\n\ndeclare const projectionDefinition: unique symbol;\ndeclare const projectionChanges: unique symbol;\ndeclare const writableInput: unique symbol;\n\n/** A lazy definition with no materialized state; root definitions are reusable. */\nexport type Projection<T, C = undefined> = {\n readonly [projectionDefinition]: T;\n readonly [projectionChanges]: C;\n};\n\n/** A runtime-local writable projection definition. */\nexport type Input<T, C = undefined> = Projection<T, C> & { readonly [writableInput]: true };\n\ntype ProjectionValues<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T, unknown> ? T : never;\n};\n\ntype Equality = (a: unknown, b: unknown) => boolean;\ntype PathSelector<S extends ObjectNode> = (path: SchemaPath<S['shape']>) => unknown;\n\nexport type IncrementalGroupDefinition = {\n readonly dependencies: GraphSources;\n readonly outputs: readonly {\n readonly path: readonly string[];\n readonly isEqual?: Equality;\n }[];\n readonly build: (...args: never[]) => unknown;\n readonly projections: readonly Projection<\n ReadonlyMap<string, unknown>,\n CollectionChange<string, unknown>\n >[];\n};\n\ntype Definition =\n | { readonly kind: 'input'; readonly initial: unknown; readonly isEqual?: Equality }\n | { readonly kind: 'collection-input'; readonly initial: ReadonlyMap<string, unknown> }\n | { readonly kind: 'readable'; readonly readable: Readable<unknown>; readonly isEqual?: Equality }\n | { readonly kind: 'source-value'; readonly source: ExternalValueSource<unknown> }\n | {\n readonly kind: 'source-collection';\n readonly source: ExternalCollectionSource<string, unknown>;\n }\n | {\n readonly kind: 'document';\n readonly document: DocumentReadable<ObjectNode>;\n readonly selector?: PathSelector<ObjectNode>;\n }\n | {\n readonly kind: 'derive';\n readonly dependencies: readonly Projection<unknown, unknown>[];\n readonly compute: (...values: readonly unknown[]) => unknown;\n readonly isEqual?: Equality;\n }\n | {\n readonly kind: 'incremental-value';\n readonly dependencies: GraphSources;\n readonly build: (...args: never[]) => unknown;\n readonly isEqual?: Equality;\n readonly name?: string;\n }\n | {\n readonly kind: 'incremental-collection';\n readonly dependencies: GraphSources;\n readonly build: (...args: never[]) => unknown;\n readonly isEqual?: Equality;\n readonly name?: string;\n }\n | {\n readonly kind: 'incremental-group-output';\n readonly group: IncrementalGroupDefinition;\n readonly output: number;\n };\n\ntype DefinitionProjection = Projection<unknown, unknown>;\nconst definitions = new WeakMap<object, Definition>();\nconst owners = new WeakMap<object, object>();\n\nconst define = <T, C = undefined>(definition: Definition): Projection<T, C> => {\n const handle = Object.freeze({}) as Projection<T, C>;\n definitions.set(handle, definition);\n return handle;\n};\n\nexport const definitionOf = (projection: DefinitionProjection): Definition => {\n const definition = definitions.get(projection);\n if (!definition) throw new TypeError('Unknown projection definition.');\n return definition;\n};\n\nexport const isProjection = (value: unknown): value is DefinitionProjection =>\n value !== null && typeof value === 'object' && definitions.has(value);\n\nexport const ownerOf = (projection: DefinitionProjection): object | undefined =>\n owners.get(projection);\n\nexport const ownDefinition = <T, C>(\n projection: Projection<T, C>,\n owner: object\n): Projection<T, C> => {\n if (!definitions.has(projection) || owners.has(projection))\n throw new TypeError('Projection definition already has an owner.');\n owners.set(projection, owner);\n return projection;\n};\n\nconst valueInput = <T>(\n initial: T,\n equality: (previous: T, next: T) => boolean = Object.is\n): Input<T> => define<T>({ kind: 'input', initial, isEqual: equality as Equality }) as Input<T>;\n\nconst collectionInput = <K extends string, V>(\n initial: ReadonlyMap<K, V> = new Map<K, V>()\n): Input<ReadonlyMap<K, V>, CollectionChange<K, V>> => {\n const entries = new Map<K, V>();\n for (const [key, value] of initial) {\n if (typeof key !== 'string') throw new TypeError('Projection keys must be strings.');\n entries.set(key, value);\n }\n return define<ReadonlyMap<K, V>, CollectionChange<K, V>>({\n kind: 'collection-input',\n initial: entries,\n }) as Input<ReadonlyMap<K, V>, CollectionChange<K, V>>;\n};\n\nexport const input = Object.assign(valueInput, { collection: collectionInput });\n\n/** Establish a lazy reactive boundary from a document, readable, or external source. */\nexport function observe<S extends ObjectNode>(document: DocumentReadable<S>): Projection<Infer<S>>;\nexport function observe<T>(source: ExternalValueSource<T>): Projection<T>;\nexport function observe<K extends string, V>(\n source: ExternalCollectionSource<K, V>\n): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>;\nexport function observe<T>(readable: Readable<T>): Projection<T>;\nexport function observe<S extends ObjectNode, P extends CollectionPath>(\n document: DocumentReadable<S>,\n selector: (path: SchemaPath<S['shape']>) => P\n): Projection<\n ReadonlyMap<CollectionId<P>, ReadonlyValue<Infer<SchemaCollectionNode<P>>>>,\n CollectionChange<CollectionId<P>, ReadonlyValue<Infer<SchemaCollectionNode<P>>>>\n>;\nexport function observe<S extends ObjectNode, P>(\n document: DocumentReadable<S>,\n selector: (path: SchemaPath<S['shape']>) => P\n): Projection<PathValueOf<P>>;\nexport function observe<S extends ObjectNode>(\n document:\n | DocumentReadable<S>\n | Readable<unknown>\n | ExternalValueSource<unknown>\n | ExternalCollectionSource<string, unknown>,\n selector?: PathSelector<S>\n): Projection<unknown, unknown> {\n if (isExternalSource(document))\n return document.kind === 'collection'\n ? defineExternalCollection(document)\n : defineExternalValue(document);\n if ('current' in document && typeof document.current === 'function')\n return defineReadable(document as Readable<unknown>);\n return define({\n kind: 'document',\n document: document as DocumentReadable<ObjectNode>,\n selector: selector as PathSelector<ObjectNode> | undefined,\n });\n}\n\nconst isExternalSource = (\n source: unknown\n): source is ExternalValueSource<unknown> | ExternalCollectionSource<string, unknown> => {\n if (!source || typeof source !== 'object') return false;\n const candidate = source as {\n readonly kind?: unknown;\n readonly current?: unknown;\n readonly revision?: unknown;\n readonly subscribe?: unknown;\n };\n return (\n (candidate.kind === 'value' || candidate.kind === 'collection') &&\n typeof candidate.current === 'function' &&\n typeof candidate.revision === 'function' &&\n typeof candidate.subscribe === 'function'\n );\n};\n\nexport function derive<const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n compute: (...values: ProjectionValues<D>) => Synchronous<T>,\n equality: (previous: T, next: T) => boolean = Object.is\n): Projection<T> {\n if (!Array.isArray(dependencies) || dependencies.some(value => !definitions.has(value)))\n throw new TypeError('derive dependencies must be projections.');\n const frozen = Object.freeze([...dependencies]) as readonly Projection<unknown, unknown>[];\n return define<T>({\n kind: 'derive',\n dependencies: frozen,\n compute: compute as (...values: readonly unknown[]) => unknown,\n isEqual: equality as Equality,\n });\n}\n\nexport const defineReadable = <T>(\n readable: Readable<T>,\n equality: (a: T, b: T) => boolean = Object.is\n): Projection<T> => define<T>({ kind: 'readable', readable, isEqual: equality as Equality });\n\nexport const defineExternalValue = <T>(source: ExternalValueSource<T>): Projection<T> =>\n define<T>({ kind: 'source-value', source: source as ExternalValueSource<unknown> });\n\nexport const defineExternalCollection = <K extends string, V>(\n source: ExternalCollectionSource<K, V>\n): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>> =>\n define<ReadonlyMap<K, V>, CollectionChange<K, V>>({\n kind: 'source-collection',\n source: source as unknown as ExternalCollectionSource<string, unknown>,\n });\n\nexport const defineIncrementalValue = <T>(definition: {\n readonly dependencies: GraphSources;\n readonly build: (...args: never[]) => unknown;\n readonly isEqual?: (a: T, b: T) => boolean;\n readonly name?: string;\n}): Projection<T> =>\n define<T>({\n kind: 'incremental-value',\n dependencies: definition.dependencies,\n build: definition.build,\n isEqual: definition.isEqual as Equality | undefined,\n name: definition.name,\n });\n\nexport const defineIncrementalCollection = <K extends string, V>(definition: {\n readonly dependencies: GraphSources;\n readonly build: (...args: never[]) => unknown;\n readonly isEqual?: (a: V, b: V) => boolean;\n readonly name?: string;\n}): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>> =>\n define<ReadonlyMap<K, V>, CollectionChange<K, V>>({\n kind: 'incremental-collection',\n dependencies: definition.dependencies,\n build: definition.build,\n isEqual: definition.isEqual as Equality | undefined,\n name: definition.name,\n });\n\nexport const defineIncrementalGroup = (definition: {\n readonly dependencies: GraphSources;\n readonly outputs: readonly {\n readonly path: readonly string[];\n readonly isEqual?: Equality;\n }[];\n readonly build: (...args: never[]) => unknown;\n}): IncrementalGroupDefinition => {\n const group = {\n dependencies: definition.dependencies,\n outputs: Object.freeze(\n definition.outputs.map(output =>\n Object.freeze({ path: Object.freeze([...output.path]), isEqual: output.isEqual })\n )\n ),\n build: definition.build,\n projections: [] as Projection<\n ReadonlyMap<string, unknown>,\n CollectionChange<string, unknown>\n >[],\n };\n const projections = group.outputs.map((_, output) =>\n define<ReadonlyMap<string, unknown>, CollectionChange<string, unknown>>({\n kind: 'incremental-group-output',\n group,\n output,\n })\n );\n group.projections = Object.freeze(projections) as typeof group.projections;\n return Object.freeze(group);\n};\n","import type { Read } from '../access/scope';\nimport type { CollectionImpact } from '../impact';\nimport type { DocumentReadable, Unsubscribe } from '../runtime/contract';\nimport type {\n CollectionNode as SchemaCollectionNode,\n CollectionId,\n CollectionPath,\n ObjectNode,\n PathPick,\n SchemaPath,\n} from '../schema';\nimport type { Readable } from './readable';\n\ndeclare const sourceContext: unique symbol;\nexport type GraphSource<T> = { readonly [sourceContext]: T };\nexport type GraphSources = Readonly<Record<string, GraphSource<unknown>>>;\nexport type InputHandles<S extends GraphSources> = {\n readonly [K in keyof S]: S[K] extends GraphSource<infer T> ? T : never;\n};\n\n/** Scheduler-owned metadata for one Runtime batch. */\nexport type BatchContext = {\n readonly id: number;\n readonly cause?: unknown;\n};\n\n/** The one processor-facing collection transition protocol. */\nexport type CollectionChange<K extends string, V> =\n | { readonly kind: 'reset' }\n | {\n readonly kind: 'incremental';\n readonly added: readonly { readonly key: K; readonly after: V }[];\n readonly updated: readonly {\n readonly key: K;\n readonly before: V;\n readonly after: V;\n }[];\n readonly removed: readonly { readonly key: K; readonly before: V }[];\n readonly order?: {\n readonly before: readonly K[];\n readonly after: readonly K[];\n };\n };\n\nexport type DocumentContext<S extends ObjectNode> = {\n readonly kind: 'document';\n readonly read: Read<S>;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type DocumentHandle<S extends ObjectNode> = GraphSource<DocumentContext<S>> & {\n collection<P extends CollectionPath>(\n pick: (path: SchemaPath<S['shape']>) => P\n ): GraphSource<CollectionContext<CollectionId<P>, Read<SchemaCollectionNode<P>>>>;\n targets(...targets: readonly [PathPick<S>, ...PathPick<S>[]]): GraphSource<DocumentContext<S>>;\n};\n\nexport type ValueContext<T> = {\n readonly kind: 'value';\n readonly value: T;\n readonly revision: number;\n readonly reset: boolean;\n readonly cause?: unknown;\n};\n\nexport type InputHandle<T> = {\n readonly source: GraphSource<ValueContext<T>>;\n set(value: T): void;\n};\n\nexport type NodeUpdate<T> =\n | { readonly kind: 'unchanged' }\n | { readonly kind: 'changed'; readonly value: T }\n | { readonly kind: 'rebuild' };\n\nexport type ValueNodeSpec<S extends GraphSources, T> = {\n readonly name?: string;\n readonly sources: S;\n readonly build: (sources: InputHandles<S>) => {\n readonly value: T;\n readonly update: (sources: InputHandles<S>) => NodeUpdate<NoInfer<T>>;\n };\n};\n\nexport type ValueNode<T> = Readable<T> & GraphSource<ValueContext<T>> & { readonly kind: 'value' };\n\nexport type CollectionRead<K extends string, V> = {\n get(key: K): V | undefined;\n has(key: K): boolean;\n ids(): readonly K[];\n};\n\nexport type ExternalCollectionRead<K extends string, V> = {\n readonly get: (key: K) => V | undefined;\n readonly has: (key: K) => boolean;\n readonly ids: () => readonly K[];\n};\n\nexport type CollectionContext<K extends string, V> = {\n readonly kind: 'collection';\n readonly read: CollectionRead<K, V>;\n readonly change: CollectionChange<K, V> | undefined;\n readonly revision: number;\n readonly cause?: unknown;\n};\n\nexport type CollectionNode<K extends string, V> = GraphSource<CollectionContext<K, V>> & {\n readonly kind: 'collection';\n current(): CollectionRead<K, V>;\n revision(): number;\n subscribe(listener: (change: CollectionChange<K, V>) => void): Unsubscribe;\n};\n\nexport type ExternalValueSource<T> = {\n readonly kind: 'value';\n current(): T;\n revision(): number;\n subscribe(listener: (event: ExternalValueEvent<T>) => void): Unsubscribe;\n};\n\nexport type ExternalCollectionSource<K extends string, V> = {\n readonly kind: 'collection';\n current(): ExternalCollectionRead<K, V>;\n revision(): number;\n subscribe(listener: (event: ExternalCollectionEvent<K, V>) => void): Unsubscribe;\n};\n\nexport type ExternalValueEvent<T> = {\n readonly value: T;\n readonly revision: number;\n readonly reset?: boolean;\n readonly cause?: unknown;\n};\n\nexport type ExternalCollectionEvent<K extends string, V> = {\n /** Stable read from the source before this event or external batch. */\n readonly previous: ExternalCollectionRead<K, V>;\n readonly revision: number;\n /** Optional document-style hint; the adapter resolves the canonical change. */\n readonly impact?: CollectionImpact<K>;\n readonly cause?: unknown;\n};\n\nexport type CollectionDraft<K extends string, V> = {\n set(key: K, value: V): void;\n remove(key: K): void;\n order(ids: readonly K[]): void;\n};\n\nexport type CollectionProcess<S extends GraphSources, K extends string, V> = {\n readonly sources: InputHandles<S>;\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type CollectionNodeSpec<S extends GraphSources, K extends string, V> = {\n readonly name?: string;\n readonly sources: S;\n readonly isEqual?: (previous: V, next: V) => boolean;\n readonly build: (input: CollectionProcess<S, K, V>) => {\n readonly update: (input: CollectionProcess<S, K, V>) => void | { readonly kind: 'rebuild' };\n };\n};\n\n/** Internal graph boundary for one atomic multi-output collection processor. */\nexport type CollectionGroupSpec = {\n readonly sources: GraphSources;\n readonly outputs: readonly {\n readonly path: readonly string[];\n readonly isEqual?: (previous: unknown, next: unknown) => boolean;\n }[];\n readonly build: (input: {\n readonly sources: Record<string, unknown>;\n readonly previous: readonly CollectionRead<string, unknown>[];\n readonly next: readonly CollectionRead<string, unknown>[];\n readonly outputs: readonly CollectionDraft<string, unknown>[];\n }) => {\n readonly update: (input: {\n readonly sources: Record<string, unknown>;\n readonly previous: readonly CollectionRead<string, unknown>[];\n readonly next: readonly CollectionRead<string, unknown>[];\n readonly outputs: readonly CollectionDraft<string, unknown>[];\n }) => void | { readonly kind: 'rebuild' };\n };\n};\n\nexport class ProjectionError extends Error {\n constructor(\n readonly phase: 'processor' | 'listener' | 'source' | 'blocked',\n readonly identity: string,\n readonly revisions: readonly number[],\n cause: unknown\n ) {\n super(`Projection ${phase} failed: ${identity}`, { cause });\n this.name = 'ProjectionError';\n }\n}\n\nexport class ProjectionDisposedError extends Error {\n constructor() {\n super('Projection has been disposed.');\n this.name = 'ProjectionDisposedError';\n }\n}\n","import type { ObserverError } from '../runtime/contract';\nimport { ProjectionDisposedError, ProjectionError, type BatchContext } from './contract';\nimport { profile } from '../profile';\n\ntype BatchOptions = { readonly cause?: unknown };\n\nexport type SourceRecord = {\n readonly consumers: Set<NodeRecord>;\n context(active: () => boolean): unknown;\n revision(): number;\n reset(): boolean;\n shouldSettle?(): boolean;\n fault: ProjectionError | undefined;\n disposed: boolean;\n clear(): void;\n};\nexport type OutputRecord = SourceRecord & {\n readonly owner: NodeRecord;\n emit(call: (listener: () => void) => void): void;\n};\nexport type NodeRecord = SourceRecord & {\n readonly owner: NodeRecord;\n readonly order: number;\n readonly name: string;\n readonly sources: readonly SourceRecord[];\n readonly outputs?: readonly OutputRecord[];\n readonly changedOutputs?: () => readonly OutputRecord[];\n evaluate(build: boolean): boolean;\n publish(): void;\n emit(call: (listener: () => void) => void): void;\n release(): void;\n};\n\n// Sources and nodes share one registry. Public structural lookalikes are never accepted.\nexport const projectionHandles = new WeakSet<object>();\nexport const createScheduler = (onError: (error: ProjectionError) => void) => {\n let disposed = false;\n let depth = 0;\n let batchSequence = 0;\n let activeBatch: BatchContext | undefined;\n let phase: 'idle' | 'compute' | 'notify' = 'idle';\n let sequence = 0;\n const records = new Map<object, SourceRecord>();\n const nodes = new Set<NodeRecord>();\n const pending = new Set<SourceRecord>();\n const heap: NodeRecord[] = [];\n const queued = new Set<NodeRecord>();\n const completed: NodeRecord[] = [];\n const emissions = new Set<OutputRecord>();\n const errors: ProjectionError[] = [];\n let reportingFailures: unknown[] = [];\n const guards = new Set<(locked: boolean) => void>();\n const cleanups = new Set<() => void>();\n const assertActive = () => {\n if (disposed) throw new ProjectionDisposedError();\n };\n const assertIdle = () => {\n assertActive();\n if (phase !== 'idle')\n throw new Error('Projection cannot be re-entered during processing or notification.');\n };\n const lock = (value: boolean) => guards.forEach(guard => guard(value));\n const enqueue = (node: NodeRecord) => {\n if (node.disposed || queued.has(node)) return;\n queued.add(node);\n profile.projection('scheduledNodes');\n let i = heap.length;\n heap.push(node);\n while (i > 0) {\n const p = (i - 1) >> 1;\n if (heap[p].order < node.order) break;\n heap[i] = heap[p];\n i = p;\n }\n heap[i] = node;\n };\n const pop = () => {\n const first = heap[0];\n const last = heap.pop()!;\n if (heap.length) {\n let i = 0;\n while (i * 2 + 1 < heap.length) {\n let c = i * 2 + 1;\n if (c + 1 < heap.length && heap[c + 1].order < heap[c].order) c++;\n if (last.order < heap[c].order) break;\n heap[i] = heap[c];\n i = c;\n }\n heap[i] = last;\n }\n return first;\n };\n const errorFor = (\n node: NodeRecord,\n cause: unknown,\n kind: ProjectionError['phase'] = 'processor'\n ) =>\n new ProjectionError(\n kind,\n node.name,\n node.sources.map(source => source.revision()),\n cause\n );\n const capture = (source: SourceRecord) => {\n if (disposed) return;\n if (phase !== 'idle') {\n source.fault = new ProjectionError(\n 'source',\n 'reentrant source',\n [source.revision()],\n new Error('Source changed while projection was running.')\n );\n errors.push(source.fault);\n throw source.fault;\n }\n pending.add(source);\n profile.projection('sourceEvents');\n if (source.fault) errors.push(source.fault);\n };\n const settle = () => {\n if (disposed || depth || phase !== 'idle') return;\n phase = 'compute';\n lock(true);\n try {\n pending.forEach(source => {\n if (source.shouldSettle?.() ?? true) source.consumers.forEach(enqueue);\n });\n while (heap.length) {\n const node = pop();\n if (node.disposed) continue;\n const wasFaulted = node.fault !== undefined;\n profile.projection('processedNodes');\n let changed = false;\n const blocked = node.sources.find(source => source.fault || source.disposed);\n if (blocked) {\n node.fault = errorFor(node, blocked.fault ?? new ProjectionDisposedError(), 'blocked');\n } else {\n const build = wasFaulted || node.sources.some(source => source.reset());\n try {\n changed = node.evaluate(build);\n const failure = node.sources.find(source => source.fault)?.fault;\n if (failure) throw failure;\n node.fault = undefined;\n } catch (cause) {\n const error = errorFor(node, cause);\n node.fault = error;\n if (!build) {\n try {\n changed = node.evaluate(true);\n const failure = node.sources.find(source => source.fault)?.fault;\n if (failure) throw failure;\n node.fault = undefined;\n errors.push(error);\n } catch (cause) {\n node.fault = errorFor(node, cause);\n errors.push(node.fault);\n }\n } else errors.push(error);\n }\n }\n completed.push(node);\n const outputs = node.changedOutputs?.() ?? (changed ? [node as OutputRecord] : []);\n const affected = node.fault\n ? (node.outputs ?? [node as OutputRecord])\n : outputs.length\n ? outputs\n : wasFaulted\n ? (node.outputs ?? [node as OutputRecord])\n : [];\n if (affected.length) {\n profile.projection('publishedNodes');\n node.publish();\n affected.forEach(output => {\n emissions.add(output);\n output.consumers.forEach(enqueue);\n });\n }\n }\n } finally {\n lock(false);\n phase = 'idle';\n }\n };\n const flush = (): readonly ObserverError[] => {\n if (disposed || depth) return [];\n if (pending.size || completed.length) profile.projection('flushes');\n phase = 'notify';\n lock(true);\n const reportFailures: unknown[] = [];\n try {\n emissions.forEach(output =>\n output.emit(listener => {\n try {\n listener();\n } catch (cause) {\n errors.push(errorFor(output.owner, cause, 'listener'));\n }\n })\n );\n for (const error of errors.slice()) {\n try {\n onError(error);\n } catch (cause) {\n reportFailures.push(cause);\n }\n }\n return Object.freeze([\n ...errors.map(error =>\n Object.freeze({\n phase: error.phase === 'listener' ? ('listener' as const) : ('processor' as const),\n error,\n })\n ),\n ...reportFailures.map(error => Object.freeze({ phase: 'listener' as const, error })),\n ]);\n } finally {\n pending.forEach(source => source.clear());\n completed.forEach(node => node.clear());\n pending.clear();\n queued.clear();\n completed.length = 0;\n emissions.clear();\n errors.length = 0;\n reportingFailures = reportFailures;\n lock(false);\n phase = 'idle';\n }\n };\n const run = () => {\n settle();\n const result = flush();\n const failures = reportingFailures;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection error reporter failed.');\n return result;\n };\n const batch = <T>(optionsOrCallback: BatchOptions | (() => T), maybeCallback?: () => T): T => {\n assertIdle();\n const options = typeof optionsOrCallback === 'function' ? undefined : optionsOrCallback;\n const callback = typeof optionsOrCallback === 'function' ? optionsOrCallback : maybeCallback;\n if (!callback) throw new TypeError('Projection batch requires a callback.');\n const outer = depth === 0;\n if (outer)\n activeBatch = Object.freeze({\n id: ++batchSequence,\n ...(options?.cause === undefined ? {} : { cause: options.cause }),\n });\n depth++;\n let failed = false;\n try {\n const value = callback();\n assertSynchronous(value);\n return value;\n } catch (error) {\n failed = true;\n throw error;\n } finally {\n depth--;\n if (!depth) {\n try {\n if (failed) {\n try {\n run();\n } catch {\n /* The original application error retains priority. */\n }\n } else run();\n } finally {\n activeBatch = undefined;\n }\n }\n }\n };\n return {\n assertActive,\n assertIdle,\n capture,\n settle,\n flush,\n run,\n records,\n guards,\n cleanups,\n get active() {\n return !disposed;\n },\n register(handle: object, record: SourceRecord) {\n assertIdle();\n records.set(handle, record);\n projectionHandles.add(handle);\n },\n unregisterSource(handle: object) {\n const record = records.get(handle);\n if (record) {\n assertIdle();\n if (record.consumers.size) throw new Error('Projection source is still used by a node.');\n record.disposed = true;\n pending.delete(record);\n record.clear();\n records.delete(handle);\n }\n },\n releaseNode(handle: object) {\n assertIdle();\n const record = records.get(handle);\n const node =\n record && 'owner' in record\n ? (record as SourceRecord & { readonly owner: NodeRecord }).owner\n : (record as NodeRecord | undefined);\n if (!node || !nodes.has(node)) throw new Error('Unknown projection node.');\n if ((node.outputs ?? [node as OutputRecord]).some(output => output.consumers.size))\n throw new Error('Projection node is still used by another node.');\n node.disposed = true;\n node.sources.forEach(source => source.consumers.delete(node));\n node.release();\n node.clear();\n nodes.delete(node);\n for (const [registered, value] of records)\n if (value === node || ('owner' in value && value.owner === node))\n records.delete(registered);\n pending.delete(node);\n queued.delete(node);\n for (const output of node.outputs ?? [node as OutputRecord]) emissions.delete(output);\n },\n source(handle: object) {\n assertActive();\n const source = records.get(handle);\n if (!source || source.disposed)\n throw new Error('Unknown, disposed, or foreign projection source.');\n return source;\n },\n addNode(node: NodeRecord) {\n nodes.add(node);\n node.sources.forEach(source => source.consumers.add(node));\n },\n order: () => sequence++,\n initialize<T>(run: () => T): T {\n assertIdle();\n phase = 'compute';\n lock(true);\n try {\n return run();\n } finally {\n lock(false);\n phase = 'idle';\n }\n },\n batch,\n batchContext: () => activeBatch,\n dispose() {\n if (disposed) return;\n assertIdle();\n disposed = true;\n const failures: unknown[] = [];\n cleanups.forEach(cleanup => {\n try {\n cleanup();\n } catch (error) {\n failures.push(error);\n }\n });\n cleanups.clear();\n nodes.forEach(node => {\n node.disposed = true;\n node.release();\n node.consumers.clear();\n });\n records.forEach(source => {\n source.disposed = true;\n source.consumers.clear();\n source.clear();\n });\n nodes.clear();\n records.clear();\n pending.clear();\n heap.length = 0;\n completed.length = 0;\n queued.clear();\n emissions.clear();\n guards.clear();\n errors.length = 0;\n reportingFailures = [];\n if (failures.length) throw new AggregateError(failures, 'Projection cleanup failed.');\n },\n };\n};\nexport type Scheduler = ReturnType<typeof createScheduler>;\nexport const assertSynchronous = (value: unknown): void => {\n if (\n value != null &&\n (typeof value === 'object' || typeof value === 'function') &&\n 'then' in value &&\n typeof value.then === 'function'\n )\n throw new TypeError('Projection callbacks must be synchronous.');\n};\nexport const assertScope = (active: () => boolean) => {\n if (!active()) throw new Error('Projection reader or writer is no longer active.');\n};\n","import type { Projection } from './definition';\nimport {\n defineIncrementalCollection,\n defineIncrementalGroup,\n defineIncrementalValue,\n definitionOf,\n} from './definition';\nimport type { CollectionChange, CollectionDraft, CollectionRead, GraphSources } from './contract';\nimport { snapshot } from '../access/scope';\nimport { assertSynchronous } from './scheduler';\n\ntype ProjectionValues<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<infer T, unknown> ? T : never;\n};\n\ntype ProjectionChanges<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D]: D[K] extends Projection<unknown, infer C>\n ? [C] extends [undefined]\n ? undefined\n : C | undefined\n : undefined;\n};\n\nexport type IncrementalValueContext<D extends readonly Projection<unknown, unknown>[], T> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: T | undefined;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n};\n\nexport type IncrementalValueProcessor<D extends readonly Projection<unknown, unknown>[], T> = (\n context: IncrementalValueContext<D, T>\n) => T | { readonly kind: 'rebuild' };\n\nexport type IncrementalCollectionContext<\n D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n readonly output: CollectionDraft<K, V>;\n};\n\nexport type IncrementalCollectionProcessor<\n D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n> = (context: IncrementalCollectionContext<D, K, V>) => void | { readonly kind: 'rebuild' };\n\ntype DependencyMap<D extends readonly Projection<unknown, unknown>[]> = {\n readonly [K in keyof D as `d${Extract<K, number>}`]: D[K];\n};\n\ndeclare const groupOutput: unique symbol;\n\ntype GroupOutput<K extends string, V> = {\n readonly [groupOutput]: { readonly key: K; readonly value: V };\n};\n\ntype GroupOutputShape = {\n readonly [name: string]: GroupOutput<string, unknown> | GroupOutputShape;\n};\n\nexport type IncrementalGroupOutputTree = GroupOutputShape;\n\ntype GroupOutputBuilder = {\n collection<K extends string, V>(equality?: (previous: V, next: V) => boolean): GroupOutput<K, V>;\n};\n\nexport type IncrementalGroupDefine = GroupOutputBuilder;\n\nexport type GroupProjections<O> =\n O extends GroupOutput<infer K, infer V>\n ? Projection<ReadonlyMap<K, V>, CollectionChange<K, V>>\n : { readonly [P in keyof O]: GroupProjections<O[P]> };\n\ntype GroupReads<O> =\n O extends GroupOutput<infer K, infer V>\n ? CollectionRead<K, V>\n : { readonly [P in keyof O]: GroupReads<O[P]> };\n\ntype GroupDrafts<O> =\n O extends GroupOutput<infer K, infer V>\n ? CollectionDraft<K, V>\n : { readonly [P in keyof O]: GroupDrafts<O[P]> };\n\nexport type IncrementalGroupContext<\n D extends readonly Projection<unknown, unknown>[],\n O extends GroupOutputShape,\n> = {\n readonly sources: ProjectionValues<D>;\n readonly changes: ProjectionChanges<D>;\n readonly previous: GroupReads<O>;\n readonly next: GroupReads<O>;\n readonly outputs: GroupDrafts<O>;\n readonly reset: boolean;\n readonly cause: unknown;\n readonly state: Record<string, unknown>;\n};\n\nexport type IncrementalGroupProcessor<\n D extends readonly Projection<unknown, unknown>[],\n O extends GroupOutputShape,\n> = (context: IncrementalGroupContext<D, O>) => void | { readonly kind: 'rebuild' };\n\nconst resetCollectionChange = Object.freeze({ kind: 'reset' as const });\n\nconst isRebuild = (value: unknown): value is { readonly kind: 'rebuild' } =>\n value !== null &&\n typeof value === 'object' &&\n (value as { readonly kind?: unknown }).kind === 'rebuild';\n\nconst collectionChange = (source: unknown): CollectionChange<string, unknown> | undefined => {\n if (!source || typeof source !== 'object' || !('kind' in source)) return undefined;\n if (source.kind !== 'collection') return undefined;\n return (source as { readonly change?: CollectionChange<string, unknown> }).change;\n};\n\nconst sourceCause = (sources: Record<string, unknown>): unknown => {\n for (const source of Object.values(sources)) {\n if (source && typeof source === 'object' && 'kind' in source) {\n const cause = (source as { readonly cause?: unknown }).cause;\n if (cause !== undefined) return cause;\n }\n }\n return undefined;\n};\n\nconst collectionView = <K extends string, V>(read: CollectionRead<K, V>): ReadonlyMap<K, V> => {\n const entries = function* (): IterableIterator<[K, V]> {\n for (const key of read.ids()) yield [key, read.get(key) as V];\n };\n const values = function* (): IterableIterator<V> {\n for (const key of read.ids()) yield read.get(key) as V;\n };\n const view: ReadonlyMap<K, V> = {\n get: key => read.get(key),\n has: key => read.has(key),\n get size() {\n return read.ids().length;\n },\n keys: () => read.ids()[Symbol.iterator](),\n values,\n entries,\n forEach: (callback, thisArg) => {\n for (const key of read.ids()) callback.call(thisArg, read.get(key) as V, key, view);\n },\n [Symbol.iterator]: entries,\n };\n return Object.freeze(view);\n};\n\nconst publicSource = (source: unknown): unknown => {\n if (!source || typeof source !== 'object') return source;\n if (!('kind' in source)) return source;\n if (source.kind === 'value') return (source as unknown as { readonly value: unknown }).value;\n if (source.kind === 'document')\n return snapshot((source as unknown as { readonly read: unknown }).read as never);\n if (source.kind === 'collection') {\n const read = (source as unknown as { readonly read: CollectionRead<string, unknown> }).read;\n return collectionView(read);\n }\n return source;\n};\n\nconst publicInputs = (\n sources: Record<string, unknown>,\n initial = false\n): { readonly values: readonly unknown[]; readonly changes: readonly unknown[] } => {\n const values: unknown[] = [];\n const changes: unknown[] = [];\n for (const key of Object.keys(sources).sort(\n (left, right) => Number(left.slice(1)) - Number(right.slice(1))\n )) {\n const source = sources[key];\n values.push(publicSource(source));\n changes.push(\n initial &&\n source &&\n typeof source === 'object' &&\n 'kind' in source &&\n source.kind === 'collection'\n ? resetCollectionChange\n : collectionChange(source)\n );\n }\n return { values, changes };\n};\n\nfunction createIncrementalValue<const D extends readonly Projection<unknown, unknown>[], T>(\n dependencies: D,\n processor: IncrementalValueProcessor<D, T>\n): Projection<T> {\n const dependencyMap = dependenciesOf(dependencies);\n const build = (sources: Record<string, unknown>) => {\n const state: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n let current!: T;\n const publicInputsForBuild = publicInputs(sources, true);\n const result = processor({\n sources: publicInputsForBuild.values as ProjectionValues<D>,\n changes: publicInputsForBuild.changes as ProjectionChanges<D>,\n previous: undefined,\n reset: true,\n cause: sourceCause(sources),\n state,\n });\n if (isRebuild(result)) throw new TypeError('Initial incremental processor cannot rebuild.');\n current = result as T;\n return {\n value: current,\n update: (nextSources: Record<string, unknown>) => {\n const publicInputsForUpdate = publicInputs(nextSources);\n const next = processor({\n sources: publicInputsForUpdate.values as ProjectionValues<D>,\n changes: publicInputsForUpdate.changes as ProjectionChanges<D>,\n previous: current,\n reset: false,\n cause: sourceCause(nextSources),\n state,\n });\n if (isRebuild(next)) return next;\n current = next as T;\n return { kind: 'changed', value: current } as const;\n },\n };\n };\n return defineIncrementalValue({ dependencies: dependencyMap, build: build as never });\n}\n\nfunction dependenciesOf<D extends readonly Projection<unknown, unknown>[]>(\n dependencies: D\n): GraphSources {\n if (!Array.isArray(dependencies))\n throw new TypeError('Incremental dependencies must be projections.');\n dependencies.forEach(dependency => definitionOf(dependency));\n return Object.freeze(\n Object.fromEntries(dependencies.map((dependency, index) => [`d${index}`, dependency]))\n ) as unknown as GraphSources;\n}\n\nfunction createIncrementalCollection<\n const D extends readonly Projection<unknown, unknown>[],\n K extends string,\n V,\n>(\n dependencies: D,\n processor: IncrementalCollectionProcessor<D, K, V>\n): Projection<ReadonlyMap<K, V>, CollectionChange<K, V>> {\n const dependencyMap = dependenciesOf(dependencies);\n const build = (input: {\n readonly sources: Record<string, unknown>;\n readonly previous: CollectionRead<K, V>;\n readonly next: CollectionRead<K, V>;\n readonly output: CollectionDraft<K, V>;\n }) => {\n const state: Record<string, unknown> = Object.create(null) as Record<string, unknown>;\n const publicInputsForBuild = publicInputs(input.sources, true);\n const result = processor({\n sources: publicInputsForBuild.values as ProjectionValues<D>,\n changes: publicInputsForBuild.changes as ProjectionChanges<D>,\n previous: input.previous,\n next: input.next,\n reset: true,\n cause: sourceCause(input.sources),\n state,\n output: input.output,\n });\n if (result?.kind === 'rebuild')\n throw new TypeError('Initial incremental collection processor cannot rebuild.');\n return {\n update: (nextInput: typeof input) => {\n const publicInputsForUpdate = publicInputs(nextInput.sources);\n return processor({\n sources: publicInputsForUpdate.values as ProjectionValues<D>,\n changes: publicInputsForUpdate.changes as ProjectionChanges<D>,\n previous: nextInput.previous,\n next: nextInput.next,\n reset: false,\n cause: sourceCause(nextInput.sources),\n state,\n output: nextInput.output,\n });\n },\n };\n };\n return defineIncrementalCollection({ dependencies: dependencyMap, build: build as never });\n}\n\ntype GroupShape = number | { readonly [key: string]: GroupShape };\nconst groupOutputMetadata = new WeakMap<\n object,\n { readonly isEqual?: (a: unknown, b: unknown) => boolean }\n>();\n\nconst isPlainGroupNamespace = (value: unknown): value is Record<string, unknown> =>\n value !== null &&\n typeof value === 'object' &&\n !groupOutputMetadata.has(value) &&\n !Array.isArray(value) &&\n (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);\n\nconst compileGroupShape = (\n value: unknown,\n path: readonly string[],\n declaredOutputs: ReadonlySet<object>,\n used: Set<object>,\n outputs: {\n readonly path: readonly string[];\n readonly isEqual?: (a: unknown, b: unknown) => boolean;\n }[]\n): GroupShape => {\n if (value !== null && typeof value === 'object') {\n const metadata = groupOutputMetadata.get(value);\n if (metadata) {\n if (!declaredOutputs.has(value))\n throw new TypeError('Incremental group outputs must be declared by this group.');\n if (used.has(value)) throw new TypeError('An incremental group output cannot be reused.');\n used.add(value);\n const index = outputs.length;\n outputs.push({ path: Object.freeze([...path]), isEqual: metadata.isEqual });\n return index;\n }\n }\n if (!isPlainGroupNamespace(value))\n throw new TypeError('Incremental group outputs must be a static object tree.');\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== 'string')\n throw new TypeError('Incremental group output names must be strings.');\n if (!Object.prototype.propertyIsEnumerable.call(value, key))\n throw new TypeError('Incremental group namespaces must contain enumerable properties.');\n }\n const keys = Object.keys(value);\n if (!keys.length) throw new TypeError('Incremental group namespaces cannot be empty.');\n const result: Record<string, GroupShape> = Object.create(null) as Record<string, GroupShape>;\n for (const key of keys) {\n if (key === '__proto__' || key === 'prototype' || key === 'constructor')\n throw new TypeError(`Invalid incremental group output name: ${key}`);\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (!descriptor || !('value' in descriptor))\n throw new TypeError('Incremental group namespaces cannot contain accessors.');\n result[key] = compileGroupShape(\n descriptor.value,\n [...path, key],\n declaredOutputs,\n used,\n outputs\n );\n }\n return Object.freeze(result);\n};\n\nconst hydrateGroupShape = <T>(shape: GroupShape, values: readonly T[]): unknown => {\n if (typeof shape === 'number') return values[shape];\n const result: Record<string, unknown> = {};\n for (const [key, child] of Object.entries(shape)) result[key] = hydrateGroupShape(child, values);\n return Object.freeze(result);\n};\n\nfunction createIncrementalGroup<\n const D extends readonly Projection<unknown, unknown>[],\n const O extends GroupOutputShape,\n>(\n dependencies: D,\n defineOutputs: (define: GroupOutputBuilder) => O,\n processor: IncrementalGroupProcessor<D, O>\n): GroupProjections<O> {\n const dependencyMap = dependenciesOf(dependencies);\n if (typeof defineOutputs !== 'function')\n throw new TypeError('Incremental group outputs must be declared by a callback.');\n if (typeof processor !== 'function')\n throw new TypeError('Incremental group processor must be a function.');\n let active = true;\n const declaredOutputs = new Set<object>();\n const defineOutput: GroupOutputBuilder = {\n collection: <K extends string, V>(equality?: (previous: V, next: V) => boolean) => {\n if (!active) throw new TypeError('Incremental group output declarations are synchronous.');\n const descriptor = Object.freeze({});\n groupOutputMetadata.set(descriptor, {\n isEqual: equality as ((a: unknown, b: unknown) => boolean) | undefined,\n });\n declaredOutputs.add(descriptor);\n return descriptor as GroupOutput<K, V>;\n },\n };\n const declared = defineOutputs(defineOutput);\n assertSynchronous(declared);\n active = false;\n const outputs: {\n readonly path: readonly string[];\n readonly isEqual?: (a: unknown, b: unknown) => boolean;\n }[] = [];\n const used = new Set<object>();\n const shape = compileGroupShape(declared, [], declaredOutputs, used, outputs);\n if (typeof shape === 'number')\n throw new TypeError('Incremental group declarations must return an output namespace.');\n if (used.size === 0 || used.size !== declaredOutputs.size)\n throw new TypeError('Every incremental group output must be returned by the declaration.');\n const stateFactory = () => Object.create(null) as Record<string, unknown>;\n const build = (input: {\n readonly sources: Record<string, unknown>;\n readonly previous: readonly CollectionRead<string, unknown>[];\n readonly next: readonly CollectionRead<string, unknown>[];\n readonly outputs: readonly CollectionDraft<string, unknown>[];\n }) => {\n const state = stateFactory();\n const run = (nextInput: typeof input, reset: boolean) => {\n const publicInput = publicInputs(nextInput.sources, reset);\n const result = processor({\n sources: publicInput.values as ProjectionValues<D>,\n changes: publicInput.changes as ProjectionChanges<D>,\n previous: hydrateGroupShape(shape, nextInput.previous) as GroupReads<O>,\n next: hydrateGroupShape(shape, nextInput.next) as GroupReads<O>,\n outputs: hydrateGroupShape(shape, nextInput.outputs) as GroupDrafts<O>,\n reset,\n cause: sourceCause(nextInput.sources),\n state,\n });\n assertSynchronous(result);\n return result;\n };\n const result = run(input, true);\n if (isRebuild(result))\n throw new TypeError('Initial incremental group processor cannot rebuild.');\n return {\n update: (nextInput: typeof input) => {\n const result = run(nextInput, false);\n return isRebuild(result) ? result : undefined;\n },\n };\n };\n const group = defineIncrementalGroup({\n dependencies: dependencyMap,\n outputs,\n build: build as never,\n });\n const materialized = hydrateGroupShape(shape, group.projections) as GroupProjections<O>;\n return materialized;\n}\n\nexport const incremental = Object.assign(createIncrementalValue, {\n collection: createIncrementalCollection,\n group: createIncrementalGroup,\n});\n\nexport type IncrementalDependencies<D extends readonly Projection<unknown, unknown>[]> =\n DependencyMap<D>;\n\nexport type { CollectionChange } from './contract';\n"],"mappings":";;;AA6FA,MAAM,8BAAc,IAAI,SAA6B;AACrD,MAAM,yBAAS,IAAI,SAAyB;AAE5C,MAAM,UAA4B,eAA6C;CAC7E,MAAM,SAAS,OAAO,OAAO,EAAE,CAAC;AAChC,aAAY,IAAI,QAAQ,WAAW;AACnC,QAA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,KAAK,SAAS,gBAAgB,KACnD,OAAM,IAAI,UAAU,sEAAsE;CAC5F,MAAM,qBAAqB,OAAO,OAAO,KAAK;CAC9C,MAAM,SAAS,UAKT;EACJ,MAAM,QAAQ,cAAc;EAC5B,MAAM,OAAO,WAAyB,UAAmB;GACvD,MAAM,cAAc,aAAa,UAAU,SAAS,MAAM;GAC1D,MAAM,SAAS,UAAU;IACvB,SAAS,YAAY;IACrB,SAAS,YAAY;IACrB,UAAU,kBAAkB,OAAO,UAAU,SAAS;IACtD,MAAM,kBAAkB,OAAO,UAAU,KAAK;IAC9C,SAAS,kBAAkB,OAAO,UAAU,QAAQ;IACpD;IACA,OAAO,YAAY,UAAU,QAAQ;IACrC;IACD,CAAC;AACF,qBAAkB,OAAO;AACzB,UAAO;;AAGT,MAAI,UADW,IAAI,OAAO,KACN,CAAC,CACnB,OAAM,IAAI,UAAU,sDAAsD;AAC5E,SAAO,EACL,SAAS,cAA4B;GACnC,MAAM,SAAS,IAAI,WAAW,MAAM;AACpC,UAAO,UAAU,OAAO,GAAG,SAAS,KAAA;KAEvC;;AAQH,QADqB,kBAAkB,OALzB,uBAAuB;EACnC,cAAc;EACd;EACO;EACR,CACkD,CAAC,YACjC;;AAGrB,MAAa,cAAc,OAAO,OAAO,wBAAwB;CAC/D,YAAY;CACZ,OAAO;CACR,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"issue-DVaGQGeP.js","names":["isRecord","isRecord","contains","anchor.indexedKeys","isTree"],"sources":["../core/src/profile.ts","../core/src/mutation/anchor.ts","../core/src/value/ownership.ts","../core/src/mutation/tree.ts","../core/src/address.ts","../core/src/mutation/issue.ts"],"sourcesContent":["const counters = () => ({\n projection: {\n sourceEvents: 0,\n scheduledNodes: 0,\n processedNodes: 0,\n touchedKeys: 0,\n changedKeys: 0,\n publishedNodes: 0,\n flushes: 0,\n },\n copy: { structures: 0 },\n equality: { calls: 0, containers: 0 },\n recorder: {\n facts: 0,\n groups: 0,\n transitions: 0,\n absorbed: 0,\n orderSnapshots: 0,\n orderCaptures: 0,\n orderItems: 0,\n publishedOrderItems: 0,\n treeNodes: 0,\n sealed: 0,\n indexedGroups: 0,\n },\n access: { scopes: 0, proxies: 0, snapshots: 0, addresses: 0, resolutions: 0 },\n address: {\n schemaSteps: 0,\n documentSteps: 0,\n prefixComparisons: 0,\n segmentsCompared: 0,\n arraysCopied: 0,\n listIndexes: 0,\n listItems: 0,\n },\n impact: { affectsChecks: 0, indexes: 0 },\n collectionView: { mappedItems: 0, idsScanned: 0, arraysCopied: 0 },\n materialized: { updated: 0, rebuilt: 0, notifications: 0 },\n});\ntype Counters = ReturnType<typeof counters>;\ntype DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] };\nexport type ProfileSnapshot = DeepReadonly<Counters>;\nlet active: Counters | undefined;\nconst freeze = <T extends object>(value: T): DeepReadonly<T> => {\n Object.values(value).forEach(child => {\n if (child && typeof child === 'object') freeze(child);\n });\n return Object.freeze(value) as DeepReadonly<T>;\n};\nexport const profile = {\n projection: (key: keyof Counters['projection'], amount = 1) => {\n if (active) active.projection[key] += amount;\n },\n recorder: (key: keyof Counters['recorder'], amount = 1) => {\n if (active) active.recorder[key] += amount;\n },\n access: (key: keyof Counters['access']) => {\n if (active) active.access[key]++;\n },\n copy: {\n structure: () => {\n if (active) active.copy.structures++;\n },\n },\n equality: {\n call: () => {\n if (active) active.equality.calls++;\n },\n container: () => {\n if (active) active.equality.containers++;\n },\n },\n address: {\n listIndex: (items: number) => {\n if (active) {\n active.address.listIndexes++;\n active.address.listItems += items;\n }\n },\n schemaStep: () => {\n if (active) active.address.schemaSteps++;\n },\n documentStep: () => {\n if (active) active.address.documentSteps++;\n },\n arrayCopied: () => {\n if (active) active.address.arraysCopied++;\n },\n prefixComparison: () => {\n if (active) active.address.prefixComparisons++;\n },\n segmentCompared: () => {\n if (active) active.address.segmentsCompared++;\n },\n },\n impact: {\n index: () => {\n if (active) active.impact.indexes++;\n },\n affects: () => {\n if (active) active.impact.affectsChecks++;\n },\n },\n collectionView: {\n mapped: () => {\n if (active) active.collectionView.mappedItems++;\n },\n idsScanned: (amount = 1) => {\n if (active) active.collectionView.idsScanned += amount;\n },\n arrayCopied: () => {\n if (active) active.collectionView.arraysCopied++;\n },\n },\n materialized: {\n updated: () => {\n if (active) active.materialized.updated++;\n },\n rebuilt: () => {\n if (active) active.materialized.rebuilt++;\n },\n notification: () => {\n if (active) active.materialized.notifications++;\n },\n },\n};\nexport type ProfileSession = { snapshot(): ProfileSnapshot; stop(): ProfileSnapshot };\nexport const startProfile = (): ProfileSession => {\n if (active) throw new Error('A document profile session is already active.');\n const value = counters();\n active = value;\n const snapshot = () => freeze(structuredClone(value));\n return {\n snapshot,\n stop: () => {\n if (active === value) active = undefined;\n return snapshot();\n },\n };\n};\nexport const measureProfile = <T>(run: () => T): { value: T; profile: ProfileSnapshot } => {\n const session = startProfile();\n try {\n return { value: run(), profile: session.stop() };\n } finally {\n session.stop();\n }\n};\n","import type { DocumentAnchor } from '../schema';\nimport { profile } from '../profile';\n\nexport const equal = (left: readonly string[], right: Keys): boolean => {\n profile.equality.call();\n if (left === right) return true;\n profile.equality.container();\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) if (left[i] !== keyAt(right, i)) return false;\n return true;\n};\n\nexport type KeyOrder = {\n readonly length: number;\n readonly at: (index: number) => string | undefined;\n readonly index: (key: string) => number;\n};\n\ntype Keys = readonly string[] | KeyOrder;\n\nconst length = (keys: Keys): number => keys.length;\nconst keyAt = (keys: Keys, index: number): string | undefined =>\n Array.isArray(keys) ? keys[index] : keys.at(index);\nconst keyIndex = (keys: Keys, key: string): number =>\n Array.isArray(keys) ? keys.indexOf(key) : (keys as KeyOrder).index(key);\n\nexport const keys = (values: readonly unknown[], keyOf: (value: unknown) => string): KeyOrder => ({\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n for (let index = 0; index < values.length; index += 1)\n if (keyOf(values[index]) === key) return index;\n return -1;\n },\n});\n\nconst listIndexes = new WeakMap<\n readonly unknown[],\n { keyOf: (value: unknown) => string; order: KeyOrder }\n>();\n\n/** Canonical lists keep their key positions until a structural write invalidates them. */\nexport const indexedKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): KeyOrder => {\n const cached = listIndexes.get(values);\n if (cached?.keyOf === keyOf) return cached.order;\n let positions: Map<string, number> | undefined;\n const order: KeyOrder = {\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let i = 0; i < values.length; i++) positions.set(keyOf(values[i]), i);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n listIndexes.set(values, { keyOf, order });\n return order;\n};\n\n/** Structural sequence writes own invalidation, including rollback writes. */\nexport const insert = (values: unknown[], index: number, value: unknown): void => {\n values.splice(index, 0, value);\n listIndexes.delete(values);\n};\n\nexport const remove = (values: unknown[], index: number): void => {\n values.splice(index, 1);\n listIndexes.delete(values);\n};\n\nexport const move = (values: unknown[], from: number, to: number): void => {\n const [value] = values.splice(from, 1);\n values.splice(to, 0, value);\n listIndexes.delete(values);\n};\n\nexport const install = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n const byKey = new Map<string, unknown>();\n for (const value of values) byKey.set(keyOf(value), value);\n values.length = order.length;\n for (let index = 0; index < order.length; index++) values[index] = byKey.get(order[index]);\n listIndexes.delete(values);\n};\n\nexport const matches = (order: readonly string[], members: readonly string[]): boolean => {\n if (order.length !== members.length) return false;\n const ids = new Set(order);\n return ids.size === order.length && members.every(id => ids.has(id));\n};\n\nexport const index = (keys: Keys, anchor?: DocumentAnchor): number => {\n if (!anchor) return length(keys);\n if ('at' in anchor) return anchor.at === 'start' ? 0 : length(keys);\n if ('before' in anchor) return keyIndex(keys, anchor.before);\n return keyIndex(keys, anchor.after) + 1;\n};\n\nexport const at = (keys: Keys, position: number): DocumentAnchor =>\n position <= 0 ? { at: 'start' } : { after: keyAt(keys, position - 1) as string };\n\nexport const valid = (keys: Keys, anchor?: DocumentAnchor): boolean => {\n if (!anchor) return true;\n if (typeof anchor !== 'object' || anchor === null) return false;\n if (Number('at' in anchor) + Number('before' in anchor) + Number('after' in anchor) !== 1)\n return false;\n if ('at' in anchor) return anchor.at === 'start' || anchor.at === 'end';\n return keyIndex(keys, 'before' in anchor ? anchor.before : anchor.after) >= 0;\n};\n\nexport const afterRemove = (keys: Keys, removedIndex: number, anchor?: DocumentAnchor): number => {\n const position = index(keys, anchor);\n return position > removedIndex ? position - 1 : position;\n};\n\nexport const validPositions = (length: number, positions: readonly number[]): boolean => {\n let previous = -1;\n for (let index = 0; index < positions.length; index += 1) {\n const position = positions[index];\n if (\n !Number.isInteger(position) ||\n position < 0 ||\n position <= previous ||\n position > length + index\n )\n return false;\n previous = position;\n }\n return true;\n};\n\nexport const restore = (\n keys: string[],\n inserted: readonly string[],\n positions: readonly number[]\n): void => {\n const currentLength = keys.length;\n if (inserted.length !== positions.length || !validPositions(currentLength, positions))\n throw new Error('Ordered restore positions are invalid.');\n let readIndex = currentLength - 1;\n let insertedIndex = inserted.length - 1;\n keys.length = currentLength + inserted.length;\n for (let writeIndex = keys.length - 1; writeIndex >= 0; writeIndex -= 1) {\n if (insertedIndex >= 0 && positions[insertedIndex] === writeIndex) {\n keys[writeIndex] = inserted[insertedIndex];\n insertedIndex -= 1;\n } else {\n keys[writeIndex] = keys[readIndex];\n readIndex -= 1;\n }\n }\n};\n","export const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n","import { isRecord } from '../value/ownership';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(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' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n 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\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { DocumentAddress, DocumentNode, ObjectNode, ObjectShape } from './schema';\nimport * as anchor from './mutation/anchor';\nimport { profile } from './profile';\nimport type { MutableTree } from './mutation/tree';\nimport { is as isTree } from './mutation/tree';\n\n/** The only resolved address representation used inside the runtime. */\nexport type AddressRef = {\n readonly path: number;\n readonly address: DocumentAddress;\n};\n\ntype RegistryNode = {\n readonly static: Map<string, RegistryNode>;\n dynamic?: RegistryNode;\n path?: number;\n};\n\ntype Registry = {\n readonly root: RegistryNode;\n nextPath: number;\n};\n\nconst registries = new WeakMap<object, Registry>();\nconst registryNode = (): RegistryNode => ({ static: new Map() });\nconst registryFor = (schema: ObjectNode): Registry => {\n const cached = registries.get(schema as object);\n if (cached) return cached;\n const registry: Registry = { root: registryNode(), nextPath: 0 };\n registries.set(schema as object, registry);\n return registry;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst variantNode = (\n node: Extract<DocumentNode, { kind: 'variant' }>,\n value: unknown\n): DocumentNode | undefined => {\n const tag = isRecord(value) && typeof value[node.tag] === 'string' ? value[node.tag] : undefined;\n return node.variants[String(tag ?? Object.keys(node.variants)[0] ?? '')];\n};\n\nconst step = (\n nodeInput: DocumentNode | undefined,\n value: unknown,\n segment: string\n): DocumentNode | undefined => {\n let node = nodeInput;\n if (!node) return undefined;\n if (node.kind === 'variant') {\n node = variantNode(node, value);\n }\n if (!node) return undefined;\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, segment) ? node.shape[segment] : undefined;\n if (node.kind === 'table' || node.kind === 'map') return node.value;\n // List items use stable keys; tree topology remains a structural unit.\n if (node.kind === 'list') return node.value;\n return undefined;\n};\n\nconst pathFor = (\n schema: ObjectNode,\n address: DocumentAddress,\n document?: unknown\n): number | undefined => {\n const registry = registryFor(schema);\n let trie = registry.root;\n let node: DocumentNode | undefined = schema;\n let value: unknown = document;\n for (const segment of address) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, value, segment);\n if (!resolved) return undefined;\n const next =\n node &&\n (node.kind === 'table' || node.kind === 'map' || node.kind === 'list' || node.kind === 'tree')\n ? (trie.dynamic ??= registryNode())\n : (() => {\n const existing = trie.static.get(segment);\n if (existing) return existing;\n const created = registryNode();\n trie.static.set(segment, created);\n return created;\n })();\n trie = next;\n value = readSegment(value, segment, node);\n node = resolved;\n }\n if (trie.path === undefined) trie.path = registry.nextPath++;\n return trie.path;\n};\n\nexport const resolveAddress = (\n schema: ObjectNode,\n address: DocumentAddress,\n document?: unknown\n): AddressRef | undefined => {\n if (!Array.isArray(address)) return undefined;\n for (const segment of address) if (typeof segment !== 'string') return undefined;\n profile.address.arrayCopied();\n const owned = Object.freeze(address.slice()) as DocumentAddress;\n const path = pathFor(schema, owned, document);\n return path === undefined ? undefined : { path, address: owned };\n};\n\nexport const nodeAt = (\n schema: DocumentNode,\n address: DocumentAddress,\n document?: unknown\n): DocumentNode | undefined => {\n let node: DocumentNode | undefined = schema;\n let value = document;\n for (const segment of address) {\n const resolved = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = resolved;\n if (!node) return undefined;\n }\n return node;\n};\n\nexport const readSegment = (value: unknown, segment: string, node?: DocumentNode): unknown => {\n if (!isRecord(value) && !Array.isArray(value)) return undefined;\n if (node?.kind === 'list' && Array.isArray(value))\n return value[anchor.indexedKeys(value, node.keyOf).index(segment)];\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId)) {\n return Object.hasOwn(value.byId, segment) ? value.byId[segment] : undefined;\n }\n return Object.prototype.hasOwnProperty.call(value, segment)\n ? (value as Record<string, unknown>)[segment]\n : undefined;\n};\n\nexport const read = (root: unknown, address: DocumentAddress, schema: DocumentNode): unknown => {\n let value = root;\n let node: DocumentNode | undefined = schema;\n for (const segment of address) {\n const next = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = next;\n if (value === undefined) return undefined;\n }\n return value;\n};\n\nexport type ResolvedAddress = {\n readonly parent: Record<string, unknown> | unknown[];\n readonly key: string | number;\n readonly node: DocumentNode;\n};\n\ntype MemberDefinition = {\n readonly node: DocumentNode;\n readonly field: boolean;\n};\nexport type FixedMember = MemberDefinition & {\n readonly kind: 'fixed';\n readonly key: string;\n readonly slot: number;\n};\ntype CollectionMember = MemberDefinition & { readonly kind: 'entry' };\nexport type CompiledMember = FixedMember | CollectionMember;\nexport type FixedLayout = {\n readonly kind: 'fixed';\n readonly members: ReadonlyMap<string, FixedMember>;\n};\ntype DynamicLayout = { readonly kind: 'dynamic'; readonly entry: CollectionMember };\nexport type MemberLayout = FixedLayout | DynamicLayout;\nconst compiledObjects = new WeakMap<object, FixedLayout>();\nconst compiledEntries = new WeakMap<DocumentNode, DynamicLayout>();\nexport const compiledShape = (node: DocumentNode, value: unknown): FixedLayout | undefined => {\n const branch = node.kind === 'variant' ? variantNode(node, value) : node;\n if (branch?.kind !== 'object') return undefined;\n const shape: ObjectShape = branch.shape;\n let layout = compiledObjects.get(shape);\n if (!layout) {\n const compiled = new Map<string, FixedMember>();\n for (const key of Object.keys(shape).sort()) {\n profile.address.schemaStep();\n compiled.set(key, {\n kind: 'fixed',\n key,\n node: shape[key],\n field: shape[key].kind === 'field',\n slot: compiled.size,\n });\n }\n layout = { kind: 'fixed', members: compiled };\n compiledObjects.set(shape, layout);\n }\n return layout;\n};\n\n/** Immutable location facts, valid only for the resolving session generation. */\nexport type ResolvedContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Exclude<DocumentNode, { kind: 'tree' }>;\n readonly parent: Record<string, unknown> | unknown[];\n readonly value: unknown;\n readonly layout: MemberLayout;\n};\nexport type ResolvedTreeContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Extract<DocumentNode, { kind: 'tree' }>;\n readonly value: MutableTree;\n};\nexport const resolveContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedContainer | undefined => {\n if (!node || (!isRecord(value) && !Array.isArray(value))) return undefined;\n const parent = node.kind === 'table' && isRecord(value) ? value.byId : value;\n if (!isRecord(parent) && !Array.isArray(parent)) return undefined;\n if (node.kind === 'tree') return undefined;\n let layout: MemberLayout;\n if (node.kind === 'map' || node.kind === 'table' || node.kind === 'list') {\n let dynamic = compiledEntries.get(node);\n if (!dynamic) {\n dynamic = {\n kind: 'dynamic',\n entry: { kind: 'entry', node: node.value, field: node.value.kind === 'field' },\n };\n compiledEntries.set(node, dynamic);\n }\n layout = dynamic;\n } else {\n const fixed = compiledShape(node, value);\n if (!fixed) return undefined;\n layout = fixed;\n }\n return { owner, generation, at, node, parent, value, layout };\n};\nexport const resolveTreeContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedTreeContainer | undefined =>\n node?.kind === 'tree' && isTree(value) ? { owner, generation, at, node, value } : undefined;\nexport const memberKey = (\n container: { readonly node: DocumentNode; readonly parent: Record<string, unknown> | unknown[] },\n key: string\n): string | number =>\n container.node.kind === 'list'\n ? anchor.indexedKeys(container.parent as unknown[], container.node.keyOf).index(key)\n : key;\n\ntype ResolutionPrefix = {\n segment: string;\n node: DocumentNode;\n value: unknown;\n};\n\n/** One recent path per transaction; structural writes invalidate all retained locations. */\nexport const createAddressResolver = (schema: DocumentNode, root: unknown) => {\n const prefix: ResolutionPrefix[] = [];\n return {\n container: (owner: object, generation: number, at: DocumentAddress) => {\n if (!at.length) return resolveContainer(owner, generation, at, schema, root);\n const location = resolveWithPrefix(schema, root, at, prefix);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return resolveContainer(\n owner,\n generation,\n at,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n },\n invalidate: () => {\n prefix.length = 0;\n },\n };\n};\n\n/** A subtree root is a value, not a fabricated member of an ObjectNode. */\nexport const resolveValue = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): { node: DocumentNode; value: unknown } | undefined => {\n if (!address.length) return { node: schema, value: root };\n const location = resolveWithPrefix(schema, root, address, prefix);\n return (\n location && {\n node: location.node,\n value: Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined,\n }\n );\n};\n\n/** Resolves schema and document location in one address traversal. */\nexport const resolveLocated = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress\n): ResolvedAddress | undefined => resolveWithPrefix(schema, root, address);\n\nconst resolveWithPrefix = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): ResolvedAddress | undefined => {\n if (address.length === 0) return undefined;\n let node: DocumentNode | undefined = schema;\n let current: unknown = root;\n let start = 0;\n if (prefix) {\n while (\n start < prefix.length &&\n start < address.length - 1 &&\n prefix[start].segment === address[start]\n )\n start++;\n prefix.length = start;\n if (start) {\n const retained = prefix[start - 1];\n node = retained.node;\n current = retained.value;\n }\n }\n let cacheable = true;\n for (let index = start; index < address.length - 1; index += 1) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, address[index]);\n if (!resolved) return undefined;\n if (node?.kind !== 'object' && node?.kind !== 'table' && node?.kind !== 'map')\n cacheable = false;\n current = readSegment(current, address[index], node);\n node = resolved;\n if (prefix && cacheable)\n prefix.push({\n segment: address[index],\n node: resolved,\n value: current,\n });\n if (!node) return undefined;\n }\n const last = address[address.length - 1];\n return resolveChild(node, current, last);\n};\n\n/** Resolves one member from an already current schema/container pair. */\nexport const resolveChild = (\n node: DocumentNode | undefined,\n current: unknown,\n last: string\n): ResolvedAddress | undefined => {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, last);\n if (!resolved || (!isRecord(current) && !Array.isArray(current))) return undefined;\n if (node?.kind === 'table' && isRecord(current) && isRecord(current.byId))\n return {\n node: resolved,\n parent: current.byId,\n key: last,\n };\n return {\n node: resolved,\n parent: current,\n key:\n node?.kind === 'list' && Array.isArray(current)\n ? anchor.indexedKeys(current, node.keyOf).index(last)\n : last,\n };\n};\n\nexport const contains = (parent: DocumentAddress, child: DocumentAddress): boolean => {\n profile.address.prefixComparison();\n if (parent.length > child.length) return false;\n for (let index = 0; index < parent.length; index += 1) {\n profile.address.segmentCompared();\n if (parent[index] !== child[index]) return false;\n }\n return true;\n};\n\nexport const overlaps = (a: DocumentAddress, b: DocumentAddress): boolean =>\n contains(a, b) || contains(b, a);\n\nexport const debugKey = (address: DocumentAddress): string => {\n let result = '';\n for (let index = 0; index < address.length; index += 1) {\n if (index > 0) result += '/';\n result += address[index].replaceAll('~', '~~').replaceAll('/', '~/');\n }\n return result;\n};\n\nexport const same = (a: AddressRef, b: AddressRef): boolean => {\n if (a.path !== b.path || a.address.length !== b.address.length) return false;\n for (let index = 0; index < a.address.length; index += 1) {\n profile.address.segmentCompared();\n if (a.address[index] !== b.address[index]) return false;\n }\n return true;\n};\n\nexport type { DocumentAddress } from './schema';\n\ntype AddressIndexNode<T> = {\n readonly children: Map<string, AddressIndexNode<T>>;\n readonly values: Set<T>;\n};\n\n/** An index over canonical address segments, shared by impact and subscriptions. */\nexport class AddressIndex<T> {\n private readonly root: AddressIndexNode<T> = { children: new Map(), values: new Set() };\n\n add(address: DocumentAddress, value: T, member?: string): void {\n let node = this.root;\n for (let i = 0; i < address.length + (member === undefined ? 0 : 1); i++) {\n const segment = i < address.length ? address[i] : member!;\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), values: new Set() };\n node.children.set(segment, child);\n }\n node = child;\n }\n node.values.add(value);\n }\n\n delete(address: DocumentAddress, value: T): void {\n const parents: AddressIndexNode<T>[] = [];\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return;\n parents.push(node);\n node = child;\n }\n node.values.delete(value);\n for (let i = address.length - 1; i >= 0 && !node.values.size && !node.children.size; i--) {\n node = parents[i];\n node.children.delete(address[i]);\n }\n }\n\n exact(address: DocumentAddress): ReadonlySet<T> | undefined {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return undefined;\n node = child;\n }\n return node.values;\n }\n\n hasAncestor(address: DocumentAddress, strict = false): boolean {\n let node = this.root;\n for (let i = 0; i < address.length; i++) {\n if (node.values.size) return true;\n const child = node.children.get(address[i]);\n if (!child) return false;\n node = child;\n }\n return !strict && node.values.size > 0;\n }\n\n someAncestor(address: DocumentAddress, predicate: (value: T) => boolean): boolean {\n let node = this.root;\n for (let i = 0; ; i++) {\n for (const value of node.values) if (predicate(value)) return true;\n if (i === address.length) return false;\n const child = node.children.get(address[i]);\n if (!child) return false;\n node = child;\n }\n }\n\n overlaps(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n if (node.values.size) return true;\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n hasDescendant(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n query(\n visit: (value: T) => void,\n relation: 'overlap' | 'ancestors' | 'descendants' = 'overlap'\n ): (address: DocumentAddress, members?: readonly { readonly key: string }[]) => void {\n const visited = new Set<AddressIndexNode<T>>();\n const subtrees = new Set<AddressIndexNode<T>>();\n const values = (node: AddressIndexNode<T>) => {\n if (visited.has(node)) return;\n visited.add(node);\n node.values.forEach(visit);\n };\n const descend = (current: AddressIndexNode<T>): void => {\n if (subtrees.has(current)) return;\n subtrees.add(current);\n values(current);\n current.children.forEach(descend);\n };\n const terminal = (node: AddressIndexNode<T>) =>\n relation === 'ancestors' ? values(node) : descend(node);\n return (address, members) => {\n let node = this.root;\n for (const segment of address) {\n if (subtrees.has(node)) return;\n if (relation !== 'descendants') values(node);\n const child = node.children.get(segment);\n if (!child) return;\n node = child;\n }\n if (!members) terminal(node);\n else {\n if (relation !== 'descendants') values(node);\n for (const member of members) {\n const child = node.children.get(member.key);\n if (child) terminal(child);\n }\n }\n };\n }\n\n clear(): void {\n this.root.values.clear();\n this.root.children.clear();\n }\n}\n","import type { DocumentAddress } from '../schema';\nimport type { ParseIssue } from '../schema-value';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-value'\n | 'invalid-key'\n | 'invalid-changes'\n | 'baseline-mismatch'\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';\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n};\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string\n): MutationIssue =>\n Object.freeze({ source: 'mutation', code, address: Object.freeze([...address]), message });\nexport class MutationRejected extends Error {\n constructor(readonly issue: MutationIssue) {\n super(issue.message);\n }\n}\nexport const fail = (address: DocumentAddress, code: MutationIssueCode, message: string): never => {\n throw new MutationRejected(at(address, code, message));\n};\n\nexport const invalidValue = (issue: ParseIssue, address = issue.address): never =>\n fail(address, issue.code === 'missing-validator' ? 'invalid-value' : issue.code, issue.message);\n"],"mappings":"AAiDA,MAAa,UAAU;CACrB,aAAa,KAAmC,SAAS,MAAM;CAG/D,WAAW,KAAiC,SAAS,MAAM;CAG3D,SAAS,QAAkC;CAG3C,MAAM,EACJ,iBAAiB,IAGlB;CACD,UAAU;EACR,YAAY;EAGZ,iBAAiB;EAGlB;CACD,SAAS;EACP,YAAY,UAAkB;EAM9B,kBAAkB;EAGlB,oBAAoB;EAGpB,mBAAmB;EAGnB,wBAAwB;EAGxB,uBAAuB;EAGxB;CACD,QAAQ;EACN,aAAa;EAGb,eAAe;EAGhB;CACD,gBAAgB;EACd,cAAc;EAGd,aAAa,SAAS,MAAM;EAG5B,mBAAmB;EAGpB;CACD,cAAc;EACZ,eAAe;EAGf,eAAe;EAGf,oBAAoB;EAGrB;CACF;;;AC1HD,MAAa,SAAS,MAAyB,UAAyB;AACtE,SAAQ,S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Aa,cAAe,QAAO,KAAK;IAC5C,MAAM,QAAQ,KAAK,SAAS,IAAI,QAAQ;AACxC,QAAI,CAAC,MAAO;AACZ,WAAO;;AAET,OAAI,CAAC,QAAS,UAAS,KAAK;QACvB;AACH,QAAI,aAAa,cAAe,QAAO,KAAK;AAC5C,SAAK,MAAM,UAAU,SAAS;KAC5B,MAAM,QAAQ,KAAK,SAAS,IAAI,OAAO,IAAI;AAC3C,SAAI,MAAO,UAAS,MAAM;;;;;CAMlC,QAAc;AACZ,OAAK,KAAK,OAAO,OAAO;AACxB,OAAK,KAAK,SAAS,OAAO;;;;;ACzgB9B,MAAa,MACX,SACA,MACA,YAEA,OAAO,OAAO;CAAE,QAAQ;CAAY;CAAM,SAAS,OAAO,OAAO,CAAC,GAAG,QAAQ,CAAC;CAAE;CAAS,CAAC;AAC5F,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,OAA+B;AACzC,QAAM,MAAM,QAAQ;AADD,OAAA,QAAA;;;AAIvB,MAAa,QAAQ,SAA0B,MAAyB,YAA2B;AACjG,OAAM,IAAI,iBAAiB,GAAG,SAAS,MAAM,QAAQ,CAAC;;AAGxD,MAAa,gBAAgB,OAAmB,UAAU,MAAM,YAC9D,KAAK,SAAS,MAAM,SAAS,sBAAsB,kBAAkB,MAAM,MAAM,MAAM,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"issue-DhrNdQNg.cjs","names":["isRecord","isRecord","contains","anchor.indexedKeys","isTree"],"sources":["../core/src/profile.ts","../core/src/mutation/anchor.ts","../core/src/value/ownership.ts","../core/src/mutation/tree.ts","../core/src/address.ts","../core/src/mutation/issue.ts"],"sourcesContent":["const counters = () => ({\n projection: {\n sourceEvents: 0,\n scheduledNodes: 0,\n processedNodes: 0,\n touchedKeys: 0,\n changedKeys: 0,\n publishedNodes: 0,\n flushes: 0,\n },\n copy: { structures: 0 },\n equality: { calls: 0, containers: 0 },\n recorder: {\n facts: 0,\n groups: 0,\n transitions: 0,\n absorbed: 0,\n orderSnapshots: 0,\n orderCaptures: 0,\n orderItems: 0,\n publishedOrderItems: 0,\n treeNodes: 0,\n sealed: 0,\n indexedGroups: 0,\n },\n access: { scopes: 0, proxies: 0, snapshots: 0, addresses: 0, resolutions: 0 },\n address: {\n schemaSteps: 0,\n documentSteps: 0,\n prefixComparisons: 0,\n segmentsCompared: 0,\n arraysCopied: 0,\n listIndexes: 0,\n listItems: 0,\n },\n impact: { affectsChecks: 0, indexes: 0 },\n collectionView: { mappedItems: 0, idsScanned: 0, arraysCopied: 0 },\n materialized: { updated: 0, rebuilt: 0, notifications: 0 },\n});\ntype Counters = ReturnType<typeof counters>;\ntype DeepReadonly<T> = { readonly [K in keyof T]: T[K] extends object ? DeepReadonly<T[K]> : T[K] };\nexport type ProfileSnapshot = DeepReadonly<Counters>;\nlet active: Counters | undefined;\nconst freeze = <T extends object>(value: T): DeepReadonly<T> => {\n Object.values(value).forEach(child => {\n if (child && typeof child === 'object') freeze(child);\n });\n return Object.freeze(value) as DeepReadonly<T>;\n};\nexport const profile = {\n projection: (key: keyof Counters['projection'], amount = 1) => {\n if (active) active.projection[key] += amount;\n },\n recorder: (key: keyof Counters['recorder'], amount = 1) => {\n if (active) active.recorder[key] += amount;\n },\n access: (key: keyof Counters['access']) => {\n if (active) active.access[key]++;\n },\n copy: {\n structure: () => {\n if (active) active.copy.structures++;\n },\n },\n equality: {\n call: () => {\n if (active) active.equality.calls++;\n },\n container: () => {\n if (active) active.equality.containers++;\n },\n },\n address: {\n listIndex: (items: number) => {\n if (active) {\n active.address.listIndexes++;\n active.address.listItems += items;\n }\n },\n schemaStep: () => {\n if (active) active.address.schemaSteps++;\n },\n documentStep: () => {\n if (active) active.address.documentSteps++;\n },\n arrayCopied: () => {\n if (active) active.address.arraysCopied++;\n },\n prefixComparison: () => {\n if (active) active.address.prefixComparisons++;\n },\n segmentCompared: () => {\n if (active) active.address.segmentsCompared++;\n },\n },\n impact: {\n index: () => {\n if (active) active.impact.indexes++;\n },\n affects: () => {\n if (active) active.impact.affectsChecks++;\n },\n },\n collectionView: {\n mapped: () => {\n if (active) active.collectionView.mappedItems++;\n },\n idsScanned: (amount = 1) => {\n if (active) active.collectionView.idsScanned += amount;\n },\n arrayCopied: () => {\n if (active) active.collectionView.arraysCopied++;\n },\n },\n materialized: {\n updated: () => {\n if (active) active.materialized.updated++;\n },\n rebuilt: () => {\n if (active) active.materialized.rebuilt++;\n },\n notification: () => {\n if (active) active.materialized.notifications++;\n },\n },\n};\nexport type ProfileSession = { snapshot(): ProfileSnapshot; stop(): ProfileSnapshot };\nexport const startProfile = (): ProfileSession => {\n if (active) throw new Error('A document profile session is already active.');\n const value = counters();\n active = value;\n const snapshot = () => freeze(structuredClone(value));\n return {\n snapshot,\n stop: () => {\n if (active === value) active = undefined;\n return snapshot();\n },\n };\n};\nexport const measureProfile = <T>(run: () => T): { value: T; profile: ProfileSnapshot } => {\n const session = startProfile();\n try {\n return { value: run(), profile: session.stop() };\n } finally {\n session.stop();\n }\n};\n","import type { DocumentAnchor } from '../schema';\nimport { profile } from '../profile';\n\nexport const equal = (left: readonly string[], right: Keys): boolean => {\n profile.equality.call();\n if (left === right) return true;\n profile.equality.container();\n if (left.length !== right.length) return false;\n for (let i = 0; i < left.length; i++) if (left[i] !== keyAt(right, i)) return false;\n return true;\n};\n\nexport type KeyOrder = {\n readonly length: number;\n readonly at: (index: number) => string | undefined;\n readonly index: (key: string) => number;\n};\n\ntype Keys = readonly string[] | KeyOrder;\n\nconst length = (keys: Keys): number => keys.length;\nconst keyAt = (keys: Keys, index: number): string | undefined =>\n Array.isArray(keys) ? keys[index] : keys.at(index);\nconst keyIndex = (keys: Keys, key: string): number =>\n Array.isArray(keys) ? keys.indexOf(key) : (keys as KeyOrder).index(key);\n\nexport const keys = (values: readonly unknown[], keyOf: (value: unknown) => string): KeyOrder => ({\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n for (let index = 0; index < values.length; index += 1)\n if (keyOf(values[index]) === key) return index;\n return -1;\n },\n});\n\nconst listIndexes = new WeakMap<\n readonly unknown[],\n { keyOf: (value: unknown) => string; order: KeyOrder }\n>();\n\n/** Canonical lists keep their key positions until a structural write invalidates them. */\nexport const indexedKeys = (\n values: readonly unknown[],\n keyOf: (value: unknown) => string\n): KeyOrder => {\n const cached = listIndexes.get(values);\n if (cached?.keyOf === keyOf) return cached.order;\n let positions: Map<string, number> | undefined;\n const order: KeyOrder = {\n length: values.length,\n at: index => (index >= 0 && index < values.length ? keyOf(values[index]) : undefined),\n index: key => {\n if (!positions) {\n positions = new Map();\n for (let i = 0; i < values.length; i++) positions.set(keyOf(values[i]), i);\n profile.address.listIndex(values.length);\n }\n return positions.get(key) ?? -1;\n },\n };\n listIndexes.set(values, { keyOf, order });\n return order;\n};\n\n/** Structural sequence writes own invalidation, including rollback writes. */\nexport const insert = (values: unknown[], index: number, value: unknown): void => {\n values.splice(index, 0, value);\n listIndexes.delete(values);\n};\n\nexport const remove = (values: unknown[], index: number): void => {\n values.splice(index, 1);\n listIndexes.delete(values);\n};\n\nexport const move = (values: unknown[], from: number, to: number): void => {\n const [value] = values.splice(from, 1);\n values.splice(to, 0, value);\n listIndexes.delete(values);\n};\n\nexport const install = (\n values: unknown[],\n keyOf: (value: unknown) => string,\n order: readonly string[]\n): void => {\n const byKey = new Map<string, unknown>();\n for (const value of values) byKey.set(keyOf(value), value);\n values.length = order.length;\n for (let index = 0; index < order.length; index++) values[index] = byKey.get(order[index]);\n listIndexes.delete(values);\n};\n\nexport const matches = (order: readonly string[], members: readonly string[]): boolean => {\n if (order.length !== members.length) return false;\n const ids = new Set(order);\n return ids.size === order.length && members.every(id => ids.has(id));\n};\n\nexport const index = (keys: Keys, anchor?: DocumentAnchor): number => {\n if (!anchor) return length(keys);\n if ('at' in anchor) return anchor.at === 'start' ? 0 : length(keys);\n if ('before' in anchor) return keyIndex(keys, anchor.before);\n return keyIndex(keys, anchor.after) + 1;\n};\n\nexport const at = (keys: Keys, position: number): DocumentAnchor =>\n position <= 0 ? { at: 'start' } : { after: keyAt(keys, position - 1) as string };\n\nexport const valid = (keys: Keys, anchor?: DocumentAnchor): boolean => {\n if (!anchor) return true;\n if (typeof anchor !== 'object' || anchor === null) return false;\n if (Number('at' in anchor) + Number('before' in anchor) + Number('after' in anchor) !== 1)\n return false;\n if ('at' in anchor) return anchor.at === 'start' || anchor.at === 'end';\n return keyIndex(keys, 'before' in anchor ? anchor.before : anchor.after) >= 0;\n};\n\nexport const afterRemove = (keys: Keys, removedIndex: number, anchor?: DocumentAnchor): number => {\n const position = index(keys, anchor);\n return position > removedIndex ? position - 1 : position;\n};\n\nexport const validPositions = (length: number, positions: readonly number[]): boolean => {\n let previous = -1;\n for (let index = 0; index < positions.length; index += 1) {\n const position = positions[index];\n if (\n !Number.isInteger(position) ||\n position < 0 ||\n position <= previous ||\n position > length + index\n )\n return false;\n previous = position;\n }\n return true;\n};\n\nexport const restore = (\n keys: string[],\n inserted: readonly string[],\n positions: readonly number[]\n): void => {\n const currentLength = keys.length;\n if (inserted.length !== positions.length || !validPositions(currentLength, positions))\n throw new Error('Ordered restore positions are invalid.');\n let readIndex = currentLength - 1;\n let insertedIndex = inserted.length - 1;\n keys.length = currentLength + inserted.length;\n for (let writeIndex = keys.length - 1; writeIndex >= 0; writeIndex -= 1) {\n if (insertedIndex >= 0 && positions[insertedIndex] === writeIndex) {\n keys[writeIndex] = inserted[insertedIndex];\n insertedIndex -= 1;\n } else {\n keys[writeIndex] = keys[readIndex];\n readIndex -= 1;\n }\n }\n};\n","export const isPlainObject = (value: unknown): value is Record<string, unknown> => {\n if (value === null || typeof value !== 'object') return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n};\n\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n","import { isRecord } from '../value/ownership';\nexport type MutableTreeNode = { parentId?: string; children: string[]; value?: unknown };\nexport type MutableTree = { rootId?: string; nodes: Record<string, MutableTreeNode> };\nconst node = (tree: MutableTree, id: string) =>\n Object.hasOwn(tree.nodes, id) ? tree.nodes[id] : undefined;\nexport const is = (value: unknown): value is MutableTree =>\n isRecord(value) && isRecord(value.nodes);\n\nexport const validNode = (value: unknown): value is MutableTreeNode => {\n if (!isRecord(value) || !Array.isArray(value.children)) return false;\n if (value.parentId !== undefined && typeof value.parentId !== 'string') return false;\n const children = new Set<string>();\n for (const id of value.children) {\n if (typeof id !== 'string' || children.has(id)) return false;\n children.add(id);\n }\n return true;\n};\n\nexport const contains = (tree: MutableTree, id: string): boolean => Object.hasOwn(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' || !Object.hasOwn(value.nodes, value.rootId)) return false;\n\n for (const id of ids) {\n const entry = value.nodes[id];\n if (!validNode(entry)) return false;\n if (id === value.rootId) {\n if (entry.parentId !== undefined) return false;\n } else if (entry.parentId === undefined || !Object.hasOwn(value.nodes, entry.parentId))\n 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\nexport type TreePosition = { readonly parentId?: string; readonly index?: number };\n","import type { DocumentAddress, DocumentNode, ObjectNode, ObjectShape } from './schema';\nimport * as anchor from './mutation/anchor';\nimport { profile } from './profile';\nimport type { MutableTree } from './mutation/tree';\nimport { is as isTree } from './mutation/tree';\n\n/** The only resolved address representation used inside the runtime. */\nexport type AddressRef = {\n readonly path: number;\n readonly address: DocumentAddress;\n};\n\ntype RegistryNode = {\n readonly static: Map<string, RegistryNode>;\n dynamic?: RegistryNode;\n path?: number;\n};\n\ntype Registry = {\n readonly root: RegistryNode;\n nextPath: number;\n};\n\nconst registries = new WeakMap<object, Registry>();\nconst registryNode = (): RegistryNode => ({ static: new Map() });\nconst registryFor = (schema: ObjectNode): Registry => {\n const cached = registries.get(schema as object);\n if (cached) return cached;\n const registry: Registry = { root: registryNode(), nextPath: 0 };\n registries.set(schema as object, registry);\n return registry;\n};\n\nconst isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\nconst variantNode = (\n node: Extract<DocumentNode, { kind: 'variant' }>,\n value: unknown\n): DocumentNode | undefined => {\n const tag = isRecord(value) && typeof value[node.tag] === 'string' ? value[node.tag] : undefined;\n return node.variants[String(tag ?? Object.keys(node.variants)[0] ?? '')];\n};\n\nconst step = (\n nodeInput: DocumentNode | undefined,\n value: unknown,\n segment: string\n): DocumentNode | undefined => {\n let node = nodeInput;\n if (!node) return undefined;\n if (node.kind === 'variant') {\n node = variantNode(node, value);\n }\n if (!node) return undefined;\n if (node.kind === 'object')\n return Object.hasOwn(node.shape, segment) ? node.shape[segment] : undefined;\n if (node.kind === 'table' || node.kind === 'map') return node.value;\n // List items use stable keys; tree topology remains a structural unit.\n if (node.kind === 'list') return node.value;\n return undefined;\n};\n\nconst pathFor = (\n schema: ObjectNode,\n address: DocumentAddress,\n document?: unknown\n): number | undefined => {\n const registry = registryFor(schema);\n let trie = registry.root;\n let node: DocumentNode | undefined = schema;\n let value: unknown = document;\n for (const segment of address) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, value, segment);\n if (!resolved) return undefined;\n const next =\n node &&\n (node.kind === 'table' || node.kind === 'map' || node.kind === 'list' || node.kind === 'tree')\n ? (trie.dynamic ??= registryNode())\n : (() => {\n const existing = trie.static.get(segment);\n if (existing) return existing;\n const created = registryNode();\n trie.static.set(segment, created);\n return created;\n })();\n trie = next;\n value = readSegment(value, segment, node);\n node = resolved;\n }\n if (trie.path === undefined) trie.path = registry.nextPath++;\n return trie.path;\n};\n\nexport const resolveAddress = (\n schema: ObjectNode,\n address: DocumentAddress,\n document?: unknown\n): AddressRef | undefined => {\n if (!Array.isArray(address)) return undefined;\n for (const segment of address) if (typeof segment !== 'string') return undefined;\n profile.address.arrayCopied();\n const owned = Object.freeze(address.slice()) as DocumentAddress;\n const path = pathFor(schema, owned, document);\n return path === undefined ? undefined : { path, address: owned };\n};\n\nexport const nodeAt = (\n schema: DocumentNode,\n address: DocumentAddress,\n document?: unknown\n): DocumentNode | undefined => {\n let node: DocumentNode | undefined = schema;\n let value = document;\n for (const segment of address) {\n const resolved = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = resolved;\n if (!node) return undefined;\n }\n return node;\n};\n\nexport const readSegment = (value: unknown, segment: string, node?: DocumentNode): unknown => {\n if (!isRecord(value) && !Array.isArray(value)) return undefined;\n if (node?.kind === 'list' && Array.isArray(value))\n return value[anchor.indexedKeys(value, node.keyOf).index(segment)];\n if (node?.kind === 'table' && isRecord(value) && isRecord(value.byId)) {\n return Object.hasOwn(value.byId, segment) ? value.byId[segment] : undefined;\n }\n return Object.prototype.hasOwnProperty.call(value, segment)\n ? (value as Record<string, unknown>)[segment]\n : undefined;\n};\n\nexport const read = (root: unknown, address: DocumentAddress, schema: DocumentNode): unknown => {\n let value = root;\n let node: DocumentNode | undefined = schema;\n for (const segment of address) {\n const next = step(node, value, segment);\n value = readSegment(value, segment, node);\n node = next;\n if (value === undefined) return undefined;\n }\n return value;\n};\n\nexport type ResolvedAddress = {\n readonly parent: Record<string, unknown> | unknown[];\n readonly key: string | number;\n readonly node: DocumentNode;\n};\n\ntype MemberDefinition = {\n readonly node: DocumentNode;\n readonly field: boolean;\n};\nexport type FixedMember = MemberDefinition & {\n readonly kind: 'fixed';\n readonly key: string;\n readonly slot: number;\n};\ntype CollectionMember = MemberDefinition & { readonly kind: 'entry' };\nexport type CompiledMember = FixedMember | CollectionMember;\nexport type FixedLayout = {\n readonly kind: 'fixed';\n readonly members: ReadonlyMap<string, FixedMember>;\n};\ntype DynamicLayout = { readonly kind: 'dynamic'; readonly entry: CollectionMember };\nexport type MemberLayout = FixedLayout | DynamicLayout;\nconst compiledObjects = new WeakMap<object, FixedLayout>();\nconst compiledEntries = new WeakMap<DocumentNode, DynamicLayout>();\nexport const compiledShape = (node: DocumentNode, value: unknown): FixedLayout | undefined => {\n const branch = node.kind === 'variant' ? variantNode(node, value) : node;\n if (branch?.kind !== 'object') return undefined;\n const shape: ObjectShape = branch.shape;\n let layout = compiledObjects.get(shape);\n if (!layout) {\n const compiled = new Map<string, FixedMember>();\n for (const key of Object.keys(shape).sort()) {\n profile.address.schemaStep();\n compiled.set(key, {\n kind: 'fixed',\n key,\n node: shape[key],\n field: shape[key].kind === 'field',\n slot: compiled.size,\n });\n }\n layout = { kind: 'fixed', members: compiled };\n compiledObjects.set(shape, layout);\n }\n return layout;\n};\n\n/** Immutable location facts, valid only for the resolving session generation. */\nexport type ResolvedContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Exclude<DocumentNode, { kind: 'tree' }>;\n readonly parent: Record<string, unknown> | unknown[];\n readonly value: unknown;\n readonly layout: MemberLayout;\n};\nexport type ResolvedTreeContainer = {\n readonly owner: object;\n readonly generation: number;\n readonly at: DocumentAddress;\n readonly node: Extract<DocumentNode, { kind: 'tree' }>;\n readonly value: MutableTree;\n};\nexport const resolveContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedContainer | undefined => {\n if (!node || (!isRecord(value) && !Array.isArray(value))) return undefined;\n const parent = node.kind === 'table' && isRecord(value) ? value.byId : value;\n if (!isRecord(parent) && !Array.isArray(parent)) return undefined;\n if (node.kind === 'tree') return undefined;\n let layout: MemberLayout;\n if (node.kind === 'map' || node.kind === 'table' || node.kind === 'list') {\n let dynamic = compiledEntries.get(node);\n if (!dynamic) {\n dynamic = {\n kind: 'dynamic',\n entry: { kind: 'entry', node: node.value, field: node.value.kind === 'field' },\n };\n compiledEntries.set(node, dynamic);\n }\n layout = dynamic;\n } else {\n const fixed = compiledShape(node, value);\n if (!fixed) return undefined;\n layout = fixed;\n }\n return { owner, generation, at, node, parent, value, layout };\n};\nexport const resolveTreeContainer = (\n owner: object,\n generation: number,\n at: DocumentAddress,\n node: DocumentNode | undefined,\n value: unknown\n): ResolvedTreeContainer | undefined =>\n node?.kind === 'tree' && isTree(value) ? { owner, generation, at, node, value } : undefined;\nexport const memberKey = (\n container: { readonly node: DocumentNode; readonly parent: Record<string, unknown> | unknown[] },\n key: string\n): string | number =>\n container.node.kind === 'list'\n ? anchor.indexedKeys(container.parent as unknown[], container.node.keyOf).index(key)\n : key;\n\ntype ResolutionPrefix = {\n segment: string;\n node: DocumentNode;\n value: unknown;\n};\n\n/** One recent path per transaction; structural writes invalidate all retained locations. */\nexport const createAddressResolver = (schema: DocumentNode, root: unknown) => {\n const prefix: ResolutionPrefix[] = [];\n return {\n container: (owner: object, generation: number, at: DocumentAddress) => {\n if (!at.length) return resolveContainer(owner, generation, at, schema, root);\n const location = resolveWithPrefix(schema, root, at, prefix);\n if (!location || !Object.hasOwn(location.parent, location.key)) return undefined;\n return resolveContainer(\n owner,\n generation,\n at,\n location.node,\n (location.parent as Record<string | number, unknown>)[location.key]\n );\n },\n invalidate: () => {\n prefix.length = 0;\n },\n };\n};\n\n/** A subtree root is a value, not a fabricated member of an ObjectNode. */\nexport const resolveValue = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): { node: DocumentNode; value: unknown } | undefined => {\n if (!address.length) return { node: schema, value: root };\n const location = resolveWithPrefix(schema, root, address, prefix);\n return (\n location && {\n node: location.node,\n value: Object.hasOwn(location.parent, location.key)\n ? (location.parent as Record<string | number, unknown>)[location.key]\n : undefined,\n }\n );\n};\n\n/** Resolves schema and document location in one address traversal. */\nexport const resolveLocated = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress\n): ResolvedAddress | undefined => resolveWithPrefix(schema, root, address);\n\nconst resolveWithPrefix = (\n schema: DocumentNode,\n root: unknown,\n address: DocumentAddress,\n prefix?: ResolutionPrefix[]\n): ResolvedAddress | undefined => {\n if (address.length === 0) return undefined;\n let node: DocumentNode | undefined = schema;\n let current: unknown = root;\n let start = 0;\n if (prefix) {\n while (\n start < prefix.length &&\n start < address.length - 1 &&\n prefix[start].segment === address[start]\n )\n start++;\n prefix.length = start;\n if (start) {\n const retained = prefix[start - 1];\n node = retained.node;\n current = retained.value;\n }\n }\n let cacheable = true;\n for (let index = start; index < address.length - 1; index += 1) {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, address[index]);\n if (!resolved) return undefined;\n if (node?.kind !== 'object' && node?.kind !== 'table' && node?.kind !== 'map')\n cacheable = false;\n current = readSegment(current, address[index], node);\n node = resolved;\n if (prefix && cacheable)\n prefix.push({\n segment: address[index],\n node: resolved,\n value: current,\n });\n if (!node) return undefined;\n }\n const last = address[address.length - 1];\n return resolveChild(node, current, last);\n};\n\n/** Resolves one member from an already current schema/container pair. */\nexport const resolveChild = (\n node: DocumentNode | undefined,\n current: unknown,\n last: string\n): ResolvedAddress | undefined => {\n profile.address.schemaStep();\n profile.address.documentStep();\n const resolved = step(node, current, last);\n if (!resolved || (!isRecord(current) && !Array.isArray(current))) return undefined;\n if (node?.kind === 'table' && isRecord(current) && isRecord(current.byId))\n return {\n node: resolved,\n parent: current.byId,\n key: last,\n };\n return {\n node: resolved,\n parent: current,\n key:\n node?.kind === 'list' && Array.isArray(current)\n ? anchor.indexedKeys(current, node.keyOf).index(last)\n : last,\n };\n};\n\nexport const contains = (parent: DocumentAddress, child: DocumentAddress): boolean => {\n profile.address.prefixComparison();\n if (parent.length > child.length) return false;\n for (let index = 0; index < parent.length; index += 1) {\n profile.address.segmentCompared();\n if (parent[index] !== child[index]) return false;\n }\n return true;\n};\n\nexport const overlaps = (a: DocumentAddress, b: DocumentAddress): boolean =>\n contains(a, b) || contains(b, a);\n\nexport const debugKey = (address: DocumentAddress): string => {\n let result = '';\n for (let index = 0; index < address.length; index += 1) {\n if (index > 0) result += '/';\n result += address[index].replaceAll('~', '~~').replaceAll('/', '~/');\n }\n return result;\n};\n\nexport const same = (a: AddressRef, b: AddressRef): boolean => {\n if (a.path !== b.path || a.address.length !== b.address.length) return false;\n for (let index = 0; index < a.address.length; index += 1) {\n profile.address.segmentCompared();\n if (a.address[index] !== b.address[index]) return false;\n }\n return true;\n};\n\nexport type { DocumentAddress } from './schema';\n\ntype AddressIndexNode<T> = {\n readonly children: Map<string, AddressIndexNode<T>>;\n readonly values: Set<T>;\n};\n\n/** An index over canonical address segments, shared by impact and subscriptions. */\nexport class AddressIndex<T> {\n private readonly root: AddressIndexNode<T> = { children: new Map(), values: new Set() };\n\n add(address: DocumentAddress, value: T, member?: string): void {\n let node = this.root;\n for (let i = 0; i < address.length + (member === undefined ? 0 : 1); i++) {\n const segment = i < address.length ? address[i] : member!;\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), values: new Set() };\n node.children.set(segment, child);\n }\n node = child;\n }\n node.values.add(value);\n }\n\n delete(address: DocumentAddress, value: T): void {\n const parents: AddressIndexNode<T>[] = [];\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return;\n parents.push(node);\n node = child;\n }\n node.values.delete(value);\n for (let i = address.length - 1; i >= 0 && !node.values.size && !node.children.size; i--) {\n node = parents[i];\n node.children.delete(address[i]);\n }\n }\n\n exact(address: DocumentAddress): ReadonlySet<T> | undefined {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return undefined;\n node = child;\n }\n return node.values;\n }\n\n hasAncestor(address: DocumentAddress, strict = false): boolean {\n let node = this.root;\n for (let i = 0; i < address.length; i++) {\n if (node.values.size) return true;\n const child = node.children.get(address[i]);\n if (!child) return false;\n node = child;\n }\n return !strict && node.values.size > 0;\n }\n\n someAncestor(address: DocumentAddress, predicate: (value: T) => boolean): boolean {\n let node = this.root;\n for (let i = 0; ; i++) {\n for (const value of node.values) if (predicate(value)) return true;\n if (i === address.length) return false;\n const child = node.children.get(address[i]);\n if (!child) return false;\n node = child;\n }\n }\n\n overlaps(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n if (node.values.size) return true;\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n hasDescendant(address: DocumentAddress): boolean {\n let node = this.root;\n for (const segment of address) {\n const child = node.children.get(segment);\n if (!child) return false;\n node = child;\n }\n return node.values.size > 0 || node.children.size > 0;\n }\n\n query(\n visit: (value: T) => void,\n relation: 'overlap' | 'ancestors' | 'descendants' = 'overlap'\n ): (address: DocumentAddress, members?: readonly { readonly key: string }[]) => void {\n const visited = new Set<AddressIndexNode<T>>();\n const subtrees = new Set<AddressIndexNode<T>>();\n const values = (node: AddressIndexNode<T>) => {\n if (visited.has(node)) return;\n visited.add(node);\n node.values.forEach(visit);\n };\n const descend = (current: AddressIndexNode<T>): void => {\n if (subtrees.has(current)) return;\n subtrees.add(current);\n values(current);\n current.children.forEach(descend);\n };\n const terminal = (node: AddressIndexNode<T>) =>\n relation === 'ancestors' ? values(node) : descend(node);\n return (address, members) => {\n let node = this.root;\n for (const segment of address) {\n if (subtrees.has(node)) return;\n if (relation !== 'descendants') values(node);\n const child = node.children.get(segment);\n if (!child) return;\n node = child;\n }\n if (!members) terminal(node);\n else {\n if (relation !== 'descendants') values(node);\n for (const member of members) {\n const child = node.children.get(member.key);\n if (child) terminal(child);\n }\n }\n };\n }\n\n clear(): void {\n this.root.values.clear();\n this.root.children.clear();\n }\n}\n","import type { DocumentAddress } from '../schema';\nimport type { ParseIssue } from '../schema-value';\n\nexport type MutationIssueCode =\n | 'invalid-address'\n | 'invalid-value'\n | 'invalid-key'\n | 'invalid-changes'\n | 'baseline-mismatch'\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';\nexport type MutationIssue = {\n readonly source: 'mutation';\n readonly code: MutationIssueCode;\n readonly address: DocumentAddress;\n readonly message: string;\n};\nexport const at = (\n address: DocumentAddress,\n code: MutationIssueCode,\n message: string\n): MutationIssue =>\n Object.freeze({ source: 'mutation', code, address: Object.freeze([...address]), message });\nexport class MutationRejected extends Error {\n constructor(readonly issue: MutationIssue) {\n super(issue.message);\n }\n}\nexport const fail = (address: DocumentAddress, code: MutationIssueCode, message: string): never => {\n throw new MutationRejected(at(address, code, message));\n};\n\nexport const invalidValue = (issue: ParseIssue, address = issue.address): never =>\n fail(address, issue.code === 'missing-validator' ? 'invalid-value' : issue.code, issue.message);\n"],"mappings":"AAiDA,MAAa,UAAU;CACrB,aAAa,KAAmC,SAAS,MAAM;CAG/D,WAAW,KAAiC,SAAS,MAAM;CAG3D,SAAS,QAAkC;CAG3C,MAAM,EACJ,iBAAiB,IAGlB;CACD,UAAU;EACR,YAAY;EAGZ,iBAAiB;EAGlB;CACD,SAAS;EACP,YAAY,UAAkB;EAM9B,kBAAkB;EAGlB,oBAAoB;EAGpB,mBAAmB;EAGnB,wBAAwB;EAGxB,uBAAuB;EAGxB;CACD,QAAQ;EACN,aAAa;EAGb,eAAe;EAGhB;CACD,gBAAgB;EACd,cAAc;EAGd,aAAa,SAAS,MAAM;EAG5B,mBAAmB;EAGpB;CACD,cAAc;EACZ,eAAe;EAGf,eAAe;EAGf,oBAAoB;EAGrB;CACF;;;AC1HD,MAAa,SAAS,MAAyB,UAAyB;AACtE,SAAQ,SAAS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cAAe,QAAO,KAAK;IAC5C,MAAM,QAAQ,KAAK,SAAS,IAAI,QAAQ;AACxC,QAAI,CAAC,MAAO;AACZ,WAAO;;AAET,OAAI,CAAC,QAAS,UAAS,KAAK;QACvB;AACH,QAAI,aAAa,cAAe,QAAO,KAAK;AAC5C,SAAK,MAAM,UAAU,SAAS;KAC5B,MAAM,QAAQ,KAAK,SAAS,IAAI,OAAO,IAAI;AAC3C,SAAI,MAAO,UAAS,MAAM;;;;;CAMlC,QAAc;AACZ,OAAK,KAAK,OAAO,OAAO;AACxB,OAAK,KAAK,SAAS,OAAO;;;;;ACzgB9B,MAAa,MACX,SACA,MACA,YAEA,OAAO,OAAO;CAAE,QAAQ;CAAY;CAAM,SAAS,OAAO,OAAO,CAAC,GAAG,QAAQ,CAAC;CAAE;CAAS,CAAC;AAC5F,IAAa,mBAAb,cAAsC,MAAM;CAC1C,YAAY,OAA+B;AACzC,QAAM,MAAM,QAAQ;AADD,OAAA,QAAA;;;AAIvB,MAAa,QAAQ,SAA0B,MAAyB,YAA2B;AACjG,OAAM,IAAI,iBAAiB,GAAG,SAAS,MAAM,QAAQ,CAAC;;AAGxD,MAAa,gBAAgB,OAAmB,UAAU,MAAM,YAC9D,KAAK,SAAS,MAAM,SAAS,sBAAsB,kBAAkB,MAAM,MAAM,MAAM,QAAQ"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"notification-CDSUfiip.cjs","names":["AddressIndex","createAccess","target.SubscriptionIndex"],"sources":["../core/src/impact-target.ts","../core/src/runtime/contract.ts","../core/src/runtime/access.ts","../core/src/runtime/notification.ts"],"sourcesContent":["import type { DocumentAddress, ObjectNode, ImpactTarget } from './schema';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex } from './address';\n\nexport const address = (target: ImpactTarget<unknown>): DocumentAddress =>\n 'at' in target ? target.at : target.address;\n\nexport const id = (target: ImpactTarget<unknown>): string | undefined =>\n target.kind === 'collection' && 'id' in target ? target.id : undefined;\n\nexport const belongs = (target: ImpactTarget<unknown>, schema: ObjectNode): boolean =>\n !('schema' in target) || target.schema === schema;\n\nexport const same = (left: ImpactTarget<unknown>, right: ImpactTarget<unknown>): boolean => {\n if (left.kind !== right.kind) return false;\n if ('schema' in left && 'schema' in right && left.schema !== right.schema) return false;\n const leftAddress = address(left);\n const rightAddress = address(right);\n if (leftAddress.length !== rightAddress.length) return false;\n for (let index = 0; index < leftAddress.length; index += 1)\n if (leftAddress[index] !== rightAddress[index]) return false;\n return left.kind !== 'collection' || id(left) === id(right);\n};\n\nexport const indexedAddress = (target: ImpactTarget<unknown>): DocumentAddress => {\n const key = id(target);\n return key === undefined ? address(target) : [...address(target), key];\n};\n\nexport const affected = (\n target: ImpactTarget,\n values: AddressIndex<true>,\n orders: AddressIndex<true>\n): boolean => {\n const at = indexedAddress(target);\n return id(target) !== undefined\n ? values.hasAncestor(at)\n : values.overlaps(at) || orders.hasDescendant(at);\n};\n\n/** Targets are classified once; commit matching never builds a reverse impact index. */\nexport class SubscriptionIndex<T> {\n private readonly ordinary = new AddressIndex<T>();\n private readonly membership = new AddressIndex<T>();\n constructor(private readonly schema: ObjectNode) {}\n add(target: ImpactTarget, value: T): void {\n if (belongs(target, this.schema))\n (id(target) === undefined ? this.ordinary : this.membership).add(\n indexedAddress(target),\n value\n );\n }\n delete(target: ImpactTarget, value: T): void {\n if (belongs(target, this.schema))\n (id(target) === undefined ? this.ordinary : this.membership).delete(\n indexedAddress(target),\n value\n );\n }\n collect(changes: ChangeSet, visit: (value: T) => void): void {\n const values = this.ordinary.query(visit);\n const members = this.membership.query(visit, 'descendants');\n const orders = this.ordinary.query(visit, 'ancestors');\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n values([]);\n members([]);\n } else if (change.kind === 'members') {\n values(change.at, change.members);\n members(change.at, change.members);\n if (change.order) orders(change.at);\n } else {\n values(change.at);\n members(change.at);\n }\n }\n }\n clear(): void {\n this.ordinary.clear();\n this.membership.clear();\n }\n}\n","import type { DocumentAddress, ObjectNode, PathPick, Infer } from '../schema';\nimport type { AddressRef } from '../address';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable } from '../projection/readable';\nexport type Unsubscribe = () => void;\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectNode> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectNode> = (commit: DocumentCommit<S>) => void;\nexport type DocumentReadable<S extends ObjectNode> = {\n readonly address: {\n resolve(address: DocumentAddress): AddressRef | undefined;\n read(address: DocumentAddress): unknown;\n contains(parent: DocumentAddress, child: DocumentAddress): boolean;\n overlaps(left: DocumentAddress, right: DocumentAddress): boolean;\n debugKey(address: DocumentAddress): string;\n };\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectNode> = DocumentReadable<S> & {\n readonly schema: S;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options: {\n readonly expectedRevision: number;\n readonly source?: Exclude<CommitSource, 'history'>;\n readonly history?: boolean;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ObjectNode, Infer } from '../schema';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { DocumentReadable } from './contract';\n\nexport type RuntimeAccessState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks?: number;\n};\n\nconst states = new WeakMap<object, RuntimeAccessState<ObjectNode>>();\n\nexport const bindRuntimeAccess = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n state: RuntimeAccessState<TSchema>\n): void => {\n states.set(runtime as object, state as RuntimeAccessState<ObjectNode>);\n};\n\nexport const accessOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeAccessState<TSchema> => {\n const state = states.get(runtime as object);\n if (!state) throw new Error('Unknown Doxum runtime.');\n return state as RuntimeAccessState<TSchema>;\n};\n\nexport const readWith = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = accessOf(runtime);\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks = (state.projectionLocks ?? 0) + 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks!--;\n }\n};\n","import type { ObjectNode, ImpactTarget } from '../schema';\nimport type {\n CommitListener,\n DocumentCommit,\n DocumentReadable,\n DocumentRuntime,\n Unsubscribe,\n ObserverError,\n} from './contract';\nimport * as target from '../impact-target';\n\nexport type ProjectionAttachment<TSchema extends ObjectNode> = {\n capture(commit: DocumentCommit<TSchema>): void;\n settle(): void;\n flush(): readonly ObserverError[];\n dispose(): void;\n};\ntype ProcessorEntry<TSchema extends ObjectNode> = {\n readonly processor: ProjectionAttachment<TSchema>;\n active: boolean;\n};\ntype RootEntry<TSchema extends ObjectNode> = {\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype FilteredEntry<TSchema extends ObjectNode> = {\n readonly targets: readonly ImpactTarget<unknown>[];\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\nexport type RuntimeNotification<TSchema extends ObjectNode> = {\n readonly root: Set<RootEntry<TSchema>>;\n readonly filtered: Set<FilteredEntry<TSchema>>;\n readonly index: target.SubscriptionIndex<FilteredEntry<TSchema>>;\n readonly cleanups: Set<() => void>;\n readonly processors: ProcessorEntry<TSchema>[];\n readonly candidates: Set<FilteredEntry<TSchema>>;\n readonly rootSnapshot: RootEntry<TSchema>[];\n notifying: boolean;\n};\n\nconst notifications = new WeakMap<object, RuntimeNotification<ObjectNode>>();\nconst readableOwners = new WeakMap<object, DocumentReadable<ObjectNode>>();\n\nexport const bindDocumentReadable = (\n readable: object,\n runtime: DocumentReadable<ObjectNode>\n): void => {\n readableOwners.set(readable, runtime);\n};\nexport const documentReadableOwner = (readable: object): DocumentReadable<ObjectNode> | undefined =>\n readableOwners.get(readable);\n\nexport const createNotification = <TSchema extends ObjectNode>(\n runtime: DocumentRuntime<TSchema>\n): RuntimeNotification<TSchema> => {\n const notification: RuntimeNotification<TSchema> = {\n root: new Set(),\n filtered: new Set(),\n index: new target.SubscriptionIndex(runtime.schema),\n cleanups: new Set(),\n processors: [],\n candidates: new Set(),\n rootSnapshot: [],\n notifying: false,\n };\n notifications.set(runtime as object, notification as RuntimeNotification<ObjectNode>);\n return notification;\n};\n\nconst notificationOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeNotification<TSchema> => {\n const value = notifications.get(runtime as object);\n if (!value) throw new Error('Unknown Doxum runtime.');\n return value as RuntimeNotification<TSchema>;\n};\n\nexport const shareNotification = <TSchema extends ObjectNode>(\n source: DocumentRuntime<TSchema>,\n target: DocumentReadable<TSchema>\n): void => {\n notifications.set(target as object, notificationOf(source) as RuntimeNotification<ObjectNode>);\n};\n\nexport const attachProjection = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n processor: ProjectionAttachment<TSchema>\n): Unsubscribe => {\n const notification = notificationOf(runtime);\n const entry: ProcessorEntry<TSchema> = { processor, active: true };\n notification.processors.push(entry);\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (!notification.notifying) {\n const index = notification.processors.indexOf(entry);\n if (index >= 0) notification.processors.splice(index, 1);\n }\n };\n};\n\nexport const subscribeRoot = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: RootEntry<TSchema> = { listener, active: true };\n notification.root.add(entry);\n return () => {\n entry.active = false;\n if (!notification.notifying) notification.root.delete(entry);\n else\n notification.cleanups.add(() => {\n notification.root.delete(entry);\n });\n };\n};\n\nexport const subscribeTargets = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: FilteredEntry<TSchema> = {\n targets: Object.freeze(targets.slice()),\n listener,\n active: true,\n };\n notification.filtered.add(entry);\n entry.targets.forEach(value => notification.index.add(value, entry));\n const remove = () => {\n notification.filtered.delete(entry);\n entry.targets.forEach(value => notification.index.delete(value, entry));\n };\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (notification.notifying) notification.cleanups.add(remove);\n else remove();\n };\n};\n\nexport const notify = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n): readonly ObserverError[] => {\n notification.notifying = true;\n const errors: ObserverError[] = [];\n const call = (listener: CommitListener<TSchema>): void => {\n try {\n listener(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'listener', error }));\n }\n };\n try {\n const processorCount = notification.processors.length;\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.capture(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.settle();\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n errors.push(...entry.processor.flush());\n } catch (error) {\n errors.push(Object.freeze({ phase: 'flush', error }));\n }\n }\n\n if (afterSettle) errors.push(...afterSettle());\n const candidates = notification.candidates;\n candidates.clear();\n if (notification.filtered.size)\n notification.index.collect(commit.changes, entry => candidates.add(entry));\n candidates.forEach(entry => {\n if (entry.active) call(entry.listener);\n });\n const rootSnapshot = notification.rootSnapshot;\n rootSnapshot.length = 0;\n notification.root.forEach(entry => rootSnapshot.push(entry));\n for (const entry of rootSnapshot) if (entry.active) call(entry.listener);\n } finally {\n notification.notifying = false;\n let writeIndex = 0;\n for (const entry of notification.processors)\n if (entry.active) notification.processors[writeIndex++] = entry;\n notification.processors.length = writeIndex;\n notification.cleanups.forEach(cleanup => cleanup());\n notification.cleanups.clear();\n }\n return Object.freeze(errors);\n};\n\nexport const subscribeDependencies = <S extends ObjectNode>(\n runtime: DocumentReadable<S>,\n targets: readonly ImpactTarget[],\n listener: CommitListener<S>\n): Unsubscribe => subscribeTargets(notificationOf(runtime), targets, listener);\n\nexport const disposeNotification = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>\n): void => {\n const attachments = notification.processors.slice();\n notification.root.clear();\n notification.filtered.clear();\n notification.index.clear();\n notification.cleanups.clear();\n notification.processors.length = 0;\n notification.candidates.clear();\n notification.rootSnapshot.length = 0;\n const errors: unknown[] = [];\n attachments.forEach(entry => {\n if (!entry.active) return;\n try {\n entry.processor.dispose();\n } catch (error) {\n errors.push(error);\n }\n });\n if (errors.length) throw new AggregateError(errors, 'Projection disposal notification failed.');\n};\n"],"mappings":";;;AAIA,MAAa,WAAW,WACtB,QAAQ,SAAS,OAAO,KAAK,OAAO;AAEtC,MAAa,MAAM,WACjB,OAAO,S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5D,eAAa,WAAW,SAAS;AACjC,eAAa,SAAS,SAAQ,YAAW,SAAS,CAAC;AACnD,eAAa,SAAS,OAAO;;AAE/B,QAAO,OAAO,OAAO,OAAO;;AAG9B,MAAa,yBACX,SACA,SACA,aACgB,iBAAiB,eAAe,QAAQ,EAAE,SAAS,SAAS;AAE9E,MAAa,uBACX,iBACS;CACT,MAAM,cAAc,aAAa,WAAW,OAAO;AACnD,cAAa,KAAK,OAAO;AACzB,cAAa,SAAS,OAAO;AAC7B,cAAa,MAAM,OAAO;AAC1B,cAAa,SAAS,OAAO;AAC7B,cAAa,WAAW,SAAS;AACjC,cAAa,WAAW,OAAO;AAC/B,cAAa,aAAa,SAAS;CACnC,MAAM,SAAoB,EAAE;AAC5B,aAAY,SAAQ,UAAS;AAC3B,MAAI,CAAC,MAAM,OAAQ;AACnB,MAAI;AACF,SAAM,UAAU,SAAS;WAClB,OAAO;AACd,UAAO,KAAK,MAAM;;GAEpB;AACF,KAAI,OAAO,OAAQ,OAAM,IAAI,eAAe,QAAQ,2CAA2C"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"notification-IQIJyH3Q.js","names":["target.SubscriptionIndex"],"sources":["../core/src/impact-target.ts","../core/src/runtime/contract.ts","../core/src/runtime/access.ts","../core/src/runtime/notification.ts"],"sourcesContent":["import type { DocumentAddress, ObjectNode, ImpactTarget } from './schema';\nimport type { ChangeSet } from './changes';\nimport { AddressIndex } from './address';\n\nexport const address = (target: ImpactTarget<unknown>): DocumentAddress =>\n 'at' in target ? target.at : target.address;\n\nexport const id = (target: ImpactTarget<unknown>): string | undefined =>\n target.kind === 'collection' && 'id' in target ? target.id : undefined;\n\nexport const belongs = (target: ImpactTarget<unknown>, schema: ObjectNode): boolean =>\n !('schema' in target) || target.schema === schema;\n\nexport const same = (left: ImpactTarget<unknown>, right: ImpactTarget<unknown>): boolean => {\n if (left.kind !== right.kind) return false;\n if ('schema' in left && 'schema' in right && left.schema !== right.schema) return false;\n const leftAddress = address(left);\n const rightAddress = address(right);\n if (leftAddress.length !== rightAddress.length) return false;\n for (let index = 0; index < leftAddress.length; index += 1)\n if (leftAddress[index] !== rightAddress[index]) return false;\n return left.kind !== 'collection' || id(left) === id(right);\n};\n\nexport const indexedAddress = (target: ImpactTarget<unknown>): DocumentAddress => {\n const key = id(target);\n return key === undefined ? address(target) : [...address(target), key];\n};\n\nexport const affected = (\n target: ImpactTarget,\n values: AddressIndex<true>,\n orders: AddressIndex<true>\n): boolean => {\n const at = indexedAddress(target);\n return id(target) !== undefined\n ? values.hasAncestor(at)\n : values.overlaps(at) || orders.hasDescendant(at);\n};\n\n/** Targets are classified once; commit matching never builds a reverse impact index. */\nexport class SubscriptionIndex<T> {\n private readonly ordinary = new AddressIndex<T>();\n private readonly membership = new AddressIndex<T>();\n constructor(private readonly schema: ObjectNode) {}\n add(target: ImpactTarget, value: T): void {\n if (belongs(target, this.schema))\n (id(target) === undefined ? this.ordinary : this.membership).add(\n indexedAddress(target),\n value\n );\n }\n delete(target: ImpactTarget, value: T): void {\n if (belongs(target, this.schema))\n (id(target) === undefined ? this.ordinary : this.membership).delete(\n indexedAddress(target),\n value\n );\n }\n collect(changes: ChangeSet, visit: (value: T) => void): void {\n const values = this.ordinary.query(visit);\n const members = this.membership.query(visit, 'descendants');\n const orders = this.ordinary.query(visit, 'ancestors');\n for (const change of changes.changes) {\n if (change.kind === 'reset') {\n values([]);\n members([]);\n } else if (change.kind === 'members') {\n values(change.at, change.members);\n members(change.at, change.members);\n if (change.order) orders(change.at);\n } else {\n values(change.at);\n members(change.at);\n }\n }\n }\n clear(): void {\n this.ordinary.clear();\n this.membership.clear();\n }\n}\n","import type { DocumentAddress, ObjectNode, PathPick, Infer } from '../schema';\nimport type { AddressRef } from '../address';\nimport type { ChangeSet } from '../changes';\nimport type { DocumentImpact } from '../impact';\nimport type { Draft } from '../access/scope';\nimport type { MutationIssue } from '../mutation/issue';\nimport type { Readable } from '../projection/readable';\nexport type Unsubscribe = () => void;\nexport type Synchronous<T> = T extends PromiseLike<unknown> ? never : T;\nexport type CommitSource = 'local' | 'system' | 'history' | 'remote';\nexport class DocumentReentrancyError extends Error {\n constructor() {\n super('Document writes cannot be re-entered during an update or notification.');\n this.name = 'DocumentReentrancyError';\n }\n}\nexport class DocumentDisposedError extends Error {\n constructor() {\n super('Doxum runtime has been disposed.');\n this.name = 'DocumentDisposedError';\n }\n}\nexport type DiagnosticInput = {\n readonly code: string;\n readonly message: string;\n readonly address?: DocumentAddress;\n};\nexport type DocumentDiagnostic = DiagnosticInput & { readonly source: 'application' };\nexport type DocumentProblem = DocumentDiagnostic | MutationIssue;\nexport class TransactionRejected extends Error {\n readonly issues: readonly DocumentDiagnostic[];\n constructor(input: DiagnosticInput | readonly DiagnosticInput[]) {\n super('Document update rejected.');\n this.name = 'TransactionRejected';\n const issues: readonly DiagnosticInput[] = Array.isArray(input)\n ? input\n : [input as DiagnosticInput];\n this.issues = Object.freeze(\n issues.map(issue =>\n Object.freeze({\n code: issue.code,\n message: issue.message,\n source: 'application' as const,\n ...(issue.address === undefined ? {} : { address: Object.freeze([...issue.address]) }),\n })\n )\n );\n }\n}\nexport type DocumentCommit<S extends ObjectNode> = {\n readonly revision: number;\n readonly source: CommitSource;\n readonly changes: ChangeSet;\n readonly impact: DocumentImpact<S>;\n};\nexport type ObserverError = {\n readonly phase: 'processor' | 'flush' | 'listener';\n readonly error: unknown;\n};\nexport type TransactionResult<V, C> =\n | {\n readonly status: 'committed';\n readonly value: V;\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly value: V; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly DocumentProblem[];\n readonly revision: number;\n };\nexport type OperationResult<C> =\n | {\n readonly status: 'committed';\n readonly commit: C;\n readonly observerErrors: readonly ObserverError[];\n }\n | { readonly status: 'unchanged'; readonly revision: number }\n | {\n readonly status: 'rejected';\n readonly issues: readonly MutationIssue[];\n readonly revision: number;\n };\nexport type HistoryState = { readonly undoDepth: number; readonly redoDepth: number };\nexport type LocalHistory<C> = Readable<HistoryState> & {\n undo(): OperationResult<C>;\n redo(): OperationResult<C>;\n clear(): void;\n group(): { end(): void; cancel(): OperationResult<C> };\n};\nexport type CommitListener<S extends ObjectNode> = (commit: DocumentCommit<S>) => void;\nexport type DocumentReadable<S extends ObjectNode> = {\n readonly address: {\n resolve(address: DocumentAddress): AddressRef | undefined;\n read(address: DocumentAddress): unknown;\n contains(parent: DocumentAddress, child: DocumentAddress): boolean;\n overlaps(left: DocumentAddress, right: DocumentAddress): boolean;\n debugKey(address: DocumentAddress): string;\n };\n revision(): number;\n subscribe(listener: CommitListener<S>): Unsubscribe;\n subscribe(\n pick: PathPick<S> | readonly [PathPick<S>, ...PathPick<S>[]],\n listener: CommitListener<S>\n ): Unsubscribe;\n};\nexport type DocumentRuntime<S extends ObjectNode> = DocumentReadable<S> & {\n readonly schema: S;\n update<V>(\n run: (draft: Draft<S>) => Synchronous<V>,\n options?: {\n readonly source?: Extract<CommitSource, 'local' | 'system'>;\n readonly history?: boolean;\n }\n ): TransactionResult<V, DocumentCommit<S>>;\n apply(\n changes: unknown,\n options: {\n readonly expectedRevision: number;\n readonly source?: Exclude<CommitSource, 'history'>;\n readonly history?: boolean;\n }\n ): OperationResult<DocumentCommit<S>>;\n replace(\n value: Infer<S>,\n options?: { readonly source?: Extract<CommitSource, 'system' | 'remote'> }\n ): OperationResult<DocumentCommit<S>>;\n snapshot(): Infer<S>;\n readonly history: LocalHistory<DocumentCommit<S>>;\n dispose(): void;\n};\n","import type { ObjectNode, Infer } from '../schema';\nimport { createAccess, type Read } from '../access/scope';\nimport type { DependencyTracker } from '../access/dependency';\nimport { DocumentDisposedError } from './contract';\nimport type { DocumentReadable } from './contract';\n\nexport type RuntimeAccessState<TSchema extends ObjectNode> = {\n readonly schema: TSchema;\n document: Infer<TSchema>;\n disposed: boolean;\n projectionLocks?: number;\n};\n\nconst states = new WeakMap<object, RuntimeAccessState<ObjectNode>>();\n\nexport const bindRuntimeAccess = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n state: RuntimeAccessState<TSchema>\n): void => {\n states.set(runtime as object, state as RuntimeAccessState<ObjectNode>);\n};\n\nexport const accessOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeAccessState<TSchema> => {\n const state = states.get(runtime as object);\n if (!state) throw new Error('Unknown Doxum runtime.');\n return state as RuntimeAccessState<TSchema>;\n};\n\nexport const readWith = <TSchema extends ObjectNode, TResult>(\n runtime: DocumentReadable<TSchema>,\n run: (read: Read<TSchema>) => TResult,\n dependencies?: DependencyTracker\n): TResult => {\n const state = accessOf(runtime);\n if (state.disposed) throw new DocumentDisposedError();\n state.projectionLocks = (state.projectionLocks ?? 0) + 1;\n try {\n const reader = createAccess({\n state,\n dependencies,\n }) as Read<TSchema>;\n return run(reader);\n } finally {\n // readWith is an internal borrowed-reader boundary. Retaining its reader or\n // collection methods after this callback is undefined behavior.\n state.projectionLocks!--;\n }\n};\n","import type { ObjectNode, ImpactTarget } from '../schema';\nimport type {\n CommitListener,\n DocumentCommit,\n DocumentReadable,\n DocumentRuntime,\n Unsubscribe,\n ObserverError,\n} from './contract';\nimport * as target from '../impact-target';\n\nexport type ProjectionAttachment<TSchema extends ObjectNode> = {\n capture(commit: DocumentCommit<TSchema>): void;\n settle(): void;\n flush(): readonly ObserverError[];\n dispose(): void;\n};\ntype ProcessorEntry<TSchema extends ObjectNode> = {\n readonly processor: ProjectionAttachment<TSchema>;\n active: boolean;\n};\ntype RootEntry<TSchema extends ObjectNode> = {\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\ntype FilteredEntry<TSchema extends ObjectNode> = {\n readonly targets: readonly ImpactTarget<unknown>[];\n readonly listener: CommitListener<TSchema>;\n active: boolean;\n};\nexport type RuntimeNotification<TSchema extends ObjectNode> = {\n readonly root: Set<RootEntry<TSchema>>;\n readonly filtered: Set<FilteredEntry<TSchema>>;\n readonly index: target.SubscriptionIndex<FilteredEntry<TSchema>>;\n readonly cleanups: Set<() => void>;\n readonly processors: ProcessorEntry<TSchema>[];\n readonly candidates: Set<FilteredEntry<TSchema>>;\n readonly rootSnapshot: RootEntry<TSchema>[];\n notifying: boolean;\n};\n\nconst notifications = new WeakMap<object, RuntimeNotification<ObjectNode>>();\nconst readableOwners = new WeakMap<object, DocumentReadable<ObjectNode>>();\n\nexport const bindDocumentReadable = (\n readable: object,\n runtime: DocumentReadable<ObjectNode>\n): void => {\n readableOwners.set(readable, runtime);\n};\nexport const documentReadableOwner = (readable: object): DocumentReadable<ObjectNode> | undefined =>\n readableOwners.get(readable);\n\nexport const createNotification = <TSchema extends ObjectNode>(\n runtime: DocumentRuntime<TSchema>\n): RuntimeNotification<TSchema> => {\n const notification: RuntimeNotification<TSchema> = {\n root: new Set(),\n filtered: new Set(),\n index: new target.SubscriptionIndex(runtime.schema),\n cleanups: new Set(),\n processors: [],\n candidates: new Set(),\n rootSnapshot: [],\n notifying: false,\n };\n notifications.set(runtime as object, notification as RuntimeNotification<ObjectNode>);\n return notification;\n};\n\nconst notificationOf = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>\n): RuntimeNotification<TSchema> => {\n const value = notifications.get(runtime as object);\n if (!value) throw new Error('Unknown Doxum runtime.');\n return value as RuntimeNotification<TSchema>;\n};\n\nexport const shareNotification = <TSchema extends ObjectNode>(\n source: DocumentRuntime<TSchema>,\n target: DocumentReadable<TSchema>\n): void => {\n notifications.set(target as object, notificationOf(source) as RuntimeNotification<ObjectNode>);\n};\n\nexport const attachProjection = <TSchema extends ObjectNode>(\n runtime: DocumentReadable<TSchema>,\n processor: ProjectionAttachment<TSchema>\n): Unsubscribe => {\n const notification = notificationOf(runtime);\n const entry: ProcessorEntry<TSchema> = { processor, active: true };\n notification.processors.push(entry);\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (!notification.notifying) {\n const index = notification.processors.indexOf(entry);\n if (index >= 0) notification.processors.splice(index, 1);\n }\n };\n};\n\nexport const subscribeRoot = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: RootEntry<TSchema> = { listener, active: true };\n notification.root.add(entry);\n return () => {\n entry.active = false;\n if (!notification.notifying) notification.root.delete(entry);\n else\n notification.cleanups.add(() => {\n notification.root.delete(entry);\n });\n };\n};\n\nexport const subscribeTargets = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n targets: readonly ImpactTarget<unknown>[],\n listener: CommitListener<TSchema>\n): Unsubscribe => {\n const entry: FilteredEntry<TSchema> = {\n targets: Object.freeze(targets.slice()),\n listener,\n active: true,\n };\n notification.filtered.add(entry);\n entry.targets.forEach(value => notification.index.add(value, entry));\n const remove = () => {\n notification.filtered.delete(entry);\n entry.targets.forEach(value => notification.index.delete(value, entry));\n };\n return () => {\n if (!entry.active) return;\n entry.active = false;\n if (notification.notifying) notification.cleanups.add(remove);\n else remove();\n };\n};\n\nexport const notify = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>,\n commit: DocumentCommit<TSchema>,\n afterSettle?: () => readonly ObserverError[]\n): readonly ObserverError[] => {\n notification.notifying = true;\n const errors: ObserverError[] = [];\n const call = (listener: CommitListener<TSchema>): void => {\n try {\n listener(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'listener', error }));\n }\n };\n try {\n const processorCount = notification.processors.length;\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.capture(commit);\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n entry.processor.settle();\n } catch (error) {\n errors.push(Object.freeze({ phase: 'processor', error }));\n }\n }\n for (let index = 0; index < processorCount; index += 1) {\n const entry = notification.processors[index];\n if (!entry?.active) continue;\n try {\n errors.push(...entry.processor.flush());\n } catch (error) {\n errors.push(Object.freeze({ phase: 'flush', error }));\n }\n }\n\n if (afterSettle) errors.push(...afterSettle());\n const candidates = notification.candidates;\n candidates.clear();\n if (notification.filtered.size)\n notification.index.collect(commit.changes, entry => candidates.add(entry));\n candidates.forEach(entry => {\n if (entry.active) call(entry.listener);\n });\n const rootSnapshot = notification.rootSnapshot;\n rootSnapshot.length = 0;\n notification.root.forEach(entry => rootSnapshot.push(entry));\n for (const entry of rootSnapshot) if (entry.active) call(entry.listener);\n } finally {\n notification.notifying = false;\n let writeIndex = 0;\n for (const entry of notification.processors)\n if (entry.active) notification.processors[writeIndex++] = entry;\n notification.processors.length = writeIndex;\n notification.cleanups.forEach(cleanup => cleanup());\n notification.cleanups.clear();\n }\n return Object.freeze(errors);\n};\n\nexport const subscribeDependencies = <S extends ObjectNode>(\n runtime: DocumentReadable<S>,\n targets: readonly ImpactTarget[],\n listener: CommitListener<S>\n): Unsubscribe => subscribeTargets(notificationOf(runtime), targets, listener);\n\nexport const disposeNotification = <TSchema extends ObjectNode>(\n notification: RuntimeNotification<TSchema>\n): void => {\n const attachments = notification.processors.slice();\n notification.root.clear();\n notification.filtered.clear();\n notification.index.clear();\n notification.cleanups.clear();\n notification.processors.length = 0;\n notification.candidates.clear();\n notification.rootSnapshot.length = 0;\n const errors: unknown[] = [];\n attachments.forEach(entry => {\n if (!entry.active) return;\n try {\n entry.processor.dispose();\n } catch (error) {\n errors.push(error);\n }\n });\n if (errors.length) throw new AggregateError(errors, 'Projection disposal notification failed.');\n};\n"],"mappings":";;;AAIA,MAAa,WAAW,WACtB,QAAQ,SAAS,OAAO,KAAK,OAAO;AAEtC,MAAa,MAAM,WACjB,OAAO,SAAS,gBAAgB,QAAQ,SAAS,OAAO,KAAK,KAAA;AAE/D,MAAa,WAAW,QAA+B,WACrD,EAAE,YAAY,WAAW,OAAO,WAAW;AAE7C,MAAa,QAAQ,MAA6B,UAA0C;AAC1F,KAAI,KAAK,SAAS,MAAM,KAAM,QAAO;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