import { LoroDoc, ContainerID, Diff, PeerID, Container, LoroTreeNode, TreeID, LoroEventBatch, Subscription, LoroText, LoroList, LoroMovableList, LoroMap, LoroTree, LoroCounter, Value } from 'loro-crdt'; type Prev = [never, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; /** * Expands a type to a reasonable depth for IDE display. * Stops at depth 4 to avoid infinite recursion with self-referential types * like tree nodes that have `children: TreeNodeJSON[]`. * * @example * ```typescript * // Without expansion, hover shows: TreeNodeJSON> * // With expansion, hover shows the actual structure: * // { id: string; parent: string | null; data: { name: string; ... }; children: ... } * ``` */ type ExpandDeep = Depth extends 0 ? T : T extends (...args: any[]) => any ? T : T extends object ? T extends infer O ? { [K in keyof O]: ExpandDeep; } : never : T; /** * Infers the plain (JSON-serializable) type from any Shape. * The result is fully expanded for better IDE hover display. * * This is the recommended way to extract types from shapes. * Works with DocShape, ContainerShape, and ValueShape. * * @example * ```typescript * const ChatSchema = Shape.doc({ * messages: Shape.list(Shape.struct({ * id: Shape.plain.string(), * content: Shape.text(), * })), * }) * * // Extract the document type * type ChatDoc = Infer * // Result: { messages: { id: string; content: string }[] } * * const PresenceSchema = Shape.plain.struct({ * name: Shape.plain.string(), * cursor: Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() }), * }) * * // Extract the presence type * type Presence = Infer * // Result: { name: string; cursor: { x: number; y: number } } * ``` */ type Infer = T extends Shape ? ExpandDeep

: never; /** * Infers the plain (JSON-serializable) type from any Shape without expansion. * Use this if you prefer to see type alias names (like TreeNodeJSON) in hover displays, * or if you need slightly faster type checking on very large schemas. */ type InferRaw = T extends Shape ? P : never; /** * Infers the mutable type from any Shape. * This is the type used within change() callbacks for mutation. */ type InferMutableType = T extends Shape ? M : never; /** * Extracts the valid placeholder type from a shape. * * For dynamic containers (list, record, etc.), this will be constrained to * empty values ([] or {}) to prevent users from expecting per-entry merging. */ type InferPlaceholderType = T extends Shape ? P : never; /** * Mutable type for use within change() callbacks and direct mutations on doc.value. * This is the type-safe wrapper around CRDT containers that allows mutation. */ type Mutable>> = InferMutableType; /** biome-ignore-all lint/suspicious/noExplicitAny: JSON Patch values can be any type */ type JsonPatchAddOperation = { op: "add"; path: string | (string | number)[]; value: any; }; type JsonPatchRemoveOperation = { op: "remove"; path: string | (string | number)[]; }; type JsonPatchReplaceOperation = { op: "replace"; path: string | (string | number)[]; value: any; }; type JsonPatchMoveOperation = { op: "move"; path: string | (string | number)[]; from: string | (string | number)[]; }; type JsonPatchCopyOperation = { op: "copy"; path: string | (string | number)[]; from: string | (string | number)[]; }; type JsonPatchTestOperation = { op: "test"; path: string | (string | number)[]; value: any; }; type JsonPatchOperation = JsonPatchAddOperation | JsonPatchRemoveOperation | JsonPatchReplaceOperation | JsonPatchMoveOperation | JsonPatchCopyOperation | JsonPatchTestOperation; type JsonPatch = JsonPatchOperation[]; /** * Symbol for internal methods that should not be enumerable or accessible to users. * Used to hide implementation details like absorbPlainValues(), getTypedRefParams(), etc. * * This achieves Success Criteria #7 from loro-api-refactor.md: * "Internal methods hidden - Via Symbol, not enumerable" */ declare const INTERNAL_SYMBOL: unique symbol; /** * Minimal interface for refs that only need absorbPlainValues. * Used by TreeNodeRef which doesn't extend TypedRef. */ interface RefInternalsBase { /** Absorb mutated plain values back into Loro containers */ absorbPlainValues(): void; /** Force materialization of the container and its nested containers */ materialize(): void; } type DiffOverlay$1 = ReadonlyMap; type TypedRefParams = { shape: Shape; placeholder?: Infer; getContainer: () => ShapeToContainer; autoCommit?: boolean; batchedMutation?: boolean; getDoc: () => LoroDoc; overlay?: DiffOverlay$1; }; /** * Abstract base class for all ref internal implementations. * Contains shared logic that was previously in TypedRef.createBaseInternals(). * * Subclasses implement specific behavior for each ref type. */ declare abstract class BaseRefInternals implements RefInternalsBase { protected readonly params: TypedRefParams; protected cachedContainer: ShapeToContainer | undefined; protected loroNamespace: LoroRefBase | undefined; private _suppressAutoCommit; constructor(params: TypedRefParams); /** Get the underlying Loro container (cached) */ getContainer(): ShapeToContainer; /** Commit changes if autoCommit is enabled and not suppressed */ commitIfAuto(): void; /** * Temporarily suppress auto-commit during batch operations. * Used by assignPlainValueToTypedRef() to batch multiple property assignments. */ setSuppressAutoCommit(suppress: boolean): void; /** Check if auto-commit is currently suppressed */ isSuppressAutoCommit(): boolean; /** Get the shape for this ref */ getShape(): Shape; /** Get the placeholder value */ getPlaceholder(): Infer | undefined; /** Check if autoCommit is enabled */ getAutoCommit(): boolean; /** Check if in batched mutation mode */ getBatchedMutation(): boolean; /** Get the LoroDoc */ getDoc(): LoroDoc; /** Get the diff overlay map (if provided) */ getOverlay(): DiffOverlay$1 | undefined; /** * Get the TypedRefParams needed to recreate this ref. * Used by change() to create draft refs with modified params. * * Returns a new params object with the same shape, placeholder, getContainer, and getDoc, * but allows overriding autoCommit and batchedMutation for draft creation. */ getTypedRefParams(): TypedRefParams; /** Get the loro namespace (cached) */ getLoroNamespace(): LoroRefBase; /** Absorb mutated plain values back into Loro containers - subclasses override */ abstract absorbPlainValues(): void; /** Force materialization of the container and its nested containers */ materialize(): void; /** Create the loro() namespace object - subclasses override for specific types */ protected createLoroNamespace(): LoroRefBase; } /** * Base class for all typed refs. * * All internal methods are accessed via [INTERNAL_SYMBOL] to prevent * namespace collisions with user data properties. * * Uses the Facade + Implementation pattern: * - TypedRef is the thin public facade * - BaseRefInternals subclasses contain all implementation logic */ declare abstract class TypedRef { /** * Internal implementation accessed via Symbol. * Subclasses must set this to their specific internals class instance. */ abstract [INTERNAL_SYMBOL]: BaseRefInternals; /** * Serializes the ref to a plain JSON-compatible value. * Returns the plain type inferred from the shape. */ abstract toJSON(): Infer; /** * Access the loro() namespace via the well-known symbol. * This is used by the loro() function to access CRDT internals. */ get [LORO_SYMBOL](): LoroRefBase; } /** biome-ignore-all lint/suspicious/noExplicitAny: fix later */ /** * The proxied TypedDoc type that provides direct schema access. * Schema properties are accessed directly on the doc object. * * @example * ```typescript * const doc = createTypedDoc(schema); * * // Direct schema access * doc.count.increment(5); * doc.title.insert(0, "Hello"); * * // Serialize to JSON (works on doc and all refs) * const snapshot = doc.toJSON(); * const users = doc.users.toJSON(); * * // Batched mutations via change() * doc.change(draft => { * draft.count.increment(10); * draft.title.update("World"); * }); * * // Access CRDT internals via loro() * import { loro } from "@loro-extended/change"; * loro(doc).doc; // LoroDoc * loro(doc).subscribe(callback); * ``` */ /** * Frontiers represent a specific version in the document's history. * Each frontier is an operation ID consisting of a peer ID and counter. */ type Frontiers = { peer: PeerID; counter: number; }[]; type CreateTypedDocOptions = { doc?: LoroDoc; overlay?: DiffOverlay$1; }; type TypedDoc = Mutable & { /** * The primary method of mutating typed documents. * Batches multiple mutations into a single transaction. * All changes commit together at the end. * * Use this for: * - Find-and-mutate operations (required due to JS limitations) * - Performance (fewer commits) * - Atomic undo (all changes = one undo step) * * Returns the doc for chaining. * * @example * ```typescript * doc.change(draft => { * draft.count.increment(10); * draft.title.update("World"); * }); * ``` */ change(fn: (draft: Mutable) => void): TypedDoc; /** * Returns the full plain JavaScript object representation of the document. * This is an O(N) operation that serializes the entire document. * * @example * ```typescript * const snapshot = doc.toJSON(); * console.log(snapshot.count); // number * ``` */ toJSON(): Infer; /** * Creates a new TypedDoc at a specified version (frontiers). * The forked doc will only contain history before the specified frontiers. * The forked doc has a different PeerID from the original. * * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)` * * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`) * @returns A new TypedDoc with the same schema at the specified version * * @example * ```typescript * import { loro } from "@loro-extended/change"; * * const doc = createTypedDoc(schema); * doc.title.update("Hello"); * const frontiers = loro(doc).doc.frontiers(); * doc.title.update("World"); * * // Fork at the earlier version * const forkedDoc = doc.forkAt(frontiers); * console.log(forkedDoc.title.toString()); // "Hello" * console.log(doc.title.toString()); // "World" * ``` */ forkAt(frontiers: Frontiers): TypedDoc; }; /** * Creates a new TypedDoc with the given schema. * Returns a proxied document where schema properties are accessed directly. * * @param shape - The document schema (with optional .placeholder() values) * @param options - Optional existing LoroDoc or diff overlay * @returns A proxied TypedDoc with direct schema access * * @example * ```typescript * const schema = Shape.doc({ * title: Shape.text(), * count: Shape.counter(), * }); * * const doc = createTypedDoc(schema); * * // Direct mutations (auto-commit) * doc.count.increment(5); * doc.title.insert(0, "Hello"); * * // Batched mutations via change() * doc.change(draft => { * draft.count.increment(10); * draft.title.update("World"); * }); * * // Get plain JSON * const snapshot = doc.toJSON(); * * // Access CRDT internals via loro() * import { loro } from "@loro-extended/change"; * loro(doc).doc; // LoroDoc * loro(doc).subscribe(callback); * ``` */ declare function createTypedDoc(shape: Shape, options?: CreateTypedDocOptions): TypedDoc; /** * Internal implementation for CounterRef. * Contains all logic, state, and implementation details. */ declare class CounterRefInternals extends BaseRefInternals { private materialized; /** Increment the counter value */ increment(value?: number): void; /** Decrement the counter value */ decrement(value?: number): void; /** Get the current counter value */ getValue(): number; /** No plain values in counter */ absorbPlainValues(): void; /** Create the loro namespace for counter */ protected createLoroNamespace(): LoroCounterRef; } /** * Counter typed ref - thin facade that delegates to CounterRefInternals. */ declare class CounterRef extends TypedRef { [INTERNAL_SYMBOL]: CounterRefInternals; constructor(params: TypedRefParams); /** Increment the counter by the given value (default 1) */ increment(value?: number): void; /** Decrement the counter by the given value (default 1) */ decrement(value?: number): void; /** Get the current counter value */ get value(): number; valueOf(): number; toJSON(): number; [Symbol.toPrimitive](hint: string): number | string; } /** * Internal implementation for ListRefBase. * Contains all logic, state, and implementation details for list operations. */ declare class ListRefBaseInternals extends BaseRefInternals { private itemCache; private overlayListCache?; getOverlayList(): Item[] | undefined; /** Get typed ref params for creating child refs at an index */ getChildTypedRefParams(index: number, shape: ContainerShape): TypedRefParams; /** Get item for predicate functions (returns plain value) */ getPredicateItem(index: number): Item | undefined; /** Get mutable item for return values (returns ref or cached value) */ getMutableItem(index: number): MutableItem | undefined; /** Insert with automatic conversion */ insertWithConversion(index: number, item: unknown): void; /** Push with automatic conversion */ pushWithConversion(item: unknown): void; /** Absorb value at specific index (for value shapes) - subclasses override */ absorbValueAtIndex(_index: number, _value: unknown): void; /** Update cache indices after a delete operation */ updateCacheForDelete(deleteIndex: number, deleteLen: number): void; /** Update cache indices after an insert operation */ updateCacheForInsert(insertIndex: number): void; /** Absorb mutated plain values back into Loro containers */ absorbPlainValues(): void; /** Create the loro namespace for list */ protected createLoroNamespace(): LoroListRef; } /** * Shared logic for list operations - thin facade that delegates to ListRefBaseInternals. */ declare abstract class ListRefBase extends TypedRef { [INTERNAL_SYMBOL]: ListRefBaseInternals; constructor(params: TypedRefParams); /** Subclasses override to create their specific internals */ protected abstract createInternals(params: TypedRefParams): ListRefBaseInternals; find(predicate: (item: Item, index: number) => boolean): MutableItem | undefined; findIndex(predicate: (item: Item, index: number) => boolean): number; map(callback: (item: Item, index: number) => ReturnType): ReturnType[]; filter(predicate: (item: Item, index: number) => boolean): MutableItem[]; forEach(callback: (item: Item, index: number) => void): void; some(predicate: (item: Item, index: number) => boolean): boolean; every(predicate: (item: Item, index: number) => boolean): boolean; slice(start?: number, end?: number): MutableItem[]; insert(index: number, item: Item): void; delete(index: number, len: number): void; push(item: Item): void; pushContainer(container: Container): Container; insertContainer(index: number, container: Container): Container; get(index: number): MutableItem | undefined; toArray(): Item[]; toJSON(): Item[]; [Symbol.iterator](): IterableIterator; get length(): number; } /** * Internal implementation for ListRef. * Extends ListRefBaseInternals with LoroList-specific absorption logic. */ declare class ListRefInternals extends ListRefBaseInternals { /** Absorb value at specific index for LoroList */ absorbValueAtIndex(index: number, value: unknown): void; } /** * List typed ref - thin facade that delegates to ListRefInternals. */ declare class ListRef extends ListRefBase { [index: number]: InferMutableType | undefined; protected createInternals(params: TypedRefParams): ListRefInternals; } /** * Internal implementation for MovableListRef. * Extends ListRefBaseInternals with LoroMovableList-specific methods. */ declare class MovableListRefInternals extends ListRefBaseInternals { /** Absorb value at specific index for LoroMovableList */ absorbValueAtIndex(index: number, value: unknown): void; /** Move an item from one index to another */ move(from: number, to: number): void; /** Set an item at a specific index */ set(index: number, item: unknown): void; } /** * Movable list typed ref - thin facade that delegates to MovableListRefInternals. */ declare class MovableListRef extends ListRefBase { [INTERNAL_SYMBOL]: MovableListRefInternals; [index: number]: InferMutableType | undefined; protected createInternals(params: TypedRefParams): MovableListRefInternals; move(from: number, to: number): void; set(index: number, item: Exclude): void; } /** * Internal implementation for RecordRef. * Contains all logic, state, and implementation details. */ declare class RecordRefInternals extends BaseRefInternals { private refCache; /** Get typed ref params for creating child refs at a key */ getChildTypedRefParams(key: string, shape: ContainerShape): TypedRefParams; /** Get a ref for a key without creating (returns undefined for non-existent container keys) */ getRef(key: string): unknown; /** Get or create a ref for a key (always creates for container shapes) */ getOrCreateRef(key: string): unknown; /** Set a value at a key */ set(key: string, value: any): void; /** Delete a key */ delete(key: string): void; /** * Replace entire contents with new values. * Keys not in `values` are removed. */ replace(values: Record): void; /** * Merge values into record. * Existing keys not in `values` are kept. */ merge(values: Record): void; /** * Remove all entries from the record. */ clear(): void; /** Absorb mutated plain values back into Loro containers */ absorbPlainValues(): void; /** Create the loro namespace for record */ protected createLoroNamespace(): LoroMapRef; } /** * Record typed ref - thin facade that delegates to RecordRefInternals. */ declare class RecordRef extends TypedRef { [key: string]: InferMutableType | undefined | any; [INTERNAL_SYMBOL]: RecordRefInternals; constructor(params: TypedRefParams); /** Set a value at a key */ set(key: string, value: any): void; /** Delete a key */ delete(key: string): void; get(key: string): InferMutableType | undefined; setContainer(key: string, container: C): C; has(key: string): boolean; keys(): string[]; /** * Returns an array of all values in the record. * For container-valued records, returns properly typed refs. */ values(): InferMutableType[]; /** * Returns an array of [key, value] pairs. * For container-valued records, values are properly typed refs. */ entries(): [string, InferMutableType][]; get size(): number; /** * Replace entire contents with new values. * Keys not in `values` are removed. * * @example * ```typescript * doc.change(draft => { * draft.players.replace({ * alice: { score: 100 }, * bob: { score: 50 } * }) * }) * ``` */ replace(values: Record>): void; /** * Merge values into record. * Existing keys not in `values` are kept. * * @example * ```typescript * doc.change(draft => { * // Adds charlie, updates alice, keeps bob unchanged * draft.players.merge({ * alice: { score: 150 }, * charlie: { score: 25 } * }) * }) * ``` */ merge(values: Record>): void; /** * Remove all entries from the record. * * @example * ```typescript * doc.change(draft => { * draft.players.clear() * }) * ``` */ clear(): void; toJSON(): Record>; } /** * Typed ref for struct containers (objects with fixed keys). * Uses LoroMap as the underlying container. * * Supports JavaScript-native object behavior: * - Property access: obj.key * - Property assignment: obj.key = value * - Object.keys(obj) * - 'key' in obj * - delete obj.key * * @example * ```typescript * const schema = Shape.doc({ * settings: Shape.struct({ * darkMode: Shape.plain.boolean().placeholder(false), * fontSize: Shape.plain.number().placeholder(14), * }), * }); * * const doc = createTypedDoc(schema); * * // Property access * doc.settings.darkMode = true; * console.log(doc.settings.darkMode); // true * * // Object.keys() * console.log(Object.keys(doc.settings)); // ['darkMode', 'fontSize'] * * // 'key' in obj * console.log('darkMode' in doc.settings); // true * * // delete obj.key * delete doc.settings.darkMode; * * // CRDT access via loro() * import { loro } from "@loro-extended/change"; * loro(doc.settings).setContainer('nested', loroMap); * loro(doc.settings).subscribe(callback); * ``` */ type StructRef> = { [K in keyof NestedShapes]: NestedShapes[K]["_mutable"]; } & { /** * Serializes the struct to a plain JSON-compatible object. */ toJSON(): Infer>; /** * Internal methods accessed via INTERNAL_SYMBOL. * @internal */ [INTERNAL_SYMBOL]: RefInternalsBase; /** * Access CRDT internals via the well-known symbol. * Used by the loro() function. */ [LORO_SYMBOL]: LoroMapRef; }; /** * Internal implementation for TextRef. * Contains all logic, state, and implementation details. */ declare class TextRefInternals extends BaseRefInternals { private materialized; /** Insert text at the given index */ insert(index: number, content: string): void; /** Delete text at the given index */ delete(index: number, len: number): void; /** Update the entire text content */ update(text: string): void; /** Mark a range of text with a key-value pair */ mark(range: { start: number; end: number; }, key: string, value: any): void; /** Remove a mark from a range of text */ unmark(range: { start: number; end: number; }, key: string): void; /** Apply a delta to the text */ applyDelta(delta: any[]): void; /** Get the text as a string */ getStringValue(): string; /** Get the text as a delta */ toDelta(): any[]; /** Get the length of the text */ getLength(): number; /** No plain values in text */ absorbPlainValues(): void; /** Create the loro namespace for text */ protected createLoroNamespace(): LoroTextRef; } /** * Text typed ref - thin facade that delegates to TextRefInternals. */ declare class TextRef extends TypedRef { [INTERNAL_SYMBOL]: TextRefInternals; constructor(params: TypedRefParams); /** Insert text at the given index */ insert(index: number, content: string): void; /** Delete text at the given index */ delete(index: number, len: number): void; /** Update the entire text content */ update(text: string): void; /** Mark a range of text with a key-value pair */ mark(range: { start: number; end: number; }, key: string, value: any): void; /** Remove a mark from a range of text */ unmark(range: { start: number; end: number; }, key: string): void; /** Apply a delta to the text */ applyDelta(delta: any[]): void; /** Get the text as a string */ toString(): string; valueOf(): string; toJSON(): string; [Symbol.toPrimitive](_hint: string): string; /** Get the text as a delta */ toDelta(): any[]; /** Get the length of the text */ get length(): number; } interface TreeRefLike { getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef; } /** * Internal implementation for TreeNodeRef. * Contains all logic, state, and implementation details. */ declare class TreeNodeRefInternals implements RefInternalsBase { private readonly params; private dataRef; private loroNamespace; constructor(params: TreeNodeRefParams); /** Get the underlying LoroTreeNode */ getNode(): LoroTreeNode; /** Get the data shape for this node */ getDataShape(): DataShape; /** Get the parent TreeRef */ getTreeRef(): TreeRefLike; /** Check if autoCommit is enabled */ getAutoCommit(): boolean; /** Check if in batched mutation mode */ getBatchedMutation(): boolean; /** Get the LoroDoc */ getDoc(): LoroDoc; /** Commit changes if autoCommit is enabled */ commitIfAuto(): void; /** Get or create the data StructRef */ getOrCreateDataRef(): StructRef; /** Absorb mutated plain values back into Loro containers */ absorbPlainValues(): void; /** Force materialization of the container and its nested containers */ materialize(): void; /** Get the loro namespace (cached) */ getLoroNamespace(): LoroTreeNodeRef; /** Create the loro namespace for tree node */ protected createLoroNamespace(): LoroTreeNodeRef; } interface TreeNodeRefParams { node: LoroTreeNode; dataShape: DataShape; treeRef: TreeRefLike; autoCommit?: boolean; batchedMutation?: boolean; getDoc: () => LoroDoc; } /** * Typed ref for a single tree node - thin facade that delegates to TreeNodeRefInternals. * Provides type-safe access to node metadata via the `.data` property. * * **Note:** TreeNodeRef is not a subclass of TypedRef, but it implements * `[INTERNAL_SYMBOL]: RefInternalsBase` for consistency with other refs. * This allows internal code to call `absorbPlainValues()` uniformly * across all ref types during the `change()` commit phase. * * @example * ```typescript * const node = tree.createNode({ name: "idle", facts: {} }) * node.data.name = "active" // Typed access * const child = node.createNode({ name: "running", facts: {} }) * ``` */ declare class TreeNodeRef { [INTERNAL_SYMBOL]: TreeNodeRefInternals; constructor(params: TreeNodeRefParams); /** * Access the loro() namespace via the well-known symbol. */ get [LORO_SYMBOL](): LoroTreeNodeRef; /** * The unique TreeID of this node. */ get id(): TreeID; /** * Typed access to the node's metadata. * This is a StructRef wrapping the node's LoroMap data container. */ get data(): StructRef & { [K in keyof DataShape["shapes"]]: DataShape["shapes"][K]["_mutable"]; }; /** * Create a child node under this node. * * @param initialData - Optional partial data to initialize the child with * @param index - Optional position among siblings * @returns The created child TreeNodeRef */ createNode(initialData?: Partial>, index?: number): TreeNodeRef; /** * Get the parent node, if any. */ parent(): TreeNodeRef | undefined; /** * Get all child nodes in order. */ children(): TreeNodeRef[]; /** * Move this node to a new parent. * * @param newParent - The new parent node (undefined for root) * @param index - Optional position among siblings */ move(newParent?: TreeNodeRef, index?: number): void; /** * Move this node to be after the given sibling. */ moveAfter(sibling: TreeNodeRef): void; /** * Move this node to be before the given sibling. */ moveBefore(sibling: TreeNodeRef): void; /** * Get the index of this node among its siblings. */ index(): number | undefined; /** * Get the fractional index string for ordering. */ fractionalIndex(): string | undefined; /** * Check if this node has been deleted. */ isDeleted(): boolean; /** * Serialize this node and its descendants to JSON. */ toJSON(): { id: TreeID; parent: TreeID | null; index: number; fractionalIndex: string; data: Infer; children: any[]; }; } /** * Internal implementation for TreeRef. * Contains all logic, state, and implementation details. */ declare class TreeRefInternals extends BaseRefInternals> { private nodeCache; private treeRef; /** Set the parent TreeRef (needed for creating node refs) */ setTreeRef(treeRef: TreeRef): void; /** Get the data shape for tree nodes */ getDataShape(): DataShape; /** Get or create a node ref for a LoroTreeNode */ getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef; /** Get a node by its ID */ getNodeByID(id: TreeID): TreeNodeRef | undefined; /** Delete a node from the tree */ delete(target: TreeID | TreeNodeRef): void; /** Absorb mutated plain values back into Loro containers */ absorbPlainValues(): void; /** Create the loro namespace for tree */ protected createLoroNamespace(): LoroTreeRef; } /** * Typed ref for tree (forest) containers - thin facade that delegates to TreeRefInternals. * Wraps LoroTree with type-safe access to node metadata. * * @example * ```typescript * const StateNodeDataShape = Shape.struct({ * name: Shape.text(), * facts: Shape.record(Shape.plain.any()), * }) * * doc.change(draft => { * const root = draft.states.createNode({ name: "idle", facts: {} }) * const child = root.createNode({ name: "running", facts: {} }) * child.data.name = "active" * }) * ``` */ declare class TreeRef extends TypedRef> { [INTERNAL_SYMBOL]: TreeRefInternals; constructor(params: TypedRefParams>); /** * Get the data shape for tree nodes. */ private get dataShape(); /** * Get or create a node ref for a LoroTreeNode. */ getOrCreateNodeRef(node: LoroTreeNode): TreeNodeRef; /** * Get a node by its ID. */ getNodeByID(id: TreeID): TreeNodeRef | undefined; /** * Delete a node from the tree. */ delete(target: TreeID | TreeNodeRef): void; /** * Serialize the tree to a nested JSON structure. * Each node includes its data and children recursively. */ toJSON(): Infer>; /** * Create a new root node with optional initial data. * * @param initialData - Optional partial data to initialize the node with * @returns The created TreeNodeRef */ createNode(initialData?: Partial>): TreeNodeRef; /** * Get all root nodes (nodes without parents). * Returns nodes in their fractional index order. */ roots(): TreeNodeRef[]; /** * Get all nodes in the tree (unordered). * By default, excludes deleted nodes (tombstones). * * @param options.includeDeleted - If true, includes deleted nodes. Default: false. * @returns Array of TreeNodeRef for matching nodes */ nodes(options?: { includeDeleted?: boolean; }): TreeNodeRef[]; /** * Check if a node with the given ID exists in the tree. */ has(id: TreeID): boolean; /** * Enable fractional index generation for ordering. * * @param jitter - Optional jitter value to avoid conflicts (0 = no jitter) */ enableFractionalIndex(jitter?: number): void; /** * Transform Loro's native JSON format to our typed format. */ private transformNativeJson; /** * Get a flat array representation of all nodes. * Flattens the nested tree structure into a single array. */ toArray(): Array<{ id: TreeID; parent: TreeID | null; index: number; fractionalIndex: string; data: Infer; }>; } /** * The `loro()` function - single escape hatch for CRDT internals. * * Design Principle: * > If it takes a plain JavaScript value, keep it on the ref. * > If it takes a Loro container or exposes CRDT internals, move to `loro()`. * * @example * ```typescript * import { loro } from "@loro-extended/change" * * // Access underlying LoroDoc * loro(ref).doc * * // Access underlying Loro container (correctly typed) * loro(ref).container // LoroList, LoroMap, LoroText, etc. * * // Subscribe to changes * loro(ref).subscribe(callback) * * // Container operations * loro(list).pushContainer(loroMap) * loro(struct).setContainer('key', loroMap) * ``` */ /** * Well-known Symbol for loro() access. * This is exported so advanced users can access it directly if needed. */ declare const LORO_SYMBOL: unique symbol; /** * Base interface for all loro() return types. * Provides access to the underlying LoroDoc, container, and subscription. */ interface LoroRefBase { /** The underlying LoroDoc */ readonly doc: LoroDoc; /** The underlying Loro container */ readonly container: unknown; /** * Subscribe to container-level changes. * @param callback - Function called when the container changes * @returns Subscription that can be used to unsubscribe */ subscribe(callback: (event: LoroEventBatch) => void): Subscription; } /** * loro() return type for ListRef and MovableListRef. * Provides container operations that take Loro containers. */ interface LoroListRef extends LoroRefBase { /** The underlying LoroList or LoroMovableList */ readonly container: LoroList | LoroMovableList; /** * Push a Loro container to the end of the list. * Use this when you need to add a pre-existing container. */ pushContainer(container: Container): Container; /** * Insert a Loro container at the specified index. * Use this when you need to insert a pre-existing container. */ insertContainer(index: number, container: Container): Container; } /** * loro() return type for StructRef and RecordRef. * Provides container operations that take Loro containers. */ interface LoroMapRef extends LoroRefBase { /** The underlying LoroMap */ readonly container: LoroMap; /** * Set a Loro container at the specified key. * Use this when you need to set a pre-existing container. */ setContainer(key: string, container: Container): Container; } /** * loro() return type for TextRef. */ interface LoroTextRef extends LoroRefBase { /** The underlying LoroText */ readonly container: LoroText; } /** * loro() return type for CounterRef. */ interface LoroCounterRef extends LoroRefBase { /** The underlying LoroCounter */ readonly container: LoroCounter; } /** * loro() return type for TreeRef. */ interface LoroTreeRef extends LoroRefBase { /** The underlying LoroTree */ readonly container: LoroTree; } /** * loro() return type for TreeNodeRef. */ interface LoroTreeNodeRef extends LoroRefBase { /** The underlying LoroTreeNode */ readonly container: LoroTreeNode; } /** * loro() return type for TypedDoc. * Provides access to doc-level operations. */ interface LoroTypedDocRef extends LoroRefBase { /** The underlying LoroDoc (same as doc for TypedDoc) */ readonly container: LoroDoc; /** * Apply JSON Patch operations to the document. * @param patch - Array of JSON Patch operations (RFC 6902) * @param pathPrefix - Optional path prefix for scoped operations */ applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void; /** Access the document schema shape */ readonly docShape: DocShape; /** Get raw CRDT value without placeholder overlay */ readonly rawValue: unknown; } /** * Access CRDT internals for a ListRef. */ declare function loro(ref: ListRef): LoroListRef; /** * Access CRDT internals for a MovableListRef. */ declare function loro(ref: MovableListRef): LoroListRef; /** * Access CRDT internals for a StructRef. */ declare function loro>(ref: StructRef): LoroMapRef; /** * Access CRDT internals for a RecordRef. */ declare function loro(ref: RecordRef): LoroMapRef; /** * Access CRDT internals for a TextRef. */ declare function loro(ref: TextRef): LoroTextRef; /** * Access CRDT internals for a CounterRef. */ declare function loro(ref: CounterRef): LoroCounterRef; /** * Access CRDT internals for a TreeRef. */ declare function loro(ref: TreeRef | TreeRefInterface): LoroTreeRef; /** * Access CRDT internals for a TreeNodeRef. */ declare function loro(ref: TreeNodeRef): LoroTreeNodeRef; /** * Access CRDT internals for a TypedDoc. */ declare function loro(doc: TypedDoc): LoroTypedDocRef; /** * Access CRDT internals for any TypedRef. */ declare function loro(ref: TypedRef): LoroRefBase; type WithPlaceholder> = S & { placeholder(value: S["_placeholder"]): S; }; /** * Type for value shapes that support the .nullable() method. * Returns a union of null and the original shape with null as the default placeholder. */ type WithNullable = { nullable(): WithPlaceholder>; }; interface DocShape = Record> extends Shape<{ [K in keyof NestedShapes]: NestedShapes[K]["_plain"]; }, { [K in keyof NestedShapes]: NestedShapes[K]["_mutable"]; }, { [K in keyof NestedShapes]: NestedShapes[K]["_placeholder"]; }> { readonly _type: "doc"; readonly shapes: NestedShapes; } interface TextContainerShape extends Shape { readonly _type: "text"; } interface CounterContainerShape extends Shape { readonly _type: "counter"; } /** * JSON representation of a tree node with typed data. * Used for serialization (toJSON) of tree structures. */ type TreeNodeJSON = { id: TreeID; parent: TreeID | null; index: number; fractionalIndex: string; data: DataShape["_plain"]; children: TreeNodeJSON[]; }; /** * Interface describing the TreeRef API for use in shape definitions. * This avoids circular type references that would occur with the TreeRef class. * @internal */ interface TreeRefInterface { /** Get or create a node ref for a LoroTreeNode */ getOrCreateNodeRef(node: unknown): TreeNodeRef; /** Get a node by its ID */ getNodeByID(id: TreeID): TreeNodeRef | undefined; /** Delete a node from the tree */ delete(target: TreeID | TreeNodeRef): void; /** Serialize the tree to a nested JSON structure */ toJSON(): TreeNodeJSON[]; /** Create a new root node with optional initial data */ createNode(initialData?: Partial): TreeNodeRef; /** Get all root nodes (nodes without parents) */ roots(): TreeNodeRef[]; /** Get all nodes in the tree (unordered). By default excludes deleted nodes. */ nodes(options?: { includeDeleted?: boolean; }): TreeNodeRef[]; /** Check if a node with the given ID exists in the tree */ has(id: TreeID): boolean; /** Enable fractional index generation for ordering */ enableFractionalIndex(jitter?: number): void; /** Get a flat array representation of all nodes */ toArray(): Array<{ id: TreeID; parent: TreeID | null; index: number; fractionalIndex: string; data: DataShape["_plain"]; }>; /** * Access CRDT internals via the well-known symbol. */ readonly [LORO_SYMBOL]: LoroTreeRef; } /** * Container shape for tree (forest) structures. * Each node in the tree has typed metadata stored in a LoroMap. * * @example * ```typescript * const StateNodeDataShape = Shape.struct({ * name: Shape.text(), * facts: Shape.record(Shape.plain.any()), * }) * * const Schema = Shape.doc({ * states: Shape.tree(StateNodeDataShape), * }) * ``` */ interface TreeContainerShape extends Shape[], TreeRefInterface, never[]> { readonly _type: "tree"; /** * The shape of each node's data (metadata). * This is a StructContainerShape that defines the typed properties on node.data. */ readonly shape: DataShape; } interface ListContainerShape extends Shape, never[]> { readonly _type: "list"; readonly shape: NestedShape; } interface MovableListContainerShape extends Shape, never[]> { readonly _type: "movableList"; readonly shape: NestedShape; } /** * Container shape for objects with fixed keys (structs). * This is the preferred way to define fixed-key objects. * Uses LoroMap as the underlying container. */ interface StructContainerShape = Record> extends Shape<{ [K in keyof NestedShapes]: NestedShapes[K]["_plain"]; }, StructRef, { [K in keyof NestedShapes]: NestedShapes[K]["_placeholder"]; }> { readonly _type: "struct"; readonly shapes: NestedShapes; } interface RecordContainerShape extends Shape, RecordRef, Record> { readonly _type: "record"; readonly shape: NestedShape; } /** * Container escape hatch - represents "any LoroContainer". * Use this when integrating with external libraries that manage their own document structure. * * @example * ```typescript * // loro-prosemirror manages its own structure * const ProseMirrorDocShape = Shape.doc({ * doc: Shape.any(), // opt out of typing for this container * }) * ``` */ interface AnyContainerShape extends Shape { readonly _type: "any"; } /** * Union of all container shape types. * * Each container shape has a `_mutable` type parameter that maps to the * corresponding TypedRef class (e.g., TextContainerShape → TextRef). * This enables deriving ref types from shapes: * * ```typescript * // Get the ref type for any container shape * type RefType = ContainerShape["_mutable"] * * // Exclude AnyContainerShape to get only typed refs * type AnyTypedRef = Exclude["_mutable"] * ``` * * This creates intentional parallel hierarchies: * - ContainerShape → defines what data looks like (schema) * - TypedRef (via _mutable) → defines how you interact with data * - loro() overloads → CRDT escape hatch (IDE DX) * - change() overloads → mutation boundaries (IDE DX) */ type ContainerShape = AnyContainerShape | CounterContainerShape | ListContainerShape | MovableListContainerShape | RecordContainerShape | StructContainerShape | TextContainerShape | TreeContainerShape; type ContainerType = ContainerShape["_type"]; interface StringValueShape extends Shape { readonly _type: "value"; readonly valueType: "string"; readonly options?: T[]; } interface NumberValueShape extends Shape { readonly _type: "value"; readonly valueType: "number"; } interface BooleanValueShape extends Shape { readonly _type: "value"; readonly valueType: "boolean"; } interface NullValueShape extends Shape { readonly _type: "value"; readonly valueType: "null"; } interface UndefinedValueShape extends Shape { readonly _type: "value"; readonly valueType: "undefined"; } interface Uint8ArrayValueShape extends Shape { readonly _type: "value"; readonly valueType: "uint8array"; } /** * Value shape for objects with fixed keys (structs). * This is the preferred way to define fixed-key plain value objects. * Identical structure to ObjectValueShape but with valueType: "struct". */ interface StructValueShape = Record> extends Shape<{ [K in keyof T]: T[K]["_plain"]; }, { [K in keyof T]: T[K]["_mutable"]; }, { [K in keyof T]: T[K]["_placeholder"]; }> { readonly _type: "value"; readonly valueType: "struct"; readonly shape: T; } interface RecordValueShape extends Shape, Record, Record> { readonly _type: "value"; readonly valueType: "record"; readonly shape: T; } interface ArrayValueShape extends Shape { readonly _type: "value"; readonly valueType: "array"; readonly shape: T; } interface UnionValueShape extends Shape { readonly _type: "value"; readonly valueType: "union"; readonly shapes: T; } /** * A discriminated union shape that uses a discriminant key to determine which variant to use. * This enables type-safe handling of tagged unions like: * * ```typescript * type GamePresence = * | { type: "client"; name: string; input: { force: number; angle: number } } * | { type: "server"; cars: Record; tick: number } * ``` * * @typeParam K - The discriminant key (e.g., "type") * @typeParam T - A record mapping discriminant values to their object shapes */ interface DiscriminatedUnionValueShape = Record, Plain = T[keyof T]["_plain"], Mutable = T[keyof T]["_mutable"], Placeholder = T[keyof T]["_placeholder"]> extends Shape { readonly _type: "value"; readonly valueType: "discriminatedUnion"; readonly discriminantKey: K; readonly variants: T; } /** * Value escape hatch - represents "any Loro Value". * Use this when you need to accept any valid Loro value type. * * @example * ```typescript * const FlexiblePresenceShape = Shape.plain.struct({ * cursor: Shape.plain.any(), // accept any value type * }) * ``` */ interface AnyValueShape extends Shape { readonly _type: "value"; readonly valueType: "any"; } type ValueShape = AnyValueShape | ArrayValueShape | BooleanValueShape | DiscriminatedUnionValueShape | NullValueShape | NumberValueShape | RecordValueShape | StringValueShape | StructValueShape | Uint8ArrayValueShape | UndefinedValueShape | UnionValueShape; type ContainerOrValueShape = ContainerShape | ValueShape; interface Shape { readonly _type: string; readonly _plain: Plain; readonly _mutable: Mutable; readonly _placeholder: Placeholder; } /** * The LoroShape factory object * * If a container has a `shape` type variable, it refers to the shape it contains-- * so for example, a `LoroShape.list(LoroShape.text())` would return a value of type * `ListContainerShape`. */ declare const Shape: { doc: >(shape: T) => DocShape; /** * Creates an "any" container shape - an escape hatch for untyped containers. * Use this when integrating with external libraries that manage their own document structure. * * @example * ```typescript * // loro-prosemirror manages its own structure * const ProseMirrorDocShape = Shape.doc({ * doc: Shape.any(), // opt out of typing for this container * }) * * const handle = repo.get(docId, ProseMirrorDocShape, CursorPresenceShape) * // handle.doc.doc is typed as `unknown` - you're on your own * ``` */ any: () => AnyContainerShape; counter: () => WithPlaceholder; list: (shape: T) => ListContainerShape; /** * Creates a struct container shape for objects with fixed keys. * This is the preferred way to define fixed-key objects. * * @example * ```typescript * const UserSchema = Shape.doc({ * user: Shape.struct({ * name: Shape.text(), * age: Shape.counter(), * }), * }) * ``` */ struct: >(shape: T) => StructContainerShape; /** * @deprecated Use `Shape.struct` instead. `Shape.struct` will be removed in a future version. */ map: >(shape: T) => StructContainerShape; record: (shape: T) => RecordContainerShape; movableList: (shape: T) => MovableListContainerShape; text: () => WithPlaceholder; /** * Creates a tree container shape for hierarchical data structures. * Each node in the tree has typed metadata defined by the data shape. * * @example * ```typescript * const StateNodeDataShape = Shape.struct({ * name: Shape.text(), * facts: Shape.record(Shape.plain.any()), * }) * * const Schema = Shape.doc({ * states: Shape.tree(StateNodeDataShape), * }) * * doc.change(draft => { * const root = draft.states.createNode({ name: "idle", facts: {} }) * const child = root.createNode({ name: "running", facts: {} }) * child.data.name = "active" * }) * ``` */ tree: (shape: T) => TreeContainerShape; plain: { string: (...options: T[]) => WithPlaceholder> & WithNullable>; number: () => WithPlaceholder & WithNullable; boolean: () => WithPlaceholder & WithNullable; null: () => NullValueShape; undefined: () => UndefinedValueShape; uint8Array: () => Uint8ArrayValueShape & WithNullable; /** * Alias for `uint8Array()` - creates a shape for binary data. * Use this for better discoverability when working with binary data like cursor positions. * * @example * ```typescript * const CursorPresenceShape = Shape.plain.struct({ * anchor: Shape.plain.bytes().nullable(), * focus: Shape.plain.bytes().nullable(), * }) * ``` */ bytes: () => Uint8ArrayValueShape & WithNullable; /** * Creates an "any" value shape - an escape hatch for untyped values. * Use this when you need to accept any valid Loro value type. * * @example * ```typescript * const FlexiblePresenceShape = Shape.plain.struct({ * metadata: Shape.plain.any(), // accept any value type * }) * ``` */ any: () => AnyValueShape; /** * Creates a struct value shape for plain objects with fixed keys. * This is the preferred way to define fixed-key plain value objects. * * @example * ```typescript * const PointSchema = Shape.plain.struct({ * x: Shape.plain.number(), * y: Shape.plain.number(), * }) * ``` */ struct: >(shape: T) => StructValueShape & WithNullable>; /** * @deprecated Use `Shape.plain.struct` instead. `Shape.plain.struct` will be removed in a future version. */ object: >(shape: T) => StructValueShape & WithNullable>; record: (shape: T) => RecordValueShape & WithNullable>; array: (shape: T) => ArrayValueShape & WithNullable>; union: (shapes: T) => WithPlaceholder>; /** * Creates a discriminated union shape for type-safe tagged unions. * * @example * ```typescript * const ClientPresenceShape = Shape.plain.struct({ * type: Shape.plain.string("client"), * name: Shape.plain.string(), * input: Shape.plain.struct({ force: Shape.plain.number(), angle: Shape.plain.number() }), * }) * * const ServerPresenceShape = Shape.plain.struct({ * type: Shape.plain.string("server"), * cars: Shape.plain.record(Shape.plain.struct({ x: Shape.plain.number(), y: Shape.plain.number() })), * tick: Shape.plain.number(), * }) * * const GamePresenceSchema = Shape.plain.discriminatedUnion("type", { * client: ClientPresenceShape, * server: ServerPresenceShape, * }) * ``` * * @param discriminantKey - The key used to discriminate between variants (e.g., "type") * @param variants - A record mapping discriminant values to their object shapes */ discriminatedUnion: >(discriminantKey: K, variants: T) => WithPlaceholder>; }; }; type ShapeToContainer = T extends TextContainerShape ? LoroText : T extends CounterContainerShape ? LoroCounter : T extends ListContainerShape ? LoroList : T extends MovableListContainerShape ? LoroMovableList : T extends StructContainerShape | RecordContainerShape ? LoroMap : T extends TreeContainerShape ? LoroTree : never; /** * Derives the placeholder state from a schema by composing placeholder values. * * For leaf nodes (text, counter, values): uses _placeholder directly * For containers (map, list, record): recurses into nested shapes */ declare function derivePlaceholder(schema: T): InferPlaceholderType; /** * Derives placeholder for a single shape. * * Leaf nodes: return _placeholder directly * Containers: recurse into nested shapes (ignore _placeholder on containers) */ declare function deriveShapePlaceholder(shape: ContainerOrValueShape): unknown; type DiffOverlay = ReadonlyMap; declare function createDiffOverlay(doc: LoroDoc, batch: LoroEventBatch): DiffOverlay; /** * The primary method of mutating typed documents and refs. * Batches multiple mutations into a single transaction. * All changes commit together at the end. * * Use this for: * - Find-and-mutate operations (required due to JS limitations) * - Performance (fewer commits) * - Atomic undo (all changes = one undo step) * * Returns the doc/ref for chaining. * * @param target - The TypedDoc or TypedRef to mutate * @param fn - Function that performs mutations on the draft * @returns The same target for chaining * * @example * ```typescript * import { change } from "@loro-extended/change" * * // Document-level change (chainable) * change(doc, draft => { * draft.count.increment(10) * draft.title.update("Hello") * }) * .count.increment(5) // Optional: continue mutating * .toJSON() // Optional: get snapshot * * // Ref-level change - enables encapsulation * function addItems(list: ListRef<...>) { * change(list, draft => { * draft.push({ name: "item1" }) * draft.push({ name: "item2" }) * }) * } * * // TreeRef example - pass around refs without exposing the doc * function addStates(states: TreeRef) { * change(states, draft => { * draft.createNode({ name: "idle" }) * draft.createNode({ name: "running" }) * }) * } * ``` */ declare function change(doc: TypedDoc, fn: (draft: Mutable) => void): TypedDoc; declare function change(ref: TreeRef, fn: (draft: TreeRef) => void): TreeRef; declare function change(ref: TreeRefInterface, fn: (draft: TreeRefInterface) => void): TreeRefInterface; declare function change>(ref: StructRef, fn: (draft: StructRef) => void): StructRef; declare function change>(ref: T, fn: (draft: T) => void): T; /** * Access the underlying LoroDoc for advanced operations. * Works on both TypedDoc and any typed ref (TextRef, CounterRef, ListRef, etc.). * * @param docOrRef - The TypedDoc or typed ref to unwrap * @returns The underlying LoroDoc instance (or undefined for refs created outside a doc context) * * @example * ```typescript * import { getLoroDoc } from "@loro-extended/change" * * // From TypedDoc * const loroDoc = getLoroDoc(doc) * const version = loroDoc.version() * loroDoc.subscribe(() => console.log("changed")) * * // From any ref (TextRef, CounterRef, ListRef, etc.) * const titleRef = doc.title * const loroDoc = getLoroDoc(titleRef) * loroDoc?.subscribe(() => console.log("changed")) * ``` */ declare function getLoroDoc(doc: TypedDoc): LoroDoc; declare function getLoroDoc(ref: TypedRef): LoroDoc; declare function getLoroDoc(ref: TreeRef): LoroDoc; declare function getLoroDoc(ref: TreeRefInterface): LoroDoc; /** * Access the underlying Loro container from a typed ref. * Returns the correctly-typed container based on the ref type. * * @param ref - The typed ref to unwrap * @returns The underlying Loro container (LoroText, LoroCounter, LoroList, etc.) * * @example * ```typescript * import { getLoroContainer } from "@loro-extended/change" * * const titleRef = doc.title * const loroText = getLoroContainer(titleRef) // LoroText * * const countRef = doc.count * const loroCounter = getLoroContainer(countRef) // LoroCounter * * const itemsRef = doc.items * const loroList = getLoroContainer(itemsRef) // LoroList * * // Subscribe to container-level changes * loroText.subscribe((event) => console.log("Text changed:", event)) * ``` */ declare function getLoroContainer(ref: TypedRef): LoroText; declare function getLoroContainer(ref: TypedRef): LoroCounter; declare function getLoroContainer(ref: TypedRef): LoroList; declare function getLoroContainer(ref: TypedRef): LoroMovableList; declare function getLoroContainer(ref: TypedRef): LoroMap; declare function getLoroContainer(ref: TypedRef): LoroMap; declare function getLoroContainer>(ref: StructRef): LoroMap; declare function getLoroContainer(ref: TreeRef): LoroTree; declare function getLoroContainer(ref: TreeRefInterface): LoroTree; declare function getLoroContainer(ref: TypedRef): ShapeToContainer; /** * Creates a new TypedDoc as a fork of the current document. * The forked doc contains all history up to the current version. * The forked doc has a different PeerID from the original by default. * * For raw LoroDoc access, use: `loro(doc).doc.fork()` * * @param doc - The TypedDoc to fork * @param options - Optional settings * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork * @returns A new TypedDoc with the same schema at the current version * * @example * ```typescript * import { fork, loro } from "@loro-extended/change" * * const doc = createTypedDoc(schema); * doc.title.update("Hello"); * * // Fork the document * const forkedDoc = fork(doc); * forkedDoc.title.update("World"); * * console.log(doc.title.toString()); // "Hello" * console.log(forkedDoc.title.toString()); // "World" * * // Fork with same peer ID (for World/Worldview pattern) * const worldview = fork(world, { preservePeerId: true }); * ``` */ declare function fork(doc: TypedDoc, options?: { preservePeerId?: boolean; }): TypedDoc; /** * Creates a new TypedDoc at a specified version (frontiers). * The forked doc will only contain history before the specified frontiers. * The forked doc has a different PeerID from the original. * * For raw LoroDoc access, use: `loro(doc).doc.forkAt(frontiers)` * * @param doc - The TypedDoc to fork * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`) * @returns A new TypedDoc with the same schema at the specified version * * @example * ```typescript * import { forkAt, loro } from "@loro-extended/change" * * const doc = createTypedDoc(schema); * doc.title.update("Hello"); * const frontiers = loro(doc).doc.frontiers(); * doc.title.update("World"); * * // Fork at the earlier version * const forkedDoc = forkAt(doc, frontiers); * console.log(forkedDoc.title.toString()); // "Hello" * console.log(doc.title.toString()); // "World" * ``` */ declare function forkAt(doc: TypedDoc, frontiers: Frontiers): TypedDoc; /** * Creates a new TypedDoc at a specified version using a shallow snapshot. * Unlike `forkAt`, this creates a "garbage-collected" snapshot that only * contains the current state and history since the specified frontiers. * * This is more memory-efficient than `forkAt` for documents with long history, * especially useful for the fork-and-merge pattern in LEA where we only need: * 1. Read current state * 2. Apply changes * 3. Export delta and merge back * * The shallow fork has a different PeerID from the original by default. * Use `preservePeerId: true` to copy the original's peer ID (useful for * fork-and-merge patterns where you want consistent frontier progression). * * @param doc - The TypedDoc to fork * @param frontiers - The version to fork at (obtained from `loro(doc).doc.frontiers()`) * @param options - Optional settings * @param options.preservePeerId - If true, copies the original doc's peer ID to the fork * @returns A new TypedDoc with the same schema at the specified version (shallow) * * @example * ```typescript * import { shallowForkAt, loro } from "@loro-extended/change" * * const doc = createTypedDoc(schema); * doc.title.update("Hello"); * const frontiers = loro(doc).doc.frontiers(); * * // Create a shallow fork (memory-efficient) * const shallowDoc = shallowForkAt(doc, frontiers, { preservePeerId: true }); * * // Modify the shallow doc * shallowDoc.title.update("World"); * * // Merge changes back * const update = loro(shallowDoc).doc.export({ * mode: "update", * from: loro(doc).doc.version() * }); * loro(doc).doc.import(update); * ``` */ declare function shallowForkAt(doc: TypedDoc, frontiers: Frontiers, options?: { preservePeerId?: boolean; }): TypedDoc; type Transition = { before: TypedDoc; after: TypedDoc; }; /** * Build a `{ before, after }` transition from a TypedDoc and a Loro event batch. * Uses a reverse diff overlay to compute the "before" view without checkout. * Throws on checkout events to avoid time-travel transitions. */ declare function getTransition(doc: TypedDoc, event: LoroEventBatch): Transition; /** * Overlays CRDT state with placeholder defaults */ declare function overlayPlaceholder(shape: Shape, crdtValue: { [key: string]: Value; }, placeholderValue: { [key: string]: Value; }): { [key: string]: Value; }; /** * Merges individual CRDT values with placeholder defaults */ declare function mergeValue(shape: Shape, crdtValue: Value, placeholderValue: Value): Value; type PathSegment = { type: "property"; key: string; } | { type: "each"; } | { type: "index"; index: number; } | { type: "key"; key: string; }; interface PathSelector { readonly __resultType: T; readonly __segments: PathSegment[]; } interface ListPathNode extends PathSelector[], InArray>> { /** Select all items (wildcard) - sets InArray to true for children */ readonly $each: PathNode; /** Select item at specific index (supports negative indices: -1 = last, -2 = second-to-last, etc.) */ $at(index: number): PathNode; /** Select first item (alias for $at(0)) */ readonly $first: PathNode; /** Select last item (alias for $at(-1)) */ readonly $last: PathNode; } type StructPathNode, InArray extends boolean> = PathSelector; }, InArray>> & { readonly [K in keyof Shapes]: PathNode; }; interface RecordPathNode extends PathSelector>, InArray>> { /** Select all values (wildcard) - sets InArray to true for children */ readonly $each: PathNode; /** Select value at specific key */ $key(key: string): PathNode; } type TextPathNode = PathSelector>; type CounterPathNode = PathSelector>; type TerminalPathNode = PathSelector>; type WrapType = InArray extends true ? T[] : T; type PathNode = S extends ListContainerShape ? ListPathNode : S extends MovableListContainerShape ? ListPathNode : S extends StructContainerShape ? StructPathNode : S extends RecordContainerShape ? RecordPathNode : S extends TextContainerShape ? TextPathNode : S extends CounterContainerShape ? CounterPathNode : S extends ValueShape ? TerminalPathNode, InArray> : never; type PathBuilder = { readonly [K in keyof D["shapes"]]: PathNode; }; /** * Creates a path builder for a given document shape. * * The path builder provides a type-safe DSL for selecting paths within * a document. The resulting PathSelector can be compiled to a JSONPath * string for use with subscribeJsonpath. * * @example * ```typescript * const docShape = Shape.doc({ * books: Shape.list(Shape.struct({ * title: Shape.text(), * price: Shape.plain.number(), * })), * }) * * const builder = createPathBuilder(docShape) * const selector = builder.books.$each.title * // selector.__segments = [ * // { type: "property", key: "books" }, * // { type: "each" }, * // { type: "property", key: "title" } * // ] * ``` */ declare function createPathBuilder(docShape: D): PathBuilder; /** * Compiles path segments to a JSONPath string. * * @example * ```typescript * const segments = [ * { type: "property", key: "books" }, * { type: "each" }, * { type: "property", key: "title" } * ] * compileToJsonPath(segments) // => '$.books[*].title' * ``` */ declare function compileToJsonPath(segments: PathSegment[]): string; /** * Check if the path contains any wildcard segments. * Paths with wildcards need deep equality checking for change detection. */ declare function hasWildcard(segments: PathSegment[]): boolean; /** * Evaluate a path selector against a TypedDoc to get the current value. * Returns the value(s) at the path, properly typed. * * @example * ```typescript * const selector = builder.books.$each.title * const titles = evaluatePath(doc, selector) * // titles: string[] * ``` */ declare function evaluatePath(doc: TypedDoc, selector: PathSelector): T; /** * Evaluate path segments against a plain JavaScript value. * This is the core recursive evaluation logic. */ declare function evaluatePathOnValue(value: unknown, segments: PathSegment[]): unknown; /** * Creates a proxy around a placeholder value (plain object/array) that mimics * the behavior of TypedRef, specifically adding a .toJSON() method. * * This ensures consistent UX where users can call .toJSON() on document state * regardless of whether it's loading (placeholder) or loaded (live ref). */ declare function createPlaceholderProxy(target: T): T; /** * Replay a diff as local operations on a document. * * Unlike doc.import() which creates import events, this creates LOCAL events * that are captured by subscribeLocalUpdates() and UndoManager. * * @param doc - The target document to apply changes to * @param diff - The diff from doc.diff(from, to, false) */ declare function replayDiff(doc: LoroDoc, diff: [ContainerID, Diff][]): void; /** * Validates placeholder against schema structure without using Zod * Combines the functionality of createPlaceholderValidator and createValueValidator */ declare function validatePlaceholder(placeholder: unknown, schema: T): Infer; export { type AnyContainerShape, type AnyValueShape, type ArrayValueShape, type BooleanValueShape, type ContainerOrValueShape, type ContainerShape, type CounterContainerShape, CounterRef, type DiffOverlay$1 as DiffOverlay, type DiscriminatedUnionValueShape, type DocShape, type Frontiers, type Infer, type InferMutableType, type InferPlaceholderType, type InferRaw, LORO_SYMBOL, type ListContainerShape, ListRef, type LoroCounterRef, type LoroListRef, type LoroMapRef, type LoroRefBase, type LoroTextRef, type LoroTreeRef, type LoroTypedDocRef, type MovableListContainerShape, MovableListRef, type Mutable, type NullValueShape, type NumberValueShape, type PathBuilder, type PathNode, type PathSegment, type PathSelector, type RecordContainerShape, RecordRef, type RecordValueShape, type ContainerType as RootContainerType, Shape, type StringValueShape, type StructContainerShape, type StructRef, type StructValueShape, type TextContainerShape, TextRef, type Transition, type TreeContainerShape, type TreeNodeJSON, TreeNodeRef, TreeRef, type TreeRefInterface, type TypedDoc, type Uint8ArrayValueShape, type UndefinedValueShape, type UnionValueShape, type ValueShape, type WithNullable, type WithPlaceholder, change, compileToJsonPath, createDiffOverlay, createPathBuilder, createPlaceholderProxy, createTypedDoc, derivePlaceholder, deriveShapePlaceholder, evaluatePath, evaluatePathOnValue, fork, forkAt, getLoroContainer, getLoroDoc, getTransition, hasWildcard, loro, mergeValue, overlayPlaceholder, replayDiff, shallowForkAt, validatePlaceholder };