/** biome-ignore-all lint/suspicious/noExplicitAny: fix later */ import { LoroDoc, type LoroEventBatch, type PeerID, type Subscription, } from "loro-crdt" import { derivePlaceholder } from "./derive-placeholder.js" import { type JsonPatch, JsonPatchApplicator, type JsonPatchOperation, normalizePath, } from "./json-patch.js" import { LORO_SYMBOL, type LoroTypedDocRef } from "./loro.js" import { overlayPlaceholder } from "./overlay.js" import type { DocShape } from "./shape.js" import { type DiffOverlay, INTERNAL_SYMBOL } from "./typed-refs/base.js" import { DocRef } from "./typed-refs/doc-ref.js" import type { Infer, InferPlaceholderType, Mutable } from "./types.js" import { validatePlaceholder } from "./validation.js" /** * Internal TypedDoc implementation (not directly exposed to users). * Users interact with the proxied version that provides direct schema access. */ class TypedDocInternal { private shape: Shape private placeholder: InferPlaceholderType private doc: LoroDoc private overlay?: DiffOverlay private valueRef: DocRef | null = null // Reference to the proxy for returning from change() proxy: TypedDoc | null = null constructor( shape: Shape, doc: LoroDoc = new LoroDoc(), overlay?: DiffOverlay, ) { this.shape = shape this.placeholder = derivePlaceholder(shape) this.doc = doc this.overlay = overlay validatePlaceholder(this.placeholder, this.shape) } get value(): Mutable { if (!this.valueRef) { this.valueRef = new DocRef({ shape: this.shape, placeholder: this.placeholder as any, doc: this.doc, autoCommit: true, overlay: this.overlay, }) } return this.valueRef as unknown as Mutable } toJSON(): Infer { const crdtValue = this.doc.toJSON() return overlayPlaceholder( this.shape, crdtValue, this.placeholder as any, ) as Infer } change(fn: (draft: Mutable) => void): void { const draft = new DocRef({ shape: this.shape, placeholder: this.placeholder as any, doc: this.doc, autoCommit: false, batchedMutation: true, // Enable value shape caching for find-and-mutate patterns overlay: this.overlay, }) fn(draft as unknown as Mutable) draft[INTERNAL_SYMBOL].absorbPlainValues() this.doc.commit() // Invalidate cached value ref since doc changed this.valueRef = null } applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void { this.change(draft => { const applicator = new JsonPatchApplicator(draft) const prefixedPatch = pathPrefix ? patch.map((op: JsonPatchOperation) => ({ ...op, path: [...pathPrefix, ...normalizePath(op.path)], })) : patch applicator.applyPatch(prefixedPatch) }) } get loroDoc(): LoroDoc { return this.doc } get docShape(): Shape { return this.shape } get rawValue(): any { return this.doc.toJSON() } } /** * 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. */ export type Frontiers = { peer: PeerID; counter: number }[] export type CreateTypedDocOptions = { doc?: LoroDoc overlay?: DiffOverlay } export 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); * ``` */ export function createTypedDoc( shape: Shape, options: CreateTypedDocOptions = {}, ): TypedDoc { const internal = new TypedDocInternal( shape, options.doc || new LoroDoc(), options.overlay, ) // Create the loro() namespace for this doc const loroNamespace: LoroTypedDocRef = { get doc(): LoroDoc { return internal.loroDoc }, get container(): LoroDoc { return internal.loroDoc }, subscribe(callback: (event: LoroEventBatch) => void): Subscription { return internal.loroDoc.subscribe(callback) }, applyPatch(patch: JsonPatch, pathPrefix?: (string | number)[]): void { internal.applyPatch(patch, pathPrefix) }, get docShape(): DocShape { return internal.docShape }, get rawValue(): unknown { return internal.rawValue }, } // Create the change() function that returns the proxy for chaining const changeFunction = ( fn: (draft: Mutable) => void, ): TypedDoc => { internal.change(fn) return proxy } // Create the forkAt() function that returns a new TypedDoc at the specified version const forkAtFunction = (frontiers: Frontiers): TypedDoc => { const forkedLoroDoc = internal.loroDoc.forkAt(frontiers) return createTypedDoc(internal.docShape, { doc: forkedLoroDoc }) } // Create a proxy that delegates schema properties to the DocRef // and provides change() and forkAt() methods const proxy = new Proxy(internal.value as object, { get(target, prop, receiver) { // loro() access via well-known symbol if (prop === LORO_SYMBOL) { return loroNamespace } // change() method directly on doc if (prop === "change") { return changeFunction } // forkAt() method directly on doc if (prop === "forkAt") { return forkAtFunction } // toJSON() should always read fresh from the CRDT if (prop === "toJSON") { return () => internal.toJSON() } // Delegate to the DocRef (which is the target) return Reflect.get(target, prop, receiver) }, set(target, prop, value, receiver) { // Don't allow setting change, forkAt, or LORO_SYMBOL if (prop === LORO_SYMBOL || prop === "change" || prop === "forkAt") { return false } // Delegate to the DocRef return Reflect.set(target, prop, value, receiver) }, // Support 'in' operator has(target, prop) { if (prop === LORO_SYMBOL || prop === "change" || prop === "forkAt") return true return Reflect.has(target, prop) }, // Support Object.keys() - filter out Symbol properties to allow proxies to be used // in place of plain objects. This prevents React's "Object keys must be strings" error. ownKeys(target) { return Reflect.ownKeys(target).filter(key => typeof key === "string") }, getOwnPropertyDescriptor(target, prop) { if (prop === "change") { return { configurable: true, enumerable: false, value: changeFunction, } } if (prop === "forkAt") { return { configurable: true, enumerable: false, value: forkAtFunction, } } if (prop === LORO_SYMBOL) { return { configurable: true, enumerable: false, value: loroNamespace, } } return Reflect.getOwnPropertyDescriptor(target, prop) }, }) as TypedDoc // Store reference to proxy for returning from change() internal.proxy = proxy return proxy }