{"version":3,"file":"immutable-tree.cjs","names":["TreeIterator","nonexist: NonExistenceProof","convertLeafOp","convertInnerOps","verifyMembership","IavlSpec","verifyNonMembership","Exporter","leaves: string[]"],"sources":["../src/immutable-tree.ts"],"sourcesContent":["/**\n * ImmutableTree contains the immutable tree at a given version.\n * It is typically created by calling MutableTree.getImmutable(), in which case\n * the returned tree is safe for concurrent access as long as the version is\n * not deleted via deleteVersion() or the tree's pruning settings.\n *\n * Returned key/value byte slices must not be modified, since they may point\n * to data located inside IAVL which would also be modified.\n */\n\nimport type {\n  Logger,\n} from \"winston\";\n\nimport {\n  Exporter,\n} from \"./export/index.js\";\nimport type {\n  ExportNode,\n} from \"./export/types.js\";\nimport type {\n  CommitmentProof,\n  ExistenceProof,\n  NonExistenceProof,\n} from \"./generated/cosmos/ics23/v1/proofs.js\";\nimport {\n  TreeIterator,\n} from \"./iterator/iterator.js\";\nimport type {\n  Node,\n} from \"./node.js\";\nimport type {\n  NodeGetter,\n} from \"./node.js\";\nimport {\n  convertInnerOps,\n  convertLeafOp,\n  IavlSpec,\n  verifyMembership,\n  verifyNonMembership,\n} from \"./proof/types.js\";\nimport type {\n  ChangeSet,\n} from \"./types/index.js\";\n\n/**\n * ImmutableTree represents a read-only snapshot of the tree at a specific version.\n */\nexport class ImmutableTree {\n  /** Root node of the tree */\n  readonly root: Node | null;\n\n  /** NodeDB instance for loading nodes (forward reference using NodeGetter interface) */\n  readonly ndb: NodeGetter;\n\n  /** Version of this tree snapshot */\n  readonly version: bigint;\n\n  /** Whether to skip fast storage upgrade (use traditional IAVL node storage only) */\n  readonly skipFastStorageUpgrade: boolean;\n\n  /** Logger instance for diagnostics */\n  readonly logger: Logger | null;\n\n  /**\n   * Creates a new ImmutableTree instance.\n   *\n   * @param root - Root node of the tree (null for empty tree)\n   * @param ndb - NodeDB instance for loading nodes\n   * @param version - Version number of this tree snapshot\n   * @param skipFastStorageUpgrade - Whether to skip fast storage (default: false)\n   * @param logger - Optional logger instance\n   */\n  constructor(\n    root: Node | null,\n    ndb: NodeGetter,\n    version: bigint,\n    skipFastStorageUpgrade = false,\n    logger: Logger | null = null,\n  ) {\n    this.root = root;\n    this.ndb = ndb;\n    this.version = version;\n    this.skipFastStorageUpgrade = skipFastStorageUpgrade;\n    this.logger = logger;\n\n    // Make the tree truly immutable by freezing it\n    Object.freeze(this);\n  }\n\n  /**\n   * Returns the version of the tree.\n   *\n   * @returns Version number\n   */\n  getVersion(): bigint {\n    return this.version;\n  }\n\n  /**\n   * Returns the root node of the tree.\n   *\n   * @returns Root node or null if tree is empty\n   */\n  getRoot(): Node | null {\n    return this.root;\n  }\n\n  /**\n   * Returns whether the tree is empty.\n   *\n   * @returns true if tree has no nodes\n   */\n  isEmpty(): boolean {\n    return this.root === null;\n  }\n\n  /**\n   * Returns the number of leaf nodes in the tree.\n   *\n   * @returns Total number of key-value pairs\n   */\n  size(): bigint {\n    if (this.root === null) {\n      return 0n;\n    }\n    return this.root.size;\n  }\n\n  /**\n   * Returns the height of the tree.\n   * Height is defined as the number of edges in the longest path from root to leaf.\n   * An empty tree has height 0, a single node has height 0, two levels have height 1.\n   *\n   * @returns Tree height\n   */\n  height(): number {\n    if (this.root === null) {\n      return 0;\n    }\n    return this.root.subtreeHeight;\n  }\n\n  /**\n   * Returns the root hash of the tree.\n   * Computes the hash if it hasn't been computed yet.\n   * Returns null for empty trees.\n   *\n   * @returns Root hash or null for empty tree\n   */\n  hash(): Uint8Array | null {\n    if (this.root === null) {\n      return null;\n    }\n    // Compute hash if not already computed\n    return this.root.computeHash(this.version);\n  }\n\n  /**\n   * Returns whether a key exists in the tree.\n   *\n   * @param key - The key to check\n   * @returns true if key exists, false otherwise\n   */\n  async has(key: Uint8Array): Promise<boolean> {\n    if (this.root === null) {\n      return false;\n    }\n    const result = await this.root.get(this.ndb, key);\n    return result.value !== null;\n  }\n\n  /**\n   * Creates a shallow clone of this ImmutableTree.\n   * The clone shares the same root node and NodeDB reference.\n   * Used for creating snapshots (e.g., lastSaved in MutableTree).\n   *\n   * @returns A new ImmutableTree instance with same root/version/ndb\n   */\n  clone(): ImmutableTree {\n    return new ImmutableTree(\n      this.root,\n      this.ndb,\n      this.version,\n      this.skipFastStorageUpgrade,\n      this.logger,\n    );\n  }\n\n  /**\n   * Returns the value for a given key.\n   * The returned value must not be modified, since it may point to data stored within IAVL.\n   *\n   * Employs fast storage optimization when available for better performance.\n   * This matches Go IAVL's Get() implementation (immutable_tree.go:180-216).\n   *\n   * @param key - The key to look up\n   * @returns The value, or null if key doesn't exist\n   */\n  async get(key: Uint8Array): Promise<Uint8Array | null> {\n    if (this.root === null) {\n      return null;\n    }\n\n    // Fast storage optimization: attempt to get FastNode directly from db/cache\n    // If this fails, fall back to tree traversal\n    // Note: ndb is typed as NodeGetter interface, but NodeDB implements additional methods\n    if (!this.skipFastStorageUpgrade && \"getFastNode\" in this.ndb && \"getLatestVersion\" in this.ndb) {\n      try {\n        // Type assertion: we've verified the methods exist\n        const ndb = this.ndb as {\n          getFastNode: (key: Uint8Array) => Promise<{\n            value: Uint8Array\n            versionLastUpdatedAt: bigint\n          } | null>\n          getLatestVersion: () => bigint\n        };\n\n        const fastNode = await ndb.getFastNode(key);\n\n        // If fast node doesn't exist\n        if (fastNode === null) {\n          // For the latest version, fast node absence means the key doesn't exist\n          // because fast nodes represent the live state\n          if (this.version === ndb.getLatestVersion()) {\n            return null;\n          }\n\n          // For historical versions, fall back to tree traversal\n          const result = await this.root.get(this.ndb, key);\n          return result.value;\n        }\n\n        // If fast node exists and was updated at or before this tree version,\n        // it's valid for this version\n        if (fastNode.versionLastUpdatedAt <= this.version) {\n          return fastNode.value;\n        }\n\n        // Fast node was updated after this tree version, fall through to tree traversal\n      }\n      catch (_err) {\n        // If fast node retrieval fails, fall back to tree traversal\n        const result = await this.root.get(this.ndb, key);\n        return result.value;\n      }\n    }\n\n    // Either skipFastStorageUpgrade is true, or the fast node was updated later\n    // than this tree version. Use tree traversal to avoid staleness.\n    const result = await this.root.get(this.ndb, key);\n    return result.value;\n  }\n\n  /**\n   * Returns the index and value of the specified key if it exists, or the next index otherwise.\n   * The returned value must not be modified, since it may point to data stored within IAVL.\n   *\n   * The index is the index in the list of leaf nodes sorted lexicographically by key.\n   * The leftmost leaf has index 0, its neighbor has index 1, and so on.\n   *\n   * @param key - The key to look up\n   * @returns Object with index and value (value is null if key doesn't exist)\n   */\n  async getWithIndex(key: Uint8Array): Promise<{\n    index: bigint\n    value: Uint8Array | null\n  }> {\n    if (this.root === null) {\n      return {\n        index: 0n,\n        value: null,\n      };\n    }\n    return await this.root.get(this.ndb, key);\n  }\n\n  /**\n   * Gets the key and value at the specified index.\n   * Index represents position in the sorted list of keys (0-based).\n   *\n   * @param index - The index to look up (0 = leftmost leaf)\n   * @returns Object with key and value, or null if index is out of bounds\n   */\n  async getByIndex(index: bigint): Promise<{\n    key: Uint8Array\n    value: Uint8Array\n  } | null> {\n    if (this.root === null) {\n      return null;\n    }\n\n    const result = await this.root.getByIndex(this.ndb, index);\n    if (result.key === null || result.value === null) {\n      return null;\n    }\n\n    return {\n      key: result.key,\n      value: result.value,\n    };\n  }\n\n  /**\n   * Creates an iterator over the tree in ascending order.\n   *\n   * @param start - Start key (null to start from beginning)\n   * @param end - End key (null for no limit)\n   * @returns TreeIterator instance\n   */\n  iterator(\n    start: Uint8Array | null = null,\n    end: Uint8Array | null = null,\n  ): TreeIterator {\n    return new TreeIterator(this, start, end, true, false);\n  }\n\n  /**\n   * Creates an iterator over the tree in descending order.\n   *\n   * @param start - Start key (null to start from end)\n   * @param end - End key (null for no limit)\n   * @returns TreeIterator instance\n   */\n  reverseIterator(\n    start: Uint8Array | null = null,\n    end: Uint8Array | null = null,\n  ): TreeIterator {\n    return new TreeIterator(this, start, end, false, false);\n  }\n\n  /**\n   * Iterates over all keys in the tree, calling a function for each key-value pair.\n   *\n   * Corresponds to Go's ImmutableTree.Iterate()\n   *\n   * @param fn - Function to call for each key-value pair. Return true to stop iteration.\n   * @returns True if iteration was stopped early, false if completed\n   */\n  async iterate(\n    fn: (key: Uint8Array, value: Uint8Array) => boolean,\n  ): Promise<boolean> {\n    if (this.root === null) {\n      return false;\n    }\n\n    const iter = new TreeIterator(this, null, null, true, false);\n\n    try {\n      // Position iterator at first element\n      await iter.next();\n\n      while (iter.valid()) {\n        const stop = fn(iter.key(), iter.value());\n        if (stop) {\n          return true;\n        }\n        await iter.next();\n      }\n      return false;\n    }\n    finally {\n      iter.close();\n    }\n  }\n\n  /**\n   * Iterates over a range of keys, calling a function for each key-value pair.\n   * End key is exclusive (non-inclusive).\n   *\n   * Corresponds to Go's ImmutableTree.IterateRange()\n   *\n   * @param start - Start key (null to start from beginning)\n   * @param end - End key (exclusive, null for no limit)\n   * @param ascending - True for ascending order, false for descending\n   * @param fn - Function to call for each key-value pair. Return true to stop iteration.\n   * @returns True if iteration was stopped early, false if completed\n   */\n  async iterateRange(\n    start: Uint8Array | null,\n    end: Uint8Array | null,\n    ascending: boolean,\n    fn: (key: Uint8Array, value: Uint8Array) => boolean,\n  ): Promise<boolean> {\n    if (this.root === null) {\n      return false;\n    }\n\n    const iter = new TreeIterator(this, start, end, ascending, false);\n\n    try {\n      // Position iterator at first element\n      await iter.next();\n\n      while (iter.valid()) {\n        const stop = fn(iter.key(), iter.value());\n        if (stop) {\n          return true;\n        }\n        await iter.next();\n      }\n      return false;\n    }\n    finally {\n      iter.close();\n    }\n  }\n\n  /**\n   * Iterates over a range of keys, calling a function for each key-value-version triple.\n   * End key is inclusive.\n   *\n   * Corresponds to Go's ImmutableTree.IterateRangeInclusive()\n   *\n   * @param start - Start key (null to start from beginning)\n   * @param end - End key (inclusive, null for no limit)\n   * @param ascending - True for ascending order, false for descending\n   * @param fn - Function to call for each key-value-version triple. Return true to stop iteration.\n   * @returns True if iteration was stopped early, false if completed\n   */\n  async iterateRangeInclusive(\n    start: Uint8Array | null,\n    end: Uint8Array | null,\n    ascending: boolean,\n    fn: (key: Uint8Array, value: Uint8Array, version: bigint) => boolean,\n  ): Promise<boolean> {\n    if (this.root === null) {\n      return false;\n    }\n\n    const iter = new TreeIterator(this, start, end, ascending, true);\n\n    try {\n      // Position iterator at first element\n      await iter.next();\n\n      while (iter.valid()) {\n        const stop = fn(iter.key(), iter.value(), iter.version());\n        if (stop) {\n          return true;\n        }\n        await iter.next();\n      }\n      return false;\n    }\n    finally {\n      iter.close();\n    }\n  }\n\n  /**\n   * Get Membership Proof generates an ICS23 existence proof for a key.\n   *\n   * Returns a CommitmentProof that the given key (and its value) exists in the IAVL tree.\n   * If the key doesn't exist in the tree, this will return an error.\n   *\n   * The proof can be verified by a light client using the ICS23 verification library\n   * with the tree's root hash.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go GetMembershipProof (lines 14-25)\n   *\n   * @param key - The key to generate a proof for\n   * @returns CommitmentProof containing an ExistenceProof\n   * @throws Error if key doesn't exist in the tree\n   */\n  async getMembershipProof(\n    key: Uint8Array,\n  ): Promise<CommitmentProof> {\n    const exist = await this.createExistenceProof(key);\n\n    return {\n      exist,\n      nonexist: undefined,\n      batch: undefined,\n      compressed: undefined,\n    };\n  }\n\n  /**\n   * Get Non-Membership Proof generates an ICS23 non-existence proof for a key.\n   *\n   * Returns a CommitmentProof that the given key doesn't exist in the IAVL tree.\n   * If the key exists in the tree, this will return an error.\n   *\n   * The proof includes existence proofs for the keys immediately to the left\n   * and right of where the queried key would be if it existed. If the keys\n   * are adjacent and neither equals the queried key, then the queried key\n   * cannot exist.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go GetNonMembershipProof (lines 42-89)\n   *\n   * @param key - The key to generate a non-existence proof for\n   * @returns CommitmentProof containing a NonExistenceProof\n   * @throws Error if key exists in the tree\n   */\n  async getNonMembershipProof(\n    key: Uint8Array,\n  ): Promise<CommitmentProof> {\n    // GetWithIndex returns the index where key would be (or is)\n    // If key doesn't exist, idx points to the next key to the right\n    const {\n      index: idx, value: val,\n    } = await this.getWithIndex(key);\n\n    if (val !== null) {\n      throw new Error(\"cannot create NonExistenceProof when key exists in tree\");\n    }\n\n    const nonexist: NonExistenceProof = {\n      key,\n      left: undefined,\n      right: undefined,\n    };\n\n    // Get left neighbor (key at idx-1)\n    if (idx >= 1n) {\n      const leftResult = await this.getByIndex(idx - 1n);\n\n      if (leftResult) {\n        nonexist.left = await this.createExistenceProof(leftResult.key);\n      }\n    }\n\n    // Get right neighbor (key at idx)\n    // idx points to the next key to the right of where our key would be\n    const rightResult = await this.getByIndex(idx);\n\n    if (rightResult) {\n      nonexist.right = await this.createExistenceProof(rightResult.key);\n    }\n\n    return {\n      exist: undefined,\n      nonexist,\n      batch: undefined,\n      compressed: undefined,\n    };\n  }\n\n  /**\n   * Create Existence Proof generates an ICS23 ExistenceProof for a key.\n   *\n   * This is an internal helper method that:\n   * 1. Calls root.pathToLeaf() to get the proof path\n   * 2. Converts the path to ICS23 format using convertLeafOp/convertInnerOps\n   * 3. Returns an ExistenceProof with the key, value, leaf op, and inner ops\n   *\n   * The returned proof can be used to verify that a key-value pair exists\n   * in the tree by hashing up from the leaf to the root.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go createExistenceProof (lines 100-113)\n   *\n   * @param key - The key to generate a proof for\n   * @returns ExistenceProof for the key\n   * @throws Error if key doesn't exist (returns proof for adjacent key)\n   */\n  private async createExistenceProof(\n    key: Uint8Array,\n  ): Promise<ExistenceProof> {\n    // Ensure tree is hashed\n    this.hash();\n\n    if (!this.root) {\n      throw new Error(\"cannot create proof for empty tree\");\n    }\n\n    // Get path from root to leaf\n    const {\n      path, node,\n    } = await this.root.pathToLeaf(this.ndb, key);\n\n    // Determine the version to use for the leaf\n    // Use node's version if available, otherwise use tree version + 1\n    const nodeVersion = node.nodeKey?.version ?? (this.version + 1n);\n\n    // Convert to ICS23 format\n    return {\n      key: node.key!,\n      value: node.value!,\n      leaf: convertLeafOp(nodeVersion),\n      path: convertInnerOps(path),\n    };\n  }\n\n  /**\n   * Verify Membership verifies an ICS23 membership proof for a key-value pair.\n   *\n   * Returns true if the proof is valid and proves that the key-value pair exists\n   * in the tree at the committed root hash.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go VerifyMembership (lines 28-36)\n   *\n   * @param proof - The commitment proof to verify\n   * @param key - The key being proven\n   * @returns true if proof is valid, false otherwise\n   */\n  async verifyMembership(\n    proof: CommitmentProof,\n    key: Uint8Array,\n  ): Promise<boolean> {\n    // Get value for key\n    const value = await this.get(key);\n    if (value === null) {\n      return false;\n    }\n\n    // Get root hash\n    const root = this.hash();\n    if (root === null) {\n      return false;\n    }\n\n    // Verify using ics23\n    return verifyMembership(IavlSpec, root, proof, key, value);\n  }\n\n  /**\n   * Verify Non-Membership verifies an ICS23 non-membership proof for a key.\n   *\n   * Returns true if the proof is valid and proves that the key does not exist\n   * in the tree at the committed root hash.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go VerifyNonMembership (lines 92-96)\n   *\n   * @param proof - The commitment proof to verify\n   * @param key - The key being proven absent\n   * @returns true if proof is valid, false otherwise\n   */\n  verifyNonMembership(\n    proof: CommitmentProof,\n    key: Uint8Array,\n  ): boolean {\n    // Get root hash\n    const root = this.hash();\n    if (root === null) {\n      return false;\n    }\n\n    // Verify using ics23\n    return verifyNonMembership(IavlSpec, root, proof, key);\n  }\n\n  /**\n   * Get Proof gets the proof for the given key.\n   * Returns a membership proof if the key exists, or a non-membership proof if it doesn't.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go GetProof (lines 178-192)\n   *\n   * @param key - The key to generate a proof for\n   * @returns CommitmentProof (either membership or non-membership)\n   * @throws Error if root is null\n   */\n  async getProof(key: Uint8Array): Promise<CommitmentProof> {\n    if (this.root === null) {\n      throw new Error(\"cannot generate the proof with nil root\");\n    }\n\n    const exists = await this.has(key);\n\n    if (exists) {\n      return this.getMembershipProof(key);\n    }\n    return this.getNonMembershipProof(key);\n  }\n\n  /**\n   * Verify Proof checks if the proof is correct for the given key.\n   * Automatically determines if it's a membership or non-membership proof and verifies accordingly.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go VerifyProof (lines 195-200)\n   *\n   * @param proof - The proof to verify\n   * @param key - The key the proof is for\n   * @returns True if proof is valid, false otherwise\n   */\n  async verifyProof(\n    proof: CommitmentProof,\n    key: Uint8Array,\n  ): Promise<boolean> {\n    if (proof.exist !== undefined) {\n      return this.verifyMembership(proof, key);\n    }\n    return this.verifyNonMembership(proof, key);\n  }\n\n  /**\n   * Export creates an Exporter for this tree.\n   * Exported nodes can be imported into an empty tree with MutableTree.import().\n   * Nodes are exported depth-first post-order (LRN), this order must be preserved\n   * when importing in order to recreate the same tree structure.\n   *\n   * Based on Go IAVL immutable_tree.go lines 159-161.\n   *\n   * @returns An Exporter that yields nodes in post-order\n   * @throws Error if tree is nil or has no root\n   *\n   * @example\n   * ```typescript\n   * const exporter = tree.export();\n   * for await (const node of exporter) {\n   *   console.log(`Key: ${node.key}, Version: ${node.version}`);\n   * }\n   * ```\n   */\n  export(): Exporter {\n    return new Exporter(this);\n  }\n\n  /**\n   * Create a compressed exporter for this tree. The compressed exporter\n   * applies delta encoding to reduce export size:\n   * - Branch keys are skipped (can be derived during import)\n   * - Leaf keys are delta-encoded compared to previous leaf\n   * - Branch node versions are delta-encoded compared to max version in children\n   *\n   * @returns An async iterable that yields compressed export nodes\n   *\n   * @example\n   * ```typescript\n   * const exporter = tree.exportCompressed();\n   * for await (const node of exporter) {\n   *   // Process compressed node\n   * }\n   * ```\n   */\n  async* exportCompressed(): AsyncIterable<ExportNode> {\n    const {\n      createCompressExporter,\n    } = await import(\"./export/compress.js\");\n    const exporter = this.export();\n    const compressed = createCompressExporter(exporter);\n    for await (const node of compressed) {\n      yield node;\n    }\n  }\n\n  /**\n   * Traverses state changes between a range of versions.\n   * For each version in the range, extracts the changes from the previous version\n   * and calls the callback function with the version number and the ChangeSet.\n   *\n   * This is useful for extracting a stream of changes across multiple versions,\n   * for example to build a changelog or to replicate state changes.\n   *\n   * Based on Go IAVL v1.3.5 immutable_tree.go TraverseStateChanges\n   *\n   * @param startVersion - First version to extract changes for\n   * @param endVersion - Last version to extract changes for\n   * @param fn - Callback function to receive changes for each version\n   * @returns Promise that resolves when traversal is complete\n   *\n   * @example\n   * ```typescript\n   * await tree.traverseStateChanges(1n, 10n, async (version, changeSet) => {\n   *   console.log(`Version ${version}: ${changeSet.pairs.length} changes`);\n   *   // Return true to stop iteration\n   *   return false;\n   * });\n   * ```\n   */\n  async traverseStateChanges(\n    startVersion: bigint,\n    endVersion: bigint,\n    fn: (version: bigint, changeSet: ChangeSet) => Promise<boolean | void>,\n  ): Promise<void> {\n    // Import NodeDB for type checking\n    const {\n      NodeDB,\n    } = await import(\"./storage/node-db.js\");\n\n    if (!(this.ndb instanceof NodeDB)) {\n      throw new Error(\"NodeGetter must be NodeDB to use traverseStateChanges\");\n    }\n\n    return this.ndb.traverseStateChanges(startVersion, endVersion, fn);\n  }\n\n  /**\n   * Returns a string representation of all leaves in the tree for debugging.\n   * Format: \"Tree{key1: value1, key2: value2, ...}\"\n   *\n   * Corresponds to Go's ImmutableTree.String()\n   *\n   * Note: In TypeScript, this must be async because tree traversal requires\n   * database access. This differs from Go where String() is synchronous.\n   *\n   * @returns Promise of string representation showing all key-value pairs\n   */\n  async toString(): Promise<string> {\n    if (this.root === null) {\n      return \"Tree{}\";\n    }\n\n    const leaves: string[] = [];\n    await this.iterate((key: Uint8Array, value: Uint8Array) => {\n      const keyHex = Buffer.from(key).toString(\"hex\");\n      const valueHex = Buffer.from(value).toString(\"hex\");\n      leaves.push(`${keyHex}: ${valueHex}`);\n      return false; // continue iteration\n    });\n\n    return `Tree{${leaves.join(\", \")}}`;\n  }\n\n  /**\n   * Returns a visual representation of the tree structure for debugging.\n   * Each line represents a node, with indentation showing depth.\n   *\n   * Corresponds to Go's ImmutableTree.RenderShape()\n   *\n   * @param indent - String to use for each level of indentation (default: \"  \")\n   * @param encoder - Optional custom encoder function for node IDs\n   * @returns Array of strings representing the tree structure\n   */\n  async renderShape(\n    indent = \"  \",\n    encoder?: (id: Uint8Array, depth: number, isLeaf: boolean) => string,\n  ): Promise<string[]> {\n    const defaultEncoder = (id: Uint8Array, _depth: number, isLeaf: boolean): string => {\n      const prefix = isLeaf ? \"* \" : \"- \";\n      if (id.length === 0) {\n        return `${prefix}<nil>`;\n      }\n      return `${prefix}${Buffer.from(id).toString(\"hex\").toUpperCase()}`;\n    };\n\n    const nodeEncoder = encoder ?? defaultEncoder;\n    return await this.renderNode(this.root, indent, 0, nodeEncoder);\n  }\n\n  /**\n   * Recursively renders a node and its children.\n   * Helper for renderShape().\n   *\n   * @param node - Node to render\n   * @param indent - Indentation string\n   * @param depth - Current depth in tree\n   * @param encoder - Function to encode node IDs\n   * @returns Array of strings for this node and its subtree\n   */\n  private async renderNode(\n    node: Node | null,\n    indent: string,\n    depth: number,\n    encoder: (id: Uint8Array, depth: number, isLeaf: boolean) => string,\n  ): Promise<string[]> {\n    const prefix = indent.repeat(depth);\n\n    // Handle nil node\n    if (node === null) {\n      return [`${prefix}<nil>`];\n    }\n\n    // Handle leaf node\n    if (node.isLeaf()) {\n      const here = `${prefix}${encoder(node.key!, depth, true)}`;\n      return [here];\n    }\n\n    // Handle inner node\n    const nodeHash = node.hash ?? new Uint8Array(0);\n    const here = `${prefix}${encoder(nodeHash, depth, false)}`;\n\n    // Get child nodes\n    const rightNode = node.rightNodeKey\n      ? await this.ndb.getNode(node.rightNodeKey)\n      : null;\n    const leftNode = node.leftNodeKey\n      ? await this.ndb.getNode(node.leftNodeKey)\n      : null;\n\n    // Recursively render children\n    const right = await this.renderNode(rightNode, indent, depth + 1, encoder);\n    const result = await this.renderNode(leftNode, indent, depth + 1, encoder);\n\n    // Build result: left subtree, current node, right subtree\n    result.push(here);\n    result.push(...right);\n\n    return result;\n  }\n}\n"],"mappings":";;;;;;;;;;;AAgDA,IAAa,gBAAb,MAAa,cAAc;;CAEzB,AAAS;;CAGT,AAAS;;CAGT,AAAS;;CAGT,AAAS;;CAGT,AAAS;;;;;;;;;;CAWT,YACE,MACA,KAC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