@loro-extended/change 5.4.0 → 5.4.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/derive-placeholder.ts","../src/functional-helpers.ts","../src/loro.ts","../src/typed-doc.ts","../src/json-patch.ts","../src/utils/type-guards.ts","../src/overlay.ts","../src/typed-refs/base.ts","../src/typed-refs/utils.ts","../src/typed-refs/counter-ref-internals.ts","../src/typed-refs/counter-ref.ts","../src/conversion.ts","../src/typed-refs/list-ref-base.ts","../src/typed-refs/list-ref-internals.ts","../src/typed-refs/list-ref.ts","../src/typed-refs/movable-list-ref-internals.ts","../src/typed-refs/movable-list-ref.ts","../src/typed-refs/proxy-handlers.ts","../src/typed-refs/record-ref-internals.ts","../src/typed-refs/record-ref.ts","../src/typed-refs/struct-ref-internals.ts","../src/typed-refs/struct-ref.ts","../src/typed-refs/text-ref-internals.ts","../src/typed-refs/text-ref.ts","../src/typed-refs/tree-node-ref-internals.ts","../src/typed-refs/tree-node-ref.ts","../src/typed-refs/tree-ref-internals.ts","../src/typed-refs/tree-ref.ts","../src/typed-refs/doc-ref-internals.ts","../src/typed-refs/doc-ref.ts","../src/validation.ts","../src/path-builder.ts","../src/path-compiler.ts","../src/path-evaluator.ts","../src/placeholder-proxy.ts","../src/replay-diff.ts","../src/shape.ts"],"sourcesContent":["import type { ContainerOrValueShape, DocShape, ValueShape } from \"./shape.js\"\nimport type { InferPlaceholderType } from \"./types.js\"\n\n/**\n * Derives the placeholder state from a schema by composing placeholder values.\n *\n * For leaf nodes (text, counter, values): uses _placeholder directly\n * For containers (map, list, record): recurses into nested shapes\n */\nexport function derivePlaceholder<T extends DocShape>(\n schema: T,\n): InferPlaceholderType<T> {\n const result: Record<string, unknown> = {}\n\n for (const [key, shape] of Object.entries(schema.shapes)) {\n result[key] = deriveShapePlaceholder(shape)\n }\n\n return result as InferPlaceholderType<T>\n}\n\n/**\n * Derives placeholder for a single shape.\n *\n * Leaf nodes: return _placeholder directly\n * Containers: recurse into nested shapes (ignore _placeholder on containers)\n */\nexport function deriveShapePlaceholder(shape: ContainerOrValueShape): unknown {\n switch (shape._type) {\n // Any container - no placeholder (undefined)\n case \"any\":\n return undefined\n\n // Leaf containers - use _placeholder directly\n case \"text\":\n return shape._placeholder\n case \"counter\":\n return shape._placeholder\n\n // Dynamic containers - always empty (no per-entry merging)\n case \"list\":\n case \"movableList\":\n case \"tree\":\n return []\n case \"record\":\n return {}\n\n // Structured container - recurse into nested shapes\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n result[key] = deriveShapePlaceholder(nestedShape)\n }\n return result\n }\n\n case \"value\":\n return deriveValueShapePlaceholder(shape)\n\n default:\n return undefined\n }\n}\n\nfunction deriveValueShapePlaceholder(shape: ValueShape): unknown {\n switch (shape.valueType) {\n // Any value - no placeholder (undefined)\n case \"any\":\n return undefined\n\n // Leaf values - use _placeholder directly\n case \"string\":\n return shape._placeholder\n case \"number\":\n return shape._placeholder\n case \"boolean\":\n return shape._placeholder\n case \"null\":\n return null\n case \"undefined\":\n return undefined\n case \"uint8array\":\n return shape._placeholder\n\n // Structured value - recurse into nested shapes (like struct)\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shape)) {\n result[key] = deriveValueShapePlaceholder(nestedShape)\n }\n return result\n }\n\n // Dynamic values - always empty\n case \"array\":\n return []\n case \"record\":\n return {}\n\n // Unions - use _placeholder if explicitly set, otherwise derive from first variant\n case \"union\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n // We need to check if it's a primitive value OR a non-empty object\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n return deriveValueShapePlaceholder(shape.shapes[0])\n }\n\n case \"discriminatedUnion\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n const firstKey = Object.keys(shape.variants)[0]\n return deriveValueShapePlaceholder(shape.variants[firstKey])\n }\n\n default:\n return undefined\n }\n}\n","import {\n type LoroCounter,\n LoroDoc,\n type LoroList,\n type LoroMap,\n type LoroMovableList,\n type LoroText,\n type LoroTree,\n} from \"loro-crdt\"\nimport { loro } from \"./loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n ShapeToContainer,\n StructContainerShape,\n TextContainerShape,\n TreeRefInterface,\n} from \"./shape.js\"\nimport { createTypedDoc, type Frontiers, type TypedDoc } from \"./typed-doc.js\"\nimport { INTERNAL_SYMBOL, type TypedRef } from \"./typed-refs/base.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TreeRef } from \"./typed-refs/tree-ref.js\"\nimport { createContainerTypedRef } from \"./typed-refs/utils.js\"\nimport type { Mutable } from \"./types.js\"\n\n/**\n * The primary method of mutating typed documents and refs.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc/ref for chaining.\n *\n * @param target - The TypedDoc or TypedRef to mutate\n * @param fn - Function that performs mutations on the draft\n * @returns The same target for chaining\n *\n * @example\n * ```typescript\n * import { change } from \"@loro-extended/change\"\n *\n * // Document-level change (chainable)\n * change(doc, draft => {\n * draft.count.increment(10)\n * draft.title.update(\"Hello\")\n * })\n * .count.increment(5) // Optional: continue mutating\n * .toJSON() // Optional: get snapshot\n *\n * // Ref-level change - enables encapsulation\n * function addItems(list: ListRef<...>) {\n * change(list, draft => {\n * draft.push({ name: \"item1\" })\n * draft.push({ name: \"item2\" })\n * })\n * }\n *\n * // TreeRef example - pass around refs without exposing the doc\n * function addStates(states: TreeRef<StateShape>) {\n * change(states, draft => {\n * draft.createNode({ name: \"idle\" })\n * draft.createNode({ name: \"running\" })\n * })\n * }\n * ```\n */\n// Overload for TypedDoc\nexport function change<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n fn: (draft: Mutable<Shape>) => void,\n): TypedDoc<Shape>\n\n// Overload for TreeRef (special case - not a TypedRef<ContainerShape>)\nexport function change<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n fn: (draft: TreeRef<DataShape>) => void,\n): TreeRef<DataShape>\n\n// Overload for TreeRefInterface (the mutable type from TreeContainerShape)\nexport function change<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n fn: (draft: TreeRefInterface<DataShape>) => void,\n): TreeRefInterface<DataShape>\n\n// Overload for StructRef (special case - uses Proxy, not a class extending TypedRef)\n// This must come before the generic TypedRef overload to match StructRef properly\nexport function change<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(\n ref: StructRef<NestedShapes>,\n fn: (draft: StructRef<NestedShapes>) => void,\n): StructRef<NestedShapes>\n\n// Overload for TypedRef (all container refs) - preserves concrete ref type\nexport function change<T extends TypedRef<ContainerShape>>(\n ref: T,\n fn: (draft: T) => void,\n): T\n\n// Implementation\nexport function change(\n target:\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | StructRef<any>,\n fn: (draft: any) => void,\n):\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | StructRef<any> {\n // Check if it's a TypedDoc (has .change method)\n if (\"change\" in target && typeof (target as any).change === \"function\") {\n return (target as TypedDoc<any>).change(fn)\n }\n\n // It's a TypedRef or TreeRef - use ref-level change logic\n return changeRef(target as TypedRef<any> | TreeRef<any>, fn)\n}\n\n/**\n * Internal implementation for ref-level change.\n * Creates a draft ref with batchedMutation=true, executes the function,\n * absorbs changes, and commits.\n */\nfunction changeRef<T extends TypedRef<any> | TreeRef<any>>(\n ref: T,\n fn: (draft: T) => void,\n): T {\n // Get internals via INTERNAL_SYMBOL\n const internals = (ref as any)[INTERNAL_SYMBOL]\n if (!internals) {\n throw new Error(\n \"change() requires a TypedRef with internal methods. \" +\n \"Make sure you're passing a valid typed ref.\",\n )\n }\n\n // Get the params needed to create a draft\n const params = internals.getTypedRefParams()\n\n // Create draft params with batchedMutation enabled and autoCommit disabled\n const draftParams = {\n ...params,\n autoCommit: false,\n batchedMutation: true,\n }\n\n // Create the draft ref using the same factory that created the original\n const draft = createContainerTypedRef(draftParams) as T\n\n // Execute the user's function with the draft\n fn(draft)\n\n // Absorb any cached plain values back into the Loro containers\n const draftInternals = (draft as any)[INTERNAL_SYMBOL]\n draftInternals.absorbPlainValues()\n\n // Commit the changes\n // Note: Loro's commit() is idempotent, so nested calls are safe\n internals.getDoc().commit()\n\n // Return the original ref for chaining\n return ref\n}\n\n/**\n * Access the underlying LoroDoc for advanced operations.\n * Works on both TypedDoc and any typed ref (TextRef, CounterRef, ListRef, etc.).\n *\n * @param docOrRef - The TypedDoc or typed ref to unwrap\n * @returns The underlying LoroDoc instance (or undefined for refs created outside a doc context)\n *\n * @example\n * ```typescript\n * import { getLoroDoc } from \"@loro-extended/change\"\n *\n * // From TypedDoc\n * const loroDoc = getLoroDoc(doc)\n * const version = loroDoc.version()\n * loroDoc.subscribe(() => console.log(\"changed\"))\n *\n * // From any ref (TextRef, CounterRef, ListRef, etc.)\n * const titleRef = doc.title\n * const loroDoc = getLoroDoc(titleRef)\n * loroDoc?.subscribe(() => console.log(\"changed\"))\n * ```\n */\nexport function getLoroDoc<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroDoc\nexport function getLoroDoc<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): LoroDoc\nexport function getLoroDoc<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n): LoroDoc\nexport function getLoroDoc<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n): LoroDoc\nexport function getLoroDoc(\n docOrRef:\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>,\n): LoroDoc {\n // Use loro() to access the underlying LoroDoc\n return loro(docOrRef as any).doc\n}\n\n/**\n * Access the underlying Loro container from a typed ref.\n * Returns the correctly-typed container based on the ref type.\n *\n * @param ref - The typed ref to unwrap\n * @returns The underlying Loro container (LoroText, LoroCounter, LoroList, etc.)\n *\n * @example\n * ```typescript\n * import { getLoroContainer } from \"@loro-extended/change\"\n *\n * const titleRef = doc.title\n * const loroText = getLoroContainer(titleRef) // LoroText\n *\n * const countRef = doc.count\n * const loroCounter = getLoroContainer(countRef) // LoroCounter\n *\n * const itemsRef = doc.items\n * const loroList = getLoroContainer(itemsRef) // LoroList\n *\n * // Subscribe to container-level changes\n * loroText.subscribe((event) => console.log(\"Text changed:\", event))\n * ```\n */\nexport function getLoroContainer(ref: TypedRef<TextContainerShape>): LoroText\nexport function getLoroContainer(\n ref: TypedRef<CounterContainerShape>,\n): LoroCounter\nexport function getLoroContainer(ref: TypedRef<ListContainerShape>): LoroList\nexport function getLoroContainer(\n ref: TypedRef<MovableListContainerShape>,\n): LoroMovableList\nexport function getLoroContainer(ref: TypedRef<RecordContainerShape>): LoroMap\nexport function getLoroContainer(ref: TypedRef<StructContainerShape>): LoroMap\nexport function getLoroContainer<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(ref: StructRef<NestedShapes>): LoroMap\nexport function getLoroContainer<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n): LoroTree\nexport function getLoroContainer<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n): LoroTree\nexport function getLoroContainer<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): ShapeToContainer<Shape>\nexport function getLoroContainer(\n ref: TypedRef<any> | TreeRef<any> | TreeRefInterface<any> | StructRef<any>,\n): unknown {\n // Use loro() to access the underlying container\n return loro(ref as any).container\n}\n\n/**\n * Creates a new TypedDoc as a fork of the current document.\n * The forked doc contains all history up to the current version.\n * The forked doc has a different PeerID from the original by default.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.fork()`\n *\n * @param doc - The TypedDoc to fork\n * @param options - Optional settings\n * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork\n * @returns A new TypedDoc with the same schema at the current version\n *\n * @example\n * ```typescript\n * import { fork, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n *\n * // Fork the document\n * const forkedDoc = fork(doc);\n * forkedDoc.title.update(\"World\");\n *\n * console.log(doc.title.toString()); // \"Hello\"\n * console.log(forkedDoc.title.toString()); // \"World\"\n *\n * // Fork with same peer ID (for World/Worldview pattern)\n * const worldview = fork(world, { preservePeerId: true });\n * ```\n */\nexport function fork<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n options?: { preservePeerId?: boolean },\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const forkedLoroDoc = loroDoc.fork()\n const shape = loro(doc).docShape as Shape\n\n // Optionally preserve the peer ID (useful for World/Worldview pattern)\n if (options?.preservePeerId) {\n forkedLoroDoc.setPeerId(loroDoc.peerId)\n }\n\n return createTypedDoc(shape, forkedLoroDoc)\n}\n\n/**\n * Creates a new TypedDoc at a specified version (frontiers).\n * The forked doc will only contain history before the specified frontiers.\n * The forked doc has a different PeerID from the original.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)`\n *\n * @param doc - The TypedDoc to fork\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @returns A new TypedDoc with the same schema at the specified version\n *\n * @example\n * ```typescript\n * import { forkAt, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n * doc.title.update(\"World\");\n *\n * // Fork at the earlier version\n * const forkedDoc = forkAt(doc, frontiers);\n * console.log(forkedDoc.title.toString()); // \"Hello\"\n * console.log(doc.title.toString()); // \"World\"\n * ```\n */\nexport function forkAt<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n frontiers: Frontiers,\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const forkedLoroDoc = loroDoc.forkAt(frontiers)\n const shape = loro(doc).docShape as Shape\n return createTypedDoc(shape, forkedLoroDoc)\n}\n\n/**\n * Creates a new TypedDoc at a specified version using a shallow snapshot.\n * Unlike `forkAt`, this creates a \"garbage-collected\" snapshot that only\n * contains the current state and history since the specified frontiers.\n *\n * This is more memory-efficient than `forkAt` for documents with long history,\n * especially useful for the fork-and-merge pattern in LEA where we only need:\n * 1. Read current state\n * 2. Apply changes\n * 3. Export delta and merge back\n *\n * The shallow fork has a different PeerID from the original by default.\n * Use `preservePeerId: true` to copy the original's peer ID (useful for\n * fork-and-merge patterns where you want consistent frontier progression).\n *\n * @param doc - The TypedDoc to fork\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @param options - Optional settings\n * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork\n * @returns A new TypedDoc with the same schema at the specified version (shallow)\n *\n * @example\n * ```typescript\n * import { shallowForkAt, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n *\n * // Create a shallow fork (memory-efficient)\n * const shallowDoc = shallowForkAt(doc, frontiers, { preservePeerId: true });\n *\n * // Modify the shallow doc\n * shallowDoc.title.update(\"World\");\n *\n * // Merge changes back\n * const update = loro(shallowDoc).doc.export({\n * mode: \"update\",\n * from: loro(doc).doc.version()\n * });\n * loro(doc).doc.import(update);\n * ```\n */\nexport function shallowForkAt<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n frontiers: Frontiers,\n options?: { preservePeerId?: boolean },\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const shape = loro(doc).docShape as Shape\n\n // Export a shallow snapshot at the specified frontiers\n const shallowBytes = loroDoc.export({\n mode: \"shallow-snapshot\",\n frontiers,\n })\n\n // Create a new LoroDoc from the shallow snapshot\n const shallowLoroDoc = LoroDoc.fromSnapshot(shallowBytes)\n\n // Optionally preserve the peer ID for consistent frontier progression\n if (options?.preservePeerId) {\n shallowLoroDoc.setPeerId(loroDoc.peerId)\n }\n\n return createTypedDoc(shape, shallowLoroDoc)\n}\n","/**\n * The `loro()` function - single escape hatch for CRDT internals.\n *\n * Design Principle:\n * > If it takes a plain JavaScript value, keep it on the ref.\n * > If it takes a Loro container or exposes CRDT internals, move to `loro()`.\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\"\n *\n * // Access underlying LoroDoc\n * loro(ref).doc\n *\n * // Access underlying Loro container (correctly typed)\n * loro(ref).container // LoroList, LoroMap, LoroText, etc.\n *\n * // Subscribe to changes\n * loro(ref).subscribe(callback)\n *\n * // Container operations\n * loro(list).pushContainer(loroMap)\n * loro(struct).setContainer('key', loroMap)\n * ```\n */\n\nimport type {\n Container,\n LoroCounter,\n LoroDoc,\n LoroEventBatch,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Subscription,\n} from \"loro-crdt\"\nimport type { JsonPatch } from \"./json-patch.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n DocShape,\n StructContainerShape,\n TreeRefInterface,\n} from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\nimport type { TypedRef } from \"./typed-refs/base.js\"\nimport type { CounterRef } from \"./typed-refs/counter-ref.js\"\nimport type { ListRef } from \"./typed-refs/list-ref.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list-ref.js\"\nimport type { RecordRef } from \"./typed-refs/record-ref.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TextRef } from \"./typed-refs/text-ref.js\"\nimport type { TreeNodeRef } from \"./typed-refs/tree-node-ref.js\"\nimport type { TreeRef } from \"./typed-refs/tree-ref.js\"\n\n// ============================================================================\n// Symbol for loro() access\n// ============================================================================\n\n/**\n * Well-known Symbol for loro() access.\n * This is exported so advanced users can access it directly if needed.\n */\nexport const LORO_SYMBOL = Symbol.for(\"loro-extended:loro\")\n\n// ============================================================================\n// Interface definitions for loro() return types\n// ============================================================================\n\n/**\n * Base interface for all loro() return types.\n * Provides access to the underlying LoroDoc, container, and subscription.\n */\nexport interface LoroRefBase {\n /** The underlying LoroDoc */\n readonly doc: LoroDoc\n\n /** The underlying Loro container */\n readonly container: unknown\n\n /**\n * Subscribe to container-level changes.\n * @param callback - Function called when the container changes\n * @returns Subscription that can be used to unsubscribe\n */\n subscribe(callback: (event: LoroEventBatch) => void): Subscription\n}\n\n/**\n * loro() return type for ListRef and MovableListRef.\n * Provides container operations that take Loro containers.\n */\nexport interface LoroListRef extends LoroRefBase {\n /** The underlying LoroList or LoroMovableList */\n readonly container: LoroList | LoroMovableList\n\n /**\n * Push a Loro container to the end of the list.\n * Use this when you need to add a pre-existing container.\n */\n pushContainer(container: Container): Container\n\n /**\n * Insert a Loro container at the specified index.\n * Use this when you need to insert a pre-existing container.\n */\n insertContainer(index: number, container: Container): Container\n}\n\n/**\n * loro() return type for StructRef and RecordRef.\n * Provides container operations that take Loro containers.\n */\nexport interface LoroMapRef extends LoroRefBase {\n /** The underlying LoroMap */\n readonly container: LoroMap\n\n /**\n * Set a Loro container at the specified key.\n * Use this when you need to set a pre-existing container.\n */\n setContainer(key: string, container: Container): Container\n}\n\n/**\n * loro() return type for TextRef.\n */\nexport interface LoroTextRef extends LoroRefBase {\n /** The underlying LoroText */\n readonly container: LoroText\n}\n\n/**\n * loro() return type for CounterRef.\n */\nexport interface LoroCounterRef extends LoroRefBase {\n /** The underlying LoroCounter */\n readonly container: LoroCounter\n}\n\n/**\n * loro() return type for TreeRef.\n */\nexport interface LoroTreeRef extends LoroRefBase {\n /** The underlying LoroTree */\n readonly container: LoroTree\n}\n\n/**\n * loro() return type for TreeNodeRef.\n */\nexport interface LoroTreeNodeRef extends LoroRefBase {\n /** The underlying LoroTreeNode */\n readonly container: LoroTreeNode\n}\n\n/**\n * loro() return type for TypedDoc.\n * Provides access to doc-level operations.\n */\nexport interface LoroTypedDocRef extends LoroRefBase {\n /** The underlying LoroDoc (same as doc for TypedDoc) */\n readonly container: LoroDoc\n\n /**\n * Apply JSON Patch operations to the document.\n * @param patch - Array of JSON Patch operations (RFC 6902)\n * @param pathPrefix - Optional path prefix for scoped operations\n */\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void\n\n /** Access the document schema shape */\n readonly docShape: DocShape\n\n /** Get raw CRDT value without placeholder overlay */\n readonly rawValue: unknown\n}\n\n// ============================================================================\n// loro() function overloads\n// ============================================================================\n\n/**\n * Access CRDT internals for a ListRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: ListRef<NestedShape>,\n): LoroListRef\n\n/**\n * Access CRDT internals for a MovableListRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: MovableListRef<NestedShape>,\n): LoroListRef\n\n/**\n * Access CRDT internals for a StructRef.\n */\nexport function loro<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(ref: StructRef<NestedShapes>): LoroMapRef\n\n/**\n * Access CRDT internals for a RecordRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: RecordRef<NestedShape>,\n): LoroMapRef\n\n/**\n * Access CRDT internals for a TextRef.\n */\nexport function loro(ref: TextRef): LoroTextRef\n\n/**\n * Access CRDT internals for a CounterRef.\n */\nexport function loro(ref: CounterRef): LoroCounterRef\n\n/**\n * Access CRDT internals for a TreeRef.\n */\nexport function loro<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape> | TreeRefInterface<DataShape>,\n): LoroTreeRef\n\n/**\n * Access CRDT internals for a TreeNodeRef.\n */\nexport function loro<DataShape extends StructContainerShape>(\n ref: TreeNodeRef<DataShape>,\n): LoroTreeNodeRef\n\n/**\n * Access CRDT internals for a TypedDoc.\n */\nexport function loro<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroTypedDocRef\n\n/**\n * Access CRDT internals for any TypedRef.\n */\nexport function loro<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): LoroRefBase\n\n/**\n * The `loro()` function - single escape hatch for CRDT internals.\n *\n * Use this to access:\n * - The underlying LoroDoc\n * - The underlying Loro container (correctly typed)\n * - Container-level subscriptions\n * - Container operations that take Loro containers (pushContainer, setContainer, etc.)\n *\n * @param refOrDoc - A TypedRef or TypedDoc\n * @returns An object with CRDT internals and operations\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\"\n *\n * // Access underlying LoroDoc\n * loro(doc.settings).doc\n *\n * // Access underlying Loro container\n * loro(doc.items).container // LoroList\n *\n * // Subscribe to changes\n * loro(doc.settings).subscribe(event => { ... })\n *\n * // Container operations\n * loro(doc.items).pushContainer(loroMap)\n * ```\n */\nexport function loro(\n refOrDoc:\n | TypedRef<any>\n | TypedDoc<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | TreeNodeRef<any>\n | StructRef<any>,\n): LoroRefBase {\n // Access the loro namespace via the well-known symbol\n const loroNamespace = (refOrDoc as any)[LORO_SYMBOL]\n if (!loroNamespace) {\n throw new Error(\n \"Invalid argument: expected TypedRef, TreeRef, or TypedDoc with loro() support\",\n )\n }\n return loroNamespace\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: fix later */\n\nimport {\n LoroDoc,\n type LoroEventBatch,\n type PeerID,\n type Subscription,\n} from \"loro-crdt\"\nimport { derivePlaceholder } from \"./derive-placeholder.js\"\nimport {\n type JsonPatch,\n JsonPatchApplicator,\n type JsonPatchOperation,\n normalizePath,\n} from \"./json-patch.js\"\nimport { LORO_SYMBOL, type LoroTypedDocRef } from \"./loro.js\"\nimport { overlayPlaceholder } from \"./overlay.js\"\nimport type { DocShape } from \"./shape.js\"\nimport { INTERNAL_SYMBOL } from \"./typed-refs/base.js\"\nimport { DocRef } from \"./typed-refs/doc-ref.js\"\nimport type { Infer, InferPlaceholderType, Mutable } from \"./types.js\"\nimport { validatePlaceholder } from \"./validation.js\"\n\n/**\n * Internal TypedDoc implementation (not directly exposed to users).\n * Users interact with the proxied version that provides direct schema access.\n */\nclass TypedDocInternal<Shape extends DocShape> {\n private shape: Shape\n private placeholder: InferPlaceholderType<Shape>\n private doc: LoroDoc\n private valueRef: DocRef<Shape> | null = null\n // Reference to the proxy for returning from change()\n proxy: TypedDoc<Shape> | null = null\n\n constructor(shape: Shape, doc: LoroDoc = new LoroDoc()) {\n this.shape = shape\n this.placeholder = derivePlaceholder(shape)\n this.doc = doc\n\n validatePlaceholder(this.placeholder, this.shape)\n }\n\n get value(): Mutable<Shape> {\n if (!this.valueRef) {\n this.valueRef = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: true,\n })\n }\n return this.valueRef as unknown as Mutable<Shape>\n }\n\n toJSON(): Infer<Shape> {\n const crdtValue = this.doc.toJSON()\n return overlayPlaceholder(\n this.shape,\n crdtValue,\n this.placeholder as any,\n ) as Infer<Shape>\n }\n\n change(fn: (draft: Mutable<Shape>) => void): void {\n const draft = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: false,\n batchedMutation: true, // Enable value shape caching for find-and-mutate patterns\n })\n fn(draft as unknown as Mutable<Shape>)\n draft[INTERNAL_SYMBOL].absorbPlainValues()\n this.doc.commit()\n\n // Invalidate cached value ref since doc changed\n this.valueRef = null\n }\n\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n this.change(draft => {\n const applicator = new JsonPatchApplicator(draft)\n\n const prefixedPatch = pathPrefix\n ? patch.map((op: JsonPatchOperation) => ({\n ...op,\n path: [...pathPrefix, ...normalizePath(op.path)],\n }))\n : patch\n\n applicator.applyPatch(prefixedPatch)\n })\n }\n\n get loroDoc(): LoroDoc {\n return this.doc\n }\n\n get docShape(): Shape {\n return this.shape\n }\n\n get rawValue(): any {\n return this.doc.toJSON()\n }\n}\n\n/**\n * The proxied TypedDoc type that provides direct schema access.\n * Schema properties are accessed directly on the doc object.\n *\n * @example\n * ```typescript\n * const doc = createTypedDoc(schema);\n *\n * // Direct schema access\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Serialize to JSON (works on doc and all refs)\n * const snapshot = doc.toJSON();\n * const users = doc.users.toJSON();\n *\n * // Batched mutations via change()\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Access CRDT internals via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc).doc; // LoroDoc\n * loro(doc).subscribe(callback);\n * ```\n */\n/**\n * Frontiers represent a specific version in the document's history.\n * Each frontier is an operation ID consisting of a peer ID and counter.\n */\nexport type Frontiers = { peer: PeerID; counter: number }[]\n\nexport type TypedDoc<Shape extends DocShape> = Mutable<Shape> & {\n /**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n * ```\n */\n change(fn: (draft: Mutable<Shape>) => void): TypedDoc<Shape>\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an O(N) operation that serializes the entire document.\n *\n * @example\n * ```typescript\n * const snapshot = doc.toJSON();\n * console.log(snapshot.count); // number\n * ```\n */\n toJSON(): Infer<Shape>\n\n /**\n * Creates a new TypedDoc at a specified version (frontiers).\n * The forked doc will only contain history before the specified frontiers.\n * The forked doc has a different PeerID from the original.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)`\n *\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @returns A new TypedDoc with the same schema at the specified version\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\";\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n * doc.title.update(\"World\");\n *\n * // Fork at the earlier version\n * const forkedDoc = doc.forkAt(frontiers);\n * console.log(forkedDoc.title.toString()); // \"Hello\"\n * console.log(doc.title.toString()); // \"World\"\n * ```\n */\n forkAt(frontiers: Frontiers): TypedDoc<Shape>\n}\n\n/**\n * Creates a new TypedDoc with the given schema.\n * Returns a proxied document where schema properties are accessed directly.\n *\n * @param shape - The document schema (with optional .placeholder() values)\n * @param existingDoc - Optional existing LoroDoc to wrap\n * @returns A proxied TypedDoc with direct schema access\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * title: Shape.text(),\n * count: Shape.counter(),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Direct mutations (auto-commit)\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Batched mutations via change()\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Get plain JSON\n * const snapshot = doc.toJSON();\n *\n * // Access CRDT internals via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc).doc; // LoroDoc\n * loro(doc).subscribe(callback);\n * ```\n */\nexport function createTypedDoc<Shape extends DocShape>(\n shape: Shape,\n existingDoc?: LoroDoc,\n): TypedDoc<Shape> {\n const internal = new TypedDocInternal(shape, existingDoc || new LoroDoc())\n\n // Create the loro() namespace for this doc\n const loroNamespace: LoroTypedDocRef = {\n get doc(): LoroDoc {\n return internal.loroDoc\n },\n get container(): LoroDoc {\n return internal.loroDoc\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return internal.loroDoc.subscribe(callback)\n },\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n internal.applyPatch(patch, pathPrefix)\n },\n get docShape(): DocShape {\n return internal.docShape\n },\n get rawValue(): unknown {\n return internal.rawValue\n },\n }\n\n // Create the change() function that returns the proxy for chaining\n const changeFunction = (\n fn: (draft: Mutable<Shape>) => void,\n ): TypedDoc<Shape> => {\n internal.change(fn)\n return proxy\n }\n\n // Create the forkAt() function that returns a new TypedDoc at the specified version\n const forkAtFunction = (frontiers: Frontiers): TypedDoc<Shape> => {\n const forkedLoroDoc = internal.loroDoc.forkAt(frontiers)\n return createTypedDoc(internal.docShape, forkedLoroDoc)\n }\n\n // Create a proxy that delegates schema properties to the DocRef\n // and provides change() and forkAt() methods\n const proxy = new Proxy(internal.value as object, {\n get(target, prop, receiver) {\n // loro() access via well-known symbol\n if (prop === LORO_SYMBOL) {\n return loroNamespace\n }\n\n // change() method directly on doc\n if (prop === \"change\") {\n return changeFunction\n }\n\n // forkAt() method directly on doc\n if (prop === \"forkAt\") {\n return forkAtFunction\n }\n\n // toJSON() should always read fresh from the CRDT\n if (prop === \"toJSON\") {\n return () => internal.toJSON()\n }\n\n // Delegate to the DocRef (which is the target)\n return Reflect.get(target, prop, receiver)\n },\n\n set(target, prop, value, receiver) {\n // Don't allow setting change, forkAt, or LORO_SYMBOL\n if (prop === LORO_SYMBOL || prop === \"change\" || prop === \"forkAt\") {\n return false\n }\n\n // Delegate to the DocRef\n return Reflect.set(target, prop, value, receiver)\n },\n\n // Support 'in' operator\n has(target, prop) {\n if (prop === LORO_SYMBOL || prop === \"change\" || prop === \"forkAt\")\n return true\n return Reflect.has(target, prop)\n },\n\n // Support Object.keys() - filter out Symbol properties to allow proxies to be used\n // in place of plain objects. This prevents React's \"Object keys must be strings\" error.\n ownKeys(target) {\n return Reflect.ownKeys(target).filter(key => typeof key === \"string\")\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === \"change\") {\n return {\n configurable: true,\n enumerable: false,\n value: changeFunction,\n }\n }\n if (prop === \"forkAt\") {\n return {\n configurable: true,\n enumerable: false,\n value: forkAtFunction,\n }\n }\n if (prop === LORO_SYMBOL) {\n return {\n configurable: true,\n enumerable: false,\n value: loroNamespace,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as TypedDoc<Shape>\n\n // Store reference to proxy for returning from change()\n internal.proxy = proxy\n\n return proxy\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: JSON Patch values can be any type */\n\nimport type { DocShape } from \"./shape.js\"\nimport type { Draft } from \"./types.js\"\n\n// =============================================================================\n// JSON PATCH TYPES - Discriminated Union for Type Safety\n// =============================================================================\n\nexport type JsonPatchAddOperation = {\n op: \"add\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchRemoveOperation = {\n op: \"remove\"\n path: string | (string | number)[]\n}\n\nexport type JsonPatchReplaceOperation = {\n op: \"replace\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchMoveOperation = {\n op: \"move\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchCopyOperation = {\n op: \"copy\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchTestOperation = {\n op: \"test\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchOperation =\n | JsonPatchAddOperation\n | JsonPatchRemoveOperation\n | JsonPatchReplaceOperation\n | JsonPatchMoveOperation\n | JsonPatchCopyOperation\n | JsonPatchTestOperation\n\nexport type JsonPatch = JsonPatchOperation[]\n\n// =============================================================================\n// PATH NAVIGATION UTILITIES\n// =============================================================================\n\n/**\n * Normalize JSON Pointer string to path array\n * Handles RFC 6901 escaping: ~1 -> /, ~0 -> ~\n */\nexport function normalizePath(\n path: string | (string | number)[],\n): (string | number)[] {\n if (Array.isArray(path)) {\n return path\n }\n\n // Handle JSON Pointer format (RFC 6901)\n if (path.startsWith(\"/\")) {\n return path\n .slice(1) // Remove leading slash\n .split(\"/\")\n .map(segment => {\n // Handle JSON Pointer escaping\n const unescaped = segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n // Try to parse as number for array indices\n const asNumber = Number(unescaped)\n return Number.isInteger(asNumber) && asNumber >= 0\n ? asNumber\n : unescaped\n })\n }\n\n // Handle simple dot notation or single segment\n return path.split(\".\").map(segment => {\n const asNumber = Number(segment)\n return Number.isInteger(asNumber) && asNumber >= 0 ? asNumber : segment\n })\n}\n\n/**\n * Navigate to a target path using natural DraftNode property access\n * This follows the existing patterns from the test suite\n */\nfunction navigateToPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): { parent: any; key: string | number } {\n if (path.length === 0) {\n throw new Error(\"Cannot navigate to empty path\")\n }\n\n let current = draft as any\n\n // Navigate to parent of target\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]\n\n if (typeof segment === \"string\") {\n // Use natural property access - this leverages existing DraftNode lazy creation\n current = current[segment]\n if (current === undefined) {\n throw new Error(`Cannot navigate to path segment: ${segment}`)\n }\n } else if (typeof segment === \"number\") {\n // List/array access using get() method (following existing patterns)\n if (current.get && typeof current.get === \"function\") {\n current = current.get(segment)\n if (current === undefined) {\n throw new Error(`List index ${segment} does not exist`)\n }\n } else {\n throw new Error(`Cannot use numeric index ${segment} on non-list`)\n }\n } else {\n throw new Error(`Invalid path segment type: ${typeof segment}`)\n }\n }\n\n const targetKey = path[path.length - 1]\n return { parent: current, key: targetKey }\n}\n\n/**\n * Get value at path using natural DraftNode access patterns\n */\nfunction getValueAtPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): any {\n if (path.length === 0) {\n return draft\n }\n\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Use natural property access or get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n return parent[key]\n } else if (typeof key === \"number\") {\n // List access using get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n throw new Error(`Cannot use numeric index ${key} on non-list`)\n }\n\n throw new Error(`Invalid key type: ${typeof key}`)\n}\n\n// =============================================================================\n// OPERATION HANDLERS - Following existing DraftNode patterns\n// =============================================================================\n\n/**\n * Handle 'add' operation using existing DraftNode methods\n */\nfunction handleAdd<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchAddOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use natural assignment or set() method\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n // Natural property assignment (follows existing test patterns)\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - use insert() method (follows existing patterns)\n if (parent.insert && typeof parent.insert === \"function\") {\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot insert at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'remove' operation using existing DraftNode methods\n */\nfunction handleRemove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchRemoveOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use delete() method (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key)\n } else {\n delete parent[key]\n }\n } else if (typeof key === \"number\") {\n // List operations - use delete() method with count (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key, 1)\n } else {\n throw new Error(`Cannot remove at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'replace' operation using existing DraftNode methods\n */\nfunction handleReplace<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchReplaceOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use set() method or natural assignment\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - delete then insert (follows existing patterns)\n if (\n parent.delete &&\n parent.insert &&\n typeof parent.delete === \"function\" &&\n typeof parent.insert === \"function\"\n ) {\n parent.delete(key, 1)\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot replace at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'move' operation using existing DraftNode methods\n */\nfunction handleMove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchMoveOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n const toPath = normalizePath(operation.path)\n\n // For list moves within the same parent, we need special handling\n if (\n fromPath.length === toPath.length &&\n fromPath.slice(0, -1).every((segment, i) => segment === toPath[i])\n ) {\n // Same parent container - use list move operation if available\n const fromIndex = fromPath[fromPath.length - 1]\n const toIndex = toPath[toPath.length - 1]\n\n if (typeof fromIndex === \"number\" && typeof toIndex === \"number\") {\n const { parent } = navigateToPath(draft, fromPath.slice(0, -1))\n\n // Check if the parent has a move method (like LoroMovableList)\n if (parent.move && typeof parent.move === \"function\") {\n parent.move(fromIndex, toIndex)\n return\n }\n\n // Otherwise, get value, remove, then add at target index\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n\n // For JSON Patch move semantics, the target index refers to the position\n // in the final array, not the intermediate array after removal.\n // No index adjustment needed - use the original target index.\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n return\n }\n }\n\n // Different parents or non-numeric indices - standard move\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'copy' operation using existing DraftNode methods\n */\nfunction handleCopy<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchCopyOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n\n // Get the value to copy\n const value = getValueAtPath(draft, fromPath)\n\n // Add to destination (no removal)\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'test' operation using existing DraftNode value access\n */\nfunction handleTest<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchTestOperation,\n): boolean {\n const path = normalizePath(operation.path)\n const actualValue = getValueAtPath(draft, path)\n\n // Deep equality check for test operation\n return JSON.stringify(actualValue) === JSON.stringify(operation.value)\n}\n\n// =============================================================================\n// MAIN APPLICATOR - Simple orchestration following existing patterns\n// =============================================================================\n\n/**\n * Main JSON Patch applicator - follows existing change() patterns\n */\nexport class JsonPatchApplicator<T extends DocShape> {\n constructor(private rootDraft: Draft<T>) {}\n\n /**\n * Apply a single JSON Patch operation\n */\n applyOperation(operation: JsonPatchOperation): void {\n switch (operation.op) {\n case \"add\":\n handleAdd(this.rootDraft, operation)\n break\n case \"remove\":\n handleRemove(this.rootDraft, operation)\n break\n case \"replace\":\n handleReplace(this.rootDraft, operation)\n break\n case \"move\":\n handleMove(this.rootDraft, operation)\n break\n case \"copy\":\n handleCopy(this.rootDraft, operation)\n break\n case \"test\":\n if (!handleTest(this.rootDraft, operation)) {\n throw new Error(`JSON Patch test failed at path: ${operation.path}`)\n }\n break\n default:\n // TypeScript will catch this at compile time with proper discriminated union\n throw new Error(\n `Unsupported JSON Patch operation: ${(operation as any).op}`,\n )\n }\n }\n\n /**\n * Apply multiple JSON Patch operations in sequence\n */\n applyPatch(patch: JsonPatch): void {\n for (const operation of patch) {\n this.applyOperation(operation)\n }\n }\n}\n","import type {\n Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Value,\n} from \"loro-crdt\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n ValueShape,\n} from \"../shape.js\"\n\nexport { isContainer, isContainerId } from \"loro-crdt\"\n\n/**\n * Type guard to check if a container is a LoroCounter\n */\nexport function isLoroCounter(container: Container): container is LoroCounter {\n return container.kind() === \"Counter\"\n}\n\n/**\n * Type guard to check if a container is a LoroList\n */\nexport function isLoroList(container: Container): container is LoroList {\n return container.kind() === \"List\"\n}\n\n/**\n * Type guard to check if a container is a LoroMap\n */\nexport function isLoroMap(container: Container): container is LoroMap {\n return container.kind() === \"Map\"\n}\n\n/**\n * Type guard to check if a container is a LoroMovableList\n */\nexport function isLoroMovableList(\n container: Container,\n): container is LoroMovableList {\n return container.kind() === \"MovableList\"\n}\n\n/**\n * Type guard to check if a container is a LoroText\n */\nexport function isLoroText(container: Container): container is LoroText {\n return container.kind() === \"Text\"\n}\n\n/**\n * Type guard to check if a container is a LoroTree\n */\nexport function isLoroTree(container: Container): container is LoroTree {\n return container.kind() === \"Tree\"\n}\n\n/**\n * Type guard to check if an object is a LoroTreeNode\n * Note: LoroTreeNode is not a Container, so we check for its specific properties\n */\nexport function isLoroTreeNode(obj: any): obj is LoroTreeNode {\n return (\n obj &&\n typeof obj === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.data === \"object\" &&\n typeof obj.parent === \"function\" &&\n typeof obj.children === \"function\" &&\n typeof obj.createNode === \"function\"\n )\n}\n\n/**\n * Type guard to ensure cached container matches expected type using kind() method\n */\nexport function assertContainerType<T extends Container>(\n cached: Container,\n expected: T,\n context: string = \"container operation\",\n): asserts cached is T {\n if (cached.kind() !== expected.kind()) {\n throw new Error(\n `Type safety violation in ${context}: ` +\n `cached container kind '${cached.kind()}' does not match ` +\n `expected kind '${expected.kind()}'`,\n )\n }\n\n // Additional safety check: ensure IDs match\n if (cached.id !== expected.id) {\n throw new Error(\n `Container ID mismatch in ${context}: ` +\n `cached ID '${cached.id}' does not match expected ID '${expected.id}'`,\n )\n }\n}\n\n/**\n * Type guard to check if a schema is for TextDraftNode\n */\nexport function isTextShape(\n schema: ContainerOrValueShape,\n): schema is TextContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"text\"\n}\n\n/**\n * Type guard to check if a schema is for CounterDraftNode\n */\nexport function isCounterShape(\n schema: ContainerOrValueShape,\n): schema is CounterContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"counter\"\n}\n\n/**\n * Type guard to check if a schema is for ListDraftNode\n */\nexport function isListShape(\n schema: ContainerOrValueShape,\n): schema is ListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"list\"\n}\n\n/**\n * Type guard to check if a schema is for MovableListDraftNode\n */\nexport function isMovableListShape(\n schema: ContainerOrValueShape,\n): schema is MovableListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"movableList\"\n}\n\n/**\n * Type guard to check if a schema is for StructDraftNode\n */\nexport function isStructShape(\n schema: ContainerOrValueShape,\n): schema is StructContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"struct\"\n}\n\n/**\n * @deprecated Use isStructShape instead. isMapShape is an alias for backward compatibility.\n */\nexport const isMapShape = isStructShape\n\n/**\n * Type guard to check if a schema is for RecordDraftNode\n */\nexport function isRecordShape(\n schema: ContainerOrValueShape,\n): schema is RecordContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"record\"\n}\n\n/**\n * Type guard to check if a schema is for TreeDraftNode\n */\nexport function isTreeShape(\n schema: ContainerOrValueShape,\n): schema is TreeContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"tree\"\n}\n\nexport function isContainerShape(\n schema: ContainerOrValueShape,\n): schema is ContainerShape {\n return schema._type && schema._type !== \"value\"\n}\n\n/**\n * Type guard to check if a schema is any of the Value shapes\n */\nexport function isValueShape(\n schema: ContainerOrValueShape,\n): schema is ValueShape {\n return (\n schema._type === \"value\" &&\n [\n \"string\",\n \"number\",\n \"boolean\",\n \"null\",\n \"undefined\",\n \"uint8array\",\n \"struct\",\n \"record\",\n \"array\",\n \"union\",\n \"discriminatedUnion\",\n \"any\",\n ].includes(schema.valueType)\n )\n}\n\nexport function isObjectValue(value: Value): value is { [key: string]: Value } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array)\n )\n}\n","import type { TreeID, Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport type {\n ContainerShape,\n DiscriminatedUnionValueShape,\n DocShape,\n StructContainerShape,\n TreeContainerShape,\n TreeNodeJSON,\n ValueShape,\n} from \"./shape.js\"\nimport { isObjectValue } from \"./utils/type-guards.js\"\n\n/**\n * Overlays CRDT state with placeholder defaults\n */\nexport function overlayPlaceholder<Shape extends DocShape>(\n shape: Shape,\n crdtValue: { [key: string]: Value },\n placeholderValue: { [key: string]: Value },\n): { [key: string]: Value } {\n if (typeof crdtValue !== \"object\") {\n throw new Error(\"crdt object is required\")\n }\n\n if (typeof placeholderValue !== \"object\") {\n throw new Error(\"placeholder object is required\")\n }\n\n const result = { ...placeholderValue }\n\n for (const [key, propShape] of Object.entries(shape.shapes)) {\n const propCrdtValue = crdtValue[key]\n\n const propPlaceholderValue =\n placeholderValue[key as keyof typeof placeholderValue]\n\n result[key as keyof typeof result] = mergeValue(\n propShape,\n propCrdtValue,\n propPlaceholderValue,\n )\n }\n\n return result\n}\n\n/**\n * Merges individual CRDT values with placeholder defaults\n */\nexport function mergeValue<Shape extends ContainerShape | ValueShape>(\n shape: Shape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n // For \"any\" shapes, just return the CRDT value as-is (no placeholder merging)\n if (shape._type === \"any\") {\n return crdtValue\n }\n\n // For \"any\" value shapes, just return the CRDT value as-is\n if (shape._type === \"value\" && (shape as any).valueType === \"any\") {\n return crdtValue\n }\n\n if (crdtValue === undefined && placeholderValue === undefined) {\n throw new Error(\"either crdt or placeholder value must be defined\")\n }\n\n switch (shape._type) {\n case \"text\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? \"\")\n case \"counter\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? 0)\n case \"list\":\n case \"movableList\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n\n const crdtArray = crdtValue as Value[]\n const itemShape = shape.shape\n const itemPlaceholder = deriveShapePlaceholder(itemShape)\n\n return crdtArray.map(item =>\n mergeValue(itemShape, item, itemPlaceholder as Value),\n )\n }\n case \"struct\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"struct crdt must be object\")\n }\n\n const crdtStructValue = crdtValue ?? {}\n\n if (!isObjectValue(placeholderValue) && placeholderValue !== undefined) {\n throw new Error(\"struct placeholder must be object\")\n }\n\n const placeholderStructValue = placeholderValue ?? {}\n\n const result = { ...placeholderStructValue }\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n const nestedCrdtValue = crdtStructValue[key]\n const nestedPlaceholderValue = placeholderStructValue[key]\n\n result[key as keyof typeof result] = mergeValue(\n nestedShape,\n nestedCrdtValue,\n nestedPlaceholderValue,\n )\n }\n\n return result\n }\n case \"tree\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n // Transform Loro's native tree format to our typed format\n const treeShape = shape as TreeContainerShape\n return transformTreeNodes(crdtValue as any[], treeShape.shape) as any\n }\n case \"record\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"record crdt must be object\")\n }\n\n const crdtRecordValue = (crdtValue as Record<string, Value>) ?? {}\n const result: Record<string, Value> = {}\n\n // For records, we iterate over the keys present in the CRDT value\n // and apply the nested shape's placeholder logic to each value\n for (const key of Object.keys(crdtRecordValue)) {\n const nestedCrdtValue = crdtRecordValue[key]\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(shape.shape)\n\n result[key] = mergeValue(\n shape.shape,\n nestedCrdtValue,\n nestedPlaceholderValue as Value,\n )\n }\n\n return result\n }\n default:\n if (shape._type === \"value\" && shape.valueType === \"struct\") {\n const crdtObj = (crdtValue as any) ?? {}\n const placeholderObj = (placeholderValue as any) ?? {}\n const result = { ...placeholderObj }\n\n if (typeof crdtObj !== \"object\" || crdtObj === null) {\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n for (const [key, propShape] of Object.entries(shape.shape)) {\n const propCrdt = crdtObj[key]\n const propPlaceholder = placeholderObj[key]\n result[key] = mergeValue(propShape, propCrdt, propPlaceholder)\n }\n return result\n }\n\n // Handle discriminated unions\n if (shape._type === \"value\" && shape.valueType === \"discriminatedUnion\") {\n return mergeDiscriminatedUnion(\n shape as DiscriminatedUnionValueShape,\n crdtValue,\n placeholderValue,\n )\n }\n\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n}\n\n/**\n * Merges a discriminated union value by determining the variant from the discriminant key.\n * Uses the placeholderValue's discriminant to determine the default variant when the discriminant is missing.\n */\nfunction mergeDiscriminatedUnion(\n shape: DiscriminatedUnionValueShape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n const crdtObj = (crdtValue as Record<string, Value>) ?? {}\n const placeholderObj = (placeholderValue as Record<string, Value>) ?? {}\n\n // Get the discriminant value from CRDT, falling back to placeholder\n const discriminantValue =\n crdtObj[shape.discriminantKey] ?? placeholderObj[shape.discriminantKey]\n\n if (typeof discriminantValue !== \"string\") {\n // If no valid discriminant, return the placeholder\n return placeholderValue\n }\n\n // Find the variant shape for this discriminant value\n const variantShape = shape.variants[discriminantValue]\n\n if (!variantShape) {\n // Unknown variant - return CRDT value or placeholder\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n // Merge using the variant's object shape\n // If the placeholder's discriminant doesn't match the current discriminant,\n // we shouldn't use the placeholder for merging as it belongs to a different variant.\n const placeholderDiscriminant = placeholderObj[shape.discriminantKey]\n const effectivePlaceholderValue =\n placeholderDiscriminant === discriminantValue ? placeholderValue : undefined\n\n return mergeValue(variantShape, crdtValue, effectivePlaceholderValue as Value)\n}\n\n/**\n * Loro's native tree node format from toJSON()\n */\ninterface LoroTreeNodeJSON {\n id: string\n parent: string | null\n index: number\n fractional_index: string\n meta: Record<string, Value>\n children: LoroTreeNodeJSON[]\n}\n\n/**\n * Transforms Loro's native tree format to our typed TreeNodeJSON format.\n * - Renames `meta` to `data`\n * - Renames `fractional_index` to `fractionalIndex`\n * - Applies placeholder merging to node data\n */\nfunction transformTreeNodes<DataShape extends StructContainerShape>(\n nodes: LoroTreeNodeJSON[],\n dataShape: DataShape,\n): TreeNodeJSON<DataShape>[] {\n const dataPlaceholder = deriveShapePlaceholder(dataShape) as Value\n\n return nodes.map(node => transformTreeNode(node, dataShape, dataPlaceholder))\n}\n\n/**\n * Transforms a single tree node and its children recursively.\n */\nfunction transformTreeNode<DataShape extends StructContainerShape>(\n node: LoroTreeNodeJSON,\n dataShape: DataShape,\n dataPlaceholder: Value,\n): TreeNodeJSON<DataShape> {\n // Merge the node's meta (data) with the placeholder\n const mergedData = mergeValue(dataShape, node.meta, dataPlaceholder)\n\n return {\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index,\n fractionalIndex: node.fractional_index,\n data: mergedData as DataShape[\"_plain\"],\n children: node.children.map(child =>\n transformTreeNode(child, dataShape, dataPlaceholder),\n ),\n }\n}\n","import type { LoroDoc, LoroEventBatch, Subscription } from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroRefBase } from \"../loro.js\"\nimport type { ContainerShape, DocShape, ShapeToContainer } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\n\n/**\n * Symbol for internal methods that should not be enumerable or accessible to users.\n * Used to hide implementation details like absorbPlainValues(), getTypedRefParams(), etc.\n *\n * This achieves Success Criteria #7 from loro-api-refactor.md:\n * \"Internal methods hidden - Via Symbol, not enumerable\"\n */\nexport const INTERNAL_SYMBOL = Symbol.for(\"loro-extended:internal\")\n\n// ============================================================================\n// Minimal Interface for absorbPlainValues contract\n// ============================================================================\n\n/**\n * Minimal interface for refs that only need absorbPlainValues.\n * Used by TreeNodeRef which doesn't extend TypedRef.\n */\nexport interface RefInternalsBase {\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void\n /** Force materialization of the container and its nested containers */\n materialize(): void\n}\n\n// ============================================================================\n// TypedRefParams and TypedRef Base Class\n// ============================================================================\n\nexport type TypedRefParams<Shape extends DocShape | ContainerShape> = {\n shape: Shape\n placeholder?: Infer<Shape>\n getContainer: () => ShapeToContainer<Shape>\n autoCommit?: boolean // Auto-commit after mutations\n batchedMutation?: boolean // True when inside change() block - enables value shape caching for find-and-mutate patterns\n getDoc: () => LoroDoc // Needed for auto-commit\n}\n\n// ============================================================================\n// BaseRefInternals - Abstract base class for all internal implementations\n// ============================================================================\n\n/**\n * Abstract base class for all ref internal implementations.\n * Contains shared logic that was previously in TypedRef.createBaseInternals().\n *\n * Subclasses implement specific behavior for each ref type.\n */\nexport abstract class BaseRefInternals<Shape extends DocShape | ContainerShape>\n implements RefInternalsBase\n{\n protected cachedContainer: ShapeToContainer<Shape> | undefined\n protected loroNamespace: LoroRefBase | undefined\n private _suppressAutoCommit = false\n\n constructor(protected readonly params: TypedRefParams<Shape>) {}\n\n /** Get the underlying Loro container (cached) */\n getContainer(): ShapeToContainer<Shape> {\n if (!this.cachedContainer) {\n this.cachedContainer = this.params.getContainer()\n }\n return this.cachedContainer\n }\n\n /** Commit changes if autoCommit is enabled and not suppressed */\n commitIfAuto(): void {\n if (this.params.autoCommit && !this._suppressAutoCommit) {\n this.params.getDoc().commit()\n }\n }\n\n /**\n * Temporarily suppress auto-commit during batch operations.\n * Used by assignPlainValueToTypedRef() to batch multiple property assignments.\n */\n setSuppressAutoCommit(suppress: boolean): void {\n this._suppressAutoCommit = suppress\n }\n\n /** Check if auto-commit is currently suppressed */\n isSuppressAutoCommit(): boolean {\n return this._suppressAutoCommit\n }\n\n /** Get the shape for this ref */\n getShape(): Shape {\n return this.params.shape\n }\n\n /** Get the placeholder value */\n getPlaceholder(): Infer<Shape> | undefined {\n return this.params.placeholder\n }\n\n /** Check if autoCommit is enabled */\n getAutoCommit(): boolean {\n return !!this.params.autoCommit\n }\n\n /** Check if in batched mutation mode */\n getBatchedMutation(): boolean {\n return !!this.params.batchedMutation\n }\n\n /** Get the LoroDoc */\n getDoc(): LoroDoc {\n return this.params.getDoc()\n }\n\n /**\n * Get the TypedRefParams needed to recreate this ref.\n * Used by change() to create draft refs with modified params.\n *\n * Returns a new params object with the same shape, placeholder, getContainer, and getDoc,\n * but allows overriding autoCommit and batchedMutation for draft creation.\n */\n getTypedRefParams(): TypedRefParams<Shape> {\n return {\n shape: this.params.shape,\n placeholder: this.params.placeholder,\n getContainer: this.params.getContainer,\n autoCommit: this.params.autoCommit,\n batchedMutation: this.params.batchedMutation,\n getDoc: this.params.getDoc,\n }\n }\n\n /** Get the loro namespace (cached) */\n getLoroNamespace(): LoroRefBase {\n if (!this.loroNamespace) {\n this.loroNamespace = this.createLoroNamespace()\n }\n return this.loroNamespace\n }\n\n /** Absorb mutated plain values back into Loro containers - subclasses override */\n abstract absorbPlainValues(): void\n\n /** Force materialization of the container and its nested containers */\n materialize(): void {\n this.getContainer()\n }\n\n /** Create the loro() namespace object - subclasses override for specific types */\n protected createLoroNamespace(): LoroRefBase {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.params.getDoc()\n },\n get container(): unknown {\n return self.getContainer()\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as any).subscribe(callback)\n },\n }\n }\n}\n\n/**\n * Base class for all typed refs.\n *\n * All internal methods are accessed via [INTERNAL_SYMBOL] to prevent\n * namespace collisions with user data properties.\n *\n * Uses the Facade + Implementation pattern:\n * - TypedRef is the thin public facade\n * - BaseRefInternals subclasses contain all implementation logic\n */\nexport abstract class TypedRef<Shape extends DocShape | ContainerShape> {\n /**\n * Internal implementation accessed via Symbol.\n * Subclasses must set this to their specific internals class instance.\n */\n abstract [INTERNAL_SYMBOL]: BaseRefInternals<Shape>\n\n /**\n * Serializes the ref to a plain JSON-compatible value.\n * Returns the plain type inferred from the shape.\n */\n abstract toJSON(): Infer<Shape>\n\n /**\n * Access the loro() namespace via the well-known symbol.\n * This is used by the loro() function to access CRDT internals.\n */\n get [LORO_SYMBOL](): LoroRefBase {\n return this[INTERNAL_SYMBOL].getLoroNamespace()\n }\n}\n","import {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n} from \"../shape.js\"\nimport { INTERNAL_SYMBOL, type TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRef } from \"./counter-ref.js\"\nimport { ListRef } from \"./list-ref.js\"\nimport { MovableListRef } from \"./movable-list-ref.js\"\nimport {\n listProxyHandler,\n movableListProxyHandler,\n recordProxyHandler,\n} from \"./proxy-handlers.js\"\nimport { RecordRef } from \"./record-ref.js\"\nimport { createStructRef } from \"./struct-ref.js\"\nimport { TextRef } from \"./text-ref.js\"\nimport { TreeRef } from \"./tree-ref.js\"\n\n/**\n * Mapping from container shape types to their Loro constructor classes.\n * Used when creating new containers via getOrCreateContainer().\n *\n * Note: \"any\" is not included because AnyContainerShape is an escape hatch\n * that doesn't create typed refs - it returns raw Loro containers.\n */\nexport const containerConstructor = {\n counter: LoroCounter,\n list: LoroList,\n movableList: LoroMovableList,\n record: LoroMap, // Records use LoroMap as their underlying container\n struct: LoroMap, // Structs use LoroMap as their underlying container\n text: LoroText,\n tree: LoroTree,\n} as const\n\n/**\n * Type guard to check if a container shape type has a constructor.\n * Returns false for \"any\" which is an escape hatch.\n */\nexport function hasContainerConstructor(\n type: string,\n): type is keyof typeof containerConstructor {\n return type in containerConstructor\n}\n\n/**\n * Unwraps a TypedRef to its primitive value for readonly access.\n * Counter refs return their numeric value, Text refs return their string.\n * Other container types are returned as-is.\n */\nexport function unwrapReadonlyPrimitive(\n ref: TypedRef<any>,\n shape: ContainerShape,\n): any {\n if (shape._type === \"counter\") {\n return (ref as any).value\n }\n if (shape._type === \"text\") {\n return (ref as any).toString()\n }\n return ref\n}\n\n/**\n * Type guard to check if a value has internal methods via INTERNAL_SYMBOL.\n */\nfunction hasInternalSymbol(\n value: unknown,\n): value is { [INTERNAL_SYMBOL]: { absorbPlainValues(): void } } {\n return value !== null && typeof value === \"object\" && INTERNAL_SYMBOL in value\n}\n\n/**\n * Absorbs cached plain values back into a LoroMap container.\n * For TypedRef entries (or any object with INTERNAL_SYMBOL), recursively calls absorbPlainValues().\n * For plain Value entries, sets them directly on the container.\n */\nexport function absorbCachedPlainValues(\n cache: Map<string, TypedRef<ContainerShape> | Value>,\n getContainer: () => LoroMap,\n): void {\n let container: LoroMap | undefined\n\n for (const [key, ref] of cache.entries()) {\n if (hasInternalSymbol(ref)) {\n // Contains a TypedRef or TreeRef, not a plain Value: keep recursing\n ref[INTERNAL_SYMBOL].absorbPlainValues()\n } else {\n // Plain value!\n if (!container) container = getContainer()\n container.set(key, ref)\n }\n }\n}\n\n/**\n * Serializes a TypedRef to JSON by iterating over its keys.\n * For nested TypedRefs with toJSON(), calls their toJSON method.\n * For plain values, includes them directly.\n */\nexport function serializeRefToJSON(\n ref: Record<string, any>,\n keys: Iterable<string>,\n): Record<string, any> {\n const result: Record<string, any> = {}\n for (const key of keys) {\n const value = ref[key]\n if (value && typeof value === \"object\" && \"toJSON\" in value) {\n result[key] = value.toJSON()\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n// Generic catch-all overload\nexport function createContainerTypedRef<T extends ContainerShape>(\n params: TypedRefParams<T>,\n): TypedRef<T>\n\n// Implementation\nexport function createContainerTypedRef(\n params: TypedRefParams<ContainerShape>,\n): TypedRef<ContainerShape> | TreeRef<StructContainerShape> {\n switch (params.shape._type) {\n case \"counter\":\n return new CounterRef(params as TypedRefParams<CounterContainerShape>)\n case \"list\":\n return new Proxy(\n new ListRef(params as TypedRefParams<ListContainerShape>),\n listProxyHandler,\n )\n case \"struct\":\n return createStructRef(\n params as TypedRefParams<StructContainerShape>,\n ) as unknown as TypedRef<ContainerShape>\n case \"movableList\":\n return new Proxy(\n new MovableListRef(params as TypedRefParams<MovableListContainerShape>),\n movableListProxyHandler,\n )\n case \"record\":\n return new Proxy(\n new RecordRef(params as TypedRefParams<RecordContainerShape>),\n recordProxyHandler,\n )\n case \"text\":\n return new TextRef(params as TypedRefParams<TextContainerShape>)\n case \"tree\": {\n const treeShape = params.shape as TreeContainerShape\n return new TreeRef({\n shape: treeShape,\n placeholder: params.placeholder as never[],\n getContainer: params.getContainer as () => LoroTree,\n autoCommit: params.autoCommit,\n getDoc: params.getDoc,\n })\n }\n default:\n throw new Error(\n `Unknown container type: ${(params.shape as ContainerShape)._type}`,\n )\n }\n}\n\n/**\n * Assigns a plain JavaScript value to a TypedRef.\n *\n * For struct/record types, this batches all property assignments and only\n * commits once at the end to avoid multiple subscription notifications.\n *\n * @param ref - The TypedRef to assign to\n * @param value - The plain value to assign\n * @param skipCommit - If true, skip the final commit (caller will handle it)\n * @returns true if assignment was successful, false otherwise\n */\nexport function assignPlainValueToTypedRef(\n ref: TypedRef<any>,\n value: any,\n skipCommit = false,\n): boolean {\n // Access internals via INTERNAL_SYMBOL\n const internals = ref[INTERNAL_SYMBOL]\n\n // Force materialization of the container\n if (internals) {\n internals.materialize()\n }\n\n const shape = internals?.getShape?.() ?? (ref as any).shape\n const shapeType = shape?._type\n\n if (shapeType === \"struct\" || shapeType === \"record\") {\n // Suppress auto-commit during batch assignment to avoid multiple notifications\n const wasSuppressed = internals?.isSuppressAutoCommit?.() ?? false\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(true)\n }\n\n try {\n for (const k in value) {\n ;(ref as any)[k] = value[k]\n }\n } finally {\n // Restore auto-commit state\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all properties are assigned (unless skipCommit is true)\n if (!skipCommit && internals?.getAutoCommit?.()) {\n internals.getDoc().commit()\n }\n\n return true\n }\n\n if (shapeType === \"list\" || shapeType === \"movableList\") {\n if (Array.isArray(value)) {\n const listRef = ref as any\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = internals?.isSuppressAutoCommit?.() ?? false\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(true)\n }\n\n try {\n if (listRef.length > 0) {\n listRef.delete(0, listRef.length)\n }\n for (const item of value) {\n listRef.push(item)\n }\n } finally {\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all items are added (unless skipCommit is true)\n if (!skipCommit && internals?.getAutoCommit?.()) {\n internals.getDoc().commit()\n }\n\n return true\n }\n }\n\n if (shapeType === \"text\") {\n if (typeof value === \"string\") {\n ;(ref as any).update(value)\n return true\n }\n return false\n }\n\n if (shapeType === \"counter\") {\n if (typeof value === \"number\") {\n const currentValue = (ref as any).value\n const diff = value - currentValue\n if (diff > 0) {\n ;(ref as any).increment(diff)\n } else if (diff < 0) {\n ;(ref as any).decrement(-diff)\n }\n return true\n }\n return false\n }\n\n return false\n}\n","import type {\n LoroCounter,\n LoroDoc,\n LoroEventBatch,\n Subscription,\n} from \"loro-crdt\"\nimport type { LoroCounterRef } from \"../loro.js\"\nimport type { CounterContainerShape } from \"../shape.js\"\nimport { BaseRefInternals } from \"./base.js\"\n\n/**\n * Internal implementation for CounterRef.\n * Contains all logic, state, and implementation details.\n */\nexport class CounterRefInternals extends BaseRefInternals<CounterContainerShape> {\n private materialized = false\n\n /** Increment the counter value */\n increment(value: number = 1): void {\n this.materialized = true\n ;(this.getContainer() as LoroCounter).increment(value)\n this.commitIfAuto()\n }\n\n /** Decrement the counter value */\n decrement(value: number = 1): void {\n this.materialized = true\n ;(this.getContainer() as LoroCounter).decrement(value)\n this.commitIfAuto()\n }\n\n /** Get the current counter value */\n getValue(): number {\n const container = this.getContainer() as LoroCounter\n const containerValue = container.value\n if (containerValue !== 0 || this.materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n const placeholder = this.getPlaceholder()\n if (placeholder !== undefined) {\n return placeholder as number\n }\n return containerValue\n }\n\n /** No plain values in counter */\n absorbPlainValues(): void {\n // no plain values contained within\n }\n\n /** Create the loro namespace for counter */\n protected override createLoroNamespace(): LoroCounterRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroCounter {\n return self.getContainer() as LoroCounter\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroCounter).subscribe(callback)\n },\n }\n }\n}\n","import type { CounterContainerShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRefInternals } from \"./counter-ref-internals.js\"\n\n/**\n * Counter typed ref - thin facade that delegates to CounterRefInternals.\n */\nexport class CounterRef extends TypedRef<CounterContainerShape> {\n [INTERNAL_SYMBOL]: CounterRefInternals\n\n constructor(params: TypedRefParams<CounterContainerShape>) {\n super()\n this[INTERNAL_SYMBOL] = new CounterRefInternals(params)\n }\n\n /** Increment the counter by the given value (default 1) */\n increment(value?: number): void {\n this[INTERNAL_SYMBOL].increment(value)\n }\n\n /** Decrement the counter by the given value (default 1) */\n decrement(value?: number): void {\n this[INTERNAL_SYMBOL].decrement(value)\n }\n\n /** Get the current counter value */\n get value(): number {\n return this[INTERNAL_SYMBOL].getValue()\n }\n\n valueOf(): number {\n return this.value\n }\n\n toJSON(): number {\n return this.value\n }\n\n [Symbol.toPrimitive](hint: string): number | string {\n if (hint === \"string\") {\n return String(this.value)\n }\n return this.value\n }\n}\n","import {\n type Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ArrayValueShape,\n ContainerOrValueShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StructContainerShape,\n StructValueShape,\n} from \"./shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isObjectValue,\n isValueShape,\n} from \"./utils/type-guards.js\"\n\n/**\n * Converts string input to LoroText container\n */\nfunction convertTextInput(value: string): LoroText {\n const text = new LoroText()\n\n text.insert(0, value)\n\n return text\n}\n\n/**\n * Converts number input to LoroCounter container\n */\nfunction convertCounterInput(value: number): LoroCounter {\n const counter = new LoroCounter()\n counter.increment(value)\n return counter\n}\n\n/**\n * Converts array input to LoroList container\n */\nfunction convertListInput(\n value: Value[],\n shape: ListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts array input to LoroMovableList container\n */\nfunction convertMovableListInput(\n value: Value[],\n shape: MovableListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroMovableList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroMovableList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts object input to LoroMap container (Struct)\n */\nfunction convertStructInput(\n value: { [key: string]: Value },\n shape: StructContainerShape | StructValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n\n // Iterate over schema keys to ensure all nested containers are materialized\n for (const k of Object.keys(shape.shapes)) {\n const nestedSchema = shape.shapes[k]\n const v = value[k]\n\n if (v !== undefined) {\n const convertedValue = convertInputToRef(v, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n } else if (isContainerShape(nestedSchema)) {\n // If value is missing but it's a container shape, create an empty container\n // This ensures deterministic container IDs across peers\n let emptyValue: any\n if (nestedSchema._type === \"struct\" || nestedSchema._type === \"record\") {\n emptyValue = {}\n } else if (\n nestedSchema._type === \"list\" ||\n nestedSchema._type === \"movableList\"\n ) {\n emptyValue = []\n } else if (nestedSchema._type === \"text\") {\n emptyValue = \"\"\n } else if (nestedSchema._type === \"counter\") {\n emptyValue = 0\n }\n\n if (emptyValue !== undefined) {\n const convertedValue = convertInputToRef(emptyValue, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n }\n }\n }\n }\n\n // Also handle keys present in value but not in schema (if any, though for structs this shouldn't happen ideally)\n // But for backward compatibility or loose typing, we might want to preserve them?\n // The original code did:\n // if (nestedSchema) { ... } else { map.set(k, value) }\n // So it allowed extra keys.\n for (const [k, v] of Object.entries(value)) {\n if (!shape.shapes[k]) {\n map.set(k, v)\n }\n }\n\n return map\n}\n\n/**\n * Converts object input to LoroMap container (Record)\n */\nfunction convertRecordInput(\n value: { [key: string]: Value },\n shape: RecordContainerShape | RecordValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const convertedValue = convertInputToRef(v, shape.shape)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n }\n\n return map\n}\n\n/**\n * Main conversion function that transforms input values to appropriate CRDT containers\n * based on schema definitions\n */\nexport function convertInputToRef<Shape extends ContainerOrValueShape>(\n value: Value,\n shape: Shape,\n): Container | Value {\n switch (shape._type) {\n case \"text\": {\n if (typeof value !== \"string\") {\n throw new Error(\"string expected\")\n }\n\n return convertTextInput(value)\n }\n case \"counter\": {\n if (typeof value !== \"number\") {\n throw new Error(\"number expected\")\n }\n\n return convertCounterInput(value)\n }\n case \"list\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertListInput(value, shape)\n }\n case \"movableList\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertMovableListInput(value, shape)\n }\n case \"struct\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertStructInput(value, shape)\n }\n case \"record\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertRecordInput(value, shape)\n }\n case \"value\": {\n if (!isValueShape(shape)) {\n throw new Error(\"value expected\")\n }\n\n return value\n }\n\n case \"tree\":\n throw new Error(\"tree type unimplemented\")\n\n default:\n throw new Error(`unexpected type: ${(shape as Shape)._type}`)\n }\n}\n","import type {\n Container,\n LoroDoc,\n LoroEventBatch,\n LoroList,\n LoroMovableList,\n Subscription,\n} from \"loro-crdt\"\nimport { convertInputToRef } from \"../conversion.js\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroListRef } from \"../loro.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type { ContainerOrValueShape, ContainerShape } from \"../shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isValueShape,\n} from \"../utils/type-guards.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createContainerTypedRef } from \"./utils.js\"\n\n// ============================================================================\n// ListRefBaseInternals - Internal implementation class\n// ============================================================================\n\n/**\n * Internal implementation for ListRefBase.\n * Contains all logic, state, and implementation details for list operations.\n */\nexport class ListRefBaseInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends BaseRefInternals<any> {\n private itemCache = new Map<number, any>()\n\n /** Get typed ref params for creating child refs at an index */\n getChildTypedRefParams(\n index: number,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n return {\n shape,\n placeholder: undefined, // List items don't have placeholder\n getContainer: () => {\n const container = this.getContainer() as LoroList | LoroMovableList\n const containerItem = container.get(index)\n if (!containerItem || !isContainer(containerItem)) {\n throw new Error(`No container found at index ${index}`)\n }\n return containerItem\n },\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n }\n }\n\n /** Get item for predicate functions (returns plain value) */\n getPredicateItem(index: number): Item | undefined {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n\n // CRITICAL FIX: For predicates to work correctly with mutations,\n // we need to check if there's a cached (mutated) version first\n const cachedItem = this.itemCache.get(index)\n if (cachedItem && isValueShape(shape.shape)) {\n // For value shapes, if we have a cached item, use it so predicates see mutations\n return cachedItem as Item\n }\n\n const containerItem = container.get(index)\n if (containerItem === undefined) {\n return undefined as Item\n }\n\n if (isValueShape(shape.shape)) {\n // For value shapes, return the plain value directly\n return containerItem as Item\n } else {\n // For container shapes, we need to return the plain object representation\n // This allows predicates to access nested properties like article.metadata.author\n if (isContainer(containerItem)) {\n // Convert container to plain object for predicate logic\n // Handle different container types that may not have toJSON method\n if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"toJSON\" in containerItem\n ) {\n return (containerItem as any).toJSON() as Item\n } else if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"getShallowValue\" in containerItem\n ) {\n // For containers like LoroCounter that don't have toJSON but have getShallowValue\n return (containerItem as any).getShallowValue() as Item\n } else {\n // Fallback for other container types\n return containerItem as Item\n }\n }\n return containerItem as Item\n }\n }\n\n /** Get mutable item for return values (returns ref or cached value) */\n getMutableItem(index: number): MutableItem | undefined {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n\n // Get the raw container item\n const containerItem = container.get(index)\n if (containerItem === undefined) {\n return undefined as MutableItem\n }\n\n if (isValueShape(shape.shape)) {\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to found/filtered items persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n return containerItem as MutableItem\n }\n\n // In batched mode (within change()), we need to cache value shapes\n // so that mutations to found/filtered items persist back to the CRDT\n // via absorbPlainValues() at the end of change()\n let cachedItem = this.itemCache.get(index)\n if (cachedItem) {\n return cachedItem\n }\n\n // For value shapes, we need to ensure mutations persist\n // The key insight: we must return the SAME object for the same index\n // so that mutations to filtered/found items persist back to the cache\n if (typeof containerItem === \"object\" && containerItem !== null) {\n // Create a deep copy for objects so mutations can be tracked\n // IMPORTANT: Only create the copy once, then always return the same cached object\n cachedItem = JSON.parse(JSON.stringify(containerItem))\n } else {\n // For primitives, just use the value directly\n cachedItem = containerItem\n }\n this.itemCache.set(index, cachedItem)\n return cachedItem as MutableItem\n }\n\n // Container shapes: safe to cache (handles)\n let cachedItem = this.itemCache.get(index)\n if (!cachedItem) {\n cachedItem = createContainerTypedRef(\n this.getChildTypedRefParams(index, shape.shape as ContainerShape),\n )\n this.itemCache.set(index, cachedItem)\n }\n\n return cachedItem as MutableItem\n }\n\n /** Insert with automatic conversion */\n insertWithConversion(index: number, item: unknown): void {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const convertedItem = convertInputToRef(item as any, shape.shape)\n if (isContainer(convertedItem)) {\n container.insertContainer(index, convertedItem)\n } else {\n container.insert(index, convertedItem)\n }\n }\n\n /** Push with automatic conversion */\n pushWithConversion(item: unknown): void {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const convertedItem = convertInputToRef(item as any, shape.shape)\n if (isContainer(convertedItem)) {\n container.pushContainer(convertedItem)\n } else {\n container.push(convertedItem)\n }\n }\n\n /** Absorb value at specific index (for value shapes) - subclasses override */\n absorbValueAtIndex(_index: number, _value: unknown): void {\n throw new Error(\"absorbValueAtIndex must be implemented by subclass\")\n }\n\n /** Update cache indices after a delete operation */\n updateCacheForDelete(deleteIndex: number, deleteLen: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < deleteIndex) {\n // Items before the deletion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else if (cachedIndex >= deleteIndex + deleteLen) {\n // Items after the deletion range shift down by deleteLen\n newCache.set(cachedIndex - deleteLen, cachedItem)\n }\n // Items within the deletion range are removed from cache\n }\n\n this.itemCache = newCache\n }\n\n /** Update cache indices after an insert operation */\n updateCacheForInsert(insertIndex: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < insertIndex) {\n // Items before the insertion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else {\n // Items at or after the insertion point shift up by 1\n newCache.set(cachedIndex + 1, cachedItem)\n }\n }\n\n this.itemCache = newCache\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n // Critical function: absorb mutated plain values back into Loro containers\n // This is called at the end of change() to persist mutations made to plain objects\n const shape = this.getShape()\n for (const [index, cachedItem] of this.itemCache.entries()) {\n if (cachedItem) {\n if (isValueShape(shape.shape)) {\n // For value shapes, delegate to subclass-specific absorption logic\n this.absorbValueAtIndex(index, cachedItem)\n } else {\n // For container shapes, the item should be a typed ref that handles its own absorption\n if (\n cachedItem &&\n typeof cachedItem === \"object\" &&\n INTERNAL_SYMBOL in cachedItem\n ) {\n ;(cachedItem as any)[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n }\n }\n\n // Clear the cache after absorbing values\n this.itemCache.clear()\n }\n\n /** Create the loro namespace for list */\n protected override createLoroNamespace(): LoroListRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroList | LoroMovableList {\n return self.getContainer() as LoroList | LoroMovableList\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroList | LoroMovableList).subscribe(\n callback,\n )\n },\n pushContainer(container: Container): Container {\n const result = (\n self.getContainer() as LoroList | LoroMovableList\n ).pushContainer(container)\n self.commitIfAuto()\n return result\n },\n insertContainer(index: number, container: Container): Container {\n const result = (\n self.getContainer() as LoroList | LoroMovableList\n ).insertContainer(index, container)\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n\n// ============================================================================\n// ListRefBase - Public facade class\n// ============================================================================\n\n/**\n * Shared logic for list operations - thin facade that delegates to ListRefBaseInternals.\n */\nexport abstract class ListRefBase<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends TypedRef<any> {\n [INTERNAL_SYMBOL]: ListRefBaseInternals<NestedShape, Item, MutableItem>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = this.createInternals(params)\n }\n\n /** Subclasses override to create their specific internals */\n protected abstract createInternals(\n params: TypedRefParams<any>,\n ): ListRefBaseInternals<NestedShape, Item, MutableItem>\n\n // Array-like methods for better developer experience\n // DUAL INTERFACE: Predicates get Item (plain data), return values are MutableItem (mutable)\n\n find(\n predicate: (item: Item, index: number) => boolean,\n ): MutableItem | undefined {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem // Return mutable item\n }\n }\n return undefined\n }\n\n findIndex(predicate: (item: Item, index: number) => boolean): number {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return i\n }\n }\n return -1\n }\n\n map<ReturnType>(\n callback: (item: Item, index: number) => ReturnType,\n ): ReturnType[] {\n const result: ReturnType[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n result.push(callback(predicateItem as Item, i))\n }\n return result\n }\n\n filter(predicate: (item: Item, index: number) => boolean): MutableItem[] {\n const result: MutableItem[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n result.push(this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem) // Return mutable items\n }\n }\n return result\n }\n\n forEach(callback: (item: Item, index: number) => void): void {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n callback(predicateItem as Item, i)\n }\n }\n\n some(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return true\n }\n }\n return false\n }\n\n every(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (!predicate(predicateItem as Item, i)) {\n return false\n }\n }\n return true\n }\n\n slice(start?: number, end?: number): MutableItem[] {\n const len = this.length\n\n // Normalize start index (following JavaScript Array.prototype.slice semantics)\n const startIndex =\n start === undefined\n ? 0\n : start < 0\n ? Math.max(len + start, 0)\n : Math.min(start, len)\n\n // Normalize end index\n const endIndex =\n end === undefined\n ? len\n : end < 0\n ? Math.max(len + end, 0)\n : Math.min(end, len)\n\n const result: MutableItem[] = []\n for (let i = startIndex; i < endIndex; i++) {\n result.push(this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem)\n }\n return result\n }\n\n insert(index: number, item: Item): void {\n // Update cache indices before performing the insert operation\n this[INTERNAL_SYMBOL].updateCacheForInsert(index)\n this[INTERNAL_SYMBOL].insertWithConversion(index, item)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n // Update cache indices before performing the delete operation\n this[INTERNAL_SYMBOL].updateCacheForDelete(index, len)\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n container.delete(index, len)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n push(item: Item): void {\n this[INTERNAL_SYMBOL].pushWithConversion(item)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n pushContainer(container: Container): Container {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const result = loroContainer.pushContainer(container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n insertContainer(index: number, container: Container): Container {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const result = loroContainer.insertContainer(index, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n get(index: number): MutableItem | undefined {\n return this[INTERNAL_SYMBOL].getMutableItem(index) as\n | MutableItem\n | undefined\n }\n\n toArray(): Item[] {\n const result: Item[] = []\n for (let i = 0; i < this.length; i++) {\n result.push(this[INTERNAL_SYMBOL].getPredicateItem(i) as Item)\n }\n return result\n }\n\n toJSON(): Item[] {\n const shape = this[INTERNAL_SYMBOL].getShape()\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const nativeJson = container.toJSON() as any[]\n\n // If the nested shape is a container shape (map, record, etc.) or an object value shape,\n // we need to overlay placeholders for each item\n if (\n isContainerShape(shape.shape) ||\n (isValueShape(shape.shape) && shape.shape.valueType === \"struct\")\n ) {\n const itemPlaceholder = deriveShapePlaceholder(shape.shape)\n return nativeJson.map(item =>\n mergeValue(shape.shape, item, itemPlaceholder as any),\n ) as Item[]\n }\n\n // For primitive value shapes, no overlay needed\n return nativeJson ?? []\n }\n\n [Symbol.iterator](): IterableIterator<MutableItem> {\n let index = 0\n return {\n next: (): IteratorResult<MutableItem> => {\n if (index < this.length) {\n return {\n value: this[INTERNAL_SYMBOL].getMutableItem(index++) as MutableItem,\n done: false,\n }\n }\n return { value: undefined, done: true }\n },\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n get length(): number {\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n return container.length\n }\n}\n","import type { LoroList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport { ListRefBaseInternals } from \"./list-ref-base.js\"\n\n/**\n * Internal implementation for ListRef.\n * Extends ListRefBaseInternals with LoroList-specific absorption logic.\n */\nexport class ListRefInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends ListRefBaseInternals<NestedShape, Item, MutableItem> {\n /** Absorb value at specific index for LoroList */\n override absorbValueAtIndex(index: number, value: unknown): void {\n // LoroList doesn't have set method, need to delete and insert\n const container = this.getContainer() as LoroList\n container.delete(index, 1)\n container.insert(index, value)\n }\n}\n","import type { ContainerOrValueShape } from \"../shape.js\"\nimport type { InferMutableType } from \"../types.js\"\nimport type { TypedRefParams } from \"./base.js\"\nimport { ListRefBase } from \"./list-ref-base.js\"\nimport { ListRefInternals } from \"./list-ref-internals.js\"\n\n/**\n * List typed ref - thin facade that delegates to ListRefInternals.\n */\nexport class ListRef<\n NestedShape extends ContainerOrValueShape,\n> extends ListRefBase<NestedShape> {\n // Returns the mutable type which has toJSON() and other ref methods.\n // For assignment, the proxy handler accepts plain values and converts them.\n // TypeScript may require type assertions for plain value assignments.\n [index: number]: InferMutableType<NestedShape> | undefined\n\n protected override createInternals(\n params: TypedRefParams<any>,\n ): ListRefInternals<NestedShape> {\n return new ListRefInternals(params)\n }\n}\n","import type { LoroMovableList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport { ListRefBaseInternals } from \"./list-ref-base.js\"\n\n// ============================================================================\n// MovableListRefInternals - Internal implementation class\n// ============================================================================\n\n/**\n * Internal implementation for MovableListRef.\n * Extends ListRefBaseInternals with LoroMovableList-specific methods.\n */\nexport class MovableListRefInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends ListRefBaseInternals<NestedShape, Item, MutableItem> {\n /** Absorb value at specific index for LoroMovableList */\n override absorbValueAtIndex(index: number, value: unknown): void {\n // LoroMovableList has set method\n const container = this.getContainer() as LoroMovableList\n container.set(index, value)\n }\n\n /** Move an item from one index to another */\n move(from: number, to: number): void {\n const container = this.getContainer() as LoroMovableList\n container.move(from, to)\n this.commitIfAuto()\n }\n\n /** Set an item at a specific index */\n set(index: number, item: unknown): void {\n const container = this.getContainer() as LoroMovableList\n container.set(index, item)\n this.commitIfAuto()\n }\n}\n","import type { Container } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { InferMutableType } from \"../types.js\"\nimport { INTERNAL_SYMBOL, type TypedRefParams } from \"./base.js\"\nimport { ListRefBase } from \"./list-ref-base.js\"\nimport { MovableListRefInternals } from \"./movable-list-ref-internals.js\"\n\n/**\n * Movable list typed ref - thin facade that delegates to MovableListRefInternals.\n */\nexport class MovableListRef<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n> extends ListRefBase<NestedShape> {\n declare [INTERNAL_SYMBOL]: MovableListRefInternals<NestedShape>;\n [index: number]: InferMutableType<NestedShape> | undefined\n\n protected override createInternals(\n params: TypedRefParams<any>,\n ): MovableListRefInternals<NestedShape> {\n return new MovableListRefInternals(params)\n }\n\n move(from: number, to: number): void {\n this[INTERNAL_SYMBOL].move(from, to)\n }\n\n set(index: number, item: Exclude<Item, Container>) {\n this[INTERNAL_SYMBOL].set(index, item)\n }\n}\n","import { INTERNAL_SYMBOL } from \"./base.js\"\nimport type { ListRef } from \"./list-ref.js\"\nimport type { MovableListRef } from \"./movable-list-ref.js\"\nimport type { RecordRef } from \"./record-ref.js\"\nimport type { RecordRefInternals } from \"./record-ref-internals.js\"\n\nexport const recordProxyHandler: ProxyHandler<RecordRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n // Use getRef for reading - returns undefined for non-existent keys\n return (target[INTERNAL_SYMBOL] as RecordRefInternals<any>).getRef(prop)\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.set(prop, value)\n return true\n }\n return Reflect.set(target, prop, value)\n },\n\n deleteProperty: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.delete(prop)\n return true\n }\n return Reflect.deleteProperty(target, prop)\n },\n\n // Support `in` operator for checking key existence\n has: (target, prop) => {\n if (typeof prop === \"string\") {\n // Check if it's a method/property on the class first\n if (prop in target) {\n return true\n }\n // Otherwise check the underlying container\n return target.has(prop)\n }\n return Reflect.has(target, prop)\n },\n\n ownKeys: target => {\n return target.keys()\n },\n\n getOwnPropertyDescriptor: (target, prop) => {\n if (typeof prop === \"string\" && target.has(prop)) {\n return {\n configurable: true,\n enumerable: true,\n value: target.get(prop),\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n}\n\nexport const listProxyHandler: ProxyHandler<ListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // For lists, assignment to index implies replacement\n target.delete(index, 1)\n target.insert(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n\nexport const movableListProxyHandler: ProxyHandler<MovableListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // MovableList supports set directly\n target.set(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n","import type {\n Container,\n LoroDoc,\n LoroEventBatch,\n LoroMap,\n Subscription,\n Value,\n} from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroMapRef } from \"../loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n RecordContainerShape,\n} from \"../shape.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { BaseRefInternals, type TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n hasContainerConstructor,\n} from \"./utils.js\"\n\n/**\n * Internal implementation for RecordRef.\n * Contains all logic, state, and implementation details.\n */\nexport class RecordRefInternals<\n NestedShape extends ContainerOrValueShape,\n> extends BaseRefInternals<any> {\n private refCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n // First try to get placeholder from the Record's placeholder (if it has an entry for this key)\n let placeholder = (this.getPlaceholder() as any)?.[key]\n\n // If no placeholder exists for this key, derive one from the schema's shape\n // This is critical for Records where the placeholder is always {} but nested\n // containers need valid placeholders to fall back to for missing values\n if (placeholder === undefined) {\n placeholder = deriveShapePlaceholder(shape)\n }\n\n // AnyContainerShape is an escape hatch - it doesn't have a constructor\n if (!hasContainerConstructor(shape._type)) {\n throw new Error(\n `Cannot create typed ref for shape type \"${shape._type}\". ` +\n `Use Shape.any() only at the document root level.`,\n )\n }\n\n const LoroContainer = containerConstructor[shape._type]\n const container = this.getContainer() as LoroMap\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n container.getOrCreateContainer(key, new (LoroContainer as any)()),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n }\n }\n\n /** Get a ref for a key without creating (returns undefined for non-existent container keys) */\n getRef(key: string): unknown {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n // For container shapes, check if the key exists first\n // This allows optional chaining (?.) to work correctly for non-existent keys\n if (isContainerShape(shape)) {\n const existing = container.get(key)\n if (existing === undefined) {\n return undefined\n }\n }\n\n return this.getOrCreateRef(key)\n }\n\n /** Get or create a ref for a key (always creates for container shapes) */\n getOrCreateRef(key: string): unknown {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(shape)) {\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n return containerValue\n }\n // Fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder !== undefined) {\n return placeholder\n }\n // Fall back to the default value from the shape\n return (shape as any)._plain\n }\n\n // In batched mode (within change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n let ref = this.refCache.get(key)\n if (!ref) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n // For objects, create a deep copy so mutations can be tracked\n if (typeof containerValue === \"object\" && containerValue !== null) {\n ref = JSON.parse(JSON.stringify(containerValue))\n } else {\n ref = containerValue as Value\n }\n } else {\n // Fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder !== undefined) {\n ref = placeholder as Value\n } else {\n // Fall back to the default value from the shape\n ref = (shape as any)._plain\n }\n }\n this.refCache.set(key, ref)\n }\n return ref\n }\n\n // For container shapes, we can safely cache the ref since it's a handle\n // to the underlying Loro container, not a value copy.\n let ref = this.refCache.get(key)\n if (!ref) {\n ref = createContainerTypedRef(\n this.getChildTypedRefParams(key, shape as ContainerShape),\n )\n this.refCache.set(key, ref)\n }\n\n return ref as any\n }\n\n /** Set a value at a key */\n set(key: string, value: any): void {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(shape)) {\n container.set(key, value)\n this.refCache.set(key, value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // Use getOrCreateRef to ensure the container is created\n // assignPlainValueToTypedRef handles batching and commits internally\n const ref = this.getOrCreateRef(key)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n // Don't call commitIfAuto here - assignPlainValueToTypedRef handles it\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n /** Delete a key */\n delete(key: string): void {\n const container = this.getContainer() as LoroMap\n container.delete(key)\n this.refCache.delete(key)\n this.commitIfAuto()\n }\n\n /**\n * Replace entire contents with new values.\n * Keys not in `values` are removed.\n */\n replace(values: Record<string, any>): void {\n const container = this.getContainer() as LoroMap\n const currentKeys = new Set(container.keys())\n const newKeys = new Set(Object.keys(values))\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Delete keys that are not in the new values\n for (const key of currentKeys) {\n if (!newKeys.has(key)) {\n container.delete(key)\n this.refCache.delete(key)\n }\n }\n\n // Set new/updated values\n for (const key of newKeys) {\n this.set(key, values[key])\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /**\n * Merge values into record.\n * Existing keys not in `values` are kept.\n */\n merge(values: Record<string, any>): void {\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Set new/updated values (no deletions)\n for (const key of Object.keys(values)) {\n this.set(key, values[key])\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /**\n * Remove all entries from the record.\n */\n clear(): void {\n const container = this.getContainer() as LoroMap\n const keys = container.keys()\n\n if (keys.length === 0) {\n return // No-op on empty record\n }\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Delete all keys\n for (const key of keys) {\n container.delete(key)\n this.refCache.delete(key)\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n absorbCachedPlainValues(this.refCache, () => this.getContainer() as LoroMap)\n }\n\n /** Create the loro namespace for record */\n protected override createLoroNamespace(): LoroMapRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroMap {\n return self.getContainer() as LoroMap\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroMap).subscribe(callback)\n },\n setContainer(key: string, container: Container): Container {\n const result = (self.getContainer() as LoroMap).setContainer(\n key,\n container,\n )\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n","import type { Container, LoroMap } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer, InferMutableType } from \"../types.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { RecordRefInternals } from \"./record-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Record typed ref - thin facade that delegates to RecordRefInternals.\n */\nexport class RecordRef<\n NestedShape extends ContainerOrValueShape,\n> extends TypedRef<any> {\n [key: string]: InferMutableType<NestedShape> | undefined | any\n\n [INTERNAL_SYMBOL]: RecordRefInternals<NestedShape>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = new RecordRefInternals(params)\n }\n\n /** Set a value at a key */\n set(key: string, value: any): void {\n this[INTERNAL_SYMBOL].set(key, value)\n }\n\n /** Delete a key */\n delete(key: string): void {\n this[INTERNAL_SYMBOL].delete(key)\n }\n\n get(key: string): InferMutableType<NestedShape> | undefined {\n // In batched mutation mode (inside change()), use getOrCreateRef to create containers\n // This allows patterns like: draft.scores.get(\"alice\")!.increment(10)\n if (this[INTERNAL_SYMBOL].getBatchedMutation()) {\n return this[INTERNAL_SYMBOL].getOrCreateRef(key) as\n | InferMutableType<NestedShape>\n | undefined\n }\n // In readonly mode, use getRef which returns undefined for non-existent keys\n return this[INTERNAL_SYMBOL].getRef(key) as\n | InferMutableType<NestedShape>\n | undefined\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n const result = loroContainer.setContainer(key, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n has(key: string): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key) !== undefined\n }\n\n keys(): string[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.keys()\n }\n\n /**\n * Returns an array of all values in the record.\n * For container-valued records, returns properly typed refs.\n */\n values(): InferMutableType<NestedShape>[] {\n // We know keys() only returns keys that exist, so get() will not return undefined\n return this.keys().map(\n key => this.get(key) as InferMutableType<NestedShape>,\n )\n }\n\n /**\n * Returns an array of [key, value] pairs.\n * For container-valued records, values are properly typed refs.\n */\n entries(): [string, InferMutableType<NestedShape>][] {\n // We know keys() only returns keys that exist, so get() will not return undefined\n return this.keys().map(key => [\n key,\n this.get(key) as InferMutableType<NestedShape>,\n ])\n }\n\n get size(): number {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.size\n }\n\n /**\n * Replace entire contents with new values.\n * Keys not in `values` are removed.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.players.replace({\n * alice: { score: 100 },\n * bob: { score: 50 }\n * })\n * })\n * ```\n */\n replace(values: Record<string, Infer<NestedShape>>): void {\n this[INTERNAL_SYMBOL].replace(values)\n }\n\n /**\n * Merge values into record.\n * Existing keys not in `values` are kept.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * // Adds charlie, updates alice, keeps bob unchanged\n * draft.players.merge({\n * alice: { score: 150 },\n * charlie: { score: 25 }\n * })\n * })\n * ```\n */\n merge(values: Record<string, Infer<NestedShape>>): void {\n this[INTERNAL_SYMBOL].merge(values)\n }\n\n /**\n * Remove all entries from the record.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.players.clear()\n * })\n * ```\n */\n clear(): void {\n this[INTERNAL_SYMBOL].clear()\n }\n\n toJSON(): Record<string, Infer<NestedShape>> {\n return serializeRefToJSON(this, this.keys()) as Record<\n string,\n Infer<NestedShape>\n >\n }\n}\n","import type {\n Container,\n LoroDoc,\n LoroEventBatch,\n LoroMap,\n Subscription,\n Value,\n} from \"loro-crdt\"\nimport type { LoroMapRef } from \"../loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n StructContainerShape,\n ValueShape,\n} from \"../shape.js\"\nimport { isValueShape } from \"../utils/type-guards.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n type TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n hasContainerConstructor,\n} from \"./utils.js\"\n\n/**\n * Internal implementation for StructRef.\n * Contains all logic, state, and implementation details.\n */\nexport class StructRefInternals<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends BaseRefInternals<any> {\n private propertyCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n const placeholder = (this.getPlaceholder() as any)?.[key]\n\n // AnyContainerShape is an escape hatch - it doesn't have a constructor\n if (!hasContainerConstructor(shape._type)) {\n throw new Error(\n `Cannot create typed ref for shape type \"${shape._type}\". ` +\n `Use Shape.any() only at the document root level.`,\n )\n }\n\n const LoroContainer = containerConstructor[shape._type]\n const container = this.getContainer() as LoroMap\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n container.getOrCreateContainer(key, new (LoroContainer as any)()),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n }\n }\n\n /** Get or create a ref for a key */\n getOrCreateRef<Shape extends ContainerShape | ValueShape>(\n key: string,\n shape?: Shape,\n ): unknown {\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n const actualShape = shape || structShape.shapes[key]\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(actualShape)) {\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n return containerValue\n }\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n return placeholder\n }\n\n // In batched mode (within change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n let ref = this.propertyCache.get(key)\n if (!ref) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n // For objects, create a deep copy so mutations can be tracked\n if (typeof containerValue === \"object\" && containerValue !== null) {\n ref = JSON.parse(JSON.stringify(containerValue))\n } else {\n ref = containerValue as Value\n }\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n ref = placeholder as Value\n }\n this.propertyCache.set(key, ref)\n }\n return ref\n }\n\n // Container shapes: safe to cache (handles)\n let ref = this.propertyCache.get(key)\n if (!ref) {\n ref = createContainerTypedRef(\n this.getChildTypedRefParams(key, actualShape as ContainerShape),\n )\n this.propertyCache.set(key, ref)\n }\n\n return ref as Shape extends ContainerShape ? TypedRef<Shape> : Value\n }\n\n /** Set a property value */\n setPropertyValue(key: string, value: unknown): void {\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n const shape = structShape.shapes[key]\n const container = this.getContainer() as LoroMap\n\n if (!shape) {\n throw new Error(`Unknown property: ${key}`)\n }\n\n if (isValueShape(shape)) {\n container.set(key, value)\n this.propertyCache.set(key, value as Value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // assignPlainValueToTypedRef handles batching and commits internally\n const ref = this.getOrCreateRef(key, shape)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n // Don't call commitIfAuto here - assignPlainValueToTypedRef handles it\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n /** Delete a property */\n deleteProperty(key: string): void {\n const container = this.getContainer() as LoroMap\n container.delete(key)\n this.propertyCache.delete(key)\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n absorbCachedPlainValues(\n this.propertyCache,\n () => this.getContainer() as LoroMap,\n )\n }\n\n /** Force materialization of the container and its nested containers */\n override materialize(): void {\n // Ensure this container exists\n this.getContainer()\n\n // Recursively materialize nested containers\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n for (const key in structShape.shapes) {\n const shape = structShape.shapes[key]\n if (!isValueShape(shape)) {\n // Get the ref (which creates it if needed)\n const ref = this.getOrCreateRef(key, shape) as TypedRef<any>\n // Force materialization\n ref[INTERNAL_SYMBOL].materialize()\n }\n }\n }\n\n /** Create the loro namespace for struct */\n protected override createLoroNamespace(): LoroMapRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroMap {\n return self.getContainer() as LoroMap\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroMap).subscribe(callback)\n },\n setContainer(key: string, container: Container): Container {\n const result = (self.getContainer() as LoroMap).setContainer(\n key,\n container,\n )\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroMapRef } from \"../loro.js\"\nimport type { ContainerOrValueShape, StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport {\n INTERNAL_SYMBOL,\n type RefInternalsBase,\n TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { StructRefInternals } from \"./struct-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Internal implementation class for struct containers.\n * The actual StructRef is a Proxy wrapping this class.\n */\nclass StructRefImpl<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends TypedRef<any> {\n [INTERNAL_SYMBOL]: StructRefInternals<NestedShapes>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = new StructRefInternals(params)\n }\n\n get structShape(): StructContainerShape<NestedShapes> {\n return this[\n INTERNAL_SYMBOL\n ].getShape() as StructContainerShape<NestedShapes>\n }\n\n toJSON(): Infer<StructContainerShape<NestedShapes>> {\n return serializeRefToJSON(\n this as any,\n Object.keys(this.structShape.shapes),\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n // Deprecated methods - kept for backward compatibility\n // @deprecated Use property access instead: obj.key\n get(key: string): any {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key)\n }\n\n // @deprecated Use property assignment instead: obj.key = value\n set(key: string, value: Value): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n container.set(key, value)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n // @deprecated Use loro(struct).setContainer() instead\n setContainer<C extends Container>(key: string, container: C): C {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n const result = loroContainer.setContainer(key, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n // @deprecated Use delete obj.key instead\n delete(key: string): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n container.delete(key)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n // @deprecated Use 'key' in obj instead\n has(key: string): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key) !== undefined\n }\n\n // @deprecated Use Object.keys(obj) instead\n keys(): string[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.keys()\n }\n\n // @deprecated Use Object.values(obj) instead\n values(): any[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.values()\n }\n\n // @deprecated Not standard for objects\n get size(): number {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.size\n }\n}\n\n/**\n * Creates a StructRef wrapped in a Proxy for JavaScript-native object behavior.\n * Supports:\n * - Property access: obj.key\n * - Property assignment: obj.key = value\n * - Object.keys(obj)\n * - 'key' in obj\n * - delete obj.key\n * - toJSON()\n * - loro(obj) for CRDT access\n */\nexport function createStructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(\n params: TypedRefParams<StructContainerShape<NestedShapes>>,\n): StructRef<NestedShapes> {\n const impl = new StructRefImpl<NestedShapes>(params)\n\n const proxy = new Proxy(impl, {\n get(target, prop, receiver) {\n // Handle Symbol access (loro(), internal, etc.)\n if (prop === LORO_SYMBOL) {\n return target[INTERNAL_SYMBOL].getLoroNamespace()\n }\n\n // Handle INTERNAL_SYMBOL for internal methods\n if (prop === INTERNAL_SYMBOL) {\n return target[INTERNAL_SYMBOL]\n }\n\n // Handle toJSON - use serializeRefToJSON with the proxy (receiver) so property access goes through the proxy\n if (prop === \"toJSON\") {\n return () =>\n serializeRefToJSON(receiver, Object.keys(target.structShape.shapes))\n }\n\n // Handle shape access (internal - needed for assignPlainValueToTypedRef)\n if (prop === \"shape\") {\n return target.structShape\n }\n\n // Schema property access\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n const shape = target.structShape.shapes[prop]\n return target[INTERNAL_SYMBOL].getOrCreateRef(prop, shape)\n }\n\n return undefined\n },\n\n set(target, prop, value) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n target[INTERNAL_SYMBOL].setPropertyValue(prop, value)\n return true\n }\n return false\n },\n\n has(target, prop) {\n if (\n prop === LORO_SYMBOL ||\n prop === INTERNAL_SYMBOL ||\n prop === \"toJSON\" ||\n prop === \"shape\"\n ) {\n return true\n }\n if (typeof prop === \"string\") {\n return prop in target.structShape.shapes\n }\n return false\n },\n\n deleteProperty(target, prop) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n target[INTERNAL_SYMBOL].deleteProperty(prop)\n return true\n }\n return false\n },\n\n ownKeys(target) {\n // Return only schema keys, not internal methods\n return Object.keys(target.structShape.shapes)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n const shape = target.structShape.shapes[prop]\n return {\n configurable: true,\n enumerable: true,\n value: target[INTERNAL_SYMBOL].getOrCreateRef(prop, shape),\n }\n }\n return undefined\n },\n }) as unknown as StructRef<NestedShapes>\n\n return proxy\n}\n\n/**\n * Typed ref for struct containers (objects with fixed keys).\n * Uses LoroMap as the underlying container.\n *\n * Supports JavaScript-native object behavior:\n * - Property access: obj.key\n * - Property assignment: obj.key = value\n * - Object.keys(obj)\n * - 'key' in obj\n * - delete obj.key\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * settings: Shape.struct({\n * darkMode: Shape.plain.boolean().placeholder(false),\n * fontSize: Shape.plain.number().placeholder(14),\n * }),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Property access\n * doc.settings.darkMode = true;\n * console.log(doc.settings.darkMode); // true\n *\n * // Object.keys()\n * console.log(Object.keys(doc.settings)); // ['darkMode', 'fontSize']\n *\n * // 'key' in obj\n * console.log('darkMode' in doc.settings); // true\n *\n * // delete obj.key\n * delete doc.settings.darkMode;\n *\n * // CRDT access via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc.settings).setContainer('nested', loroMap);\n * loro(doc.settings).subscribe(callback);\n * ```\n */\nexport type StructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> = {\n [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"]\n} & {\n /**\n * Serializes the struct to a plain JSON-compatible object.\n */\n toJSON(): Infer<StructContainerShape<NestedShapes>>\n\n /**\n * Internal methods accessed via INTERNAL_SYMBOL.\n * @internal\n */\n [INTERNAL_SYMBOL]: RefInternalsBase\n\n /**\n * Access CRDT internals via the well-known symbol.\n * Used by the loro() function.\n */\n [LORO_SYMBOL]: LoroMapRef\n}\n\n// Re-export for backward compatibility\n// The old class-based StructRef is now replaced by the proxy-based version\nexport { StructRefImpl as StructRefClass }\n","import type { LoroDoc, LoroEventBatch, LoroText, Subscription } from \"loro-crdt\"\nimport type { LoroTextRef } from \"../loro.js\"\nimport type { TextContainerShape } from \"../shape.js\"\nimport { BaseRefInternals } from \"./base.js\"\n\n/**\n * Internal implementation for TextRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TextRefInternals extends BaseRefInternals<TextContainerShape> {\n private materialized = false\n\n /** Insert text at the given index */\n insert(index: number, content: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).insert(index, content)\n this.commitIfAuto()\n }\n\n /** Delete text at the given index */\n delete(index: number, len: number): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).delete(index, len)\n this.commitIfAuto()\n }\n\n /** Update the entire text content */\n update(text: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).update(text)\n this.commitIfAuto()\n }\n\n /** Mark a range of text with a key-value pair */\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).mark(range, key, value)\n this.commitIfAuto()\n }\n\n /** Remove a mark from a range of text */\n unmark(range: { start: number; end: number }, key: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).unmark(range, key)\n this.commitIfAuto()\n }\n\n /** Apply a delta to the text */\n applyDelta(delta: any[]): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).applyDelta(delta)\n this.commitIfAuto()\n }\n\n /** Get the text as a string */\n getStringValue(): string {\n const container = this.getContainer() as LoroText\n const containerValue = container.toString()\n if (containerValue !== \"\" || this.materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n const placeholder = this.getPlaceholder()\n if (placeholder !== undefined) {\n return placeholder as string\n }\n return containerValue\n }\n\n /** Get the text as a delta */\n toDelta(): any[] {\n return (this.getContainer() as LoroText).toDelta()\n }\n\n /** Get the length of the text */\n getLength(): number {\n return (this.getContainer() as LoroText).length\n }\n\n /** No plain values in text */\n absorbPlainValues(): void {\n // no plain values contained within\n }\n\n /** Create the loro namespace for text */\n protected override createLoroNamespace(): LoroTextRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroText {\n return self.getContainer() as LoroText\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroText).subscribe(callback)\n },\n }\n }\n}\n","import type { TextContainerShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { TextRefInternals } from \"./text-ref-internals.js\"\n\n/**\n * Text typed ref - thin facade that delegates to TextRefInternals.\n */\nexport class TextRef extends TypedRef<TextContainerShape> {\n [INTERNAL_SYMBOL]: TextRefInternals\n\n constructor(params: TypedRefParams<TextContainerShape>) {\n super()\n this[INTERNAL_SYMBOL] = new TextRefInternals(params)\n }\n\n /** Insert text at the given index */\n insert(index: number, content: string): void {\n this[INTERNAL_SYMBOL].insert(index, content)\n }\n\n /** Delete text at the given index */\n delete(index: number, len: number): void {\n this[INTERNAL_SYMBOL].delete(index, len)\n }\n\n /** Update the entire text content */\n update(text: string): void {\n this[INTERNAL_SYMBOL].update(text)\n }\n\n /** Mark a range of text with a key-value pair */\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this[INTERNAL_SYMBOL].mark(range, key, value)\n }\n\n /** Remove a mark from a range of text */\n unmark(range: { start: number; end: number }, key: string): void {\n this[INTERNAL_SYMBOL].unmark(range, key)\n }\n\n /** Apply a delta to the text */\n applyDelta(delta: any[]): void {\n this[INTERNAL_SYMBOL].applyDelta(delta)\n }\n\n /** Get the text as a string */\n toString(): string {\n return this[INTERNAL_SYMBOL].getStringValue()\n }\n\n valueOf(): string {\n return this.toString()\n }\n\n toJSON(): string {\n return this.toString()\n }\n\n [Symbol.toPrimitive](_hint: string): string {\n return this.toString()\n }\n\n /** Get the text as a delta */\n toDelta(): any[] {\n return this[INTERNAL_SYMBOL].toDelta()\n }\n\n /** Get the length of the text */\n get length(): number {\n return this[INTERNAL_SYMBOL].getLength()\n }\n}\n","import type {\n LoroDoc,\n LoroEventBatch,\n LoroTreeNode,\n Subscription,\n} from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroTreeNodeRef } from \"../loro.js\"\nimport type { StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport {\n INTERNAL_SYMBOL,\n type RefInternalsBase,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createStructRef, type StructRef } from \"./struct-ref.js\"\nimport type { TreeNodeRef, TreeNodeRefParams } from \"./tree-node-ref.js\"\n\n// Forward declaration to avoid circular import\n// TreeRef will be passed in via constructor params\nexport interface TreeRefLike<DataShape extends StructContainerShape> {\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape>\n}\n\n/**\n * Internal implementation for TreeNodeRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TreeNodeRefInternals<DataShape extends StructContainerShape>\n implements RefInternalsBase\n{\n private dataRef: StructRef<DataShape[\"shapes\"]> | undefined\n private loroNamespace: LoroTreeNodeRef | undefined\n\n constructor(private readonly params: TreeNodeRefParams<DataShape>) {}\n\n /** Get the underlying LoroTreeNode */\n getNode(): LoroTreeNode {\n return this.params.node\n }\n\n /** Get the data shape for this node */\n getDataShape(): DataShape {\n return this.params.dataShape\n }\n\n /** Get the parent TreeRef */\n getTreeRef(): TreeRefLike<DataShape> {\n return this.params.treeRef\n }\n\n /** Check if autoCommit is enabled */\n getAutoCommit(): boolean {\n return this.params.autoCommit ?? false\n }\n\n /** Check if in batched mutation mode */\n getBatchedMutation(): boolean {\n return this.params.batchedMutation ?? false\n }\n\n /** Get the LoroDoc */\n getDoc(): LoroDoc {\n return this.params.getDoc()\n }\n\n /** Commit changes if autoCommit is enabled */\n commitIfAuto(): void {\n if (this.params.autoCommit) {\n this.params.getDoc().commit()\n }\n }\n\n /** Get or create the data StructRef */\n getOrCreateDataRef(): StructRef<DataShape[\"shapes\"]> {\n if (!this.dataRef) {\n const node = this.getNode()\n const dataShape = this.getDataShape()\n\n // Get the node's data container (LoroMap)\n const dataContainer = (node as any).data\n\n if (!dataContainer) {\n throw new Error(`Node ${node.id} has no data container`)\n }\n\n // Create placeholder from the data shape\n const placeholder = deriveShapePlaceholder(dataShape) as Infer<DataShape>\n\n const refParams: TypedRefParams<\n StructContainerShape<DataShape[\"shapes\"]>\n > = {\n shape: {\n _type: \"struct\" as const,\n shapes: dataShape.shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n },\n placeholder: placeholder as any,\n getContainer: () => dataContainer,\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: this.params.getDoc,\n }\n\n this.dataRef = createStructRef(refParams)\n }\n return this.dataRef\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n if (this.dataRef) {\n this.dataRef[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n\n /** Force materialization of the container and its nested containers */\n materialize(): void {\n // Ensure data ref is created and materialized\n const dataRef = this.getOrCreateDataRef()\n dataRef[INTERNAL_SYMBOL].materialize()\n }\n\n /** Get the loro namespace (cached) */\n getLoroNamespace(): LoroTreeNodeRef {\n if (!this.loroNamespace) {\n this.loroNamespace = this.createLoroNamespace()\n }\n return this.loroNamespace\n }\n\n /** Create the loro namespace for tree node */\n protected createLoroNamespace(): LoroTreeNodeRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroTreeNode {\n return self.getNode()\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n // LoroTreeNode doesn't have subscribe, but we can subscribe to the tree\n // However, LoroRefBase expects subscribe.\n // For now, we can throw or return a dummy subscription if LoroTreeNode doesn't support it.\n // But wait, LoroTreeNode is just a handle.\n // Let's check if LoroTreeNode has subscribe.\n // If not, we might need to subscribe to the tree and filter?\n // Or maybe we just cast it if it exists at runtime.\n return (self.getNode() as any).subscribe?.(callback) || (() => {})\n },\n }\n }\n}\n","import type { LoroDoc, LoroTreeNode, TreeID } from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroTreeNodeRef } from \"../loro.js\"\nimport type { StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { INTERNAL_SYMBOL } from \"./base.js\"\nimport type { StructRef } from \"./struct-ref.js\"\nimport {\n TreeNodeRefInternals,\n type TreeRefLike,\n} from \"./tree-node-ref-internals.js\"\n\nexport interface TreeNodeRefParams<DataShape extends StructContainerShape> {\n node: LoroTreeNode\n dataShape: DataShape\n treeRef: TreeRefLike<DataShape>\n autoCommit?: boolean\n batchedMutation?: boolean\n getDoc: () => LoroDoc\n}\n\n/**\n * Typed ref for a single tree node - thin facade that delegates to TreeNodeRefInternals.\n * Provides type-safe access to node metadata via the `.data` property.\n *\n * **Note:** TreeNodeRef is not a subclass of TypedRef, but it implements\n * `[INTERNAL_SYMBOL]: RefInternalsBase` for consistency with other refs.\n * This allows internal code to call `absorbPlainValues()` uniformly\n * across all ref types during the `change()` commit phase.\n *\n * @example\n * ```typescript\n * const node = tree.createNode({ name: \"idle\", facts: {} })\n * node.data.name = \"active\" // Typed access\n * const child = node.createNode({ name: \"running\", facts: {} })\n * ```\n */\nexport class TreeNodeRef<DataShape extends StructContainerShape> {\n [INTERNAL_SYMBOL]: TreeNodeRefInternals<DataShape>\n\n constructor(params: TreeNodeRefParams<DataShape>) {\n this[INTERNAL_SYMBOL] = new TreeNodeRefInternals(params)\n }\n\n /**\n * Access the loro() namespace via the well-known symbol.\n */\n get [LORO_SYMBOL](): LoroTreeNodeRef {\n return this[INTERNAL_SYMBOL].getLoroNamespace()\n }\n\n /**\n * The unique TreeID of this node.\n */\n get id(): TreeID {\n return this[INTERNAL_SYMBOL].getNode().id\n }\n\n /**\n * Typed access to the node's metadata.\n * This is a StructRef wrapping the node's LoroMap data container.\n */\n get data(): StructRef<DataShape[\"shapes\"]> & {\n [K in keyof DataShape[\"shapes\"]]: DataShape[\"shapes\"][K][\"_mutable\"]\n } {\n return this[INTERNAL_SYMBOL].getOrCreateDataRef() as StructRef<\n DataShape[\"shapes\"]\n > & {\n [K in keyof DataShape[\"shapes\"]]: DataShape[\"shapes\"][K][\"_mutable\"]\n }\n }\n\n /**\n * Create a child node under this node.\n *\n * @param initialData - Optional partial data to initialize the child with\n * @param index - Optional position among siblings\n * @returns The created child TreeNodeRef\n */\n createNode(\n initialData?: Partial<Infer<DataShape>>,\n index?: number,\n ): TreeNodeRef<DataShape> {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n // Create child node - Loro's createNode on a tree node creates a child\n const loroNode = (node as any).createNode(index)\n const nodeRef = treeRef.getOrCreateNodeRef(loroNode)\n\n // Initialize data if provided\n if (initialData) {\n for (const [key, value] of Object.entries(initialData)) {\n ;(nodeRef.data as any)[key] = value\n }\n }\n\n this[INTERNAL_SYMBOL].commitIfAuto()\n return nodeRef\n }\n\n /**\n * Get the parent node, if any.\n */\n parent(): TreeNodeRef<DataShape> | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n const parentNode = (node as any).parent?.()\n if (!parentNode) return undefined\n return treeRef.getOrCreateNodeRef(parentNode)\n }\n\n /**\n * Get all child nodes in order.\n */\n children(): TreeNodeRef<DataShape>[] {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n const childNodes = (node as any).children?.() || []\n return childNodes.map((n: LoroTreeNode) => treeRef.getOrCreateNodeRef(n))\n }\n\n /**\n * Move this node to a new parent.\n *\n * @param newParent - The new parent node (undefined for root)\n * @param index - Optional position among siblings\n */\n move(newParent?: TreeNodeRef<DataShape>, index?: number): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n\n // node.move takes a LoroTreeNode or undefined, not an ID\n const parentNode = newParent\n ? newParent[INTERNAL_SYMBOL].getNode()\n : undefined\n ;(node as any).move?.(parentNode, index)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Move this node to be after the given sibling.\n */\n moveAfter(sibling: TreeNodeRef<DataShape>): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n const siblingNode = sibling[INTERNAL_SYMBOL].getNode()\n\n node.moveAfter(siblingNode)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Move this node to be before the given sibling.\n */\n moveBefore(sibling: TreeNodeRef<DataShape>): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n const siblingNode = sibling[INTERNAL_SYMBOL].getNode()\n\n node.moveBefore(siblingNode)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Get the index of this node among its siblings.\n */\n index(): number | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.index()\n }\n\n /**\n * Get the fractional index string for ordering.\n */\n fractionalIndex(): string | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.fractionalIndex()\n }\n\n /**\n * Check if this node has been deleted.\n */\n isDeleted(): boolean {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.isDeleted()\n }\n\n /**\n * Serialize this node and its descendants to JSON.\n */\n toJSON(): {\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n children: any[]\n } {\n const children = this.children()\n return {\n id: this.id,\n parent: this.parent()?.id ?? null,\n index: this.index() ?? 0,\n fractionalIndex: this.fractionalIndex() ?? \"\",\n data: this.data.toJSON() as Infer<DataShape>,\n children: children.map(child => child.toJSON()),\n }\n }\n}\n","import type {\n LoroDoc,\n LoroEventBatch,\n LoroTree,\n LoroTreeNode,\n Subscription,\n TreeID,\n} from \"loro-crdt\"\nimport type { LoroTreeRef } from \"../loro.js\"\nimport type { StructContainerShape, TreeContainerShape } from \"../shape.js\"\nimport { BaseRefInternals, INTERNAL_SYMBOL } from \"./base.js\"\nimport { TreeNodeRef } from \"./tree-node-ref.js\"\nimport type { TreeRef } from \"./tree-ref.js\"\n\n/**\n * Internal implementation for TreeRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TreeRefInternals<\n DataShape extends StructContainerShape,\n> extends BaseRefInternals<TreeContainerShape<DataShape>> {\n private nodeCache = new Map<TreeID, TreeNodeRef<DataShape>>()\n private treeRef: TreeRef<DataShape> | null = null\n\n /** Set the parent TreeRef (needed for creating node refs) */\n setTreeRef(treeRef: TreeRef<DataShape>): void {\n this.treeRef = treeRef\n }\n\n /** Get the data shape for tree nodes */\n getDataShape(): DataShape {\n const shape = this.getShape() as TreeContainerShape<DataShape>\n return shape.shape\n }\n\n /** Get or create a node ref for a LoroTreeNode */\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape> {\n const id = node.id\n\n if (!this.treeRef) {\n throw new Error(\"treeRef required\")\n }\n\n let nodeRef = this.nodeCache.get(id)\n if (!nodeRef) {\n nodeRef = new TreeNodeRef({\n node,\n dataShape: this.getDataShape(),\n treeRef: this.treeRef,\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n })\n this.nodeCache.set(id, nodeRef)\n }\n\n return nodeRef\n }\n\n /** Get a node by its ID */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined {\n // Check cache first\n const cached = this.nodeCache.get(id)\n if (cached) return cached\n\n const container = this.getContainer() as LoroTree\n\n // Check if node exists in tree\n if (!container.has(id)) return undefined\n\n // Find the node in the tree's nodes\n const nodes = container.nodes()\n const node = nodes.find(n => n.id === id)\n if (!node) return undefined\n\n return this.getOrCreateNodeRef(node)\n }\n\n /** Delete a node from the tree */\n delete(target: TreeID | TreeNodeRef<DataShape>): void {\n const id = typeof target === \"string\" ? target : target.id\n const container = this.getContainer() as LoroTree\n container.delete(id)\n // Remove from cache\n this.nodeCache.delete(id)\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n for (const nodeRef of this.nodeCache.values()) {\n nodeRef[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n\n /** Create the loro namespace for tree */\n protected override createLoroNamespace(): LoroTreeRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroTree {\n return self.getContainer() as LoroTree\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroTree).subscribe(callback)\n },\n }\n }\n}\n","import type { LoroTree, LoroTreeNode, TreeID } from \"loro-crdt\"\nimport type {\n StructContainerShape,\n TreeContainerShape,\n TreeNodeJSON,\n} from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport type { TreeNodeRef } from \"./tree-node-ref.js\"\nimport { TreeRefInternals } from \"./tree-ref-internals.js\"\n\n/**\n * Typed ref for tree (forest) containers - thin facade that delegates to TreeRefInternals.\n * Wraps LoroTree with type-safe access to node metadata.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * doc.change(draft => {\n * const root = draft.states.createNode({ name: \"idle\", facts: {} })\n * const child = root.createNode({ name: \"running\", facts: {} })\n * child.data.name = \"active\"\n * })\n * ```\n */\nexport class TreeRef<DataShape extends StructContainerShape> extends TypedRef<\n TreeContainerShape<DataShape>\n> {\n [INTERNAL_SYMBOL]: TreeRefInternals<DataShape>\n\n constructor(params: TypedRefParams<TreeContainerShape<DataShape>>) {\n super()\n this[INTERNAL_SYMBOL] = new TreeRefInternals(params)\n this[INTERNAL_SYMBOL].setTreeRef(this)\n }\n\n /**\n * Get the data shape for tree nodes.\n */\n private get dataShape(): DataShape {\n return this[INTERNAL_SYMBOL].getDataShape()\n }\n\n /**\n * Get or create a node ref for a LoroTreeNode.\n */\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape> {\n return this[INTERNAL_SYMBOL].getOrCreateNodeRef(node)\n }\n\n /**\n * Get a node by its ID.\n */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined {\n return this[INTERNAL_SYMBOL].getNodeByID(id)\n }\n\n /**\n * Delete a node from the tree.\n */\n delete(target: TreeID | TreeNodeRef<DataShape>): void {\n this[INTERNAL_SYMBOL].delete(target)\n }\n\n /**\n * Serialize the tree to a nested JSON structure.\n * Each node includes its data and children recursively.\n */\n toJSON(): Infer<TreeContainerShape<DataShape>> {\n // Use Loro's native toJSON which returns nested structure\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const nativeJson = container.toJSON() as any[]\n return this.transformNativeJson(nativeJson) as Infer<\n TreeContainerShape<DataShape>\n >\n }\n\n /**\n * Create a new root node with optional initial data.\n *\n * @param initialData - Optional partial data to initialize the node with\n * @returns The created TreeNodeRef\n */\n createNode(initialData?: Partial<Infer<DataShape>>): TreeNodeRef<DataShape> {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const loroNode = container.createNode()\n const nodeRef = this.getOrCreateNodeRef(loroNode)\n\n // Initialize data if provided\n if (initialData) {\n for (const [key, value] of Object.entries(initialData)) {\n ;(nodeRef.data as any)[key] = value\n }\n }\n\n this[INTERNAL_SYMBOL].commitIfAuto()\n return nodeRef\n }\n\n /**\n * Get all root nodes (nodes without parents).\n * Returns nodes in their fractional index order.\n */\n roots(): TreeNodeRef<DataShape>[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n return container.roots().map(node => this.getOrCreateNodeRef(node))\n }\n\n /**\n * Get all nodes in the tree (unordered).\n * By default, excludes deleted nodes (tombstones).\n *\n * @param options.includeDeleted - If true, includes deleted nodes. Default: false.\n * @returns Array of TreeNodeRef for matching nodes\n */\n nodes(options?: { includeDeleted?: boolean }): TreeNodeRef<DataShape>[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const allNodes = container.nodes()\n const filtered = options?.includeDeleted\n ? allNodes\n : allNodes.filter(node => !node.isDeleted())\n return filtered.map(node => this.getOrCreateNodeRef(node))\n }\n\n /**\n * Check if a node with the given ID exists in the tree.\n */\n has(id: TreeID): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n return container.has(id)\n }\n\n /**\n * Enable fractional index generation for ordering.\n *\n * @param jitter - Optional jitter value to avoid conflicts (0 = no jitter)\n */\n enableFractionalIndex(jitter = 0): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n container.enableFractionalIndex(jitter)\n }\n\n /**\n * Transform Loro's native JSON format to our typed format.\n */\n private transformNativeJson(nodes: any[]): TreeNodeJSON<DataShape>[] {\n return nodes.map(node => ({\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index as number,\n fractionalIndex: node.fractional_index as string,\n data: node.meta as Infer<DataShape>,\n children: this.transformNativeJson(node.children || []),\n }))\n }\n\n /**\n * Get a flat array representation of all nodes.\n * Flattens the nested tree structure into a single array.\n */\n toArray(): Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n }> {\n const result: Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n }> = []\n\n // Flatten the nested structure\n const flattenNodes = (nodes: any[]) => {\n for (const node of nodes) {\n result.push({\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index as number,\n fractionalIndex: node.fractional_index as string,\n data: node.meta as Infer<DataShape>,\n })\n if (node.children && node.children.length > 0) {\n flattenNodes(node.children)\n }\n }\n }\n\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const nativeJson = container.toJSON() as any[]\n flattenNodes(nativeJson)\n return result\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { ContainerShape, DocShape } from \"../shape.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n type TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createContainerTypedRef } from \"./utils.js\"\n\nconst containerGetter = {\n counter: \"getCounter\",\n list: \"getList\",\n movableList: \"getMovableList\",\n record: \"getMap\",\n struct: \"getMap\", // Structs use LoroMap as their underlying container\n text: \"getText\",\n tree: \"getTree\",\n} as const satisfies Record<string, keyof LoroDoc>\n\ntype ContainerGetterKey = keyof typeof containerGetter\n\n/**\n * Internal implementation for DocRef.\n * Contains all logic, state, and implementation details.\n */\nexport class DocRefInternals<\n Shape extends DocShape,\n> extends BaseRefInternals<Shape> {\n private propertyCache = new Map<string, TypedRef<ContainerShape>>()\n private doc: LoroDoc\n private requiredPlaceholder: Infer<Shape>\n\n constructor(\n params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n batchedMutation?: boolean\n },\n ) {\n super({\n ...params,\n getContainer: () => {\n throw new Error(\"can't get container on DocRef\")\n },\n getDoc: () => params.doc,\n } as TypedRefParams<Shape>)\n\n this.doc = params.doc\n this.requiredPlaceholder = params.placeholder as Infer<Shape>\n }\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n // Handle \"any\" shape type - it's an escape hatch that doesn't have a specific getter\n if (shape._type === \"any\") {\n throw new Error(\n `Cannot get typed ref params for \"any\" shape type. ` +\n `The \"any\" shape is an escape hatch for untyped containers and should be accessed directly via loroDoc.`,\n )\n }\n\n const getterName = containerGetter[shape._type as ContainerGetterKey]\n const getter = this.doc[getterName].bind(this.doc)\n\n return {\n shape,\n placeholder: this.requiredPlaceholder[key],\n getContainer: () => getter(key),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.doc,\n }\n }\n\n /** Get or create a typed ref for a key */\n getOrCreateTypedRef(\n key: string,\n shape: ContainerShape,\n ): TypedRef<ContainerShape> | number | string {\n let ref = this.propertyCache.get(key)\n\n if (!ref) {\n ref = createContainerTypedRef(this.getChildTypedRefParams(key, shape))\n this.propertyCache.set(key, ref)\n }\n\n return ref\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n // By iterating over the propertyCache, we achieve a small optimization\n // by only absorbing values that have been 'touched' in some way\n for (const [, ref] of this.propertyCache.entries()) {\n ref[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { DocShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { DocRefInternals } from \"./doc-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Doc Ref class - thin facade that delegates to DocRefInternals.\n * The actual object passed to the change `mutation` function.\n */\nexport class DocRef<Shape extends DocShape> extends TypedRef<Shape> {\n [INTERNAL_SYMBOL]: DocRefInternals<Shape>\n\n constructor(\n params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n batchedMutation?: boolean\n },\n ) {\n super()\n if (!params.placeholder) throw new Error(\"placeholder required\")\n this[INTERNAL_SYMBOL] = new DocRefInternals(params)\n this.createLazyProperties()\n }\n\n private createLazyProperties(): void {\n const shape = this[INTERNAL_SYMBOL].getShape() as DocShape\n for (const key in shape.shapes) {\n const containerShape = shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () =>\n this[INTERNAL_SYMBOL].getOrCreateTypedRef(key, containerShape),\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<Shape> {\n const shape = this[INTERNAL_SYMBOL].getShape() as DocShape\n return serializeRefToJSON(\n this as any,\n Object.keys(shape.shapes),\n ) as Infer<Shape>\n }\n}\n","import type {\n ArrayValueShape,\n ContainerOrValueShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StringValueShape,\n StructContainerShape,\n StructValueShape,\n UnionValueShape,\n ValueShape,\n} from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * Validates a value against a ContainerShape or ValueShape schema\n */\nexport function validateValue(\n value: unknown,\n schema: ContainerOrValueShape,\n path: string = \"\",\n): unknown {\n if (!schema || typeof schema !== \"object\" || !(\"_type\" in schema)) {\n throw new Error(`Invalid schema at path ${path}: missing _type`)\n }\n\n const currentPath = path || \"root\"\n\n // Handle AnyContainerShape - no validation, accept anything\n if (schema._type === \"any\") {\n return value\n }\n\n // Handle ContainerShape types\n if (schema._type === \"text\") {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"counter\") {\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"list\" || schema._type === \"movableList\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const listSchema = schema as ListContainerShape | MovableListContainerShape\n return value.map((item, index) =>\n validateValue(item, listSchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n if (schema._type === \"struct\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = schema as StructContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shapes)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"record\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = schema as RecordContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(nestedValue, recordSchema.shape, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"tree\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array for tree at path ${currentPath}, got ${typeof value}`,\n )\n }\n // Trees can contain any structure, so we just validate it's an array\n return value\n }\n\n // Handle ValueShape types\n if (schema._type === \"value\") {\n const valueSchema = schema as ValueShape\n\n switch (valueSchema.valueType) {\n // AnyValueShape - no validation, accept anything\n case \"any\":\n return value\n\n case \"string\": {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n const stringSchema = valueSchema as StringValueShape\n if (stringSchema.options && !stringSchema.options.includes(value)) {\n throw new Error(\n `Expected one of [${stringSchema.options.join(\", \")}] at path ${currentPath}, got \"${value}\"`,\n )\n }\n return value\n }\n\n case \"number\":\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new Error(\n `Expected boolean at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"null\":\n if (value !== null) {\n throw new Error(\n `Expected null at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"undefined\":\n if (value !== undefined) {\n throw new Error(\n `Expected undefined at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"uint8array\":\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `Expected Uint8Array at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"struct\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = valueSchema as StructValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shape)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n case \"record\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = valueSchema as RecordValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(\n nestedValue,\n recordSchema.shape,\n nestedPath,\n )\n }\n return result\n }\n\n case \"array\": {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const arraySchema = valueSchema as ArrayValueShape\n return value.map((item, index) =>\n validateValue(item, arraySchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n case \"union\": {\n const unionSchema = valueSchema as UnionValueShape\n let lastError: Error | null = null\n\n // Try to validate against each shape in the union\n for (const shape of unionSchema.shapes) {\n try {\n return validateValue(value, shape, currentPath)\n } catch (error) {\n lastError = error as Error\n }\n }\n\n throw new Error(\n `Value at path ${currentPath} does not match any union type: ${lastError?.message}`,\n )\n }\n\n case \"discriminatedUnion\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n\n const unionSchema = valueSchema as DiscriminatedUnionValueShape\n const discriminantKey = unionSchema.discriminantKey\n const discriminantValue = (value as Record<string, unknown>)[\n discriminantKey\n ]\n\n if (typeof discriminantValue !== \"string\") {\n throw new Error(\n `Expected string for discriminant key \"${discriminantKey}\" at path ${currentPath}, got ${typeof discriminantValue}`,\n )\n }\n\n const variantSchema = unionSchema.variants[discriminantValue]\n\n if (!variantSchema) {\n throw new Error(\n `Invalid discriminant value \"${discriminantValue}\" at path ${currentPath}. Expected one of: ${Object.keys(\n unionSchema.variants,\n ).join(\", \")}`,\n )\n }\n\n return validateValue(value, variantSchema, currentPath)\n }\n\n default:\n throw new Error(`Unknown value type: ${(valueSchema as any).valueType}`)\n }\n }\n\n throw new Error(`Unknown schema type: ${(schema as any)._type}`)\n}\n\n/**\n * Validates placeholder against schema structure without using Zod\n * Combines the functionality of createPlaceholderValidator and createValueValidator\n */\nexport function validatePlaceholder<T extends DocShape>(\n placeholder: unknown,\n schema: T,\n): Infer<T> {\n if (\n !placeholder ||\n typeof placeholder !== \"object\" ||\n Array.isArray(placeholder)\n ) {\n throw new Error(\"Placeholder must be an object\")\n }\n\n const result: Record<string, unknown> = {}\n\n // Validate each property in the document schema\n for (const [key, schemaValue] of Object.entries(schema.shapes)) {\n const value = (placeholder as Record<string, unknown>)[key]\n result[key] = validateValue(value, schemaValue, key)\n }\n\n return result as Infer<T>\n}\n","// ============================================================================\n// Path Builder Factory\n// ============================================================================\n//\n// Runtime implementation of the path builder that creates PathSelector objects\n// with proper segments for JSONPath compilation.\n\nimport type { PathBuilder, PathSegment, PathSelector } from \"./path-selector.js\"\nimport type { ContainerOrValueShape, DocShape } from \"./shape.js\"\n\nfunction createPathSelector<T>(segments: PathSegment[]): PathSelector<T> {\n return {\n __resultType: undefined as unknown as T,\n __segments: segments,\n }\n}\n\nfunction createPathNode(\n shape: ContainerOrValueShape,\n segments: PathSegment[],\n): unknown {\n const selector = createPathSelector(segments)\n\n // Terminal shapes (text, counter, value)\n if (shape._type === \"text\" || shape._type === \"counter\") {\n return selector\n }\n if (shape._type === \"value\") {\n return selector\n }\n\n // List/MovableList\n if (shape._type === \"list\" || shape._type === \"movableList\") {\n return Object.assign(selector, {\n get $each() {\n return createPathNode(shape.shape, [...segments, { type: \"each\" }])\n },\n $at(index: number) {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index },\n ])\n },\n get $first() {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index: 0 },\n ])\n },\n get $last() {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index: -1 },\n ])\n },\n })\n }\n\n // Struct (fixed keys)\n if (shape._type === \"struct\") {\n const props: Record<string, unknown> = {}\n for (const key in shape.shapes) {\n Object.defineProperty(props, key, {\n get() {\n return createPathNode(shape.shapes[key], [\n ...segments,\n { type: \"property\", key },\n ])\n },\n enumerable: true,\n })\n }\n return Object.assign(selector, props)\n }\n\n // Record (dynamic keys)\n if (shape._type === \"record\") {\n return Object.assign(selector, {\n get $each() {\n return createPathNode(shape.shape, [...segments, { type: \"each\" }])\n },\n $key(key: string) {\n return createPathNode(shape.shape, [...segments, { type: \"key\", key }])\n },\n })\n }\n\n return selector\n}\n\n/**\n * Creates a path builder for a given document shape.\n *\n * The path builder provides a type-safe DSL for selecting paths within\n * a document. The resulting PathSelector can be compiled to a JSONPath\n * string for use with subscribeJsonpath.\n *\n * @example\n * ```typescript\n * const docShape = Shape.doc({\n * books: Shape.list(Shape.struct({\n * title: Shape.text(),\n * price: Shape.plain.number(),\n * })),\n * })\n *\n * const builder = createPathBuilder(docShape)\n * const selector = builder.books.$each.title\n * // selector.__segments = [\n * // { type: \"property\", key: \"books\" },\n * // { type: \"each\" },\n * // { type: \"property\", key: \"title\" }\n * // ]\n * ```\n */\nexport function createPathBuilder<D extends DocShape>(\n docShape: D,\n): PathBuilder<D> {\n const builder: Record<string, unknown> = {}\n\n for (const key in docShape.shapes) {\n Object.defineProperty(builder, key, {\n get() {\n return createPathNode(docShape.shapes[key], [{ type: \"property\", key }])\n },\n enumerable: true,\n })\n }\n\n return builder as PathBuilder<D>\n}\n","// ============================================================================\n// JSONPath Compiler\n// ============================================================================\n//\n// Compiles PathSelector segments to JSONPath strings for use with\n// subscribeJsonpath.\n\nimport type { PathSegment } from \"./path-selector.js\"\n\n/**\n * Compiles path segments to a JSONPath string.\n *\n * @example\n * ```typescript\n * const segments = [\n * { type: \"property\", key: \"books\" },\n * { type: \"each\" },\n * { type: \"property\", key: \"title\" }\n * ]\n * compileToJsonPath(segments) // => '$.books[*].title'\n * ```\n */\nexport function compileToJsonPath(segments: PathSegment[]): string {\n let path = \"$\"\n\n for (const segment of segments) {\n switch (segment.type) {\n case \"property\":\n // Use dot notation for simple identifiers, bracket notation for safety\n if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(segment.key)) {\n path += `.${segment.key}`\n } else {\n path += `[\"${escapeJsonPathKey(segment.key)}\"]`\n }\n break\n case \"each\":\n path += \"[*]\"\n break\n case \"index\":\n path += `[${segment.index}]`\n break\n case \"key\":\n path += `[\"${escapeJsonPathKey(segment.key)}\"]`\n break\n }\n }\n\n return path\n}\n\n/**\n * Escapes special characters in a JSONPath key.\n */\nfunction escapeJsonPathKey(key: string): string {\n return key.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')\n}\n\n/**\n * Check if the path contains any wildcard segments.\n * Paths with wildcards need deep equality checking for change detection.\n */\nexport function hasWildcard(segments: PathSegment[]): boolean {\n return segments.some(s => s.type === \"each\")\n}\n","// ============================================================================\n// Path Evaluator\n// ============================================================================\n//\n// Evaluates a path selector against a TypedDoc to get the current value.\n// This is used for:\n// 1. Establishing the initial previousValue baseline\n// 2. Getting the current value when subscribeJsonpath fires\n// 3. Deep equality comparison to filter false positives\n\nimport type { PathSegment, PathSelector } from \"./path-selector.js\"\nimport type { DocShape } from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\n\n/**\n * Evaluate a path selector against a TypedDoc to get the current value.\n * Returns the value(s) at the path, properly typed.\n *\n * @example\n * ```typescript\n * const selector = builder.books.$each.title\n * const titles = evaluatePath(doc, selector)\n * // titles: string[]\n * ```\n */\nexport function evaluatePath<D extends DocShape, T>(\n doc: TypedDoc<D>,\n selector: PathSelector<T>,\n): T {\n const json = doc.toJSON()\n return evaluatePathOnValue(json, selector.__segments) as T\n}\n\n/**\n * Evaluate path segments against a plain JavaScript value.\n * This is the core recursive evaluation logic.\n */\nexport function evaluatePathOnValue(\n value: unknown,\n segments: PathSegment[],\n): unknown {\n if (segments.length === 0) {\n return value\n }\n\n const [segment, ...rest] = segments\n\n switch (segment.type) {\n case \"property\":\n case \"key\":\n if (value == null) return undefined\n if (typeof value !== \"object\") return undefined\n return evaluatePathOnValue(\n (value as Record<string, unknown>)[segment.key],\n rest,\n )\n\n case \"index\": {\n if (!Array.isArray(value)) return undefined\n // Handle negative indices: -1 = last, -2 = second-to-last, etc.\n const index =\n segment.index < 0 ? value.length + segment.index : segment.index\n if (index < 0 || index >= value.length) return undefined\n return evaluatePathOnValue(value[index], rest)\n }\n\n case \"each\":\n if (Array.isArray(value)) {\n return value.map(item => evaluatePathOnValue(item, rest))\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).map(item => evaluatePathOnValue(item, rest))\n }\n return []\n }\n}\n","/**\n * Creates a proxy around a placeholder value (plain object/array) that mimics\n * the behavior of TypedRef, specifically adding a .toJSON() method.\n *\n * This ensures consistent UX where users can call .toJSON() on document state\n * regardless of whether it's loading (placeholder) or loaded (live ref).\n */\nexport function createPlaceholderProxy<T extends object>(target: T): T {\n // Cache for wrapped properties to ensure referential stability\n const cache = new Map<string | symbol, any>()\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n // Intercept .toJSON()\n if (prop === \"toJSON\") {\n return () => target\n }\n\n // Check cache first\n if (cache.has(prop)) {\n return cache.get(prop)\n }\n\n // Get value from target\n const value = Reflect.get(target, prop, receiver)\n\n // Recursively wrap objects/arrays\n if (value && typeof value === \"object\") {\n const wrapped = createPlaceholderProxy(value)\n cache.set(prop, wrapped)\n return wrapped\n }\n\n return value\n },\n })\n}\n","import type {\n Container,\n ContainerID,\n CounterDiff,\n Diff,\n ListDiff,\n LoroCounter,\n LoroDoc,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n MapDiff,\n TextDiff,\n TreeDiff,\n TreeDiffItem,\n Value,\n} from \"loro-crdt\"\n\n/**\n * Replay a diff as local operations on a document.\n *\n * Unlike doc.import() which creates import events, this creates LOCAL events\n * that are captured by subscribeLocalUpdates() and UndoManager.\n *\n * @param doc - The target document to apply changes to\n * @param diff - The diff from doc.diff(from, to, false)\n */\nexport function replayDiff(doc: LoroDoc, diff: [ContainerID, Diff][]): void {\n // Map from source container IDs to target containers\n // This is needed because when we create new containers, they get different IDs\n const containerMap = new Map<ContainerID, Container>()\n\n for (const [containerId, containerDiff] of diff) {\n // First, try to get the container from our map (for newly created containers)\n let container = containerMap.get(containerId)\n\n // If not in map, try to get it from the doc (for existing containers)\n if (!container) {\n container = doc.getContainerById(containerId)\n }\n\n if (!container) {\n // Container doesn't exist yet - this can happen for newly created containers\n // that haven't been mapped yet. Skip for now, it will be created when\n // processing the parent container's diff.\n continue\n }\n\n switch (containerDiff.type) {\n case \"text\":\n replayTextDiff(container as LoroText, containerDiff)\n break\n case \"list\":\n replayListDiff(\n container as LoroList | LoroMovableList,\n containerDiff,\n containerMap,\n )\n break\n case \"map\":\n replayMapDiff(container as LoroMap, containerDiff, containerMap)\n break\n case \"tree\":\n replayTreeDiff(container as LoroTree, containerDiff)\n break\n case \"counter\":\n replayCounterDiff(container as LoroCounter, containerDiff)\n break\n }\n }\n}\n\n/**\n * Replay text diff operations\n */\nfunction replayTextDiff(text: LoroText, diff: TextDiff): void {\n // LoroText has applyDelta which handles the delta format directly\n text.applyDelta(diff.diff)\n}\n\n/**\n * Replay list diff operations\n */\nfunction replayListDiff(\n list: LoroList | LoroMovableList,\n diff: ListDiff,\n containerMap: Map<ContainerID, Container>,\n): void {\n let index = 0\n\n for (const delta of diff.diff) {\n if (delta.retain !== undefined) {\n // Retain: skip over existing elements\n index += delta.retain\n } else if (delta.delete !== undefined) {\n // Delete: remove elements at current position\n list.delete(index, delta.delete)\n // Don't advance index - next operation is at same position\n } else if (delta.insert !== undefined) {\n // Insert: add elements at current position\n const values = delta.insert\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (isContainer(value)) {\n // For containers, we need to insert a new container of the same type\n // The container's contents will be handled by its own diff entry\n const newContainer = createContainerOfSameType(value)\n const insertedContainer = (list as LoroList).insertContainer(\n index + i,\n newContainer,\n )\n // Map the source container ID to the newly created container\n containerMap.set(value.id, insertedContainer)\n } else {\n ;(list as LoroList).insert(\n index + i,\n value as Exclude<Value, Container>,\n )\n }\n }\n index += values.length\n }\n }\n}\n\n/**\n * Replay map diff operations\n */\nfunction replayMapDiff(\n map: LoroMap,\n diff: MapDiff,\n containerMap: Map<ContainerID, Container>,\n): void {\n for (const [key, value] of Object.entries(diff.updated)) {\n if (value === undefined) {\n // Delete the key\n map.delete(key)\n } else if (isContainer(value)) {\n // Set a container - create a new one of the same type\n const newContainer = createContainerOfSameType(value)\n const insertedContainer = map.setContainer(key, newContainer)\n // Map the source container ID to the newly created container\n containerMap.set(value.id, insertedContainer)\n } else {\n // Set a primitive value\n map.set(key, value as Exclude<Value, Container>)\n }\n }\n}\n\n/**\n * Replay tree diff operations\n */\nfunction replayTreeDiff(tree: LoroTree, diff: TreeDiff): void {\n for (const item of diff.diff) {\n replayTreeDiffItem(tree, item)\n }\n}\n\n/**\n * Replay a single tree diff item\n */\nfunction replayTreeDiffItem(tree: LoroTree, item: TreeDiffItem): void {\n switch (item.action) {\n case \"create\":\n // Create a new node under the specified parent\n // Note: The node ID is determined by the CRDT, we can't specify it\n // This means we're creating a NEW node, not recreating the exact same one\n tree.createNode(item.parent, item.index)\n break\n case \"delete\":\n // Delete the node\n tree.delete(item.target)\n break\n case \"move\":\n // Move the node to a new parent/position\n tree.move(item.target, item.parent, item.index)\n break\n }\n}\n\n/**\n * Replay counter diff operations\n */\nfunction replayCounterDiff(counter: LoroCounter, diff: CounterDiff): void {\n if (diff.increment > 0) {\n counter.increment(diff.increment)\n } else if (diff.increment < 0) {\n counter.decrement(-diff.increment)\n }\n // If increment is 0, no operation needed\n}\n\n/**\n * Check if a value is a Container\n */\nfunction isContainer(value: Value | Container): value is Container {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"kind\" in value &&\n typeof (value as Container).kind === \"function\"\n )\n}\n\n/**\n * Create a new detached container of the same type as the given container\n */\nfunction createContainerOfSameType(container: Container): Container {\n const kind = container.kind()\n switch (kind) {\n case \"List\":\n return new (container.constructor as new () => LoroList)()\n case \"Map\":\n return new (container.constructor as new () => LoroMap)()\n case \"Text\":\n return new (container.constructor as new () => LoroText)()\n case \"Tree\":\n return new (container.constructor as new () => LoroTree)()\n case \"Counter\":\n return new (container.constructor as new () => LoroCounter)()\n case \"MovableList\":\n return new (container.constructor as new () => LoroMovableList)()\n default:\n throw new Error(`Unknown container kind: ${kind}`)\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: required\n\nimport type {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n TreeID,\n Value,\n} from \"loro-crdt\"\n\nimport { LORO_SYMBOL, type LoroTreeRef } from \"./loro.js\"\nimport type { CounterRef } from \"./typed-refs/counter-ref.js\"\nimport type { ListRef } from \"./typed-refs/list-ref.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list-ref.js\"\nimport type { RecordRef } from \"./typed-refs/record-ref.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TextRef } from \"./typed-refs/text-ref.js\"\nimport type { TreeNodeRef } from \"./typed-refs/tree-node-ref.js\"\n\nexport interface Shape<Plain, Mutable, Placeholder = Plain> {\n readonly _type: string\n readonly _plain: Plain\n readonly _mutable: Mutable\n readonly _placeholder: Placeholder\n}\n\n// Type for shapes that support placeholder customization\nexport type WithPlaceholder<S extends Shape<any, any, any>> = S & {\n placeholder(value: S[\"_placeholder\"]): S\n}\n\n/**\n * Type for value shapes that support the .nullable() method.\n * Returns a union of null and the original shape with null as the default placeholder.\n */\nexport type WithNullable<S extends ValueShape> = {\n nullable(): WithPlaceholder<UnionValueShape<[NullValueShape, S]>>\n}\n\nexport interface DocShape<\n NestedShapes extends Record<string, ContainerShape> = Record<\n string,\n ContainerShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"doc\"\n // A doc's root containers each separately has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface TextContainerShape extends Shape<string, TextRef, string> {\n readonly _type: \"text\"\n}\nexport interface CounterContainerShape\n extends Shape<number, CounterRef, number> {\n readonly _type: \"counter\"\n}\n/**\n * JSON representation of a tree node with typed data.\n * Used for serialization (toJSON) of tree structures.\n */\nexport type TreeNodeJSON<DataShape extends StructContainerShape> = {\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: DataShape[\"_plain\"]\n children: TreeNodeJSON<DataShape>[]\n}\n\n/**\n * Interface describing the TreeRef API for use in shape definitions.\n * This avoids circular type references that would occur with the TreeRef class.\n * @internal\n */\nexport interface TreeRefInterface<DataShape extends StructContainerShape> {\n /** Get or create a node ref for a LoroTreeNode */\n getOrCreateNodeRef(node: unknown): TreeNodeRef<DataShape>\n /** Get a node by its ID */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined\n /** Delete a node from the tree */\n delete(target: TreeID | TreeNodeRef<DataShape>): void\n /** Serialize the tree to a nested JSON structure */\n toJSON(): TreeNodeJSON<DataShape>[]\n /** Create a new root node with optional initial data */\n createNode(initialData?: Partial<DataShape[\"_plain\"]>): TreeNodeRef<DataShape>\n /** Get all root nodes (nodes without parents) */\n roots(): TreeNodeRef<DataShape>[]\n /** Get all nodes in the tree (unordered). By default excludes deleted nodes. */\n nodes(options?: { includeDeleted?: boolean }): TreeNodeRef<DataShape>[]\n /** Check if a node with the given ID exists in the tree */\n has(id: TreeID): boolean\n /** Enable fractional index generation for ordering */\n enableFractionalIndex(jitter?: number): void\n /** Get a flat array representation of all nodes */\n toArray(): Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: DataShape[\"_plain\"]\n }>\n\n /**\n * Access CRDT internals via the well-known symbol.\n */\n readonly [LORO_SYMBOL]: LoroTreeRef\n}\n\n/**\n * Container shape for tree (forest) structures.\n * Each node in the tree has typed metadata stored in a LoroMap.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * const Schema = Shape.doc({\n * states: Shape.tree(StateNodeDataShape),\n * })\n * ```\n */\nexport interface TreeContainerShape<\n DataShape extends StructContainerShape = StructContainerShape,\n> extends Shape<\n TreeNodeJSON<DataShape>[],\n TreeRefInterface<DataShape>,\n never[]\n > {\n readonly _type: \"tree\"\n /**\n * The shape of each node's data (metadata).\n * This is a StructContainerShape that defines the typed properties on node.data.\n */\n readonly shape: DataShape\n}\n\n// Container schemas using interfaces for recursive references\n// NOTE: List and Record use never[] and Record<string, never> for Placeholder\n// to enforce that only empty values ([] and {}) are valid in placeholder state.\n// This prevents users from expecting per-entry merging behavior.\nexport interface ListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], ListRef<NestedShape>, never[]> {\n readonly _type: \"list\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\nexport interface MovableListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], MovableListRef<NestedShape>, never[]> {\n readonly _type: \"movableList\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\n/**\n * @deprecated Use StructContainerShape instead. MapContainerShape is an alias for backward compatibility.\n */\nexport type MapContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> = StructContainerShape<NestedShapes>\n\n/**\n * Container shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key objects.\n * Uses LoroMap as the underlying container.\n */\nexport interface StructContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n StructRef<NestedShapes>,\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"struct\"\n // Each struct property has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface RecordContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<\n Record<string, NestedShape[\"_plain\"]>,\n RecordRef<NestedShape>,\n Record<string, never>\n > {\n readonly _type: \"record\"\n readonly shape: NestedShape\n}\n\n/**\n * Container escape hatch - represents \"any LoroContainer\".\n * Use this when integrating with external libraries that manage their own document structure.\n *\n * @example\n * ```typescript\n * // loro-prosemirror manages its own structure\n * const ProseMirrorDocShape = Shape.doc({\n * doc: Shape.any(), // opt out of typing for this container\n * })\n * ```\n */\nexport interface AnyContainerShape extends Shape<unknown, unknown, undefined> {\n readonly _type: \"any\"\n}\n\n/**\n * Union of all container shape types.\n *\n * Each container shape has a `_mutable` type parameter that maps to the\n * corresponding TypedRef class (e.g., TextContainerShape → TextRef).\n * This enables deriving ref types from shapes:\n *\n * ```typescript\n * // Get the ref type for any container shape\n * type RefType = ContainerShape[\"_mutable\"]\n *\n * // Exclude AnyContainerShape to get only typed refs\n * type AnyTypedRef = Exclude<ContainerShape, AnyContainerShape>[\"_mutable\"]\n * ```\n *\n * This creates intentional parallel hierarchies:\n * - ContainerShape → defines what data looks like (schema)\n * - TypedRef (via _mutable) → defines how you interact with data\n * - loro() overloads → CRDT escape hatch (IDE DX)\n * - change() overloads → mutation boundaries (IDE DX)\n */\nexport type ContainerShape =\n | AnyContainerShape\n | CounterContainerShape\n | ListContainerShape\n | MovableListContainerShape\n | RecordContainerShape\n | StructContainerShape\n | TextContainerShape\n | TreeContainerShape\n\nexport type ContainerType = ContainerShape[\"_type\"]\n\n// LoroValue shape types - a shape for each of Loro's Value types\nexport interface StringValueShape<T extends string = string>\n extends Shape<T, T, T> {\n readonly _type: \"value\"\n readonly valueType: \"string\"\n readonly options?: T[]\n}\nexport interface NumberValueShape extends Shape<number, number, number> {\n readonly _type: \"value\"\n readonly valueType: \"number\"\n}\nexport interface BooleanValueShape extends Shape<boolean, boolean, boolean> {\n readonly _type: \"value\"\n readonly valueType: \"boolean\"\n}\nexport interface NullValueShape extends Shape<null, null, null> {\n readonly _type: \"value\"\n readonly valueType: \"null\"\n}\nexport interface UndefinedValueShape\n extends Shape<undefined, undefined, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"undefined\"\n}\nexport interface Uint8ArrayValueShape\n extends Shape<Uint8Array, Uint8Array, Uint8Array> {\n readonly _type: \"value\"\n readonly valueType: \"uint8array\"\n}\n\n/**\n * @deprecated Use StructValueShape instead. ObjectValueShape is an alias for backward compatibility.\n */\nexport type ObjectValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> = StructValueShape<T>\n\n/**\n * Value shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key plain value objects.\n * Identical structure to ObjectValueShape but with valueType: \"struct\".\n */\nexport interface StructValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> extends Shape<\n { [K in keyof T]: T[K][\"_plain\"] },\n { [K in keyof T]: T[K][\"_mutable\"] },\n { [K in keyof T]: T[K][\"_placeholder\"] }\n > {\n readonly _type: \"value\"\n readonly valueType: \"struct\"\n readonly shape: T\n}\n\n// NOTE: RecordValueShape and ArrayValueShape use Record<string, never> and never[]\n// for Placeholder to enforce that only empty values ({} and []) are valid.\nexport interface RecordValueShape<T extends ValueShape = ValueShape>\n extends Shape<\n Record<string, T[\"_plain\"]>,\n Record<string, T[\"_mutable\"]>,\n Record<string, never>\n > {\n readonly _type: \"value\"\n readonly valueType: \"record\"\n readonly shape: T\n}\n\nexport interface ArrayValueShape<T extends ValueShape = ValueShape>\n extends Shape<T[\"_plain\"][], T[\"_mutable\"][], never[]> {\n readonly _type: \"value\"\n readonly valueType: \"array\"\n readonly shape: T\n}\n\nexport interface UnionValueShape<T extends ValueShape[] = ValueShape[]>\n extends Shape<\n T[number][\"_plain\"],\n T[number][\"_mutable\"],\n T[number][\"_placeholder\"]\n > {\n readonly _type: \"value\"\n readonly valueType: \"union\"\n readonly shapes: T\n}\n\n/**\n * A discriminated union shape that uses a discriminant key to determine which variant to use.\n * This enables type-safe handling of tagged unions like:\n *\n * ```typescript\n * type GamePresence =\n * | { type: \"client\"; name: string; input: { force: number; angle: number } }\n * | { type: \"server\"; cars: Record<string, CarState>; tick: number }\n * ```\n *\n * @typeParam K - The discriminant key (e.g., \"type\")\n * @typeParam T - A record mapping discriminant values to their object shapes\n */\nexport interface DiscriminatedUnionValueShape<\n K extends string = string,\n T extends Record<string, StructValueShape> = Record<string, StructValueShape>,\n Plain = T[keyof T][\"_plain\"],\n Mutable = T[keyof T][\"_mutable\"],\n Placeholder = T[keyof T][\"_placeholder\"],\n> extends Shape<Plain, Mutable, Placeholder> {\n readonly _type: \"value\"\n readonly valueType: \"discriminatedUnion\"\n readonly discriminantKey: K\n readonly variants: T\n}\n\n/**\n * Value escape hatch - represents \"any Loro Value\".\n * Use this when you need to accept any valid Loro value type.\n *\n * @example\n * ```typescript\n * const FlexiblePresenceShape = Shape.plain.struct({\n * cursor: Shape.plain.any(), // accept any value type\n * })\n * ```\n */\nexport interface AnyValueShape extends Shape<Value, Value, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"any\"\n}\n\n// Union of all ValueShapes - these can only contain other ValueShapes, not ContainerShapes\nexport type ValueShape =\n | AnyValueShape\n | StringValueShape\n | NumberValueShape\n | BooleanValueShape\n | NullValueShape\n | UndefinedValueShape\n | Uint8ArrayValueShape\n | StructValueShape\n | RecordValueShape\n | ArrayValueShape\n | UnionValueShape\n | DiscriminatedUnionValueShape\n\nexport type ContainerOrValueShape = ContainerShape | ValueShape\n\n/**\n * Creates a nullable version of a value shape.\n * @internal\n */\nfunction makeNullable<S extends ValueShape>(\n shape: S,\n): WithPlaceholder<UnionValueShape<[NullValueShape, S]>> {\n const nullShape: NullValueShape = {\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }\n\n const base: UnionValueShape<[NullValueShape, S]> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes: [nullShape, shape] as [NullValueShape, S],\n _plain: null as any,\n _mutable: null as any,\n _placeholder: null as any, // Default placeholder is null\n }\n\n return Object.assign(base, {\n placeholder(\n value: S[\"_placeholder\"] | null,\n ): UnionValueShape<[NullValueShape, S]> {\n return { ...base, _placeholder: value } as UnionValueShape<\n [NullValueShape, S]\n >\n },\n })\n}\n\n/**\n * The LoroShape factory object\n *\n * If a container has a `shape` type variable, it refers to the shape it contains--\n * so for example, a `LoroShape.list(LoroShape.text())` would return a value of type\n * `ListContainerShape<TextContainerShape>`.\n */\nexport const Shape = {\n doc: <T extends Record<string, ContainerShape>>(shape: T): DocShape<T> => ({\n _type: \"doc\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * Creates an \"any\" container shape - an escape hatch for untyped containers.\n * Use this when integrating with external libraries that manage their own document structure.\n *\n * @example\n * ```typescript\n * // loro-prosemirror manages its own structure\n * const ProseMirrorDocShape = Shape.doc({\n * doc: Shape.any(), // opt out of typing for this container\n * })\n *\n * const handle = repo.get(docId, ProseMirrorDocShape, CursorPresenceShape)\n * // handle.doc.doc is typed as `unknown` - you're on your own\n * ```\n */\n any: (): AnyContainerShape => ({\n _type: \"any\" as const,\n _plain: undefined as unknown,\n _mutable: undefined as unknown,\n _placeholder: undefined,\n }),\n\n // CRDTs are represented by Loro Containers--they converge on state using Loro's\n // various CRDT algorithms\n counter: (): WithPlaceholder<CounterContainerShape> => {\n const base: CounterContainerShape = {\n _type: \"counter\" as const,\n _plain: 0,\n _mutable: {} as CounterRef,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): CounterContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n list: <T extends ContainerOrValueShape>(shape: T): ListContainerShape<T> => ({\n _type: \"list\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n /**\n * Creates a struct container shape for objects with fixed keys.\n * This is the preferred way to define fixed-key objects.\n *\n * @example\n * ```typescript\n * const UserSchema = Shape.doc({\n * user: Shape.struct({\n * name: Shape.text(),\n * age: Shape.counter(),\n * }),\n * })\n * ```\n */\n struct: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * @deprecated Use `Shape.struct` instead. `Shape.struct` will be removed in a future version.\n */\n map: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n record: <T extends ContainerOrValueShape>(\n shape: T,\n ): RecordContainerShape<T> => ({\n _type: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }),\n\n movableList: <T extends ContainerOrValueShape>(\n shape: T,\n ): MovableListContainerShape<T> => ({\n _type: \"movableList\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n text: (): WithPlaceholder<TextContainerShape> => {\n const base: TextContainerShape = {\n _type: \"text\" as const,\n _plain: \"\",\n _mutable: {} as TextRef,\n _placeholder: \"\",\n }\n return Object.assign(base, {\n placeholder(value: string): TextContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a tree container shape for hierarchical data structures.\n * Each node in the tree has typed metadata defined by the data shape.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * const Schema = Shape.doc({\n * states: Shape.tree(StateNodeDataShape),\n * })\n *\n * doc.change(draft => {\n * const root = draft.states.createNode({ name: \"idle\", facts: {} })\n * const child = root.createNode({ name: \"running\", facts: {} })\n * child.data.name = \"active\"\n * })\n * ```\n */\n tree: <T extends StructContainerShape>(shape: T): TreeContainerShape<T> => ({\n _type: \"tree\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n // Values are represented as plain JS objects, with the limitation that they MUST be\n // representable as a Loro \"Value\"--basically JSON. The behavior of a Value is basically\n // \"Last Write Wins\", meaning there is no subtle convergent behavior here, just taking\n // the most recent value based on the current available information.\n plain: {\n string: <T extends string = string>(\n ...options: T[]\n ): WithPlaceholder<StringValueShape<T>> &\n WithNullable<StringValueShape<T>> => {\n const base: StringValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"string\" as const,\n _plain: (options[0] ?? \"\") as T,\n _mutable: (options[0] ?? \"\") as T,\n _placeholder: (options[0] ?? \"\") as T,\n options: options.length > 0 ? options : undefined,\n }\n return Object.assign(base, {\n placeholder(value: T): StringValueShape<T> {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StringValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n number: (): WithPlaceholder<NumberValueShape> &\n WithNullable<NumberValueShape> => {\n const base: NumberValueShape = {\n _type: \"value\" as const,\n valueType: \"number\" as const,\n _plain: 0,\n _mutable: 0,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): NumberValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, NumberValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n boolean: (): WithPlaceholder<BooleanValueShape> &\n WithNullable<BooleanValueShape> => {\n const base: BooleanValueShape = {\n _type: \"value\" as const,\n valueType: \"boolean\" as const,\n _plain: false,\n _mutable: false,\n _placeholder: false,\n }\n return Object.assign(base, {\n placeholder(value: boolean): BooleanValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, BooleanValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n null: (): NullValueShape => ({\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }),\n\n undefined: (): UndefinedValueShape => ({\n _type: \"value\" as const,\n valueType: \"undefined\" as const,\n _plain: undefined,\n _mutable: undefined,\n _placeholder: undefined,\n }),\n\n uint8Array: (): Uint8ArrayValueShape &\n WithNullable<Uint8ArrayValueShape> => {\n const base: Uint8ArrayValueShape = {\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, Uint8ArrayValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * Alias for `uint8Array()` - creates a shape for binary data.\n * Use this for better discoverability when working with binary data like cursor positions.\n *\n * @example\n * ```typescript\n * const CursorPresenceShape = Shape.plain.struct({\n * anchor: Shape.plain.bytes().nullable(),\n * focus: Shape.plain.bytes().nullable(),\n * })\n * ```\n */\n bytes: (): Uint8ArrayValueShape & WithNullable<Uint8ArrayValueShape> => {\n const base: Uint8ArrayValueShape = {\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, Uint8ArrayValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * Creates an \"any\" value shape - an escape hatch for untyped values.\n * Use this when you need to accept any valid Loro value type.\n *\n * @example\n * ```typescript\n * const FlexiblePresenceShape = Shape.plain.struct({\n * metadata: Shape.plain.any(), // accept any value type\n * })\n * ```\n */\n any: (): AnyValueShape => ({\n _type: \"value\" as const,\n valueType: \"any\" as const,\n _plain: undefined as unknown as Value,\n _mutable: undefined as unknown as Value,\n _placeholder: undefined,\n }),\n\n /**\n * Creates a struct value shape for plain objects with fixed keys.\n * This is the preferred way to define fixed-key plain value objects.\n *\n * @example\n * ```typescript\n * const PointSchema = Shape.plain.struct({\n * x: Shape.plain.number(),\n * y: Shape.plain.number(),\n * })\n * ```\n */\n struct: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * @deprecated Use `Shape.plain.struct` instead. `Shape.plain.struct` will be removed in a future version.\n */\n object: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n record: <T extends ValueShape>(\n shape: T,\n ): RecordValueShape<T> & WithNullable<RecordValueShape<T>> => {\n const base: RecordValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, RecordValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n array: <T extends ValueShape>(\n shape: T,\n ): ArrayValueShape<T> & WithNullable<ArrayValueShape<T>> => {\n const base: ArrayValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"array\" as const,\n shape,\n _plain: [] as any,\n _mutable: [] as any,\n _placeholder: [] as never[],\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, ArrayValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n // Special value type that helps make things like `string | null` representable\n // TODO(duane): should this be a more general type for containers too?\n union: <T extends ValueShape[]>(\n shapes: T,\n ): WithPlaceholder<UnionValueShape<T>> => {\n const base: UnionValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(value: T[number][\"_placeholder\"]): UnionValueShape<T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a discriminated union shape for type-safe tagged unions.\n *\n * @example\n * ```typescript\n * const ClientPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"client\"),\n * name: Shape.plain.string(),\n * input: Shape.plain.struct({ force: Shape.plain.number(), angle: Shape.plain.number() }),\n * })\n *\n * const ServerPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"server\"),\n * cars: Shape.plain.record(Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() })),\n * tick: Shape.plain.number(),\n * })\n *\n * const GamePresenceSchema = Shape.plain.discriminatedUnion(\"type\", {\n * client: ClientPresenceShape,\n * server: ServerPresenceShape,\n * })\n * ```\n *\n * @param discriminantKey - The key used to discriminate between variants (e.g., \"type\")\n * @param variants - A record mapping discriminant values to their object shapes\n */\n discriminatedUnion: <\n K extends string,\n T extends Record<string, StructValueShape>,\n >(\n discriminantKey: K,\n variants: T,\n ): WithPlaceholder<DiscriminatedUnionValueShape<K, T>> => {\n const base: DiscriminatedUnionValueShape<K, T> = {\n _type: \"value\" as const,\n valueType: \"discriminatedUnion\" as const,\n discriminantKey,\n variants,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(\n value: T[keyof T][\"_placeholder\"],\n ): DiscriminatedUnionValueShape<K, T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n },\n}\n\n// Add this type mapping near the top of your file, after the imports\nexport type ShapeToContainer<T extends DocShape | ContainerShape> =\n T extends TextContainerShape\n ? LoroText\n : T extends CounterContainerShape\n ? LoroCounter\n : T extends ListContainerShape\n ? LoroList\n : T extends MovableListContainerShape\n ? LoroMovableList\n : T extends StructContainerShape | RecordContainerShape\n ? LoroMap\n : T extends TreeContainerShape\n ? LoroTree\n : never // not a container\n"],"mappings":";AASO,SAAS,kBACd,QACyB;AACzB,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,MAAM,GAAG;AACxD,WAAO,GAAG,IAAI,uBAAuB,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAuC;AAC5E,UAAQ,MAAM,OAAO;AAAA;AAAA,IAEnB,KAAK;AACH,aAAO;AAAA;AAAA,IAGT,KAAK;AACH,aAAO,MAAM;AAAA,IACf,KAAK;AACH,aAAO,MAAM;AA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A;AAAA,QACA,QAAQ,CAAC;AAAA,QACT,UAAU,CAAC;AAAA,QACX,cAAc,CAAC;AAAA,MACjB;AACA,aAAO,OAAO,OAAO,MAAM;AAAA,QACzB,YACE,OACoC;AACpC,iBAAO,EAAE,GAAG,MAAM,cAAc,MAAM;AAAA,QACxC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["LoroDoc","value","LoroCounter","LoroList","LoroMap","LoroMovableList","LoroText","cachedItem","ref","ref","LoroCounter","LoroList","LoroMovableList","LoroMap","LoroText","LoroDoc","target","isContainer"]}
1
+ {"version":3,"sources":["../src/derive-placeholder.ts","../src/diff-overlay.ts","../src/functional-helpers.ts","../src/loro.ts","../src/typed-doc.ts","../src/json-patch.ts","../src/utils/type-guards.ts","../src/overlay.ts","../src/typed-refs/base.ts","../src/typed-refs/utils.ts","../src/typed-refs/counter-ref-internals.ts","../src/typed-refs/counter-ref.ts","../src/conversion.ts","../src/typed-refs/list-ref-base.ts","../src/typed-refs/list-ref-internals.ts","../src/typed-refs/list-ref.ts","../src/typed-refs/movable-list-ref-internals.ts","../src/typed-refs/movable-list-ref.ts","../src/typed-refs/proxy-handlers.ts","../src/typed-refs/record-ref-internals.ts","../src/typed-refs/record-ref.ts","../src/typed-refs/struct-ref-internals.ts","../src/typed-refs/struct-ref.ts","../src/typed-refs/text-ref-internals.ts","../src/typed-refs/text-ref.ts","../src/typed-refs/tree-node-ref-internals.ts","../src/typed-refs/tree-node-ref.ts","../src/typed-refs/tree-ref-internals.ts","../src/typed-refs/tree-ref.ts","../src/typed-refs/doc-ref-internals.ts","../src/typed-refs/doc-ref.ts","../src/validation.ts","../src/path-builder.ts","../src/path-compiler.ts","../src/path-evaluator.ts","../src/placeholder-proxy.ts","../src/replay-diff.ts","../src/shape.ts"],"sourcesContent":["import type { ContainerOrValueShape, DocShape, ValueShape } from \"./shape.js\"\nimport type { InferPlaceholderType } from \"./types.js\"\n\n/**\n * Derives the placeholder state from a schema by composing placeholder values.\n *\n * For leaf nodes (text, counter, values): uses _placeholder directly\n * For containers (map, list, record): recurses into nested shapes\n */\nexport function derivePlaceholder<T extends DocShape>(\n schema: T,\n): InferPlaceholderType<T> {\n const result: Record<string, unknown> = {}\n\n for (const [key, shape] of Object.entries(schema.shapes)) {\n result[key] = deriveShapePlaceholder(shape)\n }\n\n return result as InferPlaceholderType<T>\n}\n\n/**\n * Derives placeholder for a single shape.\n *\n * Leaf nodes: return _placeholder directly\n * Containers: recurse into nested shapes (ignore _placeholder on containers)\n */\nexport function deriveShapePlaceholder(shape: ContainerOrValueShape): unknown {\n switch (shape._type) {\n // Any container - no placeholder (undefined)\n case \"any\":\n return undefined\n\n // Leaf containers - use _placeholder directly\n case \"text\":\n return shape._placeholder\n case \"counter\":\n return shape._placeholder\n\n // Dynamic containers - always empty (no per-entry merging)\n case \"list\":\n case \"movableList\":\n case \"tree\":\n return []\n case \"record\":\n return {}\n\n // Structured container - recurse into nested shapes\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n result[key] = deriveShapePlaceholder(nestedShape)\n }\n return result\n }\n\n case \"value\":\n return deriveValueShapePlaceholder(shape)\n\n default:\n return undefined\n }\n}\n\nfunction deriveValueShapePlaceholder(shape: ValueShape): unknown {\n switch (shape.valueType) {\n // Any value - no placeholder (undefined)\n case \"any\":\n return undefined\n\n // Leaf values - use _placeholder directly\n case \"string\":\n return shape._placeholder\n case \"number\":\n return shape._placeholder\n case \"boolean\":\n return shape._placeholder\n case \"null\":\n return null\n case \"undefined\":\n return undefined\n case \"uint8array\":\n return shape._placeholder\n\n // Structured value - recurse into nested shapes (like struct)\n case \"struct\": {\n const result: Record<string, unknown> = {}\n for (const [key, nestedShape] of Object.entries(shape.shape)) {\n result[key] = deriveValueShapePlaceholder(nestedShape)\n }\n return result\n }\n\n // Dynamic values - always empty\n case \"array\":\n return []\n case \"record\":\n return {}\n\n // Unions - use _placeholder if explicitly set, otherwise derive from first variant\n case \"union\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n // We need to check if it's a primitive value OR a non-empty object\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n return deriveValueShapePlaceholder(shape.shapes[0])\n }\n\n case \"discriminatedUnion\": {\n // Check if _placeholder was explicitly set (not the default empty object)\n const placeholder = shape._placeholder\n if (placeholder !== undefined) {\n // If it's a primitive (null, string, number, boolean), use it\n if (placeholder === null || typeof placeholder !== \"object\") {\n return placeholder\n }\n // If it's an object with keys, use it\n if (Object.keys(placeholder as object).length > 0) {\n return placeholder\n }\n }\n // Otherwise derive from first variant\n const firstKey = Object.keys(shape.variants)[0]\n return deriveValueShapePlaceholder(shape.variants[firstKey])\n }\n\n default:\n return undefined\n }\n}\n","import type { ContainerID, Diff, LoroDoc, LoroEventBatch } from \"loro-crdt\"\n\nexport type DiffOverlay = ReadonlyMap<ContainerID, Diff>\n\nexport function createDiffOverlay(\n doc: LoroDoc,\n batch: LoroEventBatch,\n): DiffOverlay {\n return new Map(doc.diff(batch.to, batch.from, false))\n}\n","import {\n type LoroCounter,\n LoroDoc,\n type LoroEventBatch,\n type LoroList,\n type LoroMap,\n type LoroMovableList,\n type LoroText,\n type LoroTree,\n} from \"loro-crdt\"\nimport { createDiffOverlay } from \"./diff-overlay.js\"\nimport { loro } from \"./loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n ShapeToContainer,\n StructContainerShape,\n TextContainerShape,\n TreeRefInterface,\n} from \"./shape.js\"\nimport { createTypedDoc, type Frontiers, type TypedDoc } from \"./typed-doc.js\"\nimport { INTERNAL_SYMBOL, type TypedRef } from \"./typed-refs/base.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TreeRef } from \"./typed-refs/tree-ref.js\"\nimport { createContainerTypedRef } from \"./typed-refs/utils.js\"\nimport type { Mutable } from \"./types.js\"\n\n/**\n * The primary method of mutating typed documents and refs.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc/ref for chaining.\n *\n * @param target - The TypedDoc or TypedRef to mutate\n * @param fn - Function that performs mutations on the draft\n * @returns The same target for chaining\n *\n * @example\n * ```typescript\n * import { change } from \"@loro-extended/change\"\n *\n * // Document-level change (chainable)\n * change(doc, draft => {\n * draft.count.increment(10)\n * draft.title.update(\"Hello\")\n * })\n * .count.increment(5) // Optional: continue mutating\n * .toJSON() // Optional: get snapshot\n *\n * // Ref-level change - enables encapsulation\n * function addItems(list: ListRef<...>) {\n * change(list, draft => {\n * draft.push({ name: \"item1\" })\n * draft.push({ name: \"item2\" })\n * })\n * }\n *\n * // TreeRef example - pass around refs without exposing the doc\n * function addStates(states: TreeRef<StateShape>) {\n * change(states, draft => {\n * draft.createNode({ name: \"idle\" })\n * draft.createNode({ name: \"running\" })\n * })\n * }\n * ```\n */\n// Overload for TypedDoc\nexport function change<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n fn: (draft: Mutable<Shape>) => void,\n): TypedDoc<Shape>\n\n// Overload for TreeRef (special case - not a TypedRef<ContainerShape>)\nexport function change<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n fn: (draft: TreeRef<DataShape>) => void,\n): TreeRef<DataShape>\n\n// Overload for TreeRefInterface (the mutable type from TreeContainerShape)\nexport function change<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n fn: (draft: TreeRefInterface<DataShape>) => void,\n): TreeRefInterface<DataShape>\n\n// Overload for StructRef (special case - uses Proxy, not a class extending TypedRef)\n// This must come before the generic TypedRef overload to match StructRef properly\nexport function change<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(\n ref: StructRef<NestedShapes>,\n fn: (draft: StructRef<NestedShapes>) => void,\n): StructRef<NestedShapes>\n\n// Overload for TypedRef (all container refs) - preserves concrete ref type\nexport function change<T extends TypedRef<ContainerShape>>(\n ref: T,\n fn: (draft: T) => void,\n): T\n\n// Implementation\nexport function change(\n target:\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | StructRef<any>,\n fn: (draft: any) => void,\n):\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | StructRef<any> {\n // Check if it's a TypedDoc (has .change method)\n if (\"change\" in target && typeof (target as any).change === \"function\") {\n return (target as TypedDoc<any>).change(fn)\n }\n\n // It's a TypedRef or TreeRef - use ref-level change logic\n return changeRef(target as TypedRef<any> | TreeRef<any>, fn)\n}\n\n/**\n * Internal implementation for ref-level change.\n * Creates a draft ref with batchedMutation=true, executes the function,\n * absorbs changes, and commits.\n */\nfunction changeRef<T extends TypedRef<any> | TreeRef<any>>(\n ref: T,\n fn: (draft: T) => void,\n): T {\n // Get internals via INTERNAL_SYMBOL\n const internals = (ref as any)[INTERNAL_SYMBOL]\n if (!internals) {\n throw new Error(\n \"change() requires a TypedRef with internal methods. \" +\n \"Make sure you're passing a valid typed ref.\",\n )\n }\n\n // Get the params needed to create a draft\n const params = internals.getTypedRefParams()\n\n // Create draft params with batchedMutation enabled and autoCommit disabled\n const draftParams = {\n ...params,\n autoCommit: false,\n batchedMutation: true,\n }\n\n // Create the draft ref using the same factory that created the original\n const draft = createContainerTypedRef(draftParams) as T\n\n // Execute the user's function with the draft\n fn(draft)\n\n // Absorb any cached plain values back into the Loro containers\n const draftInternals = (draft as any)[INTERNAL_SYMBOL]\n draftInternals.absorbPlainValues()\n\n // Commit the changes\n // Note: Loro's commit() is idempotent, so nested calls are safe\n internals.getDoc().commit()\n\n // Return the original ref for chaining\n return ref\n}\n\n/**\n * Access the underlying LoroDoc for advanced operations.\n * Works on both TypedDoc and any typed ref (TextRef, CounterRef, ListRef, etc.).\n *\n * @param docOrRef - The TypedDoc or typed ref to unwrap\n * @returns The underlying LoroDoc instance (or undefined for refs created outside a doc context)\n *\n * @example\n * ```typescript\n * import { getLoroDoc } from \"@loro-extended/change\"\n *\n * // From TypedDoc\n * const loroDoc = getLoroDoc(doc)\n * const version = loroDoc.version()\n * loroDoc.subscribe(() => console.log(\"changed\"))\n *\n * // From any ref (TextRef, CounterRef, ListRef, etc.)\n * const titleRef = doc.title\n * const loroDoc = getLoroDoc(titleRef)\n * loroDoc?.subscribe(() => console.log(\"changed\"))\n * ```\n */\nexport function getLoroDoc<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroDoc\nexport function getLoroDoc<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): LoroDoc\nexport function getLoroDoc<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n): LoroDoc\nexport function getLoroDoc<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n): LoroDoc\nexport function getLoroDoc(\n docOrRef:\n | TypedDoc<any>\n | TypedRef<any>\n | TreeRef<any>\n | TreeRefInterface<any>,\n): LoroDoc {\n // Use loro() to access the underlying LoroDoc\n return loro(docOrRef as any).doc\n}\n\n/**\n * Access the underlying Loro container from a typed ref.\n * Returns the correctly-typed container based on the ref type.\n *\n * @param ref - The typed ref to unwrap\n * @returns The underlying Loro container (LoroText, LoroCounter, LoroList, etc.)\n *\n * @example\n * ```typescript\n * import { getLoroContainer } from \"@loro-extended/change\"\n *\n * const titleRef = doc.title\n * const loroText = getLoroContainer(titleRef) // LoroText\n *\n * const countRef = doc.count\n * const loroCounter = getLoroContainer(countRef) // LoroCounter\n *\n * const itemsRef = doc.items\n * const loroList = getLoroContainer(itemsRef) // LoroList\n *\n * // Subscribe to container-level changes\n * loroText.subscribe((event) => console.log(\"Text changed:\", event))\n * ```\n */\nexport function getLoroContainer(ref: TypedRef<TextContainerShape>): LoroText\nexport function getLoroContainer(\n ref: TypedRef<CounterContainerShape>,\n): LoroCounter\nexport function getLoroContainer(ref: TypedRef<ListContainerShape>): LoroList\nexport function getLoroContainer(\n ref: TypedRef<MovableListContainerShape>,\n): LoroMovableList\nexport function getLoroContainer(ref: TypedRef<RecordContainerShape>): LoroMap\nexport function getLoroContainer(ref: TypedRef<StructContainerShape>): LoroMap\nexport function getLoroContainer<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(ref: StructRef<NestedShapes>): LoroMap\nexport function getLoroContainer<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape>,\n): LoroTree\nexport function getLoroContainer<DataShape extends StructContainerShape>(\n ref: TreeRefInterface<DataShape>,\n): LoroTree\nexport function getLoroContainer<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): ShapeToContainer<Shape>\nexport function getLoroContainer(\n ref: TypedRef<any> | TreeRef<any> | TreeRefInterface<any> | StructRef<any>,\n): unknown {\n // Use loro() to access the underlying container\n return loro(ref as any).container\n}\n\n/**\n * Creates a new TypedDoc as a fork of the current document.\n * The forked doc contains all history up to the current version.\n * The forked doc has a different PeerID from the original by default.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.fork()`\n *\n * @param doc - The TypedDoc to fork\n * @param options - Optional settings\n * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork\n * @returns A new TypedDoc with the same schema at the current version\n *\n * @example\n * ```typescript\n * import { fork, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n *\n * // Fork the document\n * const forkedDoc = fork(doc);\n * forkedDoc.title.update(\"World\");\n *\n * console.log(doc.title.toString()); // \"Hello\"\n * console.log(forkedDoc.title.toString()); // \"World\"\n *\n * // Fork with same peer ID (for World/Worldview pattern)\n * const worldview = fork(world, { preservePeerId: true });\n * ```\n */\nexport function fork<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n options?: { preservePeerId?: boolean },\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const forkedLoroDoc = loroDoc.fork()\n const shape = loro(doc).docShape as Shape\n\n // Optionally preserve the peer ID (useful for World/Worldview pattern)\n if (options?.preservePeerId) {\n forkedLoroDoc.setPeerId(loroDoc.peerId)\n }\n\n return createTypedDoc(shape, { doc: forkedLoroDoc })\n}\n\n/**\n * Creates a new TypedDoc at a specified version (frontiers).\n * The forked doc will only contain history before the specified frontiers.\n * The forked doc has a different PeerID from the original.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)`\n *\n * @param doc - The TypedDoc to fork\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @returns A new TypedDoc with the same schema at the specified version\n *\n * @example\n * ```typescript\n * import { forkAt, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n * doc.title.update(\"World\");\n *\n * // Fork at the earlier version\n * const forkedDoc = forkAt(doc, frontiers);\n * console.log(forkedDoc.title.toString()); // \"Hello\"\n * console.log(doc.title.toString()); // \"World\"\n * ```\n */\nexport function forkAt<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n frontiers: Frontiers,\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const forkedLoroDoc = loroDoc.forkAt(frontiers)\n const shape = loro(doc).docShape as Shape\n return createTypedDoc(shape, { doc: forkedLoroDoc })\n}\n\n/**\n * Creates a new TypedDoc at a specified version using a shallow snapshot.\n * Unlike `forkAt`, this creates a \"garbage-collected\" snapshot that only\n * contains the current state and history since the specified frontiers.\n *\n * This is more memory-efficient than `forkAt` for documents with long history,\n * especially useful for the fork-and-merge pattern in LEA where we only need:\n * 1. Read current state\n * 2. Apply changes\n * 3. Export delta and merge back\n *\n * The shallow fork has a different PeerID from the original by default.\n * Use `preservePeerId: true` to copy the original's peer ID (useful for\n * fork-and-merge patterns where you want consistent frontier progression).\n *\n * @param doc - The TypedDoc to fork\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @param options - Optional settings\n * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork\n * @returns A new TypedDoc with the same schema at the specified version (shallow)\n *\n * @example\n * ```typescript\n * import { shallowForkAt, loro } from \"@loro-extended/change\"\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n *\n * // Create a shallow fork (memory-efficient)\n * const shallowDoc = shallowForkAt(doc, frontiers, { preservePeerId: true });\n *\n * // Modify the shallow doc\n * shallowDoc.title.update(\"World\");\n *\n * // Merge changes back\n * const update = loro(shallowDoc).doc.export({\n * mode: \"update\",\n * from: loro(doc).doc.version()\n * });\n * loro(doc).doc.import(update);\n * ```\n */\nexport function shallowForkAt<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n frontiers: Frontiers,\n options?: { preservePeerId?: boolean },\n): TypedDoc<Shape> {\n const loroDoc = loro(doc).doc\n const shape = loro(doc).docShape as Shape\n\n // Export a shallow snapshot at the specified frontiers\n const shallowBytes = loroDoc.export({\n mode: \"shallow-snapshot\",\n frontiers,\n })\n\n // Create a new LoroDoc from the shallow snapshot\n const shallowLoroDoc = LoroDoc.fromSnapshot(shallowBytes)\n\n // Optionally preserve the peer ID for consistent frontier progression\n if (options?.preservePeerId) {\n shallowLoroDoc.setPeerId(loroDoc.peerId)\n }\n\n return createTypedDoc(shape, { doc: shallowLoroDoc })\n}\n\nexport type Transition<Shape extends DocShape> = {\n before: TypedDoc<Shape>\n after: TypedDoc<Shape>\n}\n\n/**\n * Build a `{ before, after }` transition from a TypedDoc and a Loro event batch.\n * Uses a reverse diff overlay to compute the \"before\" view without checkout.\n * Throws on checkout events to avoid time-travel transitions.\n */\nexport function getTransition<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n event: LoroEventBatch,\n): Transition<Shape> {\n if (event.by === \"checkout\") {\n throw new Error(\"getTransition does not support checkout events\")\n }\n\n const loroDoc = getLoroDoc(doc)\n const shape = loro(doc).docShape as Shape\n const overlay = createDiffOverlay(loroDoc, event)\n\n return {\n before: createTypedDoc(shape, { doc: loroDoc, overlay }),\n after: createTypedDoc(shape, { doc: loroDoc }),\n }\n}\n","/**\n * The `loro()` function - single escape hatch for CRDT internals.\n *\n * Design Principle:\n * > If it takes a plain JavaScript value, keep it on the ref.\n * > If it takes a Loro container or exposes CRDT internals, move to `loro()`.\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\"\n *\n * // Access underlying LoroDoc\n * loro(ref).doc\n *\n * // Access underlying Loro container (correctly typed)\n * loro(ref).container // LoroList, LoroMap, LoroText, etc.\n *\n * // Subscribe to changes\n * loro(ref).subscribe(callback)\n *\n * // Container operations\n * loro(list).pushContainer(loroMap)\n * loro(struct).setContainer('key', loroMap)\n * ```\n */\n\nimport type {\n Container,\n LoroCounter,\n LoroDoc,\n LoroEventBatch,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Subscription,\n} from \"loro-crdt\"\nimport type { JsonPatch } from \"./json-patch.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n DocShape,\n StructContainerShape,\n TreeRefInterface,\n} from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\nimport type { TypedRef } from \"./typed-refs/base.js\"\nimport type { CounterRef } from \"./typed-refs/counter-ref.js\"\nimport type { ListRef } from \"./typed-refs/list-ref.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list-ref.js\"\nimport type { RecordRef } from \"./typed-refs/record-ref.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TextRef } from \"./typed-refs/text-ref.js\"\nimport type { TreeNodeRef } from \"./typed-refs/tree-node-ref.js\"\nimport type { TreeRef } from \"./typed-refs/tree-ref.js\"\n\n// ============================================================================\n// Symbol for loro() access\n// ============================================================================\n\n/**\n * Well-known Symbol for loro() access.\n * This is exported so advanced users can access it directly if needed.\n */\nexport const LORO_SYMBOL = Symbol.for(\"loro-extended:loro\")\n\n// ============================================================================\n// Interface definitions for loro() return types\n// ============================================================================\n\n/**\n * Base interface for all loro() return types.\n * Provides access to the underlying LoroDoc, container, and subscription.\n */\nexport interface LoroRefBase {\n /** The underlying LoroDoc */\n readonly doc: LoroDoc\n\n /** The underlying Loro container */\n readonly container: unknown\n\n /**\n * Subscribe to container-level changes.\n * @param callback - Function called when the container changes\n * @returns Subscription that can be used to unsubscribe\n */\n subscribe(callback: (event: LoroEventBatch) => void): Subscription\n}\n\n/**\n * loro() return type for ListRef and MovableListRef.\n * Provides container operations that take Loro containers.\n */\nexport interface LoroListRef extends LoroRefBase {\n /** The underlying LoroList or LoroMovableList */\n readonly container: LoroList | LoroMovableList\n\n /**\n * Push a Loro container to the end of the list.\n * Use this when you need to add a pre-existing container.\n */\n pushContainer(container: Container): Container\n\n /**\n * Insert a Loro container at the specified index.\n * Use this when you need to insert a pre-existing container.\n */\n insertContainer(index: number, container: Container): Container\n}\n\n/**\n * loro() return type for StructRef and RecordRef.\n * Provides container operations that take Loro containers.\n */\nexport interface LoroMapRef extends LoroRefBase {\n /** The underlying LoroMap */\n readonly container: LoroMap\n\n /**\n * Set a Loro container at the specified key.\n * Use this when you need to set a pre-existing container.\n */\n setContainer(key: string, container: Container): Container\n}\n\n/**\n * loro() return type for TextRef.\n */\nexport interface LoroTextRef extends LoroRefBase {\n /** The underlying LoroText */\n readonly container: LoroText\n}\n\n/**\n * loro() return type for CounterRef.\n */\nexport interface LoroCounterRef extends LoroRefBase {\n /** The underlying LoroCounter */\n readonly container: LoroCounter\n}\n\n/**\n * loro() return type for TreeRef.\n */\nexport interface LoroTreeRef extends LoroRefBase {\n /** The underlying LoroTree */\n readonly container: LoroTree\n}\n\n/**\n * loro() return type for TreeNodeRef.\n */\nexport interface LoroTreeNodeRef extends LoroRefBase {\n /** The underlying LoroTreeNode */\n readonly container: LoroTreeNode\n}\n\n/**\n * loro() return type for TypedDoc.\n * Provides access to doc-level operations.\n */\nexport interface LoroTypedDocRef extends LoroRefBase {\n /** The underlying LoroDoc (same as doc for TypedDoc) */\n readonly container: LoroDoc\n\n /**\n * Apply JSON Patch operations to the document.\n * @param patch - Array of JSON Patch operations (RFC 6902)\n * @param pathPrefix - Optional path prefix for scoped operations\n */\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void\n\n /** Access the document schema shape */\n readonly docShape: DocShape\n\n /** Get raw CRDT value without placeholder overlay */\n readonly rawValue: unknown\n}\n\n// ============================================================================\n// loro() function overloads\n// ============================================================================\n\n/**\n * Access CRDT internals for a ListRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: ListRef<NestedShape>,\n): LoroListRef\n\n/**\n * Access CRDT internals for a MovableListRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: MovableListRef<NestedShape>,\n): LoroListRef\n\n/**\n * Access CRDT internals for a StructRef.\n */\nexport function loro<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(ref: StructRef<NestedShapes>): LoroMapRef\n\n/**\n * Access CRDT internals for a RecordRef.\n */\nexport function loro<NestedShape extends ContainerShape>(\n ref: RecordRef<NestedShape>,\n): LoroMapRef\n\n/**\n * Access CRDT internals for a TextRef.\n */\nexport function loro(ref: TextRef): LoroTextRef\n\n/**\n * Access CRDT internals for a CounterRef.\n */\nexport function loro(ref: CounterRef): LoroCounterRef\n\n/**\n * Access CRDT internals for a TreeRef.\n */\nexport function loro<DataShape extends StructContainerShape>(\n ref: TreeRef<DataShape> | TreeRefInterface<DataShape>,\n): LoroTreeRef\n\n/**\n * Access CRDT internals for a TreeNodeRef.\n */\nexport function loro<DataShape extends StructContainerShape>(\n ref: TreeNodeRef<DataShape>,\n): LoroTreeNodeRef\n\n/**\n * Access CRDT internals for a TypedDoc.\n */\nexport function loro<Shape extends DocShape>(\n doc: TypedDoc<Shape>,\n): LoroTypedDocRef\n\n/**\n * Access CRDT internals for any TypedRef.\n */\nexport function loro<Shape extends ContainerShape>(\n ref: TypedRef<Shape>,\n): LoroRefBase\n\n/**\n * The `loro()` function - single escape hatch for CRDT internals.\n *\n * Use this to access:\n * - The underlying LoroDoc\n * - The underlying Loro container (correctly typed)\n * - Container-level subscriptions\n * - Container operations that take Loro containers (pushContainer, setContainer, etc.)\n *\n * @param refOrDoc - A TypedRef or TypedDoc\n * @returns An object with CRDT internals and operations\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\"\n *\n * // Access underlying LoroDoc\n * loro(doc.settings).doc\n *\n * // Access underlying Loro container\n * loro(doc.items).container // LoroList\n *\n * // Subscribe to changes\n * loro(doc.settings).subscribe(event => { ... })\n *\n * // Container operations\n * loro(doc.items).pushContainer(loroMap)\n * ```\n */\nexport function loro(\n refOrDoc:\n | TypedRef<any>\n | TypedDoc<any>\n | TreeRef<any>\n | TreeRefInterface<any>\n | TreeNodeRef<any>\n | StructRef<any>,\n): LoroRefBase {\n // Access the loro namespace via the well-known symbol\n const loroNamespace = (refOrDoc as any)[LORO_SYMBOL]\n if (!loroNamespace) {\n throw new Error(\n \"Invalid argument: expected TypedRef, TreeRef, or TypedDoc with loro() support\",\n )\n }\n return loroNamespace\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: fix later */\n\nimport {\n LoroDoc,\n type LoroEventBatch,\n type PeerID,\n type Subscription,\n} from \"loro-crdt\"\nimport { derivePlaceholder } from \"./derive-placeholder.js\"\nimport {\n type JsonPatch,\n JsonPatchApplicator,\n type JsonPatchOperation,\n normalizePath,\n} from \"./json-patch.js\"\nimport { LORO_SYMBOL, type LoroTypedDocRef } from \"./loro.js\"\nimport { overlayPlaceholder } from \"./overlay.js\"\nimport type { DocShape } from \"./shape.js\"\nimport { type DiffOverlay, INTERNAL_SYMBOL } from \"./typed-refs/base.js\"\nimport { DocRef } from \"./typed-refs/doc-ref.js\"\nimport type { Infer, InferPlaceholderType, Mutable } from \"./types.js\"\nimport { validatePlaceholder } from \"./validation.js\"\n\n/**\n * Internal TypedDoc implementation (not directly exposed to users).\n * Users interact with the proxied version that provides direct schema access.\n */\nclass TypedDocInternal<Shape extends DocShape> {\n private shape: Shape\n private placeholder: InferPlaceholderType<Shape>\n private doc: LoroDoc\n private overlay?: DiffOverlay\n private valueRef: DocRef<Shape> | null = null\n // Reference to the proxy for returning from change()\n proxy: TypedDoc<Shape> | null = null\n\n constructor(\n shape: Shape,\n doc: LoroDoc = new LoroDoc(),\n overlay?: DiffOverlay,\n ) {\n this.shape = shape\n this.placeholder = derivePlaceholder(shape)\n this.doc = doc\n this.overlay = overlay\n\n validatePlaceholder(this.placeholder, this.shape)\n }\n\n get value(): Mutable<Shape> {\n if (!this.valueRef) {\n this.valueRef = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: true,\n overlay: this.overlay,\n })\n }\n return this.valueRef as unknown as Mutable<Shape>\n }\n\n toJSON(): Infer<Shape> {\n const crdtValue = this.doc.toJSON()\n return overlayPlaceholder(\n this.shape,\n crdtValue,\n this.placeholder as any,\n ) as Infer<Shape>\n }\n\n change(fn: (draft: Mutable<Shape>) => void): void {\n const draft = new DocRef({\n shape: this.shape,\n placeholder: this.placeholder as any,\n doc: this.doc,\n autoCommit: false,\n batchedMutation: true, // Enable value shape caching for find-and-mutate patterns\n overlay: this.overlay,\n })\n fn(draft as unknown as Mutable<Shape>)\n draft[INTERNAL_SYMBOL].absorbPlainValues()\n this.doc.commit()\n\n // Invalidate cached value ref since doc changed\n this.valueRef = null\n }\n\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n this.change(draft => {\n const applicator = new JsonPatchApplicator(draft)\n\n const prefixedPatch = pathPrefix\n ? patch.map((op: JsonPatchOperation) => ({\n ...op,\n path: [...pathPrefix, ...normalizePath(op.path)],\n }))\n : patch\n\n applicator.applyPatch(prefixedPatch)\n })\n }\n\n get loroDoc(): LoroDoc {\n return this.doc\n }\n\n get docShape(): Shape {\n return this.shape\n }\n\n get rawValue(): any {\n return this.doc.toJSON()\n }\n}\n\n/**\n * The proxied TypedDoc type that provides direct schema access.\n * Schema properties are accessed directly on the doc object.\n *\n * @example\n * ```typescript\n * const doc = createTypedDoc(schema);\n *\n * // Direct schema access\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Serialize to JSON (works on doc and all refs)\n * const snapshot = doc.toJSON();\n * const users = doc.users.toJSON();\n *\n * // Batched mutations via change()\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Access CRDT internals via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc).doc; // LoroDoc\n * loro(doc).subscribe(callback);\n * ```\n */\n/**\n * Frontiers represent a specific version in the document's history.\n * Each frontier is an operation ID consisting of a peer ID and counter.\n */\nexport type Frontiers = { peer: PeerID; counter: number }[]\n\nexport type CreateTypedDocOptions = {\n doc?: LoroDoc\n overlay?: DiffOverlay\n}\n\nexport type TypedDoc<Shape extends DocShape> = Mutable<Shape> & {\n /**\n * The primary method of mutating typed documents.\n * Batches multiple mutations into a single transaction.\n * All changes commit together at the end.\n *\n * Use this for:\n * - Find-and-mutate operations (required due to JS limitations)\n * - Performance (fewer commits)\n * - Atomic undo (all changes = one undo step)\n *\n * Returns the doc for chaining.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n * ```\n */\n change(fn: (draft: Mutable<Shape>) => void): TypedDoc<Shape>\n\n /**\n * Returns the full plain JavaScript object representation of the document.\n * This is an O(N) operation that serializes the entire document.\n *\n * @example\n * ```typescript\n * const snapshot = doc.toJSON();\n * console.log(snapshot.count); // number\n * ```\n */\n toJSON(): Infer<Shape>\n\n /**\n * Creates a new TypedDoc at a specified version (frontiers).\n * The forked doc will only contain history before the specified frontiers.\n * The forked doc has a different PeerID from the original.\n *\n * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)`\n *\n * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`)\n * @returns A new TypedDoc with the same schema at the specified version\n *\n * @example\n * ```typescript\n * import { loro } from \"@loro-extended/change\";\n *\n * const doc = createTypedDoc(schema);\n * doc.title.update(\"Hello\");\n * const frontiers = loro(doc).doc.frontiers();\n * doc.title.update(\"World\");\n *\n * // Fork at the earlier version\n * const forkedDoc = doc.forkAt(frontiers);\n * console.log(forkedDoc.title.toString()); // \"Hello\"\n * console.log(doc.title.toString()); // \"World\"\n * ```\n */\n forkAt(frontiers: Frontiers): TypedDoc<Shape>\n}\n\n/**\n * Creates a new TypedDoc with the given schema.\n * Returns a proxied document where schema properties are accessed directly.\n *\n * @param shape - The document schema (with optional .placeholder() values)\n * @param options - Optional existing LoroDoc or diff overlay\n * @returns A proxied TypedDoc with direct schema access\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * title: Shape.text(),\n * count: Shape.counter(),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Direct mutations (auto-commit)\n * doc.count.increment(5);\n * doc.title.insert(0, \"Hello\");\n *\n * // Batched mutations via change()\n * doc.change(draft => {\n * draft.count.increment(10);\n * draft.title.update(\"World\");\n * });\n *\n * // Get plain JSON\n * const snapshot = doc.toJSON();\n *\n * // Access CRDT internals via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc).doc; // LoroDoc\n * loro(doc).subscribe(callback);\n * ```\n */\nexport function createTypedDoc<Shape extends DocShape>(\n shape: Shape,\n options: CreateTypedDocOptions = {},\n): TypedDoc<Shape> {\n const internal = new TypedDocInternal(\n shape,\n options.doc || new LoroDoc(),\n options.overlay,\n )\n\n // Create the loro() namespace for this doc\n const loroNamespace: LoroTypedDocRef = {\n get doc(): LoroDoc {\n return internal.loroDoc\n },\n get container(): LoroDoc {\n return internal.loroDoc\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return internal.loroDoc.subscribe(callback)\n },\n applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void {\n internal.applyPatch(patch, pathPrefix)\n },\n get docShape(): DocShape {\n return internal.docShape\n },\n get rawValue(): unknown {\n return internal.rawValue\n },\n }\n\n // Create the change() function that returns the proxy for chaining\n const changeFunction = (\n fn: (draft: Mutable<Shape>) => void,\n ): TypedDoc<Shape> => {\n internal.change(fn)\n return proxy\n }\n\n // Create the forkAt() function that returns a new TypedDoc at the specified version\n const forkAtFunction = (frontiers: Frontiers): TypedDoc<Shape> => {\n const forkedLoroDoc = internal.loroDoc.forkAt(frontiers)\n return createTypedDoc(internal.docShape, { doc: forkedLoroDoc })\n }\n\n // Create a proxy that delegates schema properties to the DocRef\n // and provides change() and forkAt() methods\n const proxy = new Proxy(internal.value as object, {\n get(target, prop, receiver) {\n // loro() access via well-known symbol\n if (prop === LORO_SYMBOL) {\n return loroNamespace\n }\n\n // change() method directly on doc\n if (prop === \"change\") {\n return changeFunction\n }\n\n // forkAt() method directly on doc\n if (prop === \"forkAt\") {\n return forkAtFunction\n }\n\n // toJSON() should always read fresh from the CRDT\n if (prop === \"toJSON\") {\n return () => internal.toJSON()\n }\n\n // Delegate to the DocRef (which is the target)\n return Reflect.get(target, prop, receiver)\n },\n\n set(target, prop, value, receiver) {\n // Don't allow setting change, forkAt, or LORO_SYMBOL\n if (prop === LORO_SYMBOL || prop === \"change\" || prop === \"forkAt\") {\n return false\n }\n\n // Delegate to the DocRef\n return Reflect.set(target, prop, value, receiver)\n },\n\n // Support 'in' operator\n has(target, prop) {\n if (prop === LORO_SYMBOL || prop === \"change\" || prop === \"forkAt\")\n return true\n return Reflect.has(target, prop)\n },\n\n // Support Object.keys() - filter out Symbol properties to allow proxies to be used\n // in place of plain objects. This prevents React's \"Object keys must be strings\" error.\n ownKeys(target) {\n return Reflect.ownKeys(target).filter(key => typeof key === \"string\")\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (prop === \"change\") {\n return {\n configurable: true,\n enumerable: false,\n value: changeFunction,\n }\n }\n if (prop === \"forkAt\") {\n return {\n configurable: true,\n enumerable: false,\n value: forkAtFunction,\n }\n }\n if (prop === LORO_SYMBOL) {\n return {\n configurable: true,\n enumerable: false,\n value: loroNamespace,\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n }) as TypedDoc<Shape>\n\n // Store reference to proxy for returning from change()\n internal.proxy = proxy\n\n return proxy\n}\n","/** biome-ignore-all lint/suspicious/noExplicitAny: JSON Patch values can be any type */\n\nimport type { DocShape } from \"./shape.js\"\nimport type { Draft } from \"./types.js\"\n\n// =============================================================================\n// JSON PATCH TYPES - Discriminated Union for Type Safety\n// =============================================================================\n\nexport type JsonPatchAddOperation = {\n op: \"add\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchRemoveOperation = {\n op: \"remove\"\n path: string | (string | number)[]\n}\n\nexport type JsonPatchReplaceOperation = {\n op: \"replace\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchMoveOperation = {\n op: \"move\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchCopyOperation = {\n op: \"copy\"\n path: string | (string | number)[]\n from: string | (string | number)[]\n}\n\nexport type JsonPatchTestOperation = {\n op: \"test\"\n path: string | (string | number)[]\n value: any\n}\n\nexport type JsonPatchOperation =\n | JsonPatchAddOperation\n | JsonPatchRemoveOperation\n | JsonPatchReplaceOperation\n | JsonPatchMoveOperation\n | JsonPatchCopyOperation\n | JsonPatchTestOperation\n\nexport type JsonPatch = JsonPatchOperation[]\n\n// =============================================================================\n// PATH NAVIGATION UTILITIES\n// =============================================================================\n\n/**\n * Normalize JSON Pointer string to path array\n * Handles RFC 6901 escaping: ~1 -> /, ~0 -> ~\n */\nexport function normalizePath(\n path: string | (string | number)[],\n): (string | number)[] {\n if (Array.isArray(path)) {\n return path\n }\n\n // Handle JSON Pointer format (RFC 6901)\n if (path.startsWith(\"/\")) {\n return path\n .slice(1) // Remove leading slash\n .split(\"/\")\n .map(segment => {\n // Handle JSON Pointer escaping\n const unescaped = segment.replace(/~1/g, \"/\").replace(/~0/g, \"~\")\n // Try to parse as number for array indices\n const asNumber = Number(unescaped)\n return Number.isInteger(asNumber) && asNumber >= 0\n ? asNumber\n : unescaped\n })\n }\n\n // Handle simple dot notation or single segment\n return path.split(\".\").map(segment => {\n const asNumber = Number(segment)\n return Number.isInteger(asNumber) && asNumber >= 0 ? asNumber : segment\n })\n}\n\n/**\n * Navigate to a target path using natural DraftNode property access\n * This follows the existing patterns from the test suite\n */\nfunction navigateToPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): { parent: any; key: string | number } {\n if (path.length === 0) {\n throw new Error(\"Cannot navigate to empty path\")\n }\n\n let current = draft as any\n\n // Navigate to parent of target\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]\n\n if (typeof segment === \"string\") {\n // Use natural property access - this leverages existing DraftNode lazy creation\n current = current[segment]\n if (current === undefined) {\n throw new Error(`Cannot navigate to path segment: ${segment}`)\n }\n } else if (typeof segment === \"number\") {\n // List/array access using get() method (following existing patterns)\n if (current.get && typeof current.get === \"function\") {\n current = current.get(segment)\n if (current === undefined) {\n throw new Error(`List index ${segment} does not exist`)\n }\n } else {\n throw new Error(`Cannot use numeric index ${segment} on non-list`)\n }\n } else {\n throw new Error(`Invalid path segment type: ${typeof segment}`)\n }\n }\n\n const targetKey = path[path.length - 1]\n return { parent: current, key: targetKey }\n}\n\n/**\n * Get value at path using natural DraftNode access patterns\n */\nfunction getValueAtPath<T extends DocShape>(\n draft: Draft<T>,\n path: (string | number)[],\n): any {\n if (path.length === 0) {\n return draft\n }\n\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Use natural property access or get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n return parent[key]\n } else if (typeof key === \"number\") {\n // List access using get() method\n if (parent.get && typeof parent.get === \"function\") {\n return parent.get(key)\n }\n throw new Error(`Cannot use numeric index ${key} on non-list`)\n }\n\n throw new Error(`Invalid key type: ${typeof key}`)\n}\n\n// =============================================================================\n// OPERATION HANDLERS - Following existing DraftNode patterns\n// =============================================================================\n\n/**\n * Handle 'add' operation using existing DraftNode methods\n */\nfunction handleAdd<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchAddOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use natural assignment or set() method\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n // Natural property assignment (follows existing test patterns)\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - use insert() method (follows existing patterns)\n if (parent.insert && typeof parent.insert === \"function\") {\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot insert at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'remove' operation using existing DraftNode methods\n */\nfunction handleRemove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchRemoveOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use delete() method (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key)\n } else {\n delete parent[key]\n }\n } else if (typeof key === \"number\") {\n // List operations - use delete() method with count (follows existing patterns)\n if (parent.delete && typeof parent.delete === \"function\") {\n parent.delete(key, 1)\n } else {\n throw new Error(`Cannot remove at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'replace' operation using existing DraftNode methods\n */\nfunction handleReplace<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchReplaceOperation,\n): void {\n const path = normalizePath(operation.path)\n const { parent, key } = navigateToPath(draft, path)\n\n if (typeof key === \"string\") {\n // Map-like operations - use set() method or natural assignment\n if (parent.set && typeof parent.set === \"function\") {\n parent.set(key, operation.value)\n } else {\n parent[key] = operation.value\n }\n } else if (typeof key === \"number\") {\n // List operations - delete then insert (follows existing patterns)\n if (\n parent.delete &&\n parent.insert &&\n typeof parent.delete === \"function\" &&\n typeof parent.insert === \"function\"\n ) {\n parent.delete(key, 1)\n parent.insert(key, operation.value)\n } else {\n throw new Error(`Cannot replace at numeric index ${key} on non-list`)\n }\n } else {\n throw new Error(`Invalid key type: ${typeof key}`)\n }\n}\n\n/**\n * Handle 'move' operation using existing DraftNode methods\n */\nfunction handleMove<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchMoveOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n const toPath = normalizePath(operation.path)\n\n // For list moves within the same parent, we need special handling\n if (\n fromPath.length === toPath.length &&\n fromPath.slice(0, -1).every((segment, i) => segment === toPath[i])\n ) {\n // Same parent container - use list move operation if available\n const fromIndex = fromPath[fromPath.length - 1]\n const toIndex = toPath[toPath.length - 1]\n\n if (typeof fromIndex === \"number\" && typeof toIndex === \"number\") {\n const { parent } = navigateToPath(draft, fromPath.slice(0, -1))\n\n // Check if the parent has a move method (like LoroMovableList)\n if (parent.move && typeof parent.move === \"function\") {\n parent.move(fromIndex, toIndex)\n return\n }\n\n // Otherwise, get value, remove, then add at target index\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n\n // For JSON Patch move semantics, the target index refers to the position\n // in the final array, not the intermediate array after removal.\n // No index adjustment needed - use the original target index.\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n return\n }\n }\n\n // Different parents or non-numeric indices - standard move\n const value = getValueAtPath(draft, fromPath)\n handleRemove(draft, { op: \"remove\", path: operation.from })\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'copy' operation using existing DraftNode methods\n */\nfunction handleCopy<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchCopyOperation,\n): void {\n const fromPath = normalizePath(operation.from)\n\n // Get the value to copy\n const value = getValueAtPath(draft, fromPath)\n\n // Add to destination (no removal)\n handleAdd(draft, { op: \"add\", path: operation.path, value })\n}\n\n/**\n * Handle 'test' operation using existing DraftNode value access\n */\nfunction handleTest<T extends DocShape>(\n draft: Draft<T>,\n operation: JsonPatchTestOperation,\n): boolean {\n const path = normalizePath(operation.path)\n const actualValue = getValueAtPath(draft, path)\n\n // Deep equality check for test operation\n return JSON.stringify(actualValue) === JSON.stringify(operation.value)\n}\n\n// =============================================================================\n// MAIN APPLICATOR - Simple orchestration following existing patterns\n// =============================================================================\n\n/**\n * Main JSON Patch applicator - follows existing change() patterns\n */\nexport class JsonPatchApplicator<T extends DocShape> {\n constructor(private rootDraft: Draft<T>) {}\n\n /**\n * Apply a single JSON Patch operation\n */\n applyOperation(operation: JsonPatchOperation): void {\n switch (operation.op) {\n case \"add\":\n handleAdd(this.rootDraft, operation)\n break\n case \"remove\":\n handleRemove(this.rootDraft, operation)\n break\n case \"replace\":\n handleReplace(this.rootDraft, operation)\n break\n case \"move\":\n handleMove(this.rootDraft, operation)\n break\n case \"copy\":\n handleCopy(this.rootDraft, operation)\n break\n case \"test\":\n if (!handleTest(this.rootDraft, operation)) {\n throw new Error(`JSON Patch test failed at path: ${operation.path}`)\n }\n break\n default:\n // TypeScript will catch this at compile time with proper discriminated union\n throw new Error(\n `Unsupported JSON Patch operation: ${(operation as any).op}`,\n )\n }\n }\n\n /**\n * Apply multiple JSON Patch operations in sequence\n */\n applyPatch(patch: JsonPatch): void {\n for (const operation of patch) {\n this.applyOperation(operation)\n }\n }\n}\n","import type {\n Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n LoroTreeNode,\n Value,\n} from \"loro-crdt\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n ValueShape,\n} from \"../shape.js\"\n\nexport { isContainer, isContainerId } from \"loro-crdt\"\n\n/**\n * Type guard to check if a container is a LoroCounter\n */\nexport function isLoroCounter(container: Container): container is LoroCounter {\n return container.kind() === \"Counter\"\n}\n\n/**\n * Type guard to check if a container is a LoroList\n */\nexport function isLoroList(container: Container): container is LoroList {\n return container.kind() === \"List\"\n}\n\n/**\n * Type guard to check if a container is a LoroMap\n */\nexport function isLoroMap(container: Container): container is LoroMap {\n return container.kind() === \"Map\"\n}\n\n/**\n * Type guard to check if a container is a LoroMovableList\n */\nexport function isLoroMovableList(\n container: Container,\n): container is LoroMovableList {\n return container.kind() === \"MovableList\"\n}\n\n/**\n * Type guard to check if a container is a LoroText\n */\nexport function isLoroText(container: Container): container is LoroText {\n return container.kind() === \"Text\"\n}\n\n/**\n * Type guard to check if a container is a LoroTree\n */\nexport function isLoroTree(container: Container): container is LoroTree {\n return container.kind() === \"Tree\"\n}\n\n/**\n * Type guard to check if an object is a LoroTreeNode\n * Note: LoroTreeNode is not a Container, so we check for its specific properties\n */\nexport function isLoroTreeNode(obj: any): obj is LoroTreeNode {\n return (\n obj &&\n typeof obj === \"object\" &&\n typeof obj.id === \"string\" &&\n typeof obj.data === \"object\" &&\n typeof obj.parent === \"function\" &&\n typeof obj.children === \"function\" &&\n typeof obj.createNode === \"function\"\n )\n}\n\n/**\n * Type guard to ensure cached container matches expected type using kind() method\n */\nexport function assertContainerType<T extends Container>(\n cached: Container,\n expected: T,\n context: string = \"container operation\",\n): asserts cached is T {\n if (cached.kind() !== expected.kind()) {\n throw new Error(\n `Type safety violation in ${context}: ` +\n `cached container kind '${cached.kind()}' does not match ` +\n `expected kind '${expected.kind()}'`,\n )\n }\n\n // Additional safety check: ensure IDs match\n if (cached.id !== expected.id) {\n throw new Error(\n `Container ID mismatch in ${context}: ` +\n `cached ID '${cached.id}' does not match expected ID '${expected.id}'`,\n )\n }\n}\n\n/**\n * Type guard to check if a schema is for TextDraftNode\n */\nexport function isTextShape(\n schema: ContainerOrValueShape,\n): schema is TextContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"text\"\n}\n\n/**\n * Type guard to check if a schema is for CounterDraftNode\n */\nexport function isCounterShape(\n schema: ContainerOrValueShape,\n): schema is CounterContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"counter\"\n}\n\n/**\n * Type guard to check if a schema is for ListDraftNode\n */\nexport function isListShape(\n schema: ContainerOrValueShape,\n): schema is ListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"list\"\n}\n\n/**\n * Type guard to check if a schema is for MovableListDraftNode\n */\nexport function isMovableListShape(\n schema: ContainerOrValueShape,\n): schema is MovableListContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"movableList\"\n}\n\n/**\n * Type guard to check if a schema is for StructDraftNode\n */\nexport function isStructShape(\n schema: ContainerOrValueShape,\n): schema is StructContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"struct\"\n}\n\n/**\n * @deprecated Use isStructShape instead. isMapShape is an alias for backward compatibility.\n */\nexport const isMapShape = isStructShape\n\n/**\n * Type guard to check if a schema is for RecordDraftNode\n */\nexport function isRecordShape(\n schema: ContainerOrValueShape,\n): schema is RecordContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"record\"\n}\n\n/**\n * Type guard to check if a schema is for TreeDraftNode\n */\nexport function isTreeShape(\n schema: ContainerOrValueShape,\n): schema is TreeContainerShape {\n return schema && typeof schema === \"object\" && schema._type === \"tree\"\n}\n\nexport function isContainerShape(\n schema: ContainerOrValueShape,\n): schema is ContainerShape {\n return schema._type && schema._type !== \"value\"\n}\n\n/**\n * Type guard to check if a schema is any of the Value shapes\n */\nexport function isValueShape(\n schema: ContainerOrValueShape,\n): schema is ValueShape {\n return (\n schema._type === \"value\" &&\n [\n \"string\",\n \"number\",\n \"boolean\",\n \"null\",\n \"undefined\",\n \"uint8array\",\n \"struct\",\n \"record\",\n \"array\",\n \"union\",\n \"discriminatedUnion\",\n \"any\",\n ].includes(schema.valueType)\n )\n}\n\nexport function isObjectValue(value: Value): value is { [key: string]: Value } {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n !(value instanceof Uint8Array)\n )\n}\n","import type { TreeID, Value } from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"./derive-placeholder.js\"\nimport type {\n ContainerShape,\n DiscriminatedUnionValueShape,\n DocShape,\n StructContainerShape,\n TreeContainerShape,\n TreeNodeJSON,\n ValueShape,\n} from \"./shape.js\"\nimport { isObjectValue } from \"./utils/type-guards.js\"\n\n/**\n * Overlays CRDT state with placeholder defaults\n */\nexport function overlayPlaceholder<Shape extends DocShape>(\n shape: Shape,\n crdtValue: { [key: string]: Value },\n placeholderValue: { [key: string]: Value },\n): { [key: string]: Value } {\n if (typeof crdtValue !== \"object\") {\n throw new Error(\"crdt object is required\")\n }\n\n if (typeof placeholderValue !== \"object\") {\n throw new Error(\"placeholder object is required\")\n }\n\n const result = { ...placeholderValue }\n\n for (const [key, propShape] of Object.entries(shape.shapes)) {\n const propCrdtValue = crdtValue[key]\n\n const propPlaceholderValue =\n placeholderValue[key as keyof typeof placeholderValue]\n\n result[key as keyof typeof result] = mergeValue(\n propShape,\n propCrdtValue,\n propPlaceholderValue,\n )\n }\n\n return result\n}\n\n/**\n * Merges individual CRDT values with placeholder defaults\n */\nexport function mergeValue<Shape extends ContainerShape | ValueShape>(\n shape: Shape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n // For \"any\" shapes, just return the CRDT value as-is (no placeholder merging)\n if (shape._type === \"any\") {\n return crdtValue\n }\n\n // For \"any\" value shapes, just return the CRDT value as-is\n if (shape._type === \"value\" && (shape as any).valueType === \"any\") {\n return crdtValue\n }\n\n if (crdtValue === undefined && placeholderValue === undefined) {\n throw new Error(\"either crdt or placeholder value must be defined\")\n }\n\n switch (shape._type) {\n case \"text\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? \"\")\n case \"counter\":\n return crdtValue !== undefined ? crdtValue : (placeholderValue ?? 0)\n case \"list\":\n case \"movableList\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n\n const crdtArray = crdtValue as Value[]\n const itemShape = shape.shape\n const itemPlaceholder = deriveShapePlaceholder(itemShape)\n\n return crdtArray.map(item =>\n mergeValue(itemShape, item, itemPlaceholder as Value),\n )\n }\n case \"struct\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"struct crdt must be object\")\n }\n\n const crdtStructValue = crdtValue ?? {}\n\n if (!isObjectValue(placeholderValue) && placeholderValue !== undefined) {\n throw new Error(\"struct placeholder must be object\")\n }\n\n const placeholderStructValue = placeholderValue ?? {}\n\n const result = { ...placeholderStructValue }\n for (const [key, nestedShape] of Object.entries(shape.shapes)) {\n const nestedCrdtValue = crdtStructValue[key]\n const nestedPlaceholderValue = placeholderStructValue[key]\n\n result[key as keyof typeof result] = mergeValue(\n nestedShape,\n nestedCrdtValue,\n nestedPlaceholderValue,\n )\n }\n\n return result\n }\n case \"tree\": {\n if (crdtValue === undefined) {\n return placeholderValue ?? []\n }\n // Transform Loro's native tree format to our typed format\n const treeShape = shape as TreeContainerShape\n return transformTreeNodes(crdtValue as any[], treeShape.shape) as any\n }\n case \"record\": {\n if (!isObjectValue(crdtValue) && crdtValue !== undefined) {\n throw new Error(\"record crdt must be object\")\n }\n\n const crdtRecordValue = (crdtValue as Record<string, Value>) ?? {}\n const result: Record<string, Value> = {}\n\n // For records, we iterate over the keys present in the CRDT value\n // and apply the nested shape's placeholder logic to each value\n for (const key of Object.keys(crdtRecordValue)) {\n const nestedCrdtValue = crdtRecordValue[key]\n // For records, the placeholder is always {}, so we need to derive\n // the placeholder for the nested shape on the fly\n const nestedPlaceholderValue = deriveShapePlaceholder(shape.shape)\n\n result[key] = mergeValue(\n shape.shape,\n nestedCrdtValue,\n nestedPlaceholderValue as Value,\n )\n }\n\n return result\n }\n default:\n if (shape._type === \"value\" && shape.valueType === \"struct\") {\n const crdtObj = (crdtValue as any) ?? {}\n const placeholderObj = (placeholderValue as any) ?? {}\n const result = { ...placeholderObj }\n\n if (typeof crdtObj !== \"object\" || crdtObj === null) {\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n for (const [key, propShape] of Object.entries(shape.shape)) {\n const propCrdt = crdtObj[key]\n const propPlaceholder = placeholderObj[key]\n result[key] = mergeValue(propShape, propCrdt, propPlaceholder)\n }\n return result\n }\n\n // Handle discriminated unions\n if (shape._type === \"value\" && shape.valueType === \"discriminatedUnion\") {\n return mergeDiscriminatedUnion(\n shape as DiscriminatedUnionValueShape,\n crdtValue,\n placeholderValue,\n )\n }\n\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n}\n\n/**\n * Merges a discriminated union value by determining the variant from the discriminant key.\n * Uses the placeholderValue's discriminant to determine the default variant when the discriminant is missing.\n */\nfunction mergeDiscriminatedUnion(\n shape: DiscriminatedUnionValueShape,\n crdtValue: Value,\n placeholderValue: Value,\n): Value {\n const crdtObj = (crdtValue as Record<string, Value>) ?? {}\n const placeholderObj = (placeholderValue as Record<string, Value>) ?? {}\n\n // Get the discriminant value from CRDT, falling back to placeholder\n const discriminantValue =\n crdtObj[shape.discriminantKey] ?? placeholderObj[shape.discriminantKey]\n\n if (typeof discriminantValue !== \"string\") {\n // If no valid discriminant, return the placeholder\n return placeholderValue\n }\n\n // Find the variant shape for this discriminant value\n const variantShape = shape.variants[discriminantValue]\n\n if (!variantShape) {\n // Unknown variant - return CRDT value or placeholder\n return crdtValue !== undefined ? crdtValue : placeholderValue\n }\n\n // Merge using the variant's object shape\n // If the placeholder's discriminant doesn't match the current discriminant,\n // we shouldn't use the placeholder for merging as it belongs to a different variant.\n const placeholderDiscriminant = placeholderObj[shape.discriminantKey]\n const effectivePlaceholderValue =\n placeholderDiscriminant === discriminantValue ? placeholderValue : undefined\n\n return mergeValue(variantShape, crdtValue, effectivePlaceholderValue as Value)\n}\n\n/**\n * Loro's native tree node format from toJSON()\n */\ninterface LoroTreeNodeJSON {\n id: string\n parent: string | null\n index: number\n fractional_index: string\n meta: Record<string, Value>\n children: LoroTreeNodeJSON[]\n}\n\n/**\n * Transforms Loro's native tree format to our typed TreeNodeJSON format.\n * - Renames `meta` to `data`\n * - Renames `fractional_index` to `fractionalIndex`\n * - Applies placeholder merging to node data\n */\nfunction transformTreeNodes<DataShape extends StructContainerShape>(\n nodes: LoroTreeNodeJSON[],\n dataShape: DataShape,\n): TreeNodeJSON<DataShape>[] {\n const dataPlaceholder = deriveShapePlaceholder(dataShape) as Value\n\n return nodes.map(node => transformTreeNode(node, dataShape, dataPlaceholder))\n}\n\n/**\n * Transforms a single tree node and its children recursively.\n */\nfunction transformTreeNode<DataShape extends StructContainerShape>(\n node: LoroTreeNodeJSON,\n dataShape: DataShape,\n dataPlaceholder: Value,\n): TreeNodeJSON<DataShape> {\n // Merge the node's meta (data) with the placeholder\n const mergedData = mergeValue(dataShape, node.meta, dataPlaceholder)\n\n return {\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index,\n fractionalIndex: node.fractional_index,\n data: mergedData as DataShape[\"_plain\"],\n children: node.children.map(child =>\n transformTreeNode(child, dataShape, dataPlaceholder),\n ),\n }\n}\n","import type {\n ContainerID,\n Diff,\n LoroDoc,\n LoroEventBatch,\n Subscription,\n} from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroRefBase } from \"../loro.js\"\nimport type { ContainerShape, DocShape, ShapeToContainer } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\n\n/**\n * Symbol for internal methods that should not be enumerable or accessible to users.\n * Used to hide implementation details like absorbPlainValues(), getTypedRefParams(), etc.\n *\n * This achieves Success Criteria #7 from loro-api-refactor.md:\n * \"Internal methods hidden - Via Symbol, not enumerable\"\n */\nexport const INTERNAL_SYMBOL = Symbol.for(\"loro-extended:internal\")\n\n// ============================================================================\n// Minimal Interface for absorbPlainValues contract\n// ============================================================================\n\n/**\n * Minimal interface for refs that only need absorbPlainValues.\n * Used by TreeNodeRef which doesn't extend TypedRef.\n */\nexport interface RefInternalsBase {\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void\n /** Force materialization of the container and its nested containers */\n materialize(): void\n}\n\n// ============================================================================\n// TypedRefParams and TypedRef Base Class\n// ============================================================================\n\nexport type DiffOverlay = ReadonlyMap<ContainerID, Diff>\n\nexport type TypedRefParams<Shape extends DocShape | ContainerShape> = {\n shape: Shape\n placeholder?: Infer<Shape>\n getContainer: () => ShapeToContainer<Shape>\n autoCommit?: boolean // Auto-commit after mutations\n batchedMutation?: boolean // True when inside change() block - enables value shape caching for find-and-mutate patterns\n getDoc: () => LoroDoc // Needed for auto-commit\n overlay?: DiffOverlay // Optional reverse diff overlay for \"before\" reads\n}\n\n// ============================================================================\n// BaseRefInternals - Abstract base class for all internal implementations\n// ============================================================================\n\n/**\n * Abstract base class for all ref internal implementations.\n * Contains shared logic that was previously in TypedRef.createBaseInternals().\n *\n * Subclasses implement specific behavior for each ref type.\n */\nexport abstract class BaseRefInternals<Shape extends DocShape | ContainerShape>\n implements RefInternalsBase\n{\n protected cachedContainer: ShapeToContainer<Shape> | undefined\n protected loroNamespace: LoroRefBase | undefined\n private _suppressAutoCommit = false\n\n constructor(protected readonly params: TypedRefParams<Shape>) {}\n\n /** Get the underlying Loro container (cached) */\n getContainer(): ShapeToContainer<Shape> {\n if (!this.cachedContainer) {\n this.cachedContainer = this.params.getContainer()\n }\n return this.cachedContainer\n }\n\n /** Commit changes if autoCommit is enabled and not suppressed */\n commitIfAuto(): void {\n if (this.params.autoCommit && !this._suppressAutoCommit) {\n this.params.getDoc().commit()\n }\n }\n\n /**\n * Temporarily suppress auto-commit during batch operations.\n * Used by assignPlainValueToTypedRef() to batch multiple property assignments.\n */\n setSuppressAutoCommit(suppress: boolean): void {\n this._suppressAutoCommit = suppress\n }\n\n /** Check if auto-commit is currently suppressed */\n isSuppressAutoCommit(): boolean {\n return this._suppressAutoCommit\n }\n\n /** Get the shape for this ref */\n getShape(): Shape {\n return this.params.shape\n }\n\n /** Get the placeholder value */\n getPlaceholder(): Infer<Shape> | undefined {\n return this.params.placeholder\n }\n\n /** Check if autoCommit is enabled */\n getAutoCommit(): boolean {\n return !!this.params.autoCommit\n }\n\n /** Check if in batched mutation mode */\n getBatchedMutation(): boolean {\n return !!this.params.batchedMutation\n }\n\n /** Get the LoroDoc */\n getDoc(): LoroDoc {\n return this.params.getDoc()\n }\n\n /** Get the diff overlay map (if provided) */\n getOverlay(): DiffOverlay | undefined {\n return this.params.overlay\n }\n\n /**\n * Get the TypedRefParams needed to recreate this ref.\n * Used by change() to create draft refs with modified params.\n *\n * Returns a new params object with the same shape, placeholder, getContainer, and getDoc,\n * but allows overriding autoCommit and batchedMutation for draft creation.\n */\n getTypedRefParams(): TypedRefParams<Shape> {\n return {\n shape: this.params.shape,\n placeholder: this.params.placeholder,\n getContainer: this.params.getContainer,\n autoCommit: this.params.autoCommit,\n batchedMutation: this.params.batchedMutation,\n getDoc: this.params.getDoc,\n overlay: this.params.overlay,\n }\n }\n\n /** Get the loro namespace (cached) */\n getLoroNamespace(): LoroRefBase {\n if (!this.loroNamespace) {\n this.loroNamespace = this.createLoroNamespace()\n }\n return this.loroNamespace\n }\n\n /** Absorb mutated plain values back into Loro containers - subclasses override */\n abstract absorbPlainValues(): void\n\n /** Force materialization of the container and its nested containers */\n materialize(): void {\n this.getContainer()\n }\n\n /** Create the loro() namespace object - subclasses override for specific types */\n protected createLoroNamespace(): LoroRefBase {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.params.getDoc()\n },\n get container(): unknown {\n return self.getContainer()\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as any).subscribe(callback)\n },\n }\n }\n}\n\n/**\n * Base class for all typed refs.\n *\n * All internal methods are accessed via [INTERNAL_SYMBOL] to prevent\n * namespace collisions with user data properties.\n *\n * Uses the Facade + Implementation pattern:\n * - TypedRef is the thin public facade\n * - BaseRefInternals subclasses contain all implementation logic\n */\nexport abstract class TypedRef<Shape extends DocShape | ContainerShape> {\n /**\n * Internal implementation accessed via Symbol.\n * Subclasses must set this to their specific internals class instance.\n */\n abstract [INTERNAL_SYMBOL]: BaseRefInternals<Shape>\n\n /**\n * Serializes the ref to a plain JSON-compatible value.\n * Returns the plain type inferred from the shape.\n */\n abstract toJSON(): Infer<Shape>\n\n /**\n * Access the loro() namespace via the well-known symbol.\n * This is used by the loro() function to access CRDT internals.\n */\n get [LORO_SYMBOL](): LoroRefBase {\n return this[INTERNAL_SYMBOL].getLoroNamespace()\n }\n}\n","import {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ContainerShape,\n CounterContainerShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n StructContainerShape,\n TextContainerShape,\n TreeContainerShape,\n} from \"../shape.js\"\nimport { INTERNAL_SYMBOL, type TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRef } from \"./counter-ref.js\"\nimport { ListRef } from \"./list-ref.js\"\nimport { MovableListRef } from \"./movable-list-ref.js\"\nimport {\n listProxyHandler,\n movableListProxyHandler,\n recordProxyHandler,\n} from \"./proxy-handlers.js\"\nimport { RecordRef } from \"./record-ref.js\"\nimport { createStructRef } from \"./struct-ref.js\"\nimport { TextRef } from \"./text-ref.js\"\nimport { TreeRef } from \"./tree-ref.js\"\n\n/**\n * Mapping from container shape types to their Loro constructor classes.\n * Used when creating new containers via getOrCreateContainer().\n *\n * Note: \"any\" is not included because AnyContainerShape is an escape hatch\n * that doesn't create typed refs - it returns raw Loro containers.\n */\nexport const containerConstructor = {\n counter: LoroCounter,\n list: LoroList,\n movableList: LoroMovableList,\n record: LoroMap, // Records use LoroMap as their underlying container\n struct: LoroMap, // Structs use LoroMap as their underlying container\n text: LoroText,\n tree: LoroTree,\n} as const\n\n/**\n * Type guard to check if a container shape type has a constructor.\n * Returns false for \"any\" which is an escape hatch.\n */\nexport function hasContainerConstructor(\n type: string,\n): type is keyof typeof containerConstructor {\n return type in containerConstructor\n}\n\n/**\n * Unwraps a TypedRef to its primitive value for readonly access.\n * Counter refs return their numeric value, Text refs return their string.\n * Other container types are returned as-is.\n */\nexport function unwrapReadonlyPrimitive(\n ref: TypedRef<any>,\n shape: ContainerShape,\n): any {\n if (shape._type === \"counter\") {\n return (ref as any).value\n }\n if (shape._type === \"text\") {\n return (ref as any).toString()\n }\n return ref\n}\n\n/**\n * Type guard to check if a value has internal methods via INTERNAL_SYMBOL.\n */\nfunction hasInternalSymbol(\n value: unknown,\n): value is { [INTERNAL_SYMBOL]: { absorbPlainValues(): void } } {\n return value !== null && typeof value === \"object\" && INTERNAL_SYMBOL in value\n}\n\n/**\n * Absorbs cached plain values back into a LoroMap container.\n * For TypedRef entries (or any object with INTERNAL_SYMBOL), recursively calls absorbPlainValues().\n * For plain Value entries, sets them directly on the container.\n */\nexport function absorbCachedPlainValues(\n cache: Map<string, TypedRef<ContainerShape> | Value>,\n getContainer: () => LoroMap,\n): void {\n let container: LoroMap | undefined\n\n for (const [key, ref] of cache.entries()) {\n if (hasInternalSymbol(ref)) {\n // Contains a TypedRef or TreeRef, not a plain Value: keep recursing\n ref[INTERNAL_SYMBOL].absorbPlainValues()\n } else {\n // Plain value!\n if (!container) container = getContainer()\n container.set(key, ref)\n }\n }\n}\n\n/**\n * Serializes a TypedRef to JSON by iterating over its keys.\n * For nested TypedRefs with toJSON(), calls their toJSON method.\n * For plain values, includes them directly.\n */\nexport function serializeRefToJSON(\n ref: Record<string, any>,\n keys: Iterable<string>,\n): Record<string, any> {\n const result: Record<string, any> = {}\n for (const key of keys) {\n const value = ref[key]\n if (value && typeof value === \"object\" && \"toJSON\" in value) {\n result[key] = value.toJSON()\n } else {\n result[key] = value\n }\n }\n return result\n}\n\n// Generic catch-all overload\nexport function createContainerTypedRef<T extends ContainerShape>(\n params: TypedRefParams<T>,\n): TypedRef<T>\n\n// Implementation\nexport function createContainerTypedRef(\n params: TypedRefParams<ContainerShape>,\n): TypedRef<ContainerShape> | TreeRef<StructContainerShape> {\n switch (params.shape._type) {\n case \"counter\":\n return new CounterRef(params as TypedRefParams<CounterContainerShape>)\n case \"list\":\n return new Proxy(\n new ListRef(params as TypedRefParams<ListContainerShape>),\n listProxyHandler,\n )\n case \"struct\":\n return createStructRef(\n params as TypedRefParams<StructContainerShape>,\n ) as unknown as TypedRef<ContainerShape>\n case \"movableList\":\n return new Proxy(\n new MovableListRef(params as TypedRefParams<MovableListContainerShape>),\n movableListProxyHandler,\n )\n case \"record\":\n return new Proxy(\n new RecordRef(params as TypedRefParams<RecordContainerShape>),\n recordProxyHandler,\n )\n case \"text\":\n return new TextRef(params as TypedRefParams<TextContainerShape>)\n case \"tree\": {\n const treeShape = params.shape as TreeContainerShape\n return new TreeRef({\n shape: treeShape,\n placeholder: params.placeholder as never[],\n getContainer: params.getContainer as () => LoroTree,\n autoCommit: params.autoCommit,\n getDoc: params.getDoc,\n })\n }\n default:\n throw new Error(\n `Unknown container type: ${(params.shape as ContainerShape)._type}`,\n )\n }\n}\n\n/**\n * Assigns a plain JavaScript value to a TypedRef.\n *\n * For struct/record types, this batches all property assignments and only\n * commits once at the end to avoid multiple subscription notifications.\n *\n * @param ref - The TypedRef to assign to\n * @param value - The plain value to assign\n * @param skipCommit - If true, skip the final commit (caller will handle it)\n * @returns true if assignment was successful, false otherwise\n */\nexport function assignPlainValueToTypedRef(\n ref: TypedRef<any>,\n value: any,\n skipCommit = false,\n): boolean {\n // Access internals via INTERNAL_SYMBOL\n const internals = ref[INTERNAL_SYMBOL]\n\n // Force materialization of the container\n if (internals) {\n internals.materialize()\n }\n\n const shape = internals?.getShape?.() ?? (ref as any).shape\n const shapeType = shape?._type\n\n if (shapeType === \"struct\" || shapeType === \"record\") {\n // Suppress auto-commit during batch assignment to avoid multiple notifications\n const wasSuppressed = internals?.isSuppressAutoCommit?.() ?? false\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(true)\n }\n\n try {\n for (const k in value) {\n ;(ref as any)[k] = value[k]\n }\n } finally {\n // Restore auto-commit state\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all properties are assigned (unless skipCommit is true)\n if (!skipCommit && internals?.getAutoCommit?.()) {\n internals.getDoc().commit()\n }\n\n return true\n }\n\n if (shapeType === \"list\" || shapeType === \"movableList\") {\n if (Array.isArray(value)) {\n const listRef = ref as any\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = internals?.isSuppressAutoCommit?.() ?? false\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(true)\n }\n\n try {\n if (listRef.length > 0) {\n listRef.delete(0, listRef.length)\n }\n for (const item of value) {\n listRef.push(item)\n }\n } finally {\n if (internals && !wasSuppressed) {\n internals.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all items are added (unless skipCommit is true)\n if (!skipCommit && internals?.getAutoCommit?.()) {\n internals.getDoc().commit()\n }\n\n return true\n }\n }\n\n if (shapeType === \"text\") {\n if (typeof value === \"string\") {\n ;(ref as any).update(value)\n return true\n }\n return false\n }\n\n if (shapeType === \"counter\") {\n if (typeof value === \"number\") {\n const currentValue = (ref as any).value\n const diff = value - currentValue\n if (diff > 0) {\n ;(ref as any).increment(diff)\n } else if (diff < 0) {\n ;(ref as any).decrement(-diff)\n }\n return true\n }\n return false\n }\n\n return false\n}\n","import type {\n CounterDiff,\n LoroCounter,\n LoroDoc,\n LoroEventBatch,\n Subscription,\n} from \"loro-crdt\"\nimport type { LoroCounterRef } from \"../loro.js\"\nimport type { CounterContainerShape } from \"../shape.js\"\nimport { BaseRefInternals } from \"./base.js\"\n\n/**\n * Internal implementation for CounterRef.\n * Contains all logic, state, and implementation details.\n */\nexport class CounterRefInternals extends BaseRefInternals<CounterContainerShape> {\n private materialized = false\n\n /** Increment the counter value */\n increment(value: number = 1): void {\n this.materialized = true\n ;(this.getContainer() as LoroCounter).increment(value)\n this.commitIfAuto()\n }\n\n /** Decrement the counter value */\n decrement(value: number = 1): void {\n this.materialized = true\n ;(this.getContainer() as LoroCounter).decrement(value)\n this.commitIfAuto()\n }\n\n /** Get the current counter value */\n getValue(): number {\n const container = this.getContainer() as LoroCounter\n const containerValue = container.value\n const overlay = this.getOverlay()\n if (overlay) {\n const diff = overlay.get((container as any).id)\n if (diff && diff.type === \"counter\") {\n const counterDiff = diff as CounterDiff\n return containerValue + counterDiff.increment\n }\n }\n if (containerValue !== 0 || this.materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n const placeholder = this.getPlaceholder()\n if (placeholder !== undefined) {\n return placeholder as number\n }\n return containerValue\n }\n\n /** No plain values in counter */\n absorbPlainValues(): void {\n // no plain values contained within\n }\n\n /** Create the loro namespace for counter */\n protected override createLoroNamespace(): LoroCounterRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroCounter {\n return self.getContainer() as LoroCounter\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroCounter).subscribe(callback)\n },\n }\n }\n}\n","import type { CounterContainerShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { CounterRefInternals } from \"./counter-ref-internals.js\"\n\n/**\n * Counter typed ref - thin facade that delegates to CounterRefInternals.\n */\nexport class CounterRef extends TypedRef<CounterContainerShape> {\n [INTERNAL_SYMBOL]: CounterRefInternals\n\n constructor(params: TypedRefParams<CounterContainerShape>) {\n super()\n this[INTERNAL_SYMBOL] = new CounterRefInternals(params)\n }\n\n /** Increment the counter by the given value (default 1) */\n increment(value?: number): void {\n this[INTERNAL_SYMBOL].increment(value)\n }\n\n /** Decrement the counter by the given value (default 1) */\n decrement(value?: number): void {\n this[INTERNAL_SYMBOL].decrement(value)\n }\n\n /** Get the current counter value */\n get value(): number {\n return this[INTERNAL_SYMBOL].getValue()\n }\n\n valueOf(): number {\n return this.value\n }\n\n toJSON(): number {\n return this.value\n }\n\n [Symbol.toPrimitive](hint: string): number | string {\n if (hint === \"string\") {\n return String(this.value)\n }\n return this.value\n }\n}\n","import {\n type Container,\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n type Value,\n} from \"loro-crdt\"\nimport type {\n ArrayValueShape,\n ContainerOrValueShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StructContainerShape,\n StructValueShape,\n} from \"./shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isObjectValue,\n isValueShape,\n} from \"./utils/type-guards.js\"\n\n/**\n * Converts string input to LoroText container\n */\nfunction convertTextInput(value: string): LoroText {\n const text = new LoroText()\n\n text.insert(0, value)\n\n return text\n}\n\n/**\n * Converts number input to LoroCounter container\n */\nfunction convertCounterInput(value: number): LoroCounter {\n const counter = new LoroCounter()\n counter.increment(value)\n return counter\n}\n\n/**\n * Converts array input to LoroList container\n */\nfunction convertListInput(\n value: Value[],\n shape: ListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts array input to LoroMovableList container\n */\nfunction convertMovableListInput(\n value: Value[],\n shape: MovableListContainerShape | ArrayValueShape,\n // parentPath: string[],\n): LoroMovableList | Value[] {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const list = new LoroMovableList()\n\n for (const item of value) {\n const convertedItem = convertInputToRef(item, shape.shape)\n if (isContainer(convertedItem)) {\n list.pushContainer(convertedItem)\n } else {\n list.push(convertedItem)\n }\n }\n\n return list\n}\n\n/**\n * Converts object input to LoroMap container (Struct)\n */\nfunction convertStructInput(\n value: { [key: string]: Value },\n shape: StructContainerShape | StructValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n\n // Iterate over schema keys to ensure all nested containers are materialized\n for (const k of Object.keys(shape.shapes)) {\n const nestedSchema = shape.shapes[k]\n const v = value[k]\n\n if (v !== undefined) {\n const convertedValue = convertInputToRef(v, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n } else if (isContainerShape(nestedSchema)) {\n // If value is missing but it's a container shape, create an empty container\n // This ensures deterministic container IDs across peers\n let emptyValue: any\n if (nestedSchema._type === \"struct\" || nestedSchema._type === \"record\") {\n emptyValue = {}\n } else if (\n nestedSchema._type === \"list\" ||\n nestedSchema._type === \"movableList\"\n ) {\n emptyValue = []\n } else if (nestedSchema._type === \"text\") {\n emptyValue = \"\"\n } else if (nestedSchema._type === \"counter\") {\n emptyValue = 0\n }\n\n if (emptyValue !== undefined) {\n const convertedValue = convertInputToRef(emptyValue, nestedSchema)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n }\n }\n }\n }\n\n // Also handle keys present in value but not in schema (if any, though for structs this shouldn't happen ideally)\n // But for backward compatibility or loose typing, we might want to preserve them?\n // The original code did:\n // if (nestedSchema) { ... } else { map.set(k, value) }\n // So it allowed extra keys.\n for (const [k, v] of Object.entries(value)) {\n if (!shape.shapes[k]) {\n map.set(k, v)\n }\n }\n\n return map\n}\n\n/**\n * Converts object input to LoroMap container (Record)\n */\nfunction convertRecordInput(\n value: { [key: string]: Value },\n shape: RecordContainerShape | RecordValueShape,\n): LoroMap | { [key: string]: Value } {\n if (!isContainerShape(shape)) {\n return value\n }\n\n const map = new LoroMap()\n for (const [k, v] of Object.entries(value)) {\n const convertedValue = convertInputToRef(v, shape.shape)\n if (isContainer(convertedValue)) {\n map.setContainer(k, convertedValue)\n } else {\n map.set(k, convertedValue)\n }\n }\n\n return map\n}\n\n/**\n * Main conversion function that transforms input values to appropriate CRDT containers\n * based on schema definitions\n */\nexport function convertInputToRef<Shape extends ContainerOrValueShape>(\n value: Value,\n shape: Shape,\n): Container | Value {\n switch (shape._type) {\n case \"text\": {\n if (typeof value !== \"string\") {\n throw new Error(\"string expected\")\n }\n\n return convertTextInput(value)\n }\n case \"counter\": {\n if (typeof value !== \"number\") {\n throw new Error(\"number expected\")\n }\n\n return convertCounterInput(value)\n }\n case \"list\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertListInput(value, shape)\n }\n case \"movableList\": {\n if (!Array.isArray(value)) {\n throw new Error(\"array expected\")\n }\n\n return convertMovableListInput(value, shape)\n }\n case \"struct\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertStructInput(value, shape)\n }\n case \"record\": {\n if (!isObjectValue(value)) {\n throw new Error(\"object expected\")\n }\n\n return convertRecordInput(value, shape)\n }\n case \"value\": {\n if (!isValueShape(shape)) {\n throw new Error(\"value expected\")\n }\n\n return value\n }\n\n case \"tree\":\n throw new Error(\"tree type unimplemented\")\n\n default:\n throw new Error(`unexpected type: ${(shape as Shape)._type}`)\n }\n}\n","import type {\n Container,\n Delta,\n ListDiff,\n LoroDoc,\n LoroEventBatch,\n LoroList,\n LoroMovableList,\n Subscription,\n} from \"loro-crdt\"\nimport { convertInputToRef } from \"../conversion.js\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroListRef } from \"../loro.js\"\nimport { mergeValue } from \"../overlay.js\"\nimport type { ContainerOrValueShape, ContainerShape } from \"../shape.js\"\nimport {\n isContainer,\n isContainerShape,\n isValueShape,\n} from \"../utils/type-guards.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createContainerTypedRef } from \"./utils.js\"\n\n// ============================================================================\n// ListRefBaseInternals - Internal implementation class\n// ============================================================================\n\n/**\n * Internal implementation for ListRefBase.\n * Contains all logic, state, and implementation details for list operations.\n */\nexport class ListRefBaseInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends BaseRefInternals<any> {\n private itemCache = new Map<number, any>()\n private overlayListCache?: Item[]\n\n getOverlayList(): Item[] | undefined {\n const overlay = this.getOverlay()\n if (!overlay) {\n return undefined\n }\n\n const shape = this.getShape()\n if (!isValueShape(shape.shape)) {\n return undefined\n }\n\n if (!this.overlayListCache) {\n const container = this.getContainer() as LoroList | LoroMovableList\n const diff = overlay.get(container.id)\n if (!diff || diff.type !== \"list\") {\n return undefined\n }\n\n const afterValues: Item[] = []\n for (let i = 0; i < container.length; i++) {\n afterValues.push(container.get(i) as Item)\n }\n\n this.overlayListCache = applyListDelta(\n afterValues,\n (diff as ListDiff).diff as Delta<Item[]>[],\n )\n }\n\n return this.overlayListCache\n }\n\n /** Get typed ref params for creating child refs at an index */\n getChildTypedRefParams(\n index: number,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n return {\n shape,\n placeholder: undefined, // List items don't have placeholder\n getContainer: () => {\n const container = this.getContainer() as LoroList | LoroMovableList\n const containerItem = container.get(index)\n if (!containerItem || !isContainer(containerItem)) {\n throw new Error(`No container found at index ${index}`)\n }\n return containerItem\n },\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n overlay: this.getOverlay(),\n }\n }\n\n /** Get item for predicate functions (returns plain value) */\n getPredicateItem(index: number): Item | undefined {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const overlayList = this.getOverlayList()\n\n // CRITICAL FIX: For predicates to work correctly with mutations,\n // we need to check if there's a cached (mutated) version first\n const cachedItem = this.itemCache.get(index)\n if (cachedItem && isValueShape(shape.shape)) {\n // For value shapes, if we have a cached item, use it so predicates see mutations\n return cachedItem as Item\n }\n\n if (overlayList && isValueShape(shape.shape)) {\n return overlayList[index]\n }\n\n const containerItem = container.get(index)\n if (containerItem === undefined) {\n return undefined as Item\n }\n\n if (isValueShape(shape.shape)) {\n // For value shapes, return the plain value directly\n return containerItem as Item\n } else {\n // For container shapes, we need to return the plain object representation\n // This allows predicates to access nested properties like article.metadata.author\n if (isContainer(containerItem)) {\n // Convert container to plain object for predicate logic\n // Handle different container types that may not have toJSON method\n if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"toJSON\" in containerItem\n ) {\n return (containerItem as any).toJSON() as Item\n } else if (\n typeof containerItem === \"object\" &&\n containerItem !== null &&\n \"getShallowValue\" in containerItem\n ) {\n // For containers like LoroCounter that don't have toJSON but have getShallowValue\n return (containerItem as any).getShallowValue() as Item\n } else {\n // Fallback for other container types\n return containerItem as Item\n }\n }\n return containerItem as Item\n }\n }\n\n /** Get mutable item for return values (returns ref or cached value) */\n getMutableItem(index: number): MutableItem | undefined {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const overlayList = this.getOverlayList()\n\n // Get the raw container item\n const containerItem = overlayList\n ? (overlayList[index] as Item | undefined)\n : (container.get(index) as Item | undefined)\n if (containerItem === undefined) {\n return undefined as MutableItem\n }\n\n if (isValueShape(shape.shape)) {\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to found/filtered items persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n return containerItem as MutableItem\n }\n\n // In batched mode (within change()), we need to cache value shapes\n // so that mutations to found/filtered items persist back to the CRDT\n // via absorbPlainValues() at the end of change()\n let cachedItem = this.itemCache.get(index)\n if (cachedItem) {\n return cachedItem\n }\n\n // For value shapes, we need to ensure mutations persist\n // The key insight: we must return the SAME object for the same index\n // so that mutations to filtered/found items persist back to the cache\n if (typeof containerItem === \"object\" && containerItem !== null) {\n // Create a deep copy for objects so mutations can be tracked\n // IMPORTANT: Only create the copy once, then always return the same cached object\n cachedItem = JSON.parse(JSON.stringify(containerItem))\n } else {\n // For primitives, just use the value directly\n cachedItem = containerItem\n }\n this.itemCache.set(index, cachedItem)\n return cachedItem as MutableItem\n }\n\n // Container shapes: only cache in batchedMutation mode (inside change())\n // Outside of change(), always create fresh refs to avoid stale cache issues\n // after move operations (where indices shift but cached refs have hardcoded indices)\n if (!this.getBatchedMutation()) {\n return createContainerTypedRef(\n this.getChildTypedRefParams(index, shape.shape as ContainerShape),\n ) as MutableItem\n }\n\n // In batched mode, cache for consistent behavior within a single change() call\n let cachedItem = this.itemCache.get(index)\n if (!cachedItem) {\n cachedItem = createContainerTypedRef(\n this.getChildTypedRefParams(index, shape.shape as ContainerShape),\n )\n this.itemCache.set(index, cachedItem)\n }\n\n return cachedItem as MutableItem\n }\n\n /** Insert with automatic conversion */\n insertWithConversion(index: number, item: unknown): void {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const convertedItem = convertInputToRef(item as any, shape.shape)\n if (isContainer(convertedItem)) {\n container.insertContainer(index, convertedItem)\n } else {\n container.insert(index, convertedItem)\n }\n }\n\n /** Push with automatic conversion */\n pushWithConversion(item: unknown): void {\n const shape = this.getShape()\n const container = this.getContainer() as LoroList | LoroMovableList\n const convertedItem = convertInputToRef(item as any, shape.shape)\n if (isContainer(convertedItem)) {\n container.pushContainer(convertedItem)\n } else {\n container.push(convertedItem)\n }\n }\n\n /** Absorb value at specific index (for value shapes) - subclasses override */\n absorbValueAtIndex(_index: number, _value: unknown): void {\n throw new Error(\"absorbValueAtIndex must be implemented by subclass\")\n }\n\n /** Update cache indices after a delete operation */\n updateCacheForDelete(deleteIndex: number, deleteLen: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < deleteIndex) {\n // Items before the deletion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else if (cachedIndex >= deleteIndex + deleteLen) {\n // Items after the deletion range shift down by deleteLen\n newCache.set(cachedIndex - deleteLen, cachedItem)\n }\n // Items within the deletion range are removed from cache\n }\n\n this.itemCache = newCache\n }\n\n /** Update cache indices after an insert operation */\n updateCacheForInsert(insertIndex: number): void {\n const newCache = new Map<number, any>()\n\n for (const [cachedIndex, cachedItem] of this.itemCache.entries()) {\n if (cachedIndex < insertIndex) {\n // Items before the insertion point keep their indices\n newCache.set(cachedIndex, cachedItem)\n } else {\n // Items at or after the insertion point shift up by 1\n newCache.set(cachedIndex + 1, cachedItem)\n }\n }\n\n this.itemCache = newCache\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n // Critical function: absorb mutated plain values back into Loro containers\n // This is called at the end of change() to persist mutations made to plain objects\n const shape = this.getShape()\n for (const [index, cachedItem] of this.itemCache.entries()) {\n if (cachedItem) {\n if (isValueShape(shape.shape)) {\n // For value shapes, delegate to subclass-specific absorption logic\n this.absorbValueAtIndex(index, cachedItem)\n } else {\n // For container shapes, the item should be a typed ref that handles its own absorption\n if (\n cachedItem &&\n typeof cachedItem === \"object\" &&\n INTERNAL_SYMBOL in cachedItem\n ) {\n ;(cachedItem as any)[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n }\n }\n\n // Clear the cache after absorbing values\n this.itemCache.clear()\n }\n\n /** Create the loro namespace for list */\n protected override createLoroNamespace(): LoroListRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroList | LoroMovableList {\n return self.getContainer() as LoroList | LoroMovableList\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroList | LoroMovableList).subscribe(\n callback,\n )\n },\n pushContainer(container: Container): Container {\n const result = (\n self.getContainer() as LoroList | LoroMovableList\n ).pushContainer(container)\n self.commitIfAuto()\n return result\n },\n insertContainer(index: number, container: Container): Container {\n const result = (\n self.getContainer() as LoroList | LoroMovableList\n ).insertContainer(index, container)\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n\n// ============================================================================\n// ListRefBase - Public facade class\n// ============================================================================\n\n/**\n * Shared logic for list operations - thin facade that delegates to ListRefBaseInternals.\n */\nexport abstract class ListRefBase<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends TypedRef<any> {\n [INTERNAL_SYMBOL]: ListRefBaseInternals<NestedShape, Item, MutableItem>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = this.createInternals(params)\n }\n\n /** Subclasses override to create their specific internals */\n protected abstract createInternals(\n params: TypedRefParams<any>,\n ): ListRefBaseInternals<NestedShape, Item, MutableItem>\n\n // Array-like methods for better developer experience\n // DUAL INTERFACE: Predicates get Item (plain data), return values are MutableItem (mutable)\n\n find(\n predicate: (item: Item, index: number) => boolean,\n ): MutableItem | undefined {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem // Return mutable item\n }\n }\n return undefined\n }\n\n findIndex(predicate: (item: Item, index: number) => boolean): number {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return i\n }\n }\n return -1\n }\n\n map<ReturnType>(\n callback: (item: Item, index: number) => ReturnType,\n ): ReturnType[] {\n const result: ReturnType[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n result.push(callback(predicateItem as Item, i))\n }\n return result\n }\n\n filter(predicate: (item: Item, index: number) => boolean): MutableItem[] {\n const result: MutableItem[] = []\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n result.push(this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem) // Return mutable items\n }\n }\n return result\n }\n\n forEach(callback: (item: Item, index: number) => void): void {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n callback(predicateItem as Item, i)\n }\n }\n\n some(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (predicate(predicateItem as Item, i)) {\n return true\n }\n }\n return false\n }\n\n every(predicate: (item: Item, index: number) => boolean): boolean {\n for (let i = 0; i < this.length; i++) {\n const predicateItem = this[INTERNAL_SYMBOL].getPredicateItem(i)\n if (!predicate(predicateItem as Item, i)) {\n return false\n }\n }\n return true\n }\n\n slice(start?: number, end?: number): MutableItem[] {\n const len = this.length\n\n // Normalize start index (following JavaScript Array.prototype.slice semantics)\n const startIndex =\n start === undefined\n ? 0\n : start < 0\n ? Math.max(len + start, 0)\n : Math.min(start, len)\n\n // Normalize end index\n const endIndex =\n end === undefined\n ? len\n : end < 0\n ? Math.max(len + end, 0)\n : Math.min(end, len)\n\n const result: MutableItem[] = []\n for (let i = startIndex; i < endIndex; i++) {\n result.push(this[INTERNAL_SYMBOL].getMutableItem(i) as MutableItem)\n }\n return result\n }\n\n insert(index: number, item: Item): void {\n // Update cache indices before performing the insert operation\n this[INTERNAL_SYMBOL].updateCacheForInsert(index)\n this[INTERNAL_SYMBOL].insertWithConversion(index, item)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n delete(index: number, len: number): void {\n // Update cache indices before performing the delete operation\n this[INTERNAL_SYMBOL].updateCacheForDelete(index, len)\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n container.delete(index, len)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n push(item: Item): void {\n this[INTERNAL_SYMBOL].pushWithConversion(item)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n pushContainer(container: Container): Container {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const result = loroContainer.pushContainer(container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n insertContainer(index: number, container: Container): Container {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const result = loroContainer.insertContainer(index, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n get(index: number): MutableItem | undefined {\n return this[INTERNAL_SYMBOL].getMutableItem(index) as\n | MutableItem\n | undefined\n }\n\n toArray(): Item[] {\n const overlayList = this[INTERNAL_SYMBOL].getOverlayList()\n if (overlayList) {\n return [...overlayList]\n }\n const result: Item[] = []\n for (let i = 0; i < this.length; i++) {\n result.push(this[INTERNAL_SYMBOL].getPredicateItem(i) as Item)\n }\n return result\n }\n\n toJSON(): Item[] {\n const shape = this[INTERNAL_SYMBOL].getShape()\n const overlayList = this[INTERNAL_SYMBOL].getOverlayList()\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n const nativeJson = overlayList ?? (container.toJSON() as any[])\n\n // If the nested shape is a container shape (map, record, etc.) or an object value shape,\n // we need to overlay placeholders for each item\n if (\n isContainerShape(shape.shape) ||\n (isValueShape(shape.shape) && shape.shape.valueType === \"struct\")\n ) {\n const itemPlaceholder = deriveShapePlaceholder(shape.shape)\n return nativeJson.map(item =>\n mergeValue(shape.shape, item, itemPlaceholder as any),\n ) as Item[]\n }\n\n // For primitive value shapes, no overlay needed\n return nativeJson ?? []\n }\n\n [Symbol.iterator](): IterableIterator<MutableItem> {\n let index = 0\n return {\n next: (): IteratorResult<MutableItem> => {\n if (index < this.length) {\n return {\n value: this[INTERNAL_SYMBOL].getMutableItem(index++) as MutableItem,\n done: false,\n }\n }\n return { value: undefined, done: true }\n },\n [Symbol.iterator]() {\n return this\n },\n }\n }\n\n get length(): number {\n const overlayList = this[INTERNAL_SYMBOL].getOverlayList()\n if (overlayList) {\n return overlayList.length\n }\n const container = this[INTERNAL_SYMBOL].getContainer() as\n | LoroList\n | LoroMovableList\n return container.length\n }\n}\n\nfunction applyListDelta<T>(input: T[], delta: Delta<T[]>[]): T[] {\n const result: T[] = []\n let index = 0\n\n for (const op of delta) {\n if (op.retain !== undefined) {\n result.push(...input.slice(index, index + op.retain))\n index += op.retain\n } else if (op.delete !== undefined) {\n index += op.delete\n } else if (op.insert !== undefined) {\n result.push(...op.insert)\n }\n }\n\n if (index < input.length) {\n result.push(...input.slice(index))\n }\n\n return result\n}\n","import type { LoroList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport { ListRefBaseInternals } from \"./list-ref-base.js\"\n\n/**\n * Internal implementation for ListRef.\n * Extends ListRefBaseInternals with LoroList-specific absorption logic.\n */\nexport class ListRefInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends ListRefBaseInternals<NestedShape, Item, MutableItem> {\n /** Absorb value at specific index for LoroList */\n override absorbValueAtIndex(index: number, value: unknown): void {\n // LoroList doesn't have set method, need to delete and insert\n const container = this.getContainer() as LoroList\n container.delete(index, 1)\n container.insert(index, value)\n }\n}\n","import type { ContainerOrValueShape } from \"../shape.js\"\nimport type { InferMutableType } from \"../types.js\"\nimport type { TypedRefParams } from \"./base.js\"\nimport { ListRefBase } from \"./list-ref-base.js\"\nimport { ListRefInternals } from \"./list-ref-internals.js\"\n\n/**\n * List typed ref - thin facade that delegates to ListRefInternals.\n */\nexport class ListRef<\n NestedShape extends ContainerOrValueShape,\n> extends ListRefBase<NestedShape> {\n // Returns the mutable type which has toJSON() and other ref methods.\n // For assignment, the proxy handler accepts plain values and converts them.\n // TypeScript may require type assertions for plain value assignments.\n [index: number]: InferMutableType<NestedShape> | undefined\n\n protected override createInternals(\n params: TypedRefParams<any>,\n ): ListRefInternals<NestedShape> {\n return new ListRefInternals(params)\n }\n}\n","import type { LoroMovableList } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport { ListRefBaseInternals } from \"./list-ref-base.js\"\n\n// ============================================================================\n// MovableListRefInternals - Internal implementation class\n// ============================================================================\n\n/**\n * Internal implementation for MovableListRef.\n * Extends ListRefBaseInternals with LoroMovableList-specific methods.\n */\nexport class MovableListRefInternals<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n MutableItem = NestedShape[\"_mutable\"],\n> extends ListRefBaseInternals<NestedShape, Item, MutableItem> {\n /** Absorb value at specific index for LoroMovableList */\n override absorbValueAtIndex(index: number, value: unknown): void {\n // LoroMovableList has set method\n const container = this.getContainer() as LoroMovableList\n container.set(index, value)\n }\n\n /** Move an item from one index to another */\n move(from: number, to: number): void {\n const container = this.getContainer() as LoroMovableList\n container.move(from, to)\n this.commitIfAuto()\n }\n\n /** Set an item at a specific index */\n set(index: number, item: unknown): void {\n const container = this.getContainer() as LoroMovableList\n container.set(index, item)\n this.commitIfAuto()\n }\n}\n","import type { Container } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { InferMutableType } from \"../types.js\"\nimport { INTERNAL_SYMBOL, type TypedRefParams } from \"./base.js\"\nimport { ListRefBase } from \"./list-ref-base.js\"\nimport { MovableListRefInternals } from \"./movable-list-ref-internals.js\"\n\n/**\n * Movable list typed ref - thin facade that delegates to MovableListRefInternals.\n */\nexport class MovableListRef<\n NestedShape extends ContainerOrValueShape,\n Item = NestedShape[\"_plain\"],\n> extends ListRefBase<NestedShape> {\n declare [INTERNAL_SYMBOL]: MovableListRefInternals<NestedShape>;\n [index: number]: InferMutableType<NestedShape> | undefined\n\n protected override createInternals(\n params: TypedRefParams<any>,\n ): MovableListRefInternals<NestedShape> {\n return new MovableListRefInternals(params)\n }\n\n move(from: number, to: number): void {\n this[INTERNAL_SYMBOL].move(from, to)\n }\n\n set(index: number, item: Exclude<Item, Container>) {\n this[INTERNAL_SYMBOL].set(index, item)\n }\n}\n","import { INTERNAL_SYMBOL } from \"./base.js\"\nimport type { ListRef } from \"./list-ref.js\"\nimport type { MovableListRef } from \"./movable-list-ref.js\"\nimport type { RecordRef } from \"./record-ref.js\"\nimport type { RecordRefInternals } from \"./record-ref-internals.js\"\n\nexport const recordProxyHandler: ProxyHandler<RecordRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n // Use getRef for reading - returns undefined for non-existent keys\n return (target[INTERNAL_SYMBOL] as RecordRefInternals<any>).getRef(prop)\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.set(prop, value)\n return true\n }\n return Reflect.set(target, prop, value)\n },\n\n deleteProperty: (target, prop) => {\n if (typeof prop === \"string\" && !(prop in target)) {\n target.delete(prop)\n return true\n }\n return Reflect.deleteProperty(target, prop)\n },\n\n // Support `in` operator for checking key existence\n has: (target, prop) => {\n if (typeof prop === \"string\") {\n // Check if it's a method/property on the class first\n if (prop in target) {\n return true\n }\n // Otherwise check the underlying container\n return target.has(prop)\n }\n return Reflect.has(target, prop)\n },\n\n ownKeys: target => {\n return target.keys()\n },\n\n getOwnPropertyDescriptor: (target, prop) => {\n if (typeof prop === \"string\" && target.has(prop)) {\n return {\n configurable: true,\n enumerable: true,\n value: target.get(prop),\n }\n }\n return Reflect.getOwnPropertyDescriptor(target, prop)\n },\n}\n\nexport const listProxyHandler: ProxyHandler<ListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // For lists, assignment to index implies replacement\n target.delete(index, 1)\n target.insert(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n\nexport const movableListProxyHandler: ProxyHandler<MovableListRef<any>> = {\n get: (target, prop) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n return target.get(index)\n }\n }\n return Reflect.get(target, prop)\n },\n\n set: (target, prop, value) => {\n if (typeof prop === \"string\") {\n const index = Number(prop)\n if (!Number.isNaN(index)) {\n // MovableList supports set directly\n target.set(index, value)\n return true\n }\n }\n return Reflect.set(target, prop, value)\n },\n}\n","import type {\n Container,\n LoroDoc,\n LoroEventBatch,\n LoroMap,\n MapDiff,\n Subscription,\n Value,\n} from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroMapRef } from \"../loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n RecordContainerShape,\n} from \"../shape.js\"\nimport { isContainerShape, isValueShape } from \"../utils/type-guards.js\"\nimport { BaseRefInternals, type TypedRef, type TypedRefParams } from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n hasContainerConstructor,\n} from \"./utils.js\"\n\n/**\n * Internal implementation for RecordRef.\n * Contains all logic, state, and implementation details.\n */\nexport class RecordRefInternals<\n NestedShape extends ContainerOrValueShape,\n> extends BaseRefInternals<any> {\n private refCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n // First try to get placeholder from the Record's placeholder (if it has an entry for this key)\n let placeholder = (this.getPlaceholder() as any)?.[key]\n\n // If no placeholder exists for this key, derive one from the schema's shape\n // This is critical for Records where the placeholder is always {} but nested\n // containers need valid placeholders to fall back to for missing values\n if (placeholder === undefined) {\n placeholder = deriveShapePlaceholder(shape)\n }\n\n // AnyContainerShape is an escape hatch - it doesn't have a constructor\n if (!hasContainerConstructor(shape._type)) {\n throw new Error(\n `Cannot create typed ref for shape type \"${shape._type}\". ` +\n `Use Shape.any() only at the document root level.`,\n )\n }\n\n const LoroContainer = containerConstructor[shape._type]\n const container = this.getContainer() as LoroMap\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n container.getOrCreateContainer(key, new (LoroContainer as any)()),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n }\n }\n\n /** Get a ref for a key without creating (returns undefined for non-existent container keys) */\n getRef(key: string): unknown {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n // For container shapes, check if the key exists first\n // This allows optional chaining (?.) to work correctly for non-existent keys\n if (isContainerShape(shape)) {\n const existing = container.get(key)\n if (existing === undefined) {\n return undefined\n }\n }\n\n return this.getOrCreateRef(key)\n }\n\n /** Get or create a ref for a key (always creates for container shapes) */\n getOrCreateRef(key: string): unknown {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(shape)) {\n const overlay = this.getOverlay()\n if (overlay) {\n const containerId = (container as any).id\n const diff = overlay.get(containerId)\n if (diff && diff.type === \"map\") {\n const mapDiff = diff as MapDiff\n if (key in mapDiff.updated) {\n return mapDiff.updated[key] as Value\n }\n }\n }\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n return containerValue\n }\n // Fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder !== undefined) {\n return placeholder\n }\n // Fall back to the default value from the shape\n return (shape as any)._plain\n }\n\n // In batched mode (within change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n let ref = this.refCache.get(key)\n if (!ref) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n // For objects, create a deep copy so mutations can be tracked\n if (typeof containerValue === \"object\" && containerValue !== null) {\n ref = JSON.parse(JSON.stringify(containerValue))\n } else {\n ref = containerValue as Value\n }\n } else {\n // Fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder !== undefined) {\n ref = placeholder as Value\n } else {\n // Fall back to the default value from the shape\n ref = (shape as any)._plain\n }\n }\n this.refCache.set(key, ref)\n }\n return ref\n }\n\n // For container shapes, we can safely cache the ref since it's a handle\n // to the underlying Loro container, not a value copy.\n let ref = this.refCache.get(key)\n if (!ref) {\n ref = createContainerTypedRef(\n this.getChildTypedRefParams(key, shape as ContainerShape),\n )\n this.refCache.set(key, ref)\n }\n\n return ref as any\n }\n\n /** Set a value at a key */\n set(key: string, value: any): void {\n const recordShape = this.getShape() as RecordContainerShape<NestedShape>\n const shape = recordShape.shape\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(shape)) {\n container.set(key, value)\n this.refCache.set(key, value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // Use getOrCreateRef to ensure the container is created\n // assignPlainValueToTypedRef handles batching and commits internally\n const ref = this.getOrCreateRef(key)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n // Don't call commitIfAuto here - assignPlainValueToTypedRef handles it\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n /** Delete a key */\n delete(key: string): void {\n const container = this.getContainer() as LoroMap\n container.delete(key)\n this.refCache.delete(key)\n this.commitIfAuto()\n }\n\n /**\n * Replace entire contents with new values.\n * Keys not in `values` are removed.\n */\n replace(values: Record<string, any>): void {\n const container = this.getContainer() as LoroMap\n const currentKeys = new Set(container.keys())\n const newKeys = new Set(Object.keys(values))\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Delete keys that are not in the new values\n for (const key of currentKeys) {\n if (!newKeys.has(key)) {\n container.delete(key)\n this.refCache.delete(key)\n }\n }\n\n // Set new/updated values\n for (const key of newKeys) {\n this.set(key, values[key])\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /**\n * Merge values into record.\n * Existing keys not in `values` are kept.\n */\n merge(values: Record<string, any>): void {\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Set new/updated values (no deletions)\n for (const key of Object.keys(values)) {\n this.set(key, values[key])\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /**\n * Remove all entries from the record.\n */\n clear(): void {\n const container = this.getContainer() as LoroMap\n const keys = container.keys()\n\n if (keys.length === 0) {\n return // No-op on empty record\n }\n\n // Suppress auto-commit during batch operations\n const wasSuppressed = this.isSuppressAutoCommit()\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(true)\n }\n\n try {\n // Delete all keys\n for (const key of keys) {\n container.delete(key)\n this.refCache.delete(key)\n }\n } finally {\n // Restore auto-commit state\n if (!wasSuppressed) {\n this.setSuppressAutoCommit(false)\n }\n }\n\n // Commit once after all operations\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n absorbCachedPlainValues(this.refCache, () => this.getContainer() as LoroMap)\n }\n\n /** Create the loro namespace for record */\n protected override createLoroNamespace(): LoroMapRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroMap {\n return self.getContainer() as LoroMap\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroMap).subscribe(callback)\n },\n setContainer(key: string, container: Container): Container {\n const result = (self.getContainer() as LoroMap).setContainer(\n key,\n container,\n )\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n","import type { Container, LoroMap } from \"loro-crdt\"\nimport type { ContainerOrValueShape } from \"../shape.js\"\nimport type { Infer, InferMutableType } from \"../types.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { RecordRefInternals } from \"./record-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Record typed ref - thin facade that delegates to RecordRefInternals.\n */\nexport class RecordRef<\n NestedShape extends ContainerOrValueShape,\n> extends TypedRef<any> {\n [key: string]: InferMutableType<NestedShape> | undefined | any\n\n [INTERNAL_SYMBOL]: RecordRefInternals<NestedShape>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = new RecordRefInternals(params)\n }\n\n /** Set a value at a key */\n set(key: string, value: any): void {\n this[INTERNAL_SYMBOL].set(key, value)\n }\n\n /** Delete a key */\n delete(key: string): void {\n this[INTERNAL_SYMBOL].delete(key)\n }\n\n get(key: string): InferMutableType<NestedShape> | undefined {\n // In batched mutation mode (inside change()), use getOrCreateRef to create containers\n // This allows patterns like: draft.scores.get(\"alice\")!.increment(10)\n if (this[INTERNAL_SYMBOL].getBatchedMutation()) {\n return this[INTERNAL_SYMBOL].getOrCreateRef(key) as\n | InferMutableType<NestedShape>\n | undefined\n }\n // In readonly mode, use getRef which returns undefined for non-existent keys\n return this[INTERNAL_SYMBOL].getRef(key) as\n | InferMutableType<NestedShape>\n | undefined\n }\n\n setContainer<C extends Container>(key: string, container: C): C {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n const result = loroContainer.setContainer(key, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n has(key: string): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key) !== undefined\n }\n\n keys(): string[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.keys()\n }\n\n /**\n * Returns an array of all values in the record.\n * For container-valued records, returns properly typed refs.\n */\n values(): InferMutableType<NestedShape>[] {\n // We know keys() only returns keys that exist, so get() will not return undefined\n return this.keys().map(\n key => this.get(key) as InferMutableType<NestedShape>,\n )\n }\n\n /**\n * Returns an array of [key, value] pairs.\n * For container-valued records, values are properly typed refs.\n */\n entries(): [string, InferMutableType<NestedShape>][] {\n // We know keys() only returns keys that exist, so get() will not return undefined\n return this.keys().map(key => [\n key,\n this.get(key) as InferMutableType<NestedShape>,\n ])\n }\n\n get size(): number {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.size\n }\n\n /**\n * Replace entire contents with new values.\n * Keys not in `values` are removed.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.players.replace({\n * alice: { score: 100 },\n * bob: { score: 50 }\n * })\n * })\n * ```\n */\n replace(values: Record<string, Infer<NestedShape>>): void {\n this[INTERNAL_SYMBOL].replace(values)\n }\n\n /**\n * Merge values into record.\n * Existing keys not in `values` are kept.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * // Adds charlie, updates alice, keeps bob unchanged\n * draft.players.merge({\n * alice: { score: 150 },\n * charlie: { score: 25 }\n * })\n * })\n * ```\n */\n merge(values: Record<string, Infer<NestedShape>>): void {\n this[INTERNAL_SYMBOL].merge(values)\n }\n\n /**\n * Remove all entries from the record.\n *\n * @example\n * ```typescript\n * doc.change(draft => {\n * draft.players.clear()\n * })\n * ```\n */\n clear(): void {\n this[INTERNAL_SYMBOL].clear()\n }\n\n toJSON(): Record<string, Infer<NestedShape>> {\n return serializeRefToJSON(this, this.keys()) as Record<\n string,\n Infer<NestedShape>\n >\n }\n}\n","import type {\n Container,\n LoroDoc,\n LoroEventBatch,\n LoroMap,\n MapDiff,\n Subscription,\n Value,\n} from \"loro-crdt\"\nimport type { LoroMapRef } from \"../loro.js\"\nimport type {\n ContainerOrValueShape,\n ContainerShape,\n StructContainerShape,\n ValueShape,\n} from \"../shape.js\"\nimport { isValueShape } from \"../utils/type-guards.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n type TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport {\n absorbCachedPlainValues,\n assignPlainValueToTypedRef,\n containerConstructor,\n createContainerTypedRef,\n hasContainerConstructor,\n} from \"./utils.js\"\n\n/**\n * Internal implementation for StructRef.\n * Contains all logic, state, and implementation details.\n */\nexport class StructRefInternals<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends BaseRefInternals<any> {\n private propertyCache = new Map<string, TypedRef<ContainerShape> | Value>()\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n const placeholder = (this.getPlaceholder() as any)?.[key]\n\n // AnyContainerShape is an escape hatch - it doesn't have a constructor\n if (!hasContainerConstructor(shape._type)) {\n throw new Error(\n `Cannot create typed ref for shape type \"${shape._type}\". ` +\n `Use Shape.any() only at the document root level.`,\n )\n }\n\n const LoroContainer = containerConstructor[shape._type]\n const container = this.getContainer() as LoroMap\n\n return {\n shape,\n placeholder,\n getContainer: () =>\n container.getOrCreateContainer(key, new (LoroContainer as any)()),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n }\n }\n\n /** Get or create a ref for a key */\n getOrCreateRef<Shape extends ContainerShape | ValueShape>(\n key: string,\n shape?: Shape,\n ): unknown {\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n const actualShape = shape || structShape.shapes[key]\n const container = this.getContainer() as LoroMap\n\n if (isValueShape(actualShape)) {\n const overlay = this.getOverlay()\n if (overlay) {\n const containerId = (container as any).id\n const diff = overlay.get(containerId)\n if (diff && diff.type === \"map\") {\n const mapDiff = diff as MapDiff\n if (key in mapDiff.updated) {\n return mapDiff.updated[key] as Value\n }\n }\n }\n // When NOT in batchedMutation mode (direct access outside of change()), ALWAYS read fresh\n // from container (NEVER cache). This ensures we always get the latest value\n // from the CRDT, even when modified by a different ref instance (e.g., drafts from change())\n //\n // When in batchedMutation mode (inside change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n if (!this.getBatchedMutation()) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n return containerValue\n }\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n return placeholder\n }\n\n // In batched mode (within change()), we cache value shapes so that\n // mutations to nested objects persist back to the CRDT via absorbPlainValues()\n let ref = this.propertyCache.get(key)\n if (!ref) {\n const containerValue = container.get(key)\n if (containerValue !== undefined) {\n // For objects, create a deep copy so mutations can be tracked\n if (typeof containerValue === \"object\" && containerValue !== null) {\n ref = JSON.parse(JSON.stringify(containerValue))\n } else {\n ref = containerValue as Value\n }\n } else {\n // Only fall back to placeholder if the container doesn't have the value\n const placeholder = (this.getPlaceholder() as any)?.[key]\n if (placeholder === undefined) {\n throw new Error(\"placeholder required\")\n }\n ref = placeholder as Value\n }\n this.propertyCache.set(key, ref)\n }\n return ref\n }\n\n // Container shapes: safe to cache (handles)\n let ref = this.propertyCache.get(key)\n if (!ref) {\n ref = createContainerTypedRef(\n this.getChildTypedRefParams(key, actualShape as ContainerShape),\n )\n this.propertyCache.set(key, ref)\n }\n\n return ref as Shape extends ContainerShape ? TypedRef<Shape> : Value\n }\n\n /** Set a property value */\n setPropertyValue(key: string, value: unknown): void {\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n const shape = structShape.shapes[key]\n const container = this.getContainer() as LoroMap\n\n if (!shape) {\n throw new Error(`Unknown property: ${key}`)\n }\n\n if (isValueShape(shape)) {\n container.set(key, value)\n this.propertyCache.set(key, value as Value)\n this.commitIfAuto()\n } else {\n // For container shapes, try to assign the plain value\n // assignPlainValueToTypedRef handles batching and commits internally\n const ref = this.getOrCreateRef(key, shape)\n if (assignPlainValueToTypedRef(ref as TypedRef<any>, value)) {\n // Don't call commitIfAuto here - assignPlainValueToTypedRef handles it\n return\n }\n throw new Error(\n \"Cannot set container directly, modify the typed ref instead\",\n )\n }\n }\n\n /** Delete a property */\n deleteProperty(key: string): void {\n const container = this.getContainer() as LoroMap\n container.delete(key)\n this.propertyCache.delete(key)\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n absorbCachedPlainValues(\n this.propertyCache,\n () => this.getContainer() as LoroMap,\n )\n }\n\n /** Force materialization of the container and its nested containers */\n override materialize(): void {\n // Ensure this container exists\n this.getContainer()\n\n // Recursively materialize nested containers\n const structShape = this.getShape() as StructContainerShape<NestedShapes>\n for (const key in structShape.shapes) {\n const shape = structShape.shapes[key]\n if (!isValueShape(shape)) {\n // Get the ref (which creates it if needed)\n const ref = this.getOrCreateRef(key, shape) as TypedRef<any>\n // Force materialization\n ref[INTERNAL_SYMBOL].materialize()\n }\n }\n }\n\n /** Create the loro namespace for struct */\n protected override createLoroNamespace(): LoroMapRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroMap {\n return self.getContainer() as LoroMap\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroMap).subscribe(callback)\n },\n setContainer(key: string, container: Container): Container {\n const result = (self.getContainer() as LoroMap).setContainer(\n key,\n container,\n )\n self.commitIfAuto()\n return result\n },\n }\n }\n}\n","import type { Container, LoroMap, Value } from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroMapRef } from \"../loro.js\"\nimport type { ContainerOrValueShape, StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport {\n INTERNAL_SYMBOL,\n type RefInternalsBase,\n TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { StructRefInternals } from \"./struct-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Internal implementation class for struct containers.\n * The actual StructRef is a Proxy wrapping this class.\n */\nclass StructRefImpl<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> extends TypedRef<any> {\n [INTERNAL_SYMBOL]: StructRefInternals<NestedShapes>\n\n constructor(params: TypedRefParams<any>) {\n super()\n this[INTERNAL_SYMBOL] = new StructRefInternals(params)\n }\n\n get structShape(): StructContainerShape<NestedShapes> {\n return this[\n INTERNAL_SYMBOL\n ].getShape() as StructContainerShape<NestedShapes>\n }\n\n toJSON(): Infer<StructContainerShape<NestedShapes>> {\n return serializeRefToJSON(\n this as any,\n Object.keys(this.structShape.shapes),\n ) as Infer<StructContainerShape<NestedShapes>>\n }\n\n // Deprecated methods - kept for backward compatibility\n // @deprecated Use property access instead: obj.key\n get(key: string): any {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key)\n }\n\n // @deprecated Use property assignment instead: obj.key = value\n set(key: string, value: Value): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n container.set(key, value)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n // @deprecated Use loro(struct).setContainer() instead\n setContainer<C extends Container>(key: string, container: C): C {\n const loroContainer = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n const result = loroContainer.setContainer(key, container)\n this[INTERNAL_SYMBOL].commitIfAuto()\n return result\n }\n\n // @deprecated Use delete obj.key instead\n delete(key: string): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n container.delete(key)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n // @deprecated Use 'key' in obj instead\n has(key: string): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.get(key) !== undefined\n }\n\n // @deprecated Use Object.keys(obj) instead\n keys(): string[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.keys()\n }\n\n // @deprecated Use Object.values(obj) instead\n values(): any[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.values()\n }\n\n // @deprecated Not standard for objects\n get size(): number {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroMap\n return container.size\n }\n}\n\n/**\n * Creates a StructRef wrapped in a Proxy for JavaScript-native object behavior.\n * Supports:\n * - Property access: obj.key\n * - Property assignment: obj.key = value\n * - Object.keys(obj)\n * - 'key' in obj\n * - delete obj.key\n * - toJSON()\n * - loro(obj) for CRDT access\n */\nexport function createStructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n>(\n params: TypedRefParams<StructContainerShape<NestedShapes>>,\n): StructRef<NestedShapes> {\n const impl = new StructRefImpl<NestedShapes>(params)\n\n const proxy = new Proxy(impl, {\n get(target, prop, receiver) {\n // Handle Symbol access (loro(), internal, etc.)\n if (prop === LORO_SYMBOL) {\n return target[INTERNAL_SYMBOL].getLoroNamespace()\n }\n\n // Handle INTERNAL_SYMBOL for internal methods\n if (prop === INTERNAL_SYMBOL) {\n return target[INTERNAL_SYMBOL]\n }\n\n // Handle toJSON - use serializeRefToJSON with the proxy (receiver) so property access goes through the proxy\n if (prop === \"toJSON\") {\n return () =>\n serializeRefToJSON(receiver, Object.keys(target.structShape.shapes))\n }\n\n // Handle shape access (internal - needed for assignPlainValueToTypedRef)\n if (prop === \"shape\") {\n return target.structShape\n }\n\n // Schema property access\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n const shape = target.structShape.shapes[prop]\n return target[INTERNAL_SYMBOL].getOrCreateRef(prop, shape)\n }\n\n return undefined\n },\n\n set(target, prop, value) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n target[INTERNAL_SYMBOL].setPropertyValue(prop, value)\n return true\n }\n return false\n },\n\n has(target, prop) {\n if (\n prop === LORO_SYMBOL ||\n prop === INTERNAL_SYMBOL ||\n prop === \"toJSON\" ||\n prop === \"shape\"\n ) {\n return true\n }\n if (typeof prop === \"string\") {\n return prop in target.structShape.shapes\n }\n return false\n },\n\n deleteProperty(target, prop) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n target[INTERNAL_SYMBOL].deleteProperty(prop)\n return true\n }\n return false\n },\n\n ownKeys(target) {\n // Return only schema keys, not internal methods\n return Object.keys(target.structShape.shapes)\n },\n\n getOwnPropertyDescriptor(target, prop) {\n if (typeof prop === \"string\" && prop in target.structShape.shapes) {\n const shape = target.structShape.shapes[prop]\n return {\n configurable: true,\n enumerable: true,\n value: target[INTERNAL_SYMBOL].getOrCreateRef(prop, shape),\n }\n }\n return undefined\n },\n }) as unknown as StructRef<NestedShapes>\n\n return proxy\n}\n\n/**\n * Typed ref for struct containers (objects with fixed keys).\n * Uses LoroMap as the underlying container.\n *\n * Supports JavaScript-native object behavior:\n * - Property access: obj.key\n * - Property assignment: obj.key = value\n * - Object.keys(obj)\n * - 'key' in obj\n * - delete obj.key\n *\n * @example\n * ```typescript\n * const schema = Shape.doc({\n * settings: Shape.struct({\n * darkMode: Shape.plain.boolean().placeholder(false),\n * fontSize: Shape.plain.number().placeholder(14),\n * }),\n * });\n *\n * const doc = createTypedDoc(schema);\n *\n * // Property access\n * doc.settings.darkMode = true;\n * console.log(doc.settings.darkMode); // true\n *\n * // Object.keys()\n * console.log(Object.keys(doc.settings)); // ['darkMode', 'fontSize']\n *\n * // 'key' in obj\n * console.log('darkMode' in doc.settings); // true\n *\n * // delete obj.key\n * delete doc.settings.darkMode;\n *\n * // CRDT access via loro()\n * import { loro } from \"@loro-extended/change\";\n * loro(doc.settings).setContainer('nested', loroMap);\n * loro(doc.settings).subscribe(callback);\n * ```\n */\nexport type StructRef<\n NestedShapes extends Record<string, ContainerOrValueShape>,\n> = {\n [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"]\n} & {\n /**\n * Serializes the struct to a plain JSON-compatible object.\n */\n toJSON(): Infer<StructContainerShape<NestedShapes>>\n\n /**\n * Internal methods accessed via INTERNAL_SYMBOL.\n * @internal\n */\n [INTERNAL_SYMBOL]: RefInternalsBase\n\n /**\n * Access CRDT internals via the well-known symbol.\n * Used by the loro() function.\n */\n [LORO_SYMBOL]: LoroMapRef\n}\n\n// Re-export for backward compatibility\n// The old class-based StructRef is now replaced by the proxy-based version\nexport { StructRefImpl as StructRefClass }\n","import type {\n Delta,\n LoroDoc,\n LoroEventBatch,\n LoroText,\n Subscription,\n TextDiff,\n} from \"loro-crdt\"\nimport type { LoroTextRef } from \"../loro.js\"\nimport type { TextContainerShape } from \"../shape.js\"\nimport { BaseRefInternals } from \"./base.js\"\n\n/**\n * Internal implementation for TextRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TextRefInternals extends BaseRefInternals<TextContainerShape> {\n private materialized = false\n\n /** Insert text at the given index */\n insert(index: number, content: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).insert(index, content)\n this.commitIfAuto()\n }\n\n /** Delete text at the given index */\n delete(index: number, len: number): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).delete(index, len)\n this.commitIfAuto()\n }\n\n /** Update the entire text content */\n update(text: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).update(text)\n this.commitIfAuto()\n }\n\n /** Mark a range of text with a key-value pair */\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).mark(range, key, value)\n this.commitIfAuto()\n }\n\n /** Remove a mark from a range of text */\n unmark(range: { start: number; end: number }, key: string): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).unmark(range, key)\n this.commitIfAuto()\n }\n\n /** Apply a delta to the text */\n applyDelta(delta: any[]): void {\n this.materialized = true\n ;(this.getContainer() as LoroText).applyDelta(delta)\n this.commitIfAuto()\n }\n\n /** Get the text as a string */\n getStringValue(): string {\n const container = this.getContainer() as LoroText\n const overlay = this.getOverlay()\n if (overlay) {\n const diff = overlay.get(container.id)\n if (diff && diff.type === \"text\") {\n const containerValue = container.toString()\n return applyTextDelta(containerValue, (diff as TextDiff).diff)\n }\n }\n const containerValue = container.toString()\n if (containerValue !== \"\" || this.materialized) {\n return containerValue\n }\n // Return placeholder if available and container is at default state\n const placeholder = this.getPlaceholder()\n if (placeholder !== undefined) {\n return placeholder as string\n }\n return containerValue\n }\n\n /** Get the text as a delta */\n toDelta(): any[] {\n const container = this.getContainer() as LoroText\n const overlay = this.getOverlay()\n if (overlay) {\n const diff = overlay.get(container.id)\n if (diff && diff.type === \"text\") {\n const base = container.toDelta() as Delta<string>[]\n return applyDeltaToDelta(base, (diff as TextDiff).diff)\n }\n }\n return container.toDelta()\n }\n\n /** Get the length of the text */\n getLength(): number {\n const container = this.getContainer() as LoroText\n const overlay = this.getOverlay()\n if (overlay) {\n const diff = overlay.get(container.id)\n if (diff && diff.type === \"text\") {\n return applyTextDelta(container.toString(), (diff as TextDiff).diff)\n .length\n }\n }\n return container.length\n }\n\n /** No plain values in text */\n absorbPlainValues(): void {\n // no plain values contained within\n }\n\n /** Create the loro namespace for text */\n protected override createLoroNamespace(): LoroTextRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroText {\n return self.getContainer() as LoroText\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroText).subscribe(callback)\n },\n }\n }\n}\n\nfunction applyTextDelta(text: string, delta: Delta<string>[]): string {\n let result = \"\"\n let index = 0\n\n for (const op of delta) {\n if (op.retain !== undefined) {\n result += text.slice(index, index + op.retain)\n index += op.retain\n } else if (op.delete !== undefined) {\n index += op.delete\n } else if (op.insert !== undefined) {\n result += op.insert\n }\n }\n\n if (index < text.length) {\n result += text.slice(index)\n }\n\n return result\n}\n\nfunction applyDeltaToDelta(\n base: Delta<string>[],\n diff: Delta<string>[],\n): Delta<string>[] {\n const baseText = base\n .map(op => (op.insert !== undefined ? op.insert : \"\"))\n .join(\"\")\n const nextText = applyTextDelta(baseText, diff)\n return nextText ? [{ insert: nextText }] : []\n}\n","import type { TextContainerShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { TextRefInternals } from \"./text-ref-internals.js\"\n\n/**\n * Text typed ref - thin facade that delegates to TextRefInternals.\n */\nexport class TextRef extends TypedRef<TextContainerShape> {\n [INTERNAL_SYMBOL]: TextRefInternals\n\n constructor(params: TypedRefParams<TextContainerShape>) {\n super()\n this[INTERNAL_SYMBOL] = new TextRefInternals(params)\n }\n\n /** Insert text at the given index */\n insert(index: number, content: string): void {\n this[INTERNAL_SYMBOL].insert(index, content)\n }\n\n /** Delete text at the given index */\n delete(index: number, len: number): void {\n this[INTERNAL_SYMBOL].delete(index, len)\n }\n\n /** Update the entire text content */\n update(text: string): void {\n this[INTERNAL_SYMBOL].update(text)\n }\n\n /** Mark a range of text with a key-value pair */\n mark(range: { start: number; end: number }, key: string, value: any): void {\n this[INTERNAL_SYMBOL].mark(range, key, value)\n }\n\n /** Remove a mark from a range of text */\n unmark(range: { start: number; end: number }, key: string): void {\n this[INTERNAL_SYMBOL].unmark(range, key)\n }\n\n /** Apply a delta to the text */\n applyDelta(delta: any[]): void {\n this[INTERNAL_SYMBOL].applyDelta(delta)\n }\n\n /** Get the text as a string */\n toString(): string {\n return this[INTERNAL_SYMBOL].getStringValue()\n }\n\n valueOf(): string {\n return this.toString()\n }\n\n toJSON(): string {\n return this.toString()\n }\n\n [Symbol.toPrimitive](_hint: string): string {\n return this.toString()\n }\n\n /** Get the text as a delta */\n toDelta(): any[] {\n return this[INTERNAL_SYMBOL].toDelta()\n }\n\n /** Get the length of the text */\n get length(): number {\n return this[INTERNAL_SYMBOL].getLength()\n }\n}\n","import type {\n LoroDoc,\n LoroEventBatch,\n LoroTreeNode,\n Subscription,\n} from \"loro-crdt\"\nimport { deriveShapePlaceholder } from \"../derive-placeholder.js\"\nimport type { LoroTreeNodeRef } from \"../loro.js\"\nimport type { StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport {\n INTERNAL_SYMBOL,\n type RefInternalsBase,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createStructRef, type StructRef } from \"./struct-ref.js\"\nimport type { TreeNodeRef, TreeNodeRefParams } from \"./tree-node-ref.js\"\n\n// Forward declaration to avoid circular import\n// TreeRef will be passed in via constructor params\nexport interface TreeRefLike<DataShape extends StructContainerShape> {\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape>\n}\n\n/**\n * Internal implementation for TreeNodeRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TreeNodeRefInternals<DataShape extends StructContainerShape>\n implements RefInternalsBase\n{\n private dataRef: StructRef<DataShape[\"shapes\"]> | undefined\n private loroNamespace: LoroTreeNodeRef | undefined\n\n constructor(private readonly params: TreeNodeRefParams<DataShape>) {}\n\n /** Get the underlying LoroTreeNode */\n getNode(): LoroTreeNode {\n return this.params.node\n }\n\n /** Get the data shape for this node */\n getDataShape(): DataShape {\n return this.params.dataShape\n }\n\n /** Get the parent TreeRef */\n getTreeRef(): TreeRefLike<DataShape> {\n return this.params.treeRef\n }\n\n /** Check if autoCommit is enabled */\n getAutoCommit(): boolean {\n return this.params.autoCommit ?? false\n }\n\n /** Check if in batched mutation mode */\n getBatchedMutation(): boolean {\n return this.params.batchedMutation ?? false\n }\n\n /** Get the LoroDoc */\n getDoc(): LoroDoc {\n return this.params.getDoc()\n }\n\n /** Commit changes if autoCommit is enabled */\n commitIfAuto(): void {\n if (this.params.autoCommit) {\n this.params.getDoc().commit()\n }\n }\n\n /** Get or create the data StructRef */\n getOrCreateDataRef(): StructRef<DataShape[\"shapes\"]> {\n if (!this.dataRef) {\n const node = this.getNode()\n const dataShape = this.getDataShape()\n\n // Get the node's data container (LoroMap)\n const dataContainer = (node as any).data\n\n if (!dataContainer) {\n throw new Error(`Node ${node.id} has no data container`)\n }\n\n // Create placeholder from the data shape\n const placeholder = deriveShapePlaceholder(dataShape) as Infer<DataShape>\n\n const refParams: TypedRefParams<\n StructContainerShape<DataShape[\"shapes\"]>\n > = {\n shape: {\n _type: \"struct\" as const,\n shapes: dataShape.shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n },\n placeholder: placeholder as any,\n getContainer: () => dataContainer,\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: this.params.getDoc,\n }\n\n this.dataRef = createStructRef(refParams)\n }\n return this.dataRef\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n if (this.dataRef) {\n this.dataRef[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n\n /** Force materialization of the container and its nested containers */\n materialize(): void {\n // Ensure data ref is created and materialized\n const dataRef = this.getOrCreateDataRef()\n dataRef[INTERNAL_SYMBOL].materialize()\n }\n\n /** Get the loro namespace (cached) */\n getLoroNamespace(): LoroTreeNodeRef {\n if (!this.loroNamespace) {\n this.loroNamespace = this.createLoroNamespace()\n }\n return this.loroNamespace\n }\n\n /** Create the loro namespace for tree node */\n protected createLoroNamespace(): LoroTreeNodeRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroTreeNode {\n return self.getNode()\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n // LoroTreeNode doesn't have subscribe, but we can subscribe to the tree\n // However, LoroRefBase expects subscribe.\n // For now, we can throw or return a dummy subscription if LoroTreeNode doesn't support it.\n // But wait, LoroTreeNode is just a handle.\n // Let's check if LoroTreeNode has subscribe.\n // If not, we might need to subscribe to the tree and filter?\n // Or maybe we just cast it if it exists at runtime.\n return (self.getNode() as any).subscribe?.(callback) || (() => {})\n },\n }\n }\n}\n","import type { LoroDoc, LoroTreeNode, TreeID } from \"loro-crdt\"\nimport { LORO_SYMBOL, type LoroTreeNodeRef } from \"../loro.js\"\nimport type { StructContainerShape } from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { INTERNAL_SYMBOL } from \"./base.js\"\nimport type { StructRef } from \"./struct-ref.js\"\nimport {\n TreeNodeRefInternals,\n type TreeRefLike,\n} from \"./tree-node-ref-internals.js\"\n\nexport interface TreeNodeRefParams<DataShape extends StructContainerShape> {\n node: LoroTreeNode\n dataShape: DataShape\n treeRef: TreeRefLike<DataShape>\n autoCommit?: boolean\n batchedMutation?: boolean\n getDoc: () => LoroDoc\n}\n\n/**\n * Typed ref for a single tree node - thin facade that delegates to TreeNodeRefInternals.\n * Provides type-safe access to node metadata via the `.data` property.\n *\n * **Note:** TreeNodeRef is not a subclass of TypedRef, but it implements\n * `[INTERNAL_SYMBOL]: RefInternalsBase` for consistency with other refs.\n * This allows internal code to call `absorbPlainValues()` uniformly\n * across all ref types during the `change()` commit phase.\n *\n * @example\n * ```typescript\n * const node = tree.createNode({ name: \"idle\", facts: {} })\n * node.data.name = \"active\" // Typed access\n * const child = node.createNode({ name: \"running\", facts: {} })\n * ```\n */\nexport class TreeNodeRef<DataShape extends StructContainerShape> {\n [INTERNAL_SYMBOL]: TreeNodeRefInternals<DataShape>\n\n constructor(params: TreeNodeRefParams<DataShape>) {\n this[INTERNAL_SYMBOL] = new TreeNodeRefInternals(params)\n }\n\n /**\n * Access the loro() namespace via the well-known symbol.\n */\n get [LORO_SYMBOL](): LoroTreeNodeRef {\n return this[INTERNAL_SYMBOL].getLoroNamespace()\n }\n\n /**\n * The unique TreeID of this node.\n */\n get id(): TreeID {\n return this[INTERNAL_SYMBOL].getNode().id\n }\n\n /**\n * Typed access to the node's metadata.\n * This is a StructRef wrapping the node's LoroMap data container.\n */\n get data(): StructRef<DataShape[\"shapes\"]> & {\n [K in keyof DataShape[\"shapes\"]]: DataShape[\"shapes\"][K][\"_mutable\"]\n } {\n return this[INTERNAL_SYMBOL].getOrCreateDataRef() as StructRef<\n DataShape[\"shapes\"]\n > & {\n [K in keyof DataShape[\"shapes\"]]: DataShape[\"shapes\"][K][\"_mutable\"]\n }\n }\n\n /**\n * Create a child node under this node.\n *\n * @param initialData - Optional partial data to initialize the child with\n * @param index - Optional position among siblings\n * @returns The created child TreeNodeRef\n */\n createNode(\n initialData?: Partial<Infer<DataShape>>,\n index?: number,\n ): TreeNodeRef<DataShape> {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n // Create child node - Loro's createNode on a tree node creates a child\n const loroNode = (node as any).createNode(index)\n const nodeRef = treeRef.getOrCreateNodeRef(loroNode)\n\n // Initialize data if provided\n if (initialData) {\n for (const [key, value] of Object.entries(initialData)) {\n ;(nodeRef.data as any)[key] = value\n }\n }\n\n this[INTERNAL_SYMBOL].commitIfAuto()\n return nodeRef\n }\n\n /**\n * Get the parent node, if any.\n */\n parent(): TreeNodeRef<DataShape> | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n const parentNode = (node as any).parent?.()\n if (!parentNode) return undefined\n return treeRef.getOrCreateNodeRef(parentNode)\n }\n\n /**\n * Get all child nodes in order.\n */\n children(): TreeNodeRef<DataShape>[] {\n const node = this[INTERNAL_SYMBOL].getNode()\n const treeRef = this[INTERNAL_SYMBOL].getTreeRef()\n\n const childNodes = (node as any).children?.() || []\n return childNodes.map((n: LoroTreeNode) => treeRef.getOrCreateNodeRef(n))\n }\n\n /**\n * Move this node to a new parent.\n *\n * @param newParent - The new parent node (undefined for root)\n * @param index - Optional position among siblings\n */\n move(newParent?: TreeNodeRef<DataShape>, index?: number): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n\n // node.move takes a LoroTreeNode or undefined, not an ID\n const parentNode = newParent\n ? newParent[INTERNAL_SYMBOL].getNode()\n : undefined\n ;(node as any).move?.(parentNode, index)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Move this node to be after the given sibling.\n */\n moveAfter(sibling: TreeNodeRef<DataShape>): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n const siblingNode = sibling[INTERNAL_SYMBOL].getNode()\n\n node.moveAfter(siblingNode)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Move this node to be before the given sibling.\n */\n moveBefore(sibling: TreeNodeRef<DataShape>): void {\n const node = this[INTERNAL_SYMBOL].getNode()\n const siblingNode = sibling[INTERNAL_SYMBOL].getNode()\n\n node.moveBefore(siblingNode)\n this[INTERNAL_SYMBOL].commitIfAuto()\n }\n\n /**\n * Get the index of this node among its siblings.\n */\n index(): number | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.index()\n }\n\n /**\n * Get the fractional index string for ordering.\n */\n fractionalIndex(): string | undefined {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.fractionalIndex()\n }\n\n /**\n * Check if this node has been deleted.\n */\n isDeleted(): boolean {\n const node = this[INTERNAL_SYMBOL].getNode()\n return node.isDeleted()\n }\n\n /**\n * Serialize this node and its descendants to JSON.\n */\n toJSON(): {\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n children: any[]\n } {\n const children = this.children()\n return {\n id: this.id,\n parent: this.parent()?.id ?? null,\n index: this.index() ?? 0,\n fractionalIndex: this.fractionalIndex() ?? \"\",\n data: this.data.toJSON() as Infer<DataShape>,\n children: children.map(child => child.toJSON()),\n }\n }\n}\n","import type {\n LoroDoc,\n LoroEventBatch,\n LoroTree,\n LoroTreeNode,\n Subscription,\n TreeID,\n} from \"loro-crdt\"\nimport type { LoroTreeRef } from \"../loro.js\"\nimport type { StructContainerShape, TreeContainerShape } from \"../shape.js\"\nimport { BaseRefInternals, INTERNAL_SYMBOL } from \"./base.js\"\nimport { TreeNodeRef } from \"./tree-node-ref.js\"\nimport type { TreeRef } from \"./tree-ref.js\"\n\n/**\n * Internal implementation for TreeRef.\n * Contains all logic, state, and implementation details.\n */\nexport class TreeRefInternals<\n DataShape extends StructContainerShape,\n> extends BaseRefInternals<TreeContainerShape<DataShape>> {\n private nodeCache = new Map<TreeID, TreeNodeRef<DataShape>>()\n private treeRef: TreeRef<DataShape> | null = null\n\n /** Set the parent TreeRef (needed for creating node refs) */\n setTreeRef(treeRef: TreeRef<DataShape>): void {\n this.treeRef = treeRef\n }\n\n /** Get the data shape for tree nodes */\n getDataShape(): DataShape {\n const shape = this.getShape() as TreeContainerShape<DataShape>\n return shape.shape\n }\n\n /** Get or create a node ref for a LoroTreeNode */\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape> {\n const id = node.id\n\n if (!this.treeRef) {\n throw new Error(\"treeRef required\")\n }\n\n let nodeRef = this.nodeCache.get(id)\n if (!nodeRef) {\n nodeRef = new TreeNodeRef({\n node,\n dataShape: this.getDataShape(),\n treeRef: this.treeRef,\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.getDoc(),\n })\n this.nodeCache.set(id, nodeRef)\n }\n\n return nodeRef\n }\n\n /** Get a node by its ID */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined {\n // Check cache first\n const cached = this.nodeCache.get(id)\n if (cached) return cached\n\n const container = this.getContainer() as LoroTree\n\n // Check if node exists in tree\n if (!container.has(id)) return undefined\n\n // Find the node in the tree's nodes\n const nodes = container.nodes()\n const node = nodes.find(n => n.id === id)\n if (!node) return undefined\n\n return this.getOrCreateNodeRef(node)\n }\n\n /** Delete a node from the tree */\n delete(target: TreeID | TreeNodeRef<DataShape>): void {\n const id = typeof target === \"string\" ? target : target.id\n const container = this.getContainer() as LoroTree\n container.delete(id)\n // Remove from cache\n this.nodeCache.delete(id)\n this.commitIfAuto()\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n for (const nodeRef of this.nodeCache.values()) {\n nodeRef[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n\n /** Create the loro namespace for tree */\n protected override createLoroNamespace(): LoroTreeRef {\n const self = this\n return {\n get doc(): LoroDoc {\n return self.getDoc()\n },\n get container(): LoroTree {\n return self.getContainer() as LoroTree\n },\n subscribe(callback: (event: LoroEventBatch) => void): Subscription {\n return (self.getContainer() as LoroTree).subscribe(callback)\n },\n }\n }\n}\n","import type { LoroTree, LoroTreeNode, TreeID } from \"loro-crdt\"\nimport type {\n StructContainerShape,\n TreeContainerShape,\n TreeNodeJSON,\n} from \"../shape.js\"\nimport type { Infer } from \"../types.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport type { TreeNodeRef } from \"./tree-node-ref.js\"\nimport { TreeRefInternals } from \"./tree-ref-internals.js\"\n\n/**\n * Typed ref for tree (forest) containers - thin facade that delegates to TreeRefInternals.\n * Wraps LoroTree with type-safe access to node metadata.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * doc.change(draft => {\n * const root = draft.states.createNode({ name: \"idle\", facts: {} })\n * const child = root.createNode({ name: \"running\", facts: {} })\n * child.data.name = \"active\"\n * })\n * ```\n */\nexport class TreeRef<DataShape extends StructContainerShape> extends TypedRef<\n TreeContainerShape<DataShape>\n> {\n [INTERNAL_SYMBOL]: TreeRefInternals<DataShape>\n\n constructor(params: TypedRefParams<TreeContainerShape<DataShape>>) {\n super()\n this[INTERNAL_SYMBOL] = new TreeRefInternals(params)\n this[INTERNAL_SYMBOL].setTreeRef(this)\n }\n\n /**\n * Get the data shape for tree nodes.\n */\n private get dataShape(): DataShape {\n return this[INTERNAL_SYMBOL].getDataShape()\n }\n\n /**\n * Get or create a node ref for a LoroTreeNode.\n */\n getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef<DataShape> {\n return this[INTERNAL_SYMBOL].getOrCreateNodeRef(node)\n }\n\n /**\n * Get a node by its ID.\n */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined {\n return this[INTERNAL_SYMBOL].getNodeByID(id)\n }\n\n /**\n * Delete a node from the tree.\n */\n delete(target: TreeID | TreeNodeRef<DataShape>): void {\n this[INTERNAL_SYMBOL].delete(target)\n }\n\n /**\n * Serialize the tree to a nested JSON structure.\n * Each node includes its data and children recursively.\n */\n toJSON(): Infer<TreeContainerShape<DataShape>> {\n // Use Loro's native toJSON which returns nested structure\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const nativeJson = container.toJSON() as any[]\n return this.transformNativeJson(nativeJson) as Infer<\n TreeContainerShape<DataShape>\n >\n }\n\n /**\n * Create a new root node with optional initial data.\n *\n * @param initialData - Optional partial data to initialize the node with\n * @returns The created TreeNodeRef\n */\n createNode(initialData?: Partial<Infer<DataShape>>): TreeNodeRef<DataShape> {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const loroNode = container.createNode()\n const nodeRef = this.getOrCreateNodeRef(loroNode)\n\n // Initialize data if provided\n if (initialData) {\n for (const [key, value] of Object.entries(initialData)) {\n ;(nodeRef.data as any)[key] = value\n }\n }\n\n this[INTERNAL_SYMBOL].commitIfAuto()\n return nodeRef\n }\n\n /**\n * Get all root nodes (nodes without parents).\n * Returns nodes in their fractional index order.\n */\n roots(): TreeNodeRef<DataShape>[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n return container.roots().map(node => this.getOrCreateNodeRef(node))\n }\n\n /**\n * Get all nodes in the tree (unordered).\n * By default, excludes deleted nodes (tombstones).\n *\n * @param options.includeDeleted - If true, includes deleted nodes. Default: false.\n * @returns Array of TreeNodeRef for matching nodes\n */\n nodes(options?: { includeDeleted?: boolean }): TreeNodeRef<DataShape>[] {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const allNodes = container.nodes()\n const filtered = options?.includeDeleted\n ? allNodes\n : allNodes.filter(node => !node.isDeleted())\n return filtered.map(node => this.getOrCreateNodeRef(node))\n }\n\n /**\n * Check if a node with the given ID exists in the tree.\n */\n has(id: TreeID): boolean {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n return container.has(id)\n }\n\n /**\n * Enable fractional index generation for ordering.\n *\n * @param jitter - Optional jitter value to avoid conflicts (0 = no jitter)\n */\n enableFractionalIndex(jitter = 0): void {\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n container.enableFractionalIndex(jitter)\n }\n\n /**\n * Transform Loro's native JSON format to our typed format.\n */\n private transformNativeJson(nodes: any[]): TreeNodeJSON<DataShape>[] {\n return nodes.map(node => ({\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index as number,\n fractionalIndex: node.fractional_index as string,\n data: node.meta as Infer<DataShape>,\n children: this.transformNativeJson(node.children || []),\n }))\n }\n\n /**\n * Get a flat array representation of all nodes.\n * Flattens the nested tree structure into a single array.\n */\n toArray(): Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n }> {\n const result: Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: Infer<DataShape>\n }> = []\n\n // Flatten the nested structure\n const flattenNodes = (nodes: any[]) => {\n for (const node of nodes) {\n result.push({\n id: node.id as TreeID,\n parent: node.parent as TreeID | null,\n index: node.index as number,\n fractionalIndex: node.fractional_index as string,\n data: node.meta as Infer<DataShape>,\n })\n if (node.children && node.children.length > 0) {\n flattenNodes(node.children)\n }\n }\n }\n\n const container = this[INTERNAL_SYMBOL].getContainer() as LoroTree\n const nativeJson = container.toJSON() as any[]\n flattenNodes(nativeJson)\n return result\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { ContainerShape, DocShape } from \"../shape.js\"\nimport {\n BaseRefInternals,\n INTERNAL_SYMBOL,\n type TypedRef,\n type TypedRefParams,\n} from \"./base.js\"\nimport { createContainerTypedRef } from \"./utils.js\"\n\nconst containerGetter = {\n counter: \"getCounter\",\n list: \"getList\",\n movableList: \"getMovableList\",\n record: \"getMap\",\n struct: \"getMap\", // Structs use LoroMap as their underlying container\n text: \"getText\",\n tree: \"getTree\",\n} as const satisfies Record<string, keyof LoroDoc>\n\ntype ContainerGetterKey = keyof typeof containerGetter\n\n/**\n * Internal implementation for DocRef.\n * Contains all logic, state, and implementation details.\n */\nexport class DocRefInternals<\n Shape extends DocShape,\n> extends BaseRefInternals<Shape> {\n private propertyCache = new Map<string, TypedRef<ContainerShape>>()\n private doc: LoroDoc\n private requiredPlaceholder: Infer<Shape>\n\n constructor(\n params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n batchedMutation?: boolean\n },\n ) {\n super({\n ...params,\n getContainer: () => {\n throw new Error(\"can't get container on DocRef\")\n },\n getDoc: () => params.doc,\n } as TypedRefParams<Shape>)\n\n this.doc = params.doc\n this.requiredPlaceholder = params.placeholder as Infer<Shape>\n }\n\n /** Get typed ref params for creating child refs at a key */\n getChildTypedRefParams(\n key: string,\n shape: ContainerShape,\n ): TypedRefParams<ContainerShape> {\n // Handle \"any\" shape type - it's an escape hatch that doesn't have a specific getter\n if (shape._type === \"any\") {\n throw new Error(\n `Cannot get typed ref params for \"any\" shape type. ` +\n `The \"any\" shape is an escape hatch for untyped containers and should be accessed directly via loroDoc.`,\n )\n }\n\n const getterName = containerGetter[shape._type as ContainerGetterKey]\n const getter = this.doc[getterName].bind(this.doc)\n\n return {\n shape,\n placeholder: this.requiredPlaceholder[key],\n getContainer: () => getter(key),\n autoCommit: this.getAutoCommit(),\n batchedMutation: this.getBatchedMutation(),\n getDoc: () => this.doc,\n overlay: this.getOverlay(),\n }\n }\n\n /** Get or create a typed ref for a key */\n getOrCreateTypedRef(\n key: string,\n shape: ContainerShape,\n ): TypedRef<ContainerShape> | number | string {\n let ref = this.propertyCache.get(key)\n\n if (!ref) {\n ref = createContainerTypedRef(this.getChildTypedRefParams(key, shape))\n this.propertyCache.set(key, ref)\n }\n\n return ref\n }\n\n /** Absorb mutated plain values back into Loro containers */\n absorbPlainValues(): void {\n // By iterating over the propertyCache, we achieve a small optimization\n // by only absorbing values that have been 'touched' in some way\n for (const [, ref] of this.propertyCache.entries()) {\n ref[INTERNAL_SYMBOL].absorbPlainValues()\n }\n }\n}\n","import type { LoroDoc } from \"loro-crdt\"\nimport type { Infer } from \"../index.js\"\nimport type { DocShape } from \"../shape.js\"\nimport { INTERNAL_SYMBOL, TypedRef, type TypedRefParams } from \"./base.js\"\nimport { DocRefInternals } from \"./doc-ref-internals.js\"\nimport { serializeRefToJSON } from \"./utils.js\"\n\n/**\n * Doc Ref class - thin facade that delegates to DocRefInternals.\n * The actual object passed to the change `mutation` function.\n */\nexport class DocRef<Shape extends DocShape> extends TypedRef<Shape> {\n [INTERNAL_SYMBOL]: DocRefInternals<Shape>\n\n constructor(\n params: Omit<TypedRefParams<Shape>, \"getContainer\" | \"getDoc\"> & {\n doc: LoroDoc\n autoCommit?: boolean\n batchedMutation?: boolean\n },\n ) {\n super()\n if (!params.placeholder) throw new Error(\"placeholder required\")\n this[INTERNAL_SYMBOL] = new DocRefInternals(params)\n this.createLazyProperties()\n }\n\n private createLazyProperties(): void {\n const shape = this[INTERNAL_SYMBOL].getShape() as DocShape\n for (const key in shape.shapes) {\n const containerShape = shape.shapes[key]\n Object.defineProperty(this, key, {\n get: () =>\n this[INTERNAL_SYMBOL].getOrCreateTypedRef(key, containerShape),\n enumerable: true,\n })\n }\n }\n\n toJSON(): Infer<Shape> {\n const shape = this[INTERNAL_SYMBOL].getShape() as DocShape\n return serializeRefToJSON(\n this as any,\n Object.keys(shape.shapes),\n ) as Infer<Shape>\n }\n}\n","import type {\n ArrayValueShape,\n ContainerOrValueShape,\n DiscriminatedUnionValueShape,\n DocShape,\n ListContainerShape,\n MovableListContainerShape,\n RecordContainerShape,\n RecordValueShape,\n StringValueShape,\n StructContainerShape,\n StructValueShape,\n UnionValueShape,\n ValueShape,\n} from \"./shape.js\"\nimport type { Infer } from \"./types.js\"\n\n/**\n * Validates a value against a ContainerShape or ValueShape schema\n */\nexport function validateValue(\n value: unknown,\n schema: ContainerOrValueShape,\n path: string = \"\",\n): unknown {\n if (!schema || typeof schema !== \"object\" || !(\"_type\" in schema)) {\n throw new Error(`Invalid schema at path ${path}: missing _type`)\n }\n\n const currentPath = path || \"root\"\n\n // Handle AnyContainerShape - no validation, accept anything\n if (schema._type === \"any\") {\n return value\n }\n\n // Handle ContainerShape types\n if (schema._type === \"text\") {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"counter\") {\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n }\n\n if (schema._type === \"list\" || schema._type === \"movableList\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const listSchema = schema as ListContainerShape | MovableListContainerShape\n return value.map((item, index) =>\n validateValue(item, listSchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n if (schema._type === \"struct\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = schema as StructContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shapes)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"record\") {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = schema as RecordContainerShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(nestedValue, recordSchema.shape, nestedPath)\n }\n return result\n }\n\n if (schema._type === \"tree\") {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array for tree at path ${currentPath}, got ${typeof value}`,\n )\n }\n // Trees can contain any structure, so we just validate it's an array\n return value\n }\n\n // Handle ValueShape types\n if (schema._type === \"value\") {\n const valueSchema = schema as ValueShape\n\n switch (valueSchema.valueType) {\n // AnyValueShape - no validation, accept anything\n case \"any\":\n return value\n\n case \"string\": {\n if (typeof value !== \"string\") {\n throw new Error(\n `Expected string at path ${currentPath}, got ${typeof value}`,\n )\n }\n const stringSchema = valueSchema as StringValueShape\n if (stringSchema.options && !stringSchema.options.includes(value)) {\n throw new Error(\n `Expected one of [${stringSchema.options.join(\", \")}] at path ${currentPath}, got \"${value}\"`,\n )\n }\n return value\n }\n\n case \"number\":\n if (typeof value !== \"number\") {\n throw new Error(\n `Expected number at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n throw new Error(\n `Expected boolean at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"null\":\n if (value !== null) {\n throw new Error(\n `Expected null at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"undefined\":\n if (value !== undefined) {\n throw new Error(\n `Expected undefined at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"uint8array\":\n if (!(value instanceof Uint8Array)) {\n throw new Error(\n `Expected Uint8Array at path ${currentPath}, got ${typeof value}`,\n )\n }\n return value\n\n case \"struct\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const structSchema = valueSchema as StructValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the struct shape\n for (const [key, nestedSchema] of Object.entries(structSchema.shape)) {\n const nestedPath = `${currentPath}.${key}`\n const nestedValue = (value as Record<string, unknown>)[key]\n result[key] = validateValue(nestedValue, nestedSchema, nestedPath)\n }\n return result\n }\n\n case \"record\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n const recordSchema = valueSchema as RecordValueShape\n const result: Record<string, unknown> = {}\n\n // Validate each property in the record\n for (const [key, nestedValue] of Object.entries(value)) {\n const nestedPath = `${currentPath}.${key}`\n result[key] = validateValue(\n nestedValue,\n recordSchema.shape,\n nestedPath,\n )\n }\n return result\n }\n\n case \"array\": {\n if (!Array.isArray(value)) {\n throw new Error(\n `Expected array at path ${currentPath}, got ${typeof value}`,\n )\n }\n const arraySchema = valueSchema as ArrayValueShape\n return value.map((item, index) =>\n validateValue(item, arraySchema.shape, `${currentPath}[${index}]`),\n )\n }\n\n case \"union\": {\n const unionSchema = valueSchema as UnionValueShape\n let lastError: Error | null = null\n\n // Try to validate against each shape in the union\n for (const shape of unionSchema.shapes) {\n try {\n return validateValue(value, shape, currentPath)\n } catch (error) {\n lastError = error as Error\n }\n }\n\n throw new Error(\n `Value at path ${currentPath} does not match any union type: ${lastError?.message}`,\n )\n }\n\n case \"discriminatedUnion\": {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) {\n throw new Error(\n `Expected object at path ${currentPath}, got ${typeof value}`,\n )\n }\n\n const unionSchema = valueSchema as DiscriminatedUnionValueShape\n const discriminantKey = unionSchema.discriminantKey\n const discriminantValue = (value as Record<string, unknown>)[\n discriminantKey\n ]\n\n if (typeof discriminantValue !== \"string\") {\n throw new Error(\n `Expected string for discriminant key \"${discriminantKey}\" at path ${currentPath}, got ${typeof discriminantValue}`,\n )\n }\n\n const variantSchema = unionSchema.variants[discriminantValue]\n\n if (!variantSchema) {\n throw new Error(\n `Invalid discriminant value \"${discriminantValue}\" at path ${currentPath}. Expected one of: ${Object.keys(\n unionSchema.variants,\n ).join(\", \")}`,\n )\n }\n\n return validateValue(value, variantSchema, currentPath)\n }\n\n default:\n throw new Error(`Unknown value type: ${(valueSchema as any).valueType}`)\n }\n }\n\n throw new Error(`Unknown schema type: ${(schema as any)._type}`)\n}\n\n/**\n * Validates placeholder against schema structure without using Zod\n * Combines the functionality of createPlaceholderValidator and createValueValidator\n */\nexport function validatePlaceholder<T extends DocShape>(\n placeholder: unknown,\n schema: T,\n): Infer<T> {\n if (\n !placeholder ||\n typeof placeholder !== \"object\" ||\n Array.isArray(placeholder)\n ) {\n throw new Error(\"Placeholder must be an object\")\n }\n\n const result: Record<string, unknown> = {}\n\n // Validate each property in the document schema\n for (const [key, schemaValue] of Object.entries(schema.shapes)) {\n const value = (placeholder as Record<string, unknown>)[key]\n result[key] = validateValue(value, schemaValue, key)\n }\n\n return result as Infer<T>\n}\n","// ============================================================================\n// Path Builder Factory\n// ============================================================================\n//\n// Runtime implementation of the path builder that creates PathSelector objects\n// with proper segments for JSONPath compilation.\n\nimport type { PathBuilder, PathSegment, PathSelector } from \"./path-selector.js\"\nimport type { ContainerOrValueShape, DocShape } from \"./shape.js\"\n\nfunction createPathSelector<T>(segments: PathSegment[]): PathSelector<T> {\n return {\n __resultType: undefined as unknown as T,\n __segments: segments,\n }\n}\n\nfunction createPathNode(\n shape: ContainerOrValueShape,\n segments: PathSegment[],\n): unknown {\n const selector = createPathSelector(segments)\n\n // Terminal shapes (text, counter, value)\n if (shape._type === \"text\" || shape._type === \"counter\") {\n return selector\n }\n if (shape._type === \"value\") {\n return selector\n }\n\n // List/MovableList\n if (shape._type === \"list\" || shape._type === \"movableList\") {\n return Object.assign(selector, {\n get $each() {\n return createPathNode(shape.shape, [...segments, { type: \"each\" }])\n },\n $at(index: number) {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index },\n ])\n },\n get $first() {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index: 0 },\n ])\n },\n get $last() {\n return createPathNode(shape.shape, [\n ...segments,\n { type: \"index\", index: -1 },\n ])\n },\n })\n }\n\n // Struct (fixed keys)\n if (shape._type === \"struct\") {\n const props: Record<string, unknown> = {}\n for (const key in shape.shapes) {\n Object.defineProperty(props, key, {\n get() {\n return createPathNode(shape.shapes[key], [\n ...segments,\n { type: \"property\", key },\n ])\n },\n enumerable: true,\n })\n }\n return Object.assign(selector, props)\n }\n\n // Record (dynamic keys)\n if (shape._type === \"record\") {\n return Object.assign(selector, {\n get $each() {\n return createPathNode(shape.shape, [...segments, { type: \"each\" }])\n },\n $key(key: string) {\n return createPathNode(shape.shape, [...segments, { type: \"key\", key }])\n },\n })\n }\n\n return selector\n}\n\n/**\n * Creates a path builder for a given document shape.\n *\n * The path builder provides a type-safe DSL for selecting paths within\n * a document. The resulting PathSelector can be compiled to a JSONPath\n * string for use with subscribeJsonpath.\n *\n * @example\n * ```typescript\n * const docShape = Shape.doc({\n * books: Shape.list(Shape.struct({\n * title: Shape.text(),\n * price: Shape.plain.number(),\n * })),\n * })\n *\n * const builder = createPathBuilder(docShape)\n * const selector = builder.books.$each.title\n * // selector.__segments = [\n * // { type: \"property\", key: \"books\" },\n * // { type: \"each\" },\n * // { type: \"property\", key: \"title\" }\n * // ]\n * ```\n */\nexport function createPathBuilder<D extends DocShape>(\n docShape: D,\n): PathBuilder<D> {\n const builder: Record<string, unknown> = {}\n\n for (const key in docShape.shapes) {\n Object.defineProperty(builder, key, {\n get() {\n return createPathNode(docShape.shapes[key], [{ type: \"property\", key }])\n },\n enumerable: true,\n })\n }\n\n return builder as PathBuilder<D>\n}\n","// ============================================================================\n// JSONPath Compiler\n// ============================================================================\n//\n// Compiles PathSelector segments to JSONPath strings for use with\n// subscribeJsonpath.\n\nimport type { PathSegment } from \"./path-selector.js\"\n\n/**\n * Compiles path segments to a JSONPath string.\n *\n * @example\n * ```typescript\n * const segments = [\n * { type: \"property\", key: \"books\" },\n * { type: \"each\" },\n * { type: \"property\", key: \"title\" }\n * ]\n * compileToJsonPath(segments) // => '$.books[*].title'\n * ```\n */\nexport function compileToJsonPath(segments: PathSegment[]): string {\n let path = \"$\"\n\n for (const segment of segments) {\n switch (segment.type) {\n case \"property\":\n // Use dot notation for simple identifiers, bracket notation for safety\n if (/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(segment.key)) {\n path += `.${segment.key}`\n } else {\n path += `[\"${escapeJsonPathKey(segment.key)}\"]`\n }\n break\n case \"each\":\n path += \"[*]\"\n break\n case \"index\":\n path += `[${segment.index}]`\n break\n case \"key\":\n path += `[\"${escapeJsonPathKey(segment.key)}\"]`\n break\n }\n }\n\n return path\n}\n\n/**\n * Escapes special characters in a JSONPath key.\n */\nfunction escapeJsonPathKey(key: string): string {\n return key.replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')\n}\n\n/**\n * Check if the path contains any wildcard segments.\n * Paths with wildcards need deep equality checking for change detection.\n */\nexport function hasWildcard(segments: PathSegment[]): boolean {\n return segments.some(s => s.type === \"each\")\n}\n","// ============================================================================\n// Path Evaluator\n// ============================================================================\n//\n// Evaluates a path selector against a TypedDoc to get the current value.\n// This is used for:\n// 1. Establishing the initial previousValue baseline\n// 2. Getting the current value when subscribeJsonpath fires\n// 3. Deep equality comparison to filter false positives\n\nimport type { PathSegment, PathSelector } from \"./path-selector.js\"\nimport type { DocShape } from \"./shape.js\"\nimport type { TypedDoc } from \"./typed-doc.js\"\n\n/**\n * Evaluate a path selector against a TypedDoc to get the current value.\n * Returns the value(s) at the path, properly typed.\n *\n * @example\n * ```typescript\n * const selector = builder.books.$each.title\n * const titles = evaluatePath(doc, selector)\n * // titles: string[]\n * ```\n */\nexport function evaluatePath<D extends DocShape, T>(\n doc: TypedDoc<D>,\n selector: PathSelector<T>,\n): T {\n const json = doc.toJSON()\n return evaluatePathOnValue(json, selector.__segments) as T\n}\n\n/**\n * Evaluate path segments against a plain JavaScript value.\n * This is the core recursive evaluation logic.\n */\nexport function evaluatePathOnValue(\n value: unknown,\n segments: PathSegment[],\n): unknown {\n if (segments.length === 0) {\n return value\n }\n\n const [segment, ...rest] = segments\n\n switch (segment.type) {\n case \"property\":\n case \"key\":\n if (value == null) return undefined\n if (typeof value !== \"object\") return undefined\n return evaluatePathOnValue(\n (value as Record<string, unknown>)[segment.key],\n rest,\n )\n\n case \"index\": {\n if (!Array.isArray(value)) return undefined\n // Handle negative indices: -1 = last, -2 = second-to-last, etc.\n const index =\n segment.index < 0 ? value.length + segment.index : segment.index\n if (index < 0 || index >= value.length) return undefined\n return evaluatePathOnValue(value[index], rest)\n }\n\n case \"each\":\n if (Array.isArray(value)) {\n return value.map(item => evaluatePathOnValue(item, rest))\n }\n if (typeof value === \"object\" && value !== null) {\n return Object.values(value).map(item => evaluatePathOnValue(item, rest))\n }\n return []\n }\n}\n","/**\n * Creates a proxy around a placeholder value (plain object/array) that mimics\n * the behavior of TypedRef, specifically adding a .toJSON() method.\n *\n * This ensures consistent UX where users can call .toJSON() on document state\n * regardless of whether it's loading (placeholder) or loaded (live ref).\n */\nexport function createPlaceholderProxy<T extends object>(target: T): T {\n // Cache for wrapped properties to ensure referential stability\n const cache = new Map<string | symbol, any>()\n\n return new Proxy(target, {\n get(target, prop, receiver) {\n // Intercept .toJSON()\n if (prop === \"toJSON\") {\n return () => target\n }\n\n // Check cache first\n if (cache.has(prop)) {\n return cache.get(prop)\n }\n\n // Get value from target\n const value = Reflect.get(target, prop, receiver)\n\n // Recursively wrap objects/arrays\n if (value && typeof value === \"object\") {\n const wrapped = createPlaceholderProxy(value)\n cache.set(prop, wrapped)\n return wrapped\n }\n\n return value\n },\n })\n}\n","import type {\n Container,\n ContainerID,\n CounterDiff,\n Diff,\n ListDiff,\n LoroCounter,\n LoroDoc,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n MapDiff,\n TextDiff,\n TreeDiff,\n TreeDiffItem,\n Value,\n} from \"loro-crdt\"\n\n/**\n * Replay a diff as local operations on a document.\n *\n * Unlike doc.import() which creates import events, this creates LOCAL events\n * that are captured by subscribeLocalUpdates() and UndoManager.\n *\n * @param doc - The target document to apply changes to\n * @param diff - The diff from doc.diff(from, to, false)\n */\nexport function replayDiff(doc: LoroDoc, diff: [ContainerID, Diff][]): void {\n // Map from source container IDs to target containers\n // This is needed because when we create new containers, they get different IDs\n const containerMap = new Map<ContainerID, Container>()\n\n for (const [containerId, containerDiff] of diff) {\n // First, try to get the container from our map (for newly created containers)\n let container = containerMap.get(containerId)\n\n // If not in map, try to get it from the doc (for existing containers)\n if (!container) {\n container = doc.getContainerById(containerId)\n }\n\n if (!container) {\n // Container doesn't exist yet - this can happen for newly created containers\n // that haven't been mapped yet. Skip for now, it will be created when\n // processing the parent container's diff.\n continue\n }\n\n switch (containerDiff.type) {\n case \"text\":\n replayTextDiff(container as LoroText, containerDiff)\n break\n case \"list\":\n replayListDiff(\n container as LoroList | LoroMovableList,\n containerDiff,\n containerMap,\n )\n break\n case \"map\":\n replayMapDiff(container as LoroMap, containerDiff, containerMap)\n break\n case \"tree\":\n replayTreeDiff(container as LoroTree, containerDiff)\n break\n case \"counter\":\n replayCounterDiff(container as LoroCounter, containerDiff)\n break\n }\n }\n}\n\n/**\n * Replay text diff operations\n */\nfunction replayTextDiff(text: LoroText, diff: TextDiff): void {\n // LoroText has applyDelta which handles the delta format directly\n text.applyDelta(diff.diff)\n}\n\n/**\n * Replay list diff operations\n */\nfunction replayListDiff(\n list: LoroList | LoroMovableList,\n diff: ListDiff,\n containerMap: Map<ContainerID, Container>,\n): void {\n let index = 0\n\n for (const delta of diff.diff) {\n if (delta.retain !== undefined) {\n // Retain: skip over existing elements\n index += delta.retain\n } else if (delta.delete !== undefined) {\n // Delete: remove elements at current position\n list.delete(index, delta.delete)\n // Don't advance index - next operation is at same position\n } else if (delta.insert !== undefined) {\n // Insert: add elements at current position\n const values = delta.insert\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n if (isContainer(value)) {\n // For containers, we need to insert a new container of the same type\n // The container's contents will be handled by its own diff entry\n const newContainer = createContainerOfSameType(value)\n const insertedContainer = (list as LoroList).insertContainer(\n index + i,\n newContainer,\n )\n // Map the source container ID to the newly created container\n containerMap.set(value.id, insertedContainer)\n } else {\n ;(list as LoroList).insert(\n index + i,\n value as Exclude<Value, Container>,\n )\n }\n }\n index += values.length\n }\n }\n}\n\n/**\n * Replay map diff operations\n */\nfunction replayMapDiff(\n map: LoroMap,\n diff: MapDiff,\n containerMap: Map<ContainerID, Container>,\n): void {\n for (const [key, value] of Object.entries(diff.updated)) {\n if (value === undefined) {\n // Delete the key\n map.delete(key)\n } else if (isContainer(value)) {\n // Set a container - create a new one of the same type\n const newContainer = createContainerOfSameType(value)\n const insertedContainer = map.setContainer(key, newContainer)\n // Map the source container ID to the newly created container\n containerMap.set(value.id, insertedContainer)\n } else {\n // Set a primitive value\n map.set(key, value as Exclude<Value, Container>)\n }\n }\n}\n\n/**\n * Replay tree diff operations\n */\nfunction replayTreeDiff(tree: LoroTree, diff: TreeDiff): void {\n for (const item of diff.diff) {\n replayTreeDiffItem(tree, item)\n }\n}\n\n/**\n * Replay a single tree diff item\n */\nfunction replayTreeDiffItem(tree: LoroTree, item: TreeDiffItem): void {\n switch (item.action) {\n case \"create\":\n // Create a new node under the specified parent\n // Note: The node ID is determined by the CRDT, we can't specify it\n // This means we're creating a NEW node, not recreating the exact same one\n tree.createNode(item.parent, item.index)\n break\n case \"delete\":\n // Delete the node\n tree.delete(item.target)\n break\n case \"move\":\n // Move the node to a new parent/position\n tree.move(item.target, item.parent, item.index)\n break\n }\n}\n\n/**\n * Replay counter diff operations\n */\nfunction replayCounterDiff(counter: LoroCounter, diff: CounterDiff): void {\n if (diff.increment > 0) {\n counter.increment(diff.increment)\n } else if (diff.increment < 0) {\n counter.decrement(-diff.increment)\n }\n // If increment is 0, no operation needed\n}\n\n/**\n * Check if a value is a Container\n */\nfunction isContainer(value: Value | Container): value is Container {\n return (\n value !== null &&\n typeof value === \"object\" &&\n \"kind\" in value &&\n typeof (value as Container).kind === \"function\"\n )\n}\n\n/**\n * Create a new detached container of the same type as the given container\n */\nfunction createContainerOfSameType(container: Container): Container {\n const kind = container.kind()\n switch (kind) {\n case \"List\":\n return new (container.constructor as new () => LoroList)()\n case \"Map\":\n return new (container.constructor as new () => LoroMap)()\n case \"Text\":\n return new (container.constructor as new () => LoroText)()\n case \"Tree\":\n return new (container.constructor as new () => LoroTree)()\n case \"Counter\":\n return new (container.constructor as new () => LoroCounter)()\n case \"MovableList\":\n return new (container.constructor as new () => LoroMovableList)()\n default:\n throw new Error(`Unknown container kind: ${kind}`)\n }\n}\n","// biome-ignore-all lint/suspicious/noExplicitAny: required\n\nimport type {\n LoroCounter,\n LoroList,\n LoroMap,\n LoroMovableList,\n LoroText,\n LoroTree,\n TreeID,\n Value,\n} from \"loro-crdt\"\n\nimport { LORO_SYMBOL, type LoroTreeRef } from \"./loro.js\"\nimport type { CounterRef } from \"./typed-refs/counter-ref.js\"\nimport type { ListRef } from \"./typed-refs/list-ref.js\"\nimport type { MovableListRef } from \"./typed-refs/movable-list-ref.js\"\nimport type { RecordRef } from \"./typed-refs/record-ref.js\"\nimport type { StructRef } from \"./typed-refs/struct-ref.js\"\nimport type { TextRef } from \"./typed-refs/text-ref.js\"\nimport type { TreeNodeRef } from \"./typed-refs/tree-node-ref.js\"\n\nexport interface Shape<Plain, Mutable, Placeholder = Plain> {\n readonly _type: string\n readonly _plain: Plain\n readonly _mutable: Mutable\n readonly _placeholder: Placeholder\n}\n\n// Type for shapes that support placeholder customization\nexport type WithPlaceholder<S extends Shape<any, any, any>> = S & {\n placeholder(value: S[\"_placeholder\"]): S\n}\n\n/**\n * Type for value shapes that support the .nullable() method.\n * Returns a union of null and the original shape with null as the default placeholder.\n */\nexport type WithNullable<S extends ValueShape> = {\n nullable(): WithPlaceholder<UnionValueShape<[NullValueShape, S]>>\n}\n\nexport interface DocShape<\n NestedShapes extends Record<string, ContainerShape> = Record<\n string,\n ContainerShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_mutable\"] },\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"doc\"\n // A doc's root containers each separately has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface TextContainerShape extends Shape<string, TextRef, string> {\n readonly _type: \"text\"\n}\nexport interface CounterContainerShape\n extends Shape<number, CounterRef, number> {\n readonly _type: \"counter\"\n}\n/**\n * JSON representation of a tree node with typed data.\n * Used for serialization (toJSON) of tree structures.\n */\nexport type TreeNodeJSON<DataShape extends StructContainerShape> = {\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: DataShape[\"_plain\"]\n children: TreeNodeJSON<DataShape>[]\n}\n\n/**\n * Interface describing the TreeRef API for use in shape definitions.\n * This avoids circular type references that would occur with the TreeRef class.\n * @internal\n */\nexport interface TreeRefInterface<DataShape extends StructContainerShape> {\n /** Get or create a node ref for a LoroTreeNode */\n getOrCreateNodeRef(node: unknown): TreeNodeRef<DataShape>\n /** Get a node by its ID */\n getNodeByID(id: TreeID): TreeNodeRef<DataShape> | undefined\n /** Delete a node from the tree */\n delete(target: TreeID | TreeNodeRef<DataShape>): void\n /** Serialize the tree to a nested JSON structure */\n toJSON(): TreeNodeJSON<DataShape>[]\n /** Create a new root node with optional initial data */\n createNode(initialData?: Partial<DataShape[\"_plain\"]>): TreeNodeRef<DataShape>\n /** Get all root nodes (nodes without parents) */\n roots(): TreeNodeRef<DataShape>[]\n /** Get all nodes in the tree (unordered). By default excludes deleted nodes. */\n nodes(options?: { includeDeleted?: boolean }): TreeNodeRef<DataShape>[]\n /** Check if a node with the given ID exists in the tree */\n has(id: TreeID): boolean\n /** Enable fractional index generation for ordering */\n enableFractionalIndex(jitter?: number): void\n /** Get a flat array representation of all nodes */\n toArray(): Array<{\n id: TreeID\n parent: TreeID | null\n index: number\n fractionalIndex: string\n data: DataShape[\"_plain\"]\n }>\n\n /**\n * Access CRDT internals via the well-known symbol.\n */\n readonly [LORO_SYMBOL]: LoroTreeRef\n}\n\n/**\n * Container shape for tree (forest) structures.\n * Each node in the tree has typed metadata stored in a LoroMap.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * const Schema = Shape.doc({\n * states: Shape.tree(StateNodeDataShape),\n * })\n * ```\n */\nexport interface TreeContainerShape<\n DataShape extends StructContainerShape = StructContainerShape,\n> extends Shape<\n TreeNodeJSON<DataShape>[],\n TreeRefInterface<DataShape>,\n never[]\n > {\n readonly _type: \"tree\"\n /**\n * The shape of each node's data (metadata).\n * This is a StructContainerShape that defines the typed properties on node.data.\n */\n readonly shape: DataShape\n}\n\n// Container schemas using interfaces for recursive references\n// NOTE: List and Record use never[] and Record<string, never> for Placeholder\n// to enforce that only empty values ([] and {}) are valid in placeholder state.\n// This prevents users from expecting per-entry merging behavior.\nexport interface ListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], ListRef<NestedShape>, never[]> {\n readonly _type: \"list\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\nexport interface MovableListContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<NestedShape[\"_plain\"][], MovableListRef<NestedShape>, never[]> {\n readonly _type: \"movableList\"\n // A list contains many elements, all of the same 'shape'\n readonly shape: NestedShape\n}\n\n/**\n * @deprecated Use StructContainerShape instead. MapContainerShape is an alias for backward compatibility.\n */\nexport type MapContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> = StructContainerShape<NestedShapes>\n\n/**\n * Container shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key objects.\n * Uses LoroMap as the underlying container.\n */\nexport interface StructContainerShape<\n NestedShapes extends Record<string, ContainerOrValueShape> = Record<\n string,\n ContainerOrValueShape\n >,\n> extends Shape<\n { [K in keyof NestedShapes]: NestedShapes[K][\"_plain\"] },\n StructRef<NestedShapes>,\n { [K in keyof NestedShapes]: NestedShapes[K][\"_placeholder\"] }\n > {\n readonly _type: \"struct\"\n // Each struct property has its own shape, hence 'shapes'\n readonly shapes: NestedShapes\n}\n\nexport interface RecordContainerShape<\n NestedShape extends ContainerOrValueShape = ContainerOrValueShape,\n> extends Shape<\n Record<string, NestedShape[\"_plain\"]>,\n RecordRef<NestedShape>,\n Record<string, never>\n > {\n readonly _type: \"record\"\n readonly shape: NestedShape\n}\n\n/**\n * Container escape hatch - represents \"any LoroContainer\".\n * Use this when integrating with external libraries that manage their own document structure.\n *\n * @example\n * ```typescript\n * // loro-prosemirror manages its own structure\n * const ProseMirrorDocShape = Shape.doc({\n * doc: Shape.any(), // opt out of typing for this container\n * })\n * ```\n */\nexport interface AnyContainerShape extends Shape<unknown, unknown, undefined> {\n readonly _type: \"any\"\n}\n\n/**\n * Union of all container shape types.\n *\n * Each container shape has a `_mutable` type parameter that maps to the\n * corresponding TypedRef class (e.g., TextContainerShape → TextRef).\n * This enables deriving ref types from shapes:\n *\n * ```typescript\n * // Get the ref type for any container shape\n * type RefType = ContainerShape[\"_mutable\"]\n *\n * // Exclude AnyContainerShape to get only typed refs\n * type AnyTypedRef = Exclude<ContainerShape, AnyContainerShape>[\"_mutable\"]\n * ```\n *\n * This creates intentional parallel hierarchies:\n * - ContainerShape → defines what data looks like (schema)\n * - TypedRef (via _mutable) → defines how you interact with data\n * - loro() overloads → CRDT escape hatch (IDE DX)\n * - change() overloads → mutation boundaries (IDE DX)\n */\nexport type ContainerShape =\n | AnyContainerShape\n | CounterContainerShape\n | ListContainerShape\n | MovableListContainerShape\n | RecordContainerShape\n | StructContainerShape\n | TextContainerShape\n | TreeContainerShape\n\nexport type ContainerType = ContainerShape[\"_type\"]\n\n// LoroValue shape types - a shape for each of Loro's Value types\nexport interface StringValueShape<T extends string = string>\n extends Shape<T, T, T> {\n readonly _type: \"value\"\n readonly valueType: \"string\"\n readonly options?: T[]\n}\nexport interface NumberValueShape extends Shape<number, number, number> {\n readonly _type: \"value\"\n readonly valueType: \"number\"\n}\nexport interface BooleanValueShape extends Shape<boolean, boolean, boolean> {\n readonly _type: \"value\"\n readonly valueType: \"boolean\"\n}\nexport interface NullValueShape extends Shape<null, null, null> {\n readonly _type: \"value\"\n readonly valueType: \"null\"\n}\nexport interface UndefinedValueShape\n extends Shape<undefined, undefined, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"undefined\"\n}\nexport interface Uint8ArrayValueShape\n extends Shape<Uint8Array, Uint8Array, Uint8Array> {\n readonly _type: \"value\"\n readonly valueType: \"uint8array\"\n}\n\n/**\n * @deprecated Use StructValueShape instead. ObjectValueShape is an alias for backward compatibility.\n */\nexport type ObjectValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> = StructValueShape<T>\n\n/**\n * Value shape for objects with fixed keys (structs).\n * This is the preferred way to define fixed-key plain value objects.\n * Identical structure to ObjectValueShape but with valueType: \"struct\".\n */\nexport interface StructValueShape<\n T extends Record<string, ValueShape> = Record<string, ValueShape>,\n> extends Shape<\n { [K in keyof T]: T[K][\"_plain\"] },\n { [K in keyof T]: T[K][\"_mutable\"] },\n { [K in keyof T]: T[K][\"_placeholder\"] }\n > {\n readonly _type: \"value\"\n readonly valueType: \"struct\"\n readonly shape: T\n}\n\n// NOTE: RecordValueShape and ArrayValueShape use Record<string, never> and never[]\n// for Placeholder to enforce that only empty values ({} and []) are valid.\nexport interface RecordValueShape<T extends ValueShape = ValueShape>\n extends Shape<\n Record<string, T[\"_plain\"]>,\n Record<string, T[\"_mutable\"]>,\n Record<string, never>\n > {\n readonly _type: \"value\"\n readonly valueType: \"record\"\n readonly shape: T\n}\n\nexport interface ArrayValueShape<T extends ValueShape = ValueShape>\n extends Shape<T[\"_plain\"][], T[\"_mutable\"][], never[]> {\n readonly _type: \"value\"\n readonly valueType: \"array\"\n readonly shape: T\n}\n\nexport interface UnionValueShape<T extends ValueShape[] = ValueShape[]>\n extends Shape<\n T[number][\"_plain\"],\n T[number][\"_mutable\"],\n T[number][\"_placeholder\"]\n > {\n readonly _type: \"value\"\n readonly valueType: \"union\"\n readonly shapes: T\n}\n\n/**\n * A discriminated union shape that uses a discriminant key to determine which variant to use.\n * This enables type-safe handling of tagged unions like:\n *\n * ```typescript\n * type GamePresence =\n * | { type: \"client\"; name: string; input: { force: number; angle: number } }\n * | { type: \"server\"; cars: Record<string, CarState>; tick: number }\n * ```\n *\n * @typeParam K - The discriminant key (e.g., \"type\")\n * @typeParam T - A record mapping discriminant values to their object shapes\n */\nexport interface DiscriminatedUnionValueShape<\n K extends string = string,\n T extends Record<string, StructValueShape> = Record<string, StructValueShape>,\n Plain = T[keyof T][\"_plain\"],\n Mutable = T[keyof T][\"_mutable\"],\n Placeholder = T[keyof T][\"_placeholder\"],\n> extends Shape<Plain, Mutable, Placeholder> {\n readonly _type: \"value\"\n readonly valueType: \"discriminatedUnion\"\n readonly discriminantKey: K\n readonly variants: T\n}\n\n/**\n * Value escape hatch - represents \"any Loro Value\".\n * Use this when you need to accept any valid Loro value type.\n *\n * @example\n * ```typescript\n * const FlexiblePresenceShape = Shape.plain.struct({\n * cursor: Shape.plain.any(), // accept any value type\n * })\n * ```\n */\nexport interface AnyValueShape extends Shape<Value, Value, undefined> {\n readonly _type: \"value\"\n readonly valueType: \"any\"\n}\n\n// Union of all ValueShapes - these can only contain other ValueShapes, not ContainerShapes\nexport type ValueShape =\n | AnyValueShape\n | ArrayValueShape\n | BooleanValueShape\n | DiscriminatedUnionValueShape\n | NullValueShape\n | NumberValueShape\n | RecordValueShape\n | StringValueShape\n | StructValueShape\n | Uint8ArrayValueShape\n | UndefinedValueShape\n | UnionValueShape\n\nexport type ContainerOrValueShape = ContainerShape | ValueShape\n\n/**\n * Creates a nullable version of a value shape.\n * @internal\n */\nfunction makeNullable<S extends ValueShape>(\n shape: S,\n): WithPlaceholder<UnionValueShape<[NullValueShape, S]>> {\n const nullShape: NullValueShape = {\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }\n\n const base: UnionValueShape<[NullValueShape, S]> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes: [nullShape, shape] as [NullValueShape, S],\n _plain: null as any,\n _mutable: null as any,\n _placeholder: null as any, // Default placeholder is null\n }\n\n return Object.assign(base, {\n placeholder(\n value: S[\"_placeholder\"] | null,\n ): UnionValueShape<[NullValueShape, S]> {\n return { ...base, _placeholder: value } as UnionValueShape<\n [NullValueShape, S]\n >\n },\n })\n}\n\n/**\n * The LoroShape factory object\n *\n * If a container has a `shape` type variable, it refers to the shape it contains--\n * so for example, a `LoroShape.list(LoroShape.text())` would return a value of type\n * `ListContainerShape<TextContainerShape>`.\n */\nexport const Shape = {\n doc: <T extends Record<string, ContainerShape>>(shape: T): DocShape<T> => ({\n _type: \"doc\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * Creates an \"any\" container shape - an escape hatch for untyped containers.\n * Use this when integrating with external libraries that manage their own document structure.\n *\n * @example\n * ```typescript\n * // loro-prosemirror manages its own structure\n * const ProseMirrorDocShape = Shape.doc({\n * doc: Shape.any(), // opt out of typing for this container\n * })\n *\n * const handle = repo.get(docId, ProseMirrorDocShape, CursorPresenceShape)\n * // handle.doc.doc is typed as `unknown` - you're on your own\n * ```\n */\n any: (): AnyContainerShape => ({\n _type: \"any\" as const,\n _plain: undefined as unknown,\n _mutable: undefined as unknown,\n _placeholder: undefined,\n }),\n\n // CRDTs are represented by Loro Containers--they converge on state using Loro's\n // various CRDT algorithms\n counter: (): WithPlaceholder<CounterContainerShape> => {\n const base: CounterContainerShape = {\n _type: \"counter\" as const,\n _plain: 0,\n _mutable: {} as CounterRef,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): CounterContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n list: <T extends ContainerOrValueShape>(shape: T): ListContainerShape<T> => ({\n _type: \"list\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n /**\n * Creates a struct container shape for objects with fixed keys.\n * This is the preferred way to define fixed-key objects.\n *\n * @example\n * ```typescript\n * const UserSchema = Shape.doc({\n * user: Shape.struct({\n * name: Shape.text(),\n * age: Shape.counter(),\n * }),\n * })\n * ```\n */\n struct: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n /**\n * @deprecated Use `Shape.struct` instead. `Shape.struct` will be removed in a future version.\n */\n map: <T extends Record<string, ContainerOrValueShape>>(\n shape: T,\n ): StructContainerShape<T> => ({\n _type: \"struct\" as const,\n shapes: shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }),\n\n record: <T extends ContainerOrValueShape>(\n shape: T,\n ): RecordContainerShape<T> => ({\n _type: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }),\n\n movableList: <T extends ContainerOrValueShape>(\n shape: T,\n ): MovableListContainerShape<T> => ({\n _type: \"movableList\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n text: (): WithPlaceholder<TextContainerShape> => {\n const base: TextContainerShape = {\n _type: \"text\" as const,\n _plain: \"\",\n _mutable: {} as TextRef,\n _placeholder: \"\",\n }\n return Object.assign(base, {\n placeholder(value: string): TextContainerShape {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a tree container shape for hierarchical data structures.\n * Each node in the tree has typed metadata defined by the data shape.\n *\n * @example\n * ```typescript\n * const StateNodeDataShape = Shape.struct({\n * name: Shape.text(),\n * facts: Shape.record(Shape.plain.any()),\n * })\n *\n * const Schema = Shape.doc({\n * states: Shape.tree(StateNodeDataShape),\n * })\n *\n * doc.change(draft => {\n * const root = draft.states.createNode({ name: \"idle\", facts: {} })\n * const child = root.createNode({ name: \"running\", facts: {} })\n * child.data.name = \"active\"\n * })\n * ```\n */\n tree: <T extends StructContainerShape>(shape: T): TreeContainerShape<T> => ({\n _type: \"tree\" as const,\n shape,\n _plain: [] as any,\n _mutable: {} as any,\n _placeholder: [] as never[],\n }),\n\n // Values are represented as plain JS objects, with the limitation that they MUST be\n // representable as a Loro \"Value\"--basically JSON. The behavior of a Value is basically\n // \"Last Write Wins\", meaning there is no subtle convergent behavior here, just taking\n // the most recent value based on the current available information.\n plain: {\n string: <T extends string = string>(\n ...options: T[]\n ): WithPlaceholder<StringValueShape<T>> &\n WithNullable<StringValueShape<T>> => {\n const base: StringValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"string\" as const,\n _plain: (options[0] ?? \"\") as T,\n _mutable: (options[0] ?? \"\") as T,\n _placeholder: (options[0] ?? \"\") as T,\n options: options.length > 0 ? options : undefined,\n }\n return Object.assign(base, {\n placeholder(value: T): StringValueShape<T> {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StringValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n number: (): WithPlaceholder<NumberValueShape> &\n WithNullable<NumberValueShape> => {\n const base: NumberValueShape = {\n _type: \"value\" as const,\n valueType: \"number\" as const,\n _plain: 0,\n _mutable: 0,\n _placeholder: 0,\n }\n return Object.assign(base, {\n placeholder(value: number): NumberValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, NumberValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n boolean: (): WithPlaceholder<BooleanValueShape> &\n WithNullable<BooleanValueShape> => {\n const base: BooleanValueShape = {\n _type: \"value\" as const,\n valueType: \"boolean\" as const,\n _plain: false,\n _mutable: false,\n _placeholder: false,\n }\n return Object.assign(base, {\n placeholder(value: boolean): BooleanValueShape {\n return { ...base, _placeholder: value }\n },\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, BooleanValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n null: (): NullValueShape => ({\n _type: \"value\" as const,\n valueType: \"null\" as const,\n _plain: null,\n _mutable: null,\n _placeholder: null,\n }),\n\n undefined: (): UndefinedValueShape => ({\n _type: \"value\" as const,\n valueType: \"undefined\" as const,\n _plain: undefined,\n _mutable: undefined,\n _placeholder: undefined,\n }),\n\n uint8Array: (): Uint8ArrayValueShape &\n WithNullable<Uint8ArrayValueShape> => {\n const base: Uint8ArrayValueShape = {\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, Uint8ArrayValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * Alias for `uint8Array()` - creates a shape for binary data.\n * Use this for better discoverability when working with binary data like cursor positions.\n *\n * @example\n * ```typescript\n * const CursorPresenceShape = Shape.plain.struct({\n * anchor: Shape.plain.bytes().nullable(),\n * focus: Shape.plain.bytes().nullable(),\n * })\n * ```\n */\n bytes: (): Uint8ArrayValueShape & WithNullable<Uint8ArrayValueShape> => {\n const base: Uint8ArrayValueShape = {\n _type: \"value\" as const,\n valueType: \"uint8array\" as const,\n _plain: new Uint8Array(),\n _mutable: new Uint8Array(),\n _placeholder: new Uint8Array(),\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, Uint8ArrayValueShape]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * Creates an \"any\" value shape - an escape hatch for untyped values.\n * Use this when you need to accept any valid Loro value type.\n *\n * @example\n * ```typescript\n * const FlexiblePresenceShape = Shape.plain.struct({\n * metadata: Shape.plain.any(), // accept any value type\n * })\n * ```\n */\n any: (): AnyValueShape => ({\n _type: \"value\" as const,\n valueType: \"any\" as const,\n _plain: undefined as unknown as Value,\n _mutable: undefined as unknown as Value,\n _placeholder: undefined,\n }),\n\n /**\n * Creates a struct value shape for plain objects with fixed keys.\n * This is the preferred way to define fixed-key plain value objects.\n *\n * @example\n * ```typescript\n * const PointSchema = Shape.plain.struct({\n * x: Shape.plain.number(),\n * y: Shape.plain.number(),\n * })\n * ```\n */\n struct: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n /**\n * @deprecated Use `Shape.plain.struct` instead. `Shape.plain.struct` will be removed in a future version.\n */\n object: <T extends Record<string, ValueShape>>(\n shape: T,\n ): StructValueShape<T> & WithNullable<StructValueShape<T>> => {\n const base: StructValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"struct\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, StructValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n record: <T extends ValueShape>(\n shape: T,\n ): RecordValueShape<T> & WithNullable<RecordValueShape<T>> => {\n const base: RecordValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"record\" as const,\n shape,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as Record<string, never>,\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, RecordValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n array: <T extends ValueShape>(\n shape: T,\n ): ArrayValueShape<T> & WithNullable<ArrayValueShape<T>> => {\n const base: ArrayValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"array\" as const,\n shape,\n _plain: [] as any,\n _mutable: [] as any,\n _placeholder: [] as never[],\n }\n return Object.assign(base, {\n nullable(): WithPlaceholder<\n UnionValueShape<[NullValueShape, ArrayValueShape<T>]>\n > {\n return makeNullable(base)\n },\n })\n },\n\n // Special value type that helps make things like `string | null` representable\n // TODO(duane): should this be a more general type for containers too?\n union: <T extends ValueShape[]>(\n shapes: T,\n ): WithPlaceholder<UnionValueShape<T>> => {\n const base: UnionValueShape<T> = {\n _type: \"value\" as const,\n valueType: \"union\" as const,\n shapes,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(value: T[number][\"_placeholder\"]): UnionValueShape<T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n\n /**\n * Creates a discriminated union shape for type-safe tagged unions.\n *\n * @example\n * ```typescript\n * const ClientPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"client\"),\n * name: Shape.plain.string(),\n * input: Shape.plain.struct({ force: Shape.plain.number(), angle: Shape.plain.number() }),\n * })\n *\n * const ServerPresenceShape = Shape.plain.struct({\n * type: Shape.plain.string(\"server\"),\n * cars: Shape.plain.record(Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() })),\n * tick: Shape.plain.number(),\n * })\n *\n * const GamePresenceSchema = Shape.plain.discriminatedUnion(\"type\", {\n * client: ClientPresenceShape,\n * server: ServerPresenceShape,\n * })\n * ```\n *\n * @param discriminantKey - The key used to discriminate between variants (e.g., \"type\")\n * @param variants - A record mapping discriminant values to their object shapes\n */\n discriminatedUnion: <\n K extends string,\n T extends Record<string, StructValueShape>,\n >(\n discriminantKey: K,\n variants: T,\n ): WithPlaceholder<DiscriminatedUnionValueShape<K, T>> => {\n const base: DiscriminatedUnionValueShape<K, T> = {\n _type: \"value\" as const,\n valueType: \"discriminatedUnion\" as const,\n discriminantKey,\n variants,\n _plain: {} as any,\n _mutable: {} as any,\n _placeholder: {} as any,\n }\n return Object.assign(base, {\n placeholder(\n value: T[keyof T][\"_placeholder\"],\n ): DiscriminatedUnionValueShape<K, T> {\n return { ...base, _placeholder: value }\n },\n })\n },\n },\n}\n\n// Add this type mapping near the top of your file, after the imports\nexport type ShapeToContainer<T extends DocShape | ContainerShape> =\n T extends TextContainerShape\n ? LoroText\n : T extends CounterContainerShape\n ? LoroCounter\n : T extends ListContainerShape\n ? LoroList\n : T extends MovableListContainerShape\n ? LoroMovableList\n : T extends StructContainerShape | RecordContainerShape\n ? LoroMap\n : T extends TreeContainerShape\n ? LoroTree\n : never // not a container\n"],"mappings":";AASO,SAAS,kBACd,QACyB;AACzB,QAAM,SAAkC,CAAC;AAEzC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,OAAO,MAAM,GAAG;AACxD,WAAO,GAAG,IAAI,uBAAuB,KAAK;AAAA,EAC5C;AAEA,SAAO;AACT;AAQO,SAAS,uBAAuB,OAAuC;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;AAAA,QAC1B;AAAA,MACF,CAAC;AAAA,IACH;AAAA,IAEA,OAAO,CACL,UAC0D;AAC1D,YAAM,OAA2B;AAAA,QAC/B,OAAO;AAAA,QACP,WAAW;AAAA,QACX;AAAA,QACA,QAAQ,CAAC;AAAA,QACT,UAAU,CAAC;AAAA,QACX,cAAc,CAAC;AAAA,MACjB;AACA,aAAO,OAAO,OAAO,MAAM;AAAA,QACzB,WAEE;AACA,iBAAO,aAAa,IAAI;AAAA,QAC1B;AAAA,MACF,CAAC;AAAA,IACH;AAAA;AAAA;AAAA,IAIA,OAAO,CACL,WACwC;AACxC,YAAM,OAA2B;AAAA,QAC/B,OAAO;AAAA,QACP,WAAW;AAAA,QACX;AAAA,QACA,QAAQ,CAAC;AAAA,QACT,UAAU,CAAC;AAAA,QACX,cAAc,CAAC;AAAA,MACjB;AACA,aAAO,OAAO,OAAO,MAAM;AAAA,QACzB,YAAY,OAAsD;AAChE,iBAAO,EAAE,GAAG,MAAM,cAAc,MAAM;AAAA,QACxC;AAAA,MACF,CAAC;AAAA,IACH;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IA4BA,oBAAoB,CAIlB,iBACA,aACwD;AACxD,YAAM,OAA2C;AAAA,QAC/C,OAAO;AAAA,QACP,WAAW;AAAA,QACX;AAAA,QACA;AAAA,QACA,QAAQ,CAAC;AAAA,QACT,UAAU,CAAC;AAAA,QACX,cAAc,CAAC;AAAA,MACjB;AACA,aAAO,OAAO,OAAO,MAAM;AAAA,QACzB,YACE,OACoC;AACpC,iBAAO,EAAE,GAAG,MAAM,cAAc,MAAM;AAAA,QACxC;AAAA,MACF,CAAC;AAAA,IACH;AAAA,EACF;AACF;","names":["LoroDoc","value","LoroCounter","LoroList","LoroMap","LoroMovableList","LoroText","cachedItem","ref","ref","containerValue","LoroCounter","LoroList","LoroMovableList","LoroMap","LoroText","LoroDoc","target","isContainer"]}