{"version":3,"file":"node.cjs","names":["hash","encodeVarint","parts: Uint8Array[]","NodeKeyClass","decodeVarint","decodeVarintBigInt","decodeBytes","path: ProofInnerNode[]","ProofInnerNode","encodeUvarint"],"sources":["../src/node.ts"],"sourcesContent":["/**\n * Node represents a node in the IAVL tree.\n * Based on the Go iavl node.go implementation.\n *\n * A node can be either:\n * - Leaf node: has key and value, subtreeHeight = 0\n * - Branch node: has left and right children, subtreeHeight > 0\n */\n\nimport type {\n  NodeKey,\n} from \"./node-key.js\";\nimport {\n  NodeKey as NodeKeyClass,\n} from \"./node-key.js\";\nimport {\n  ProofInnerNode,\n} from \"./proof/types.js\";\nimport {\n  decodeBytes,\n  decodeVarint,\n  decodeVarintBigInt,\n  encodeUvarint,\n  encodeVarint,\n} from \"./utils/encoding.js\";\nimport {\n  hash,\n} from \"./utils/hash.js\";\n\n/**\n * Mode constants for node encoding/decoding.\n * These flags indicate whether child node keys are in legacy format (hash-based)\n * or v1 format (NodeKey-based).\n */\nconst MODE_LEGACY_LEFT_NODE = 0x01;\nconst MODE_LEGACY_RIGHT_NODE = 0x02;\n\n/**\n * Hash size in bytes (SHA-256).\n */\nconst HASH_SIZE = 32;\n\n/**\n * Interface for loading nodes from storage.\n * This allows traversal methods to work without depending on the full tree implementation.\n */\nexport interface NodeGetter {\n  /**\n   * Gets a node by its key (12 bytes for v1, 32 bytes for legacy).\n   * @param nodeKey - The node's database key\n   * @returns The node, or null if not found\n   */\n  getNode(nodeKey: Uint8Array): Promise<Node | null>\n}\n\n/**\n * Node represents a node in the IAVL tree.\n *\n * Leaf nodes:\n * - Have key and value\n * - Have subtreeHeight = 0\n * - Have size = 1\n * - Do not have children\n *\n * Branch nodes:\n * - Have key (from leftmost descendant)\n * - Have left and right children (references or pointers)\n * - Have subtreeHeight > 0\n * - Have size = sum of children sizes\n */\nexport class Node {\n  /** Key for leaf nodes, leftmost descendant key for branch nodes */\n  key: Uint8Array | null = null;\n\n  /** Value for leaf nodes only */\n  value: Uint8Array | null = null;\n\n  /** Cached hash of the node, computed lazily */\n  hash: Uint8Array | null = null;\n\n  /** NodeKey (version + nonce) for this node in the database */\n  nodeKey: NodeKey | null = null;\n\n  /**\n   * Left child node key (12 bytes) or legacy hash (32 bytes)\n   * For v1: 12-byte NodeKey\n   * For legacy: 32-byte hash\n   */\n  leftNodeKey: Uint8Array | null = null;\n\n  /**\n   * Right child node key (12 bytes) or legacy hash (32 bytes)\n   * For v1: 12-byte NodeKey\n   * For legacy: 32-byte hash\n   */\n  rightNodeKey: Uint8Array | null = null;\n\n  /** Cached left child node */\n  leftNode: Node | null = null;\n\n  /** Cached right child node */\n  rightNode: Node | null = null;\n\n  /** Height of the subtree rooted at this node (0 for leaves) */\n  subtreeHeight: number = 0;\n\n  /** Number of nodes in the subtree rooted at this node (1 for leaves) */\n  size: bigint = 1n;\n\n  /**\n   * Whether this node uses legacy format (hash-based child references)\n   * Legacy nodes use 32-byte hashes instead of 12-byte NodeKeys\n   */\n  isLegacy: boolean = false;\n\n  /**\n   * Creates a new leaf node with the given key and value.\n   *\n   * @param key - The key for this leaf node\n   * @param value - The value for this leaf node\n   * @returns A new leaf node\n   */\n  static newLeafNode(key: Uint8Array, value: Uint8Array): Node {\n    const node = new Node();\n    node.key = key;\n    node.value = value;\n    node.subtreeHeight = 0;\n    node.size = 1n;\n    return node;\n  }\n\n  /**\n   * Creates a new branch node with the given children.\n   *\n   * @param left - The left child node\n   * @param right - The right child node\n   * @returns A new branch node\n   */\n  static newBranchNode(left: Node, right: Node): Node {\n    const node = new Node();\n\n    // Key is the smallest key in the right subtree\n    // This allows search logic: if key < node.key, go left; otherwise go right\n    node.key = right.key;\n\n    // Set children\n    node.leftNode = left;\n    node.rightNode = right;\n\n    // Height is 1 + max(left.height, right.height)\n    node.subtreeHeight = 1 + Math.max(left.subtreeHeight, right.subtreeHeight);\n\n    // Size is sum of children\n    node.size = left.size + right.size;\n\n    return node;\n  }\n\n  /**\n   * Checks if this node is a leaf node.\n   * A leaf node has subtreeHeight = 0.\n   *\n   * @returns true if this is a leaf node, false otherwise\n   */\n  isLeaf(): boolean {\n    return this.subtreeHeight === 0;\n  }\n\n  /**\n   * Gets the key of this node.\n   * For legacy nodes, returns the hash.\n   * For v1 nodes, returns the NodeKey bytes.\n   *\n   * @returns The node's key as a byte array\n   */\n  getNodeKey(): Uint8Array {\n    if (this.isLegacy) {\n      if (!this.hash) {\n        throw new Error(\"Legacy node must have hash\");\n      }\n      return this.hash;\n    }\n\n    if (!this.nodeKey) {\n      throw new Error(\"Node must have nodeKey\");\n    }\n\n    return this.nodeKey.toBytes();\n  }\n\n  /**\n   * Gets the balance factor of this node.\n   * Balance factor = left.height - right.height\n   *\n   * @returns The balance factor (-2 to +2 for balanced tree)\n   */\n  getBalanceFactor(): number {\n    const leftHeight = this.leftNode?.subtreeHeight ?? -1;\n    const rightHeight = this.rightNode?.subtreeHeight ?? -1;\n    return leftHeight - rightHeight;\n  }\n\n  /**\n   * Recalculates and updates the height and size of this node based on its children.\n   * This should be called after any modification to child nodes.\n   *\n   * IMPORTANT: This method loads children from storage if needed.\n   * For performance, prefer to call this only after structural changes.\n   *\n   * @param getter - NodeGetter for loading child nodes from storage if needed\n   */\n  async calcHeightAndSize(getter: NodeGetter): Promise<void> {\n    // Load children from storage if needed\n    const leftNode = await this.getLeftNode(getter);\n    const rightNode = await this.getRightNode(getter);\n\n    // Calculate height: max of children + 1\n    const leftHeight = leftNode?.subtreeHeight ?? -1;\n    const rightHeight = rightNode?.subtreeHeight ?? -1;\n    this.subtreeHeight = Math.max(leftHeight, rightHeight) + 1;\n\n    // Calculate size: sum of children\n    const leftSize = leftNode?.size ?? 0n;\n    const rightSize = rightNode?.size ?? 0n;\n    this.size = leftSize + rightSize;\n  }\n\n  /**\n   * Validates the node structure.\n   * Checks for common invariant violations.\n   *\n   * @returns Error message if invalid, null if valid\n   */\n  validate(): string | null {\n    if (this.key === null) {\n      return \"key cannot be null\";\n    }\n\n    if (this.nodeKey === null && !this.isLegacy) {\n      return \"nodeKey cannot be null for non-legacy nodes\";\n    }\n\n    if (this.nodeKey && this.nodeKey.version <= 0n) {\n      return \"version must be greater than 0\";\n    }\n\n    if (this.subtreeHeight < 0) {\n      return \"height cannot be less than 0\";\n    }\n\n    if (this.size <= 0n) {\n      return \"size must be greater than 0\";\n    }\n\n    // Leaf node validation\n    if (this.isLeaf()) {\n      if (this.value === null) {\n        return \"leaf node must have a value\";\n      }\n\n      if (this.size !== 1n) {\n        return \"leaf node must have size = 1\";\n      }\n\n      if (this.leftNode !== null || this.rightNode !== null) {\n        return \"leaf node cannot have children\";\n      }\n\n      if (this.leftNodeKey !== null || this.rightNodeKey !== null) {\n        return \"leaf node cannot have child keys\";\n      }\n    }\n    else {\n      // Branch node validation\n      if (this.value !== null) {\n        return \"branch node cannot have a value\";\n      }\n\n      // Must have child keys (either loaded children or keys)\n      const hasLeftRef = this.leftNode !== null || this.leftNodeKey !== null;\n      const hasRightRef = this.rightNode !== null || this.rightNodeKey !== null;\n\n      if (!hasLeftRef) {\n        return \"branch node must have left child reference\";\n      }\n\n      if (!hasRightRef) {\n        return \"branch node must have right child reference\";\n      }\n\n      // If children are loaded, validate height and size\n      if (this.leftNode && this.rightNode) {\n        const expectedHeight = 1 + Math.max(\n          this.leftNode.subtreeHeight,\n          this.rightNode.subtreeHeight,\n        );\n\n        if (this.subtreeHeight !== expectedHeight) {\n          return `invalid height: expected ${expectedHeight}, got ${this.subtreeHeight}`;\n        }\n\n        const expectedSize = this.leftNode.size + this.rightNode.size;\n        if (this.size !== expectedSize) {\n          return `invalid size: expected ${expectedSize}, got ${this.size}`;\n        }\n      }\n    }\n\n    return null;\n  }\n\n  /**\n   * Returns a string representation of the node.\n   * Useful for debugging.\n   *\n   * @returns String representation\n   */\n  toString(): string {\n    const keyStr = this.key ? `key=${this.key.length}B` : \"key=null\";\n    const valueStr = this.value ? `value=${this.value.length}B` : \"value=null\";\n    const typeStr = this.isLeaf() ? \"LEAF\" : \"BRANCH\";\n    const heightStr = `h=${this.subtreeHeight}`;\n    const sizeStr = `s=${this.size}`;\n    const nodeKeyStr = this.nodeKey ? this.nodeKey.toString() : \"nk=null\";\n\n    return `Node[${typeStr} ${keyStr} ${valueStr} ${heightStr} ${sizeStr} ${nodeKeyStr}]`;\n  }\n\n  /**\n   * Computes and caches the hash of this node.\n   * The hash is computed based on the node type:\n   * - For leaves: SHA256(height || size || version || key || valueHash)\n   * - For branches: SHA256(height || size || version || leftHash || rightHash)\n   *\n   * @param version - The version to use for hash computation\n   * @returns The 32-byte hash of this node\n   */\n  computeHash(version: bigint): Uint8Array {\n    // Return cached hash if available\n    if (this.hash !== null) {\n      return this.hash;\n    }\n\n    // Build the hash input\n    const hashInput = this._buildHashInput(version);\n\n    // Compute hash and cache it\n    this.hash = hash(hashInput);\n    return this.hash;\n  }\n\n  /**\n   * Recursively computes and caches hashes for this node and all descendants.\n   * This is used when computing the working hash of a tree that has unsaved nodes.\n   * Corresponds to Go's hashWithCount method.\n   *\n   * @param version - Version to use for hash computation\n   * @returns The computed hash\n   */\n  computeHashWithDescendants(version: bigint): Uint8Array {\n    // Return cached hash if available\n    if (this.hash !== null) {\n      return this.hash;\n    }\n\n    // For branch nodes, recursively hash children first\n    if (!this.isLeaf()) {\n      if (this.leftNode) {\n        this.leftNode.computeHashWithDescendants(\n          this.leftNode.nodeKey?.version ?? version,\n        );\n      }\n      if (this.rightNode) {\n        this.rightNode.computeHashWithDescendants(\n          this.rightNode.nodeKey?.version ?? version,\n        );\n      }\n    }\n\n    // Now compute this node's hash\n    return this.computeHash(version);\n  }\n\n  /**\n   * Builds the byte array to be hashed for this node.\n   * This is the internal implementation that constructs the hash input.\n   *\n   * @param version - The version to use for hash computation\n   * @returns The byte array to be hashed\n   * @private\n   */\n  private _buildHashInput(version: bigint): Uint8Array {\n    // Encode height, size, and version as varints\n    const heightBytes = encodeVarint(this.subtreeHeight);\n    const sizeBytes = encodeVarint(this.size);\n    const versionBytes = encodeVarint(version);\n\n    if (this.isLeaf()) {\n      // Leaf node: encode key and value hash\n      if (!this.key) {\n        throw new Error(\"Leaf node must have key\");\n      }\n      if (!this.value) {\n        throw new Error(\"Leaf node must have value\");\n      }\n\n      // Encode key with length prefix\n      const keyBytes = encodeBytes(this.key);\n\n      // Hash the value and encode the hash\n      const valueHash = hash(this.value);\n      const valueHashBytes = encode32BytesHash(valueHash);\n\n      // Concatenate all parts\n      const totalLength = heightBytes.length + sizeBytes.length + versionBytes.length\n        + keyBytes.length + valueHashBytes.length;\n      const result = new Uint8Array(totalLength);\n\n      let offset = 0;\n      result.set(heightBytes, offset);\n      offset += heightBytes.length;\n      result.set(sizeBytes, offset);\n      offset += sizeBytes.length;\n      result.set(versionBytes, offset);\n      offset += versionBytes.length;\n      result.set(keyBytes, offset);\n      offset += keyBytes.length;\n      result.set(valueHashBytes, offset);\n\n      return result;\n    }\n    else {\n      // Branch node: encode left and right child hashes\n      if (!this.leftNode || !this.rightNode) {\n        throw new Error(\"Branch node must have both children loaded for hashing\");\n      }\n\n      // Ensure child hashes are computed\n      // If child is persisted (has nodeKey), compute its hash with its own version\n      if (!this.leftNode.hash) {\n        if (this.leftNode.nodeKey !== null) {\n          this.leftNode.computeHash(this.leftNode.nodeKey.version);\n        }\n        else {\n          throw new Error(\"Left child hash must be computed before parent\");\n        }\n      }\n      if (!this.rightNode.hash) {\n        if (this.rightNode.nodeKey !== null) {\n          this.rightNode.computeHash(this.rightNode.nodeKey.version);\n        }\n        else {\n          throw new Error(\"Right child hash must be computed before parent\");\n        }\n      }\n\n      // Encode child hashes\n      // At this point, hashes are guaranteed to be non-null (computed above)\n      const leftHashBytes = encode32BytesHash(this.leftNode.hash!);\n      const rightHashBytes = encode32BytesHash(this.rightNode.hash!);\n\n      // Concatenate all parts\n      const totalLength = heightBytes.length + sizeBytes.length + versionBytes.length\n        + leftHashBytes.length + rightHashBytes.length;\n      const result = new Uint8Array(totalLength);\n\n      let offset = 0;\n      result.set(heightBytes, offset);\n      offset += heightBytes.length;\n      result.set(sizeBytes, offset);\n      offset += sizeBytes.length;\n      result.set(versionBytes, offset);\n      offset += versionBytes.length;\n      result.set(leftHashBytes, offset);\n      offset += leftHashBytes.length;\n      result.set(rightHashBytes, offset);\n\n      return result;\n    }\n  }\n\n  /**\n   * Serializes this node to bytes.\n   * The format depends on whether this is a leaf or branch node.\n   *\n   * Leaf format:\n   *   height (varint) || size (varint) || key (length-prefixed) || value (length-prefixed)\n   *\n   * Branch format:\n   *   height (varint) || size (varint) || key (length-prefixed) || hash (33 bytes) ||\n   *   mode (varint) || leftNodeKey || rightNodeKey\n   *\n   * @returns Serialized bytes\n   */\n  toBytes(): Uint8Array {\n    // Calculate required buffer size\n    const parts: Uint8Array[] = [];\n\n    // Encode height\n    parts.push(encodeVarint(this.subtreeHeight));\n\n    // Encode size\n    parts.push(encodeVarint(this.size));\n\n    // Encode key\n    if (!this.key) {\n      throw new Error(\"Node must have key for serialization\");\n    }\n    parts.push(encodeBytes(this.key));\n\n    if (this.isLeaf()) {\n      // Leaf node: encode value\n      if (!this.value) {\n        throw new Error(\"Leaf node must have value for serialization\");\n      }\n      parts.push(encodeBytes(this.value));\n    }\n    else {\n      // Branch node: encode hash and child keys\n      if (!this.hash) {\n        throw new Error(\"Branch node must have hash for serialization\");\n      }\n      parts.push(encode32BytesHash(this.hash));\n\n      // Determine mode based on child key formats\n      if (!this.leftNodeKey) {\n        throw new Error(\"Branch node must have leftNodeKey for serialization\");\n      }\n      if (!this.rightNodeKey) {\n        throw new Error(\"Branch node must have rightNodeKey for serialization\");\n      }\n\n      let mode = 0;\n      if (this.leftNodeKey.length === HASH_SIZE) {\n        mode |= MODE_LEGACY_LEFT_NODE;\n      }\n      if (this.rightNodeKey.length === HASH_SIZE) {\n        mode |= MODE_LEGACY_RIGHT_NODE;\n      }\n\n      parts.push(encodeVarint(mode));\n\n      // Encode left child key\n      if (mode & MODE_LEGACY_LEFT_NODE) {\n        // Legacy: 32-byte hash\n        parts.push(encode32BytesHash(this.leftNodeKey));\n      }\n      else {\n        // V1: version + nonce varints\n        const leftNodeKey = NodeKeyClass.fromBytes(this.leftNodeKey);\n        parts.push(encodeVarint(leftNodeKey.version));\n        parts.push(encodeVarint(leftNodeKey.nonce));\n      }\n\n      // Encode right child key\n      if (mode & MODE_LEGACY_RIGHT_NODE) {\n        // Legacy: 32-byte hash\n        parts.push(encode32BytesHash(this.rightNodeKey));\n      }\n      else {\n        // V1: version + nonce varints\n        const rightNodeKey = NodeKeyClass.fromBytes(this.rightNodeKey);\n        parts.push(encodeVarint(rightNodeKey.version));\n        parts.push(encodeVarint(rightNodeKey.nonce));\n      }\n    }\n\n    // Concatenate all parts\n    const totalLength = parts.reduce((sum, part) => sum + part.length, 0);\n    const result = new Uint8Array(totalLength);\n    let offset = 0;\n    for (const part of parts) {\n      result.set(part, offset);\n      offset += part.length;\n    }\n\n    return result;\n  }\n\n  /**\n   * Deserializes a node from bytes.\n   * The nodeKey parameter identifies this node in the database.\n   *\n   * @param nodeKey - The NodeKey bytes (12 bytes for v1, 32 bytes for legacy)\n   * @param bytes - Serialized node bytes\n   * @returns Deserialized node\n   */\n  static fromBytes(nodeKey: Uint8Array, bytes: Uint8Array): Node {\n    let offset = 0;\n\n    // Decode height\n    const heightResult = decodeVarint(bytes, offset);\n    const height = heightResult.value;\n    if (height < -128 || height > 127) {\n      throw new Error(`Invalid height: ${height} (must fit in int8)`);\n    }\n    offset += heightResult.bytesRead;\n\n    // Decode size\n    const sizeResult = decodeVarintBigInt(bytes, offset);\n    const size = sizeResult.value;\n    offset += sizeResult.bytesRead;\n\n    // Decode key\n    const keyResult = decodeBytes(bytes, offset);\n    const key = keyResult.bytes;\n    offset += keyResult.bytesRead;\n\n    // Determine if this is a legacy node\n    const isLegacy = nodeKey.length === HASH_SIZE;\n\n    // Create node with basic fields\n    const node = new Node();\n    node.subtreeHeight = height;\n    node.size = size;\n    node.key = key;\n    node.isLegacy = isLegacy;\n\n    if (isLegacy) {\n      node.hash = nodeKey;\n    }\n    else {\n      node.nodeKey = NodeKeyClass.fromBytes(nodeKey);\n    }\n\n    // Decode node body\n    if (height === 0) {\n      // Leaf node: decode value\n      const valueResult = decodeBytes(bytes, offset);\n      node.value = valueResult.bytes;\n      offset += valueResult.bytesRead;\n\n      // Compute hash for leaf nodes\n      if (!isLegacy && node.nodeKey) {\n        node.computeHash(node.nodeKey.version);\n      }\n    }\n    else {\n      // Branch node: decode hash and children\n      const hashResult = decodeBytes(bytes, offset);\n      node.hash = hashResult.bytes;\n      offset += hashResult.bytesRead;\n\n      // Decode mode\n      const modeResult = decodeVarint(bytes, offset);\n      const mode = modeResult.value;\n\n      // Validate mode before using it\n      if (mode < 0 || mode > 3) {\n        throw new Error(`Invalid mode: ${mode}`);\n      }\n\n      offset += modeResult.bytesRead;\n\n      // Decode left child key\n      if (mode & MODE_LEGACY_LEFT_NODE) {\n        // Legacy: 32-byte hash\n        const leftHashResult = decodeBytes(bytes, offset);\n        node.leftNodeKey = leftHashResult.bytes;\n        offset += leftHashResult.bytesRead;\n      }\n      else {\n        // V1: version + nonce varints\n        const leftVersionResult = decodeVarintBigInt(bytes, offset);\n        offset += leftVersionResult.bytesRead;\n\n        const leftNonceResult = decodeVarint(bytes, offset);\n        const leftNonce = leftNonceResult.value;\n        if (leftNonce < 0 || leftNonce > 0xFFFFFFFF) {\n          throw new Error(`Invalid left nonce: ${leftNonce}`);\n        }\n        offset += leftNonceResult.bytesRead;\n\n        const leftNodeKey = new NodeKeyClass(leftVersionResult.value, leftNonce);\n        node.leftNodeKey = leftNodeKey.toBytes();\n      }\n\n      // Decode right child key\n      if (mode & MODE_LEGACY_RIGHT_NODE) {\n        // Legacy: 32-byte hash\n        const rightHashResult = decodeBytes(bytes, offset);\n        node.rightNodeKey = rightHashResult.bytes;\n        offset += rightHashResult.bytesRead;\n      }\n      else {\n        // V1: version + nonce varints\n        const rightVersionResult = decodeVarintBigInt(bytes, offset);\n        offset += rightVersionResult.bytesRead;\n\n        const rightNonceResult = decodeVarint(bytes, offset);\n        const rightNonce = rightNonceResult.value;\n        if (rightNonce < 0 || rightNonce > 0xFFFFFFFF) {\n          throw new Error(`Invalid right nonce: ${rightNonce}`);\n        }\n        offset += rightNonceResult.bytesRead;\n\n        const rightNodeKey = new NodeKeyClass(rightVersionResult.value, rightNonce);\n        node.rightNodeKey = rightNodeKey.toBytes();\n      }\n    }\n\n    return node;\n  }\n\n  /**\n   * Gets the left child node, loading it from storage if needed.\n   * @param getter - NodeGetter for loading nodes from storage\n   * @returns The left child node, or null if not found\n   */\n  async getLeftNode(getter: NodeGetter): Promise<Node | null> {\n    // Return cached node if available\n    if (this.leftNode !== null) {\n      return this.leftNode;\n    }\n\n    // Load from storage if we have a key\n    if (this.leftNodeKey !== null) {\n      return await getter.getNode(this.leftNodeKey);\n    }\n\n    return null;\n  }\n\n  /**\n   * Gets the right child node, loading it from storage if needed.\n   * @param getter - NodeGetter for loading nodes from storage\n   * @returns The right child node, or null if not found\n   */\n  async getRightNode(getter: NodeGetter): Promise<Node | null> {\n    // Return cached node if available\n    if (this.rightNode !== null) {\n      return this.rightNode;\n    }\n\n    // Load from storage if we have a key\n    if (this.rightNodeKey !== null) {\n      return await getter.getNode(this.rightNodeKey);\n    }\n\n    return null;\n  }\n\n  /**\n   * Creates a clone of this node for copy-on-write operations.\n   * Leaf nodes cannot be cloned (throw error).\n   * Branch nodes are cloned with children loaded from storage if needed.\n   *\n   * IMPORTANT: In JavaScript, we must be careful with reference semantics:\n   * - Primitive fields (subtreeHeight, size) are copied by value\n   * - Object references (key, leftNodeKey, rightNodeKey, leftNode, rightNode) are copied by reference\n   * - The clone shares references to child nodes (copy-on-write semantics)\n   * - hash and nodeKey are set to null (will be recomputed/assigned)\n   *\n   * @param getter - NodeGetter for loading child nodes from storage\n   * @returns A new cloned Node instance\n   * @throws Error if called on a leaf node\n   */\n  async clone(getter: NodeGetter): Promise<Node> {\n    // Leaf nodes cannot be cloned\n    if (this.isLeaf()) {\n      throw new Error(\"Cannot clone leaf node\");\n    }\n\n    // Ensure children are loaded from storage if needed\n    // NOTE: In Go, this clears the cached children in the original node\n    // In TypeScript, we just load them but don't clear (no side effects on original)\n    let leftNode = this.leftNode;\n    let rightNode = this.rightNode;\n\n    if (this.nodeKey !== null) {\n      // Node has been persisted, need to load children\n      leftNode = await this.getLeftNode(getter);\n      rightNode = await this.getRightNode(getter);\n    }\n\n    // Create new node with same structure but cleared hash/nodeKey\n    // NOTE: This shares references to child nodes (copy-on-write)\n    const cloned = new Node();\n\n    // Copy fields\n    cloned.key = this.key; // Reference to same Uint8Array (shared)\n    cloned.value = null; // Branch nodes have no value\n    cloned.subtreeHeight = this.subtreeHeight;\n    cloned.size = this.size;\n    cloned.leftNodeKey = this.leftNodeKey; // Reference to same Uint8Array (shared)\n    cloned.rightNodeKey = this.rightNodeKey; // Reference to same Uint8Array (shared)\n    cloned.leftNode = leftNode; // Reference to same Node (shared)\n    cloned.rightNode = rightNode; // Reference to same Node (shared)\n\n    // Clear hash and nodeKey - these will be recomputed/assigned\n    cloned.hash = null;\n    cloned.nodeKey = null;\n\n    return cloned;\n  }\n\n  /**\n   * Searches for a key in the subtree rooted at this node.\n   * Returns the index and value if found.\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param key - The key to search for\n   * @returns Object with index (position in tree), value (if found), and error\n   */\n  async get(getter: NodeGetter, key: Uint8Array): Promise<{\n    index: bigint\n    value: Uint8Array | null\n  }> {\n    if (this.isLeaf()) {\n      if (!this.key) {\n        throw new Error(\"Leaf node must have key\");\n      }\n\n      // Compare keys\n      const cmp = compareBytes(key, this.key);\n      if (cmp < 0) {\n        // Key is less than this node's key\n        return {\n          index: 0n,\n          value: null,\n        };\n      }\n      else if (cmp > 0) {\n        // Key is greater than this node's key\n        return {\n          index: 1n,\n          value: null,\n        };\n      }\n      else {\n        // Found the key\n        return {\n          index: 0n,\n          value: this.value,\n        };\n      }\n    }\n\n    // Branch node: recursively search children\n    if (!this.key) {\n      throw new Error(\"Branch node must have key\");\n    }\n\n    // Go implementation (node.go lines 375-395):\n    // If key < node.key: search left subtree, return immediately\n    // Otherwise: search right subtree, adjust index\n    if (compareBytes(key, this.key) < 0) {\n      // Key is in left subtree\n      const leftNode = await this.getLeftNode(getter);\n      if (!leftNode) {\n        throw new Error(\"Failed to load left child node\");\n      }\n\n      return await leftNode.get(getter, key);\n    }\n\n    // Key is in right subtree (>= node.key)\n    const rightNode = await this.getRightNode(getter);\n    if (!rightNode) {\n      throw new Error(\"Failed to load right child node\");\n    }\n\n    const result = await rightNode.get(getter, key);\n\n    // Adjust index to account for left subtree\n    result.index += this.size - rightNode.size;\n\n    return result;\n  }\n\n  /**\n   * Gets the key-value pair at the specified index (0-based).\n   * Index represents the position in an in-order traversal.\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param index - The index to retrieve (0-based)\n   * @returns Object with key and value, or null if index out of bounds\n   */\n  async getByIndex(getter: NodeGetter, index: bigint): Promise<{\n    key: Uint8Array | null\n    value: Uint8Array | null\n  }> {\n    if (this.isLeaf()) {\n      if (index === 0n) {\n        return {\n          key: this.key,\n          value: this.value,\n        };\n      }\n      return {\n        key: null,\n        value: null,\n      };\n    }\n\n    // Branch node: find which subtree contains the index\n    const leftNode = await this.getLeftNode(getter);\n    if (!leftNode) {\n      throw new Error(\"Failed to load left child node\");\n    }\n\n    if (index < leftNode.size) {\n      // Index is in left subtree\n      return await leftNode.getByIndex(getter, index);\n    }\n\n    // Index is in right subtree\n    const rightNode = await this.getRightNode(getter);\n    if (!rightNode) {\n      throw new Error(\"Failed to load right child node\");\n    }\n\n    return await rightNode.getByIndex(getter, index - leftNode.size);\n  }\n\n  /**\n   * Traverses the subtree in order, calling the callback for each node.\n   * Traversal continues until the callback returns true (stop) or all nodes visited.\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param ascending - If true, traverse in ascending order; otherwise descending\n   * @param callback - Function called for each node; return true to stop\n   * @returns True if traversal was stopped by callback, false if completed\n   */\n  async traverse(\n    getter: NodeGetter,\n    ascending: boolean,\n    callback: (node: Node) => boolean,\n  ): Promise<boolean> {\n    return await this.traverseInRange(\n      getter,\n      null,\n      null,\n      ascending,\n      false,\n      false, // pre-order (normal in-order traversal)\n      callback,\n    );\n  }\n\n  /**\n   * Traverses the entire tree in post-order (LRN: left, right, node).\n   * Post-order traversal visits children before parents, which is required for export.\n   * Based on Go IAVL node.go lines 725-729.\n   *\n   * @param getter - NodeGetter for loading child nodes\n   * @param ascending - If true, traverse in ascending order; otherwise descending\n   * @param callback - Function called for each node; return true to stop\n   * @returns True if traversal was stopped by callback, false if completed\n   */\n  async traversePost(\n    getter: NodeGetter,\n    ascending: boolean,\n    callback: (node: Node) => boolean,\n  ): Promise<boolean> {\n    return await this.traverseInRange(\n      getter,\n      null,\n      null,\n      ascending,\n      false,\n      true, // post-order traversal\n      callback,\n    );\n  }\n\n  /**\n   * Traverses nodes within a key range, calling the callback for each node.\n   * Supports both ascending and descending order.\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param start - Start key (inclusive if inclusive=true), or null for no lower bound\n   * @param end - End key (inclusive if inclusive=true), or null for no upper bound\n   * @param ascending - If true, traverse in ascending order; otherwise descending\n   * @param inclusive - If true, include start and end keys; otherwise exclusive\n   * @param callback - Function called for each node; return true to stop\n   * @returns True if traversal was stopped by callback, false if completed\n   */\n  async traverseInRange(\n    getter: NodeGetter,\n    start: Uint8Array | null,\n    end: Uint8Array | null,\n    ascending: boolean,\n    inclusive: boolean,\n    post: boolean,\n    callback: (node: Node) => boolean,\n  ): Promise<boolean> {\n    if (this.isLeaf()) {\n      if (!this.key) {\n        throw new Error(\"Leaf node must have key\");\n      }\n\n      // Check if this leaf is in range\n      if (start !== null) {\n        const cmp = compareBytes(this.key, start);\n        if (cmp < 0 || (!inclusive && cmp === 0)) {\n          return false; // Key is before range\n        }\n      }\n\n      if (end !== null) {\n        const cmp = compareBytes(this.key, end);\n        if (cmp > 0 || (!inclusive && cmp === 0)) {\n          return false; // Key is after range\n        }\n      }\n\n      // Key is in range, call callback\n      return callback(this);\n    }\n\n    // Branch node: recursively traverse children\n    if (!this.key) {\n      throw new Error(\"Branch node must have key\");\n    }\n\n    if (ascending) {\n      // Ascending: left, then right\n      // Always traverse left subtree (it may contain nodes in range)\n      const leftNode = await this.getLeftNode(getter);\n      if (leftNode) {\n        const stop = await leftNode.traverseInRange(\n          getter,\n          start,\n          end,\n          ascending,\n          inclusive,\n          post,\n          callback,\n        );\n        if (stop) return true;\n      }\n\n      // Always traverse right subtree (it may contain nodes in range)\n      const rightNode = await this.getRightNode(getter);\n      if (rightNode) {\n        const stop = await rightNode.traverseInRange(\n          getter,\n          start,\n          end,\n          ascending,\n          inclusive,\n          post,\n          callback,\n        );\n        if (stop) return true;\n      }\n\n      // Post-order: visit node after children (for export)\n      // Pre-order: node is visited implicitly by callback in leaves only\n      if (post) {\n        // In post-order, also visit branch nodes after their children\n        return callback(this);\n      }\n    }\n    else {\n      // Descending: right, then left\n      // Always traverse right subtree (it may contain nodes in range)\n      const rightNode = await this.getRightNode(getter);\n      if (rightNode) {\n        const stop = await rightNode.traverseInRange(\n          getter,\n          start,\n          end,\n          ascending,\n          inclusive,\n          post,\n          callback,\n        );\n        if (stop) return true;\n      }\n\n      // Always traverse left subtree (it may contain nodes in range)\n      const leftNode = await this.getLeftNode(getter);\n      if (leftNode) {\n        const stop = await leftNode.traverseInRange(\n          getter,\n          start,\n          end,\n          ascending,\n          inclusive,\n          post,\n          callback,\n        );\n        if (stop) return true;\n      }\n\n      // Post-order: visit node after children\n      if (post) {\n        return callback(this);\n      }\n    }\n\n    return false;\n  }\n\n  /**\n   * PathToLeaf generates a proof path from this node to the leaf containing the given key.\n   *\n   * If the key does not exist, returns the path to the next leaf left of the key,\n   * except when the key is less than the least item, in which case it returns\n   * a path to the least item.\n   *\n   * The path is ordered ROOT to LEAF, where path[0] is the topmost node and\n   * path[path.length-1] is the leaf's parent.\n   *\n   * Based on Go IAVL v1.3.5 proof.go PathToLeaf (lines 169-173)\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param key - The key to search for\n   * @returns Object containing the path and the leaf node found\n   * @throws Error if there's an issue loading nodes from storage\n   */\n  async pathToLeaf(\n    getter: NodeGetter,\n    key: Uint8Array,\n  ): Promise<{\n    path: ProofInnerNode[]\n    node: Node\n  }> {\n    const path: ProofInnerNode[] = [];\n    const node = await this._pathToLeaf(getter, key, path);\n    return {\n      path,\n      node,\n    };\n  }\n\n  /**\n   * _pathToLeaf is a helper which recursively constructs the PathToLeaf.\n   * As an optimization, the already constructed path is passed in as an argument\n   * and is shared among recursive calls.\n   *\n   * Based on Go IAVL v1.3.5 proof.go pathToLeaf (lines 178-239)\n   *\n   * @param getter - NodeGetter for loading nodes from storage\n   * @param key - The key to search for\n   * @param path - The path being constructed (mutated in place)\n   * @returns The leaf node found\n   * @throws Error if there's an issue loading nodes from storage\n   */\n  private async _pathToLeaf(\n    getter: NodeGetter,\n    key: Uint8Array,\n    path: ProofInnerNode[],\n  ): Promise<Node> {\n    // Base case: we've reached a leaf\n    if (this.subtreeHeight === 0) {\n      // Note: In Go, this returns an error if key doesn't match.\n      // In TypeScript, we just return the leaf (closest match).\n      // The caller can check if the key matches if needed.\n      return this;\n    }\n\n    // Get the version for this node\n    // Use nodeKey.version if available, otherwise use a default\n    const nodeVersion = this.nodeKey?.version ?? 0n;\n\n    // Determine which direction to traverse\n    const cmp = compareBytes(key, this.key!);\n\n    if (cmp < 0) {\n      // Go left\n      // Load right sibling to include its hash in the proof\n      const rightNode = await this.getRightNode(getter);\n      if (!rightNode) {\n        throw new Error(\"Right child node not found\");\n      }\n\n      // Create ProofInnerNode for this level\n      // Note: left is null because we're traversing left (optimization)\n      const pin = new ProofInnerNode(\n        this.subtreeHeight,\n        this.size,\n        nodeVersion,\n        null, // left (we're going left, so don't store)\n        rightNode.hash!, // right sibling hash\n      );\n      path.push(pin);\n\n      // Recurse into left child\n      const leftNode = await this.getLeftNode(getter);\n      if (!leftNode) {\n        throw new Error(\"Left child node not found\");\n      }\n\n      return await leftNode._pathToLeaf(getter, key, path);\n    }\n    else {\n      // Go right (includes the case where cmp === 0, i.e., key === node.key)\n      // Load left sibling to include its hash in the proof\n      const leftNode = await this.getLeftNode(getter);\n      if (!leftNode) {\n        throw new Error(\"Left child node not found\");\n      }\n\n      // Create ProofInnerNode for this level\n      // Note: right is null because we're traversing right (optimization)\n      const pin = new ProofInnerNode(\n        this.subtreeHeight,\n        this.size,\n        nodeVersion,\n        leftNode.hash!, // left sibling hash\n        null, // right (we're going right, so don't store)\n      );\n      path.push(pin);\n\n      // Recurse into right child\n      const rightNode = await this.getRightNode(getter);\n      if (!rightNode) {\n        throw new Error(\"Right child node not found\");\n      }\n\n      return await rightNode._pathToLeaf(getter, key, path);\n    }\n  }\n}\n\n/**\n * Compares two byte arrays lexicographically.\n * @param a - First byte array\n * @param b - Second byte array\n * @returns -1 if a < b, 0 if a === b, 1 if a > b\n */\nfunction compareBytes(a: Uint8Array, b: Uint8Array): number {\n  const minLen = Math.min(a.length, b.length);\n\n  for (let i = 0; i < minLen; i++) {\n    if (a[i] < b[i]) return -1;\n    if (a[i] > b[i]) return 1;\n  }\n\n  if (a.length < b.length) return -1;\n  if (a.length > b.length) return 1;\n  return 0;\n}\n\n/**\n * Encodes a byte array with a varint length prefix.\n * Compatible with Go's encoding.EncodeBytes.\n *\n * Note: Uses UNSIGNED varint for length (EncodeUvarint in Go)\n *\n * @param bytes - The byte array to encode\n * @returns Unsigned varint length + bytes\n */\nfunction encodeBytes(bytes: Uint8Array): Uint8Array {\n  const lengthBytes = encodeUvarint(bytes.length);\n  const result = new Uint8Array(lengthBytes.length + bytes.length);\n  result.set(lengthBytes, 0);\n  result.set(bytes, lengthBytes.length);\n  return result;\n}\n\n/**\n * Encodes a 32-byte hash with an optimized prefix.\n * Compatible with Go's encoding.Encode32BytesHash.\n * Uses 0x20 as the length prefix for 32-byte hashes.\n *\n * @param hashBytes - The 32-byte hash to encode\n * @returns 0x20 + hash (33 bytes total)\n */\nfunction encode32BytesHash(hashBytes: Uint8Array): Uint8Array {\n  if (hashBytes.length !== 32) {\n    throw new Error(`Hash must be 32 bytes, got ${hashBytes.length}`);\n  }\n  const result = new Uint8Array(33);\n  result[0] = 0x20; // Length prefix for 32 bytes\n  result.set(hashBytes, 1);\n  return result;\n}\n"],"mappings":";;;;;;;;;;;;AAkCA,MAAM,wBAAwB;AAC9B,MAAM,yBAAyB;;;;AAK/B,MAAM,YAAY;;;;;;;;;;;;;;;;AA8BlB,IAAa,OAAb,MAAa,KAAK;;CAEhB,MAAyB;;CAGzB,QAA2B;;CAG3B,OAA0B;;CAG1B,UAA0B;;;;;;CAO1B,cAAiC;;;;;;CAOjC,eAAkC;;CAGlC,WAAwB;;CAGxB,YAAyB;;CAGzB,gBAAwB;;CAGxB,OAAe;;;;;CAMf,WAAoB;;;;;;;;CASpB,OAAO,YAAY,KAAiB,OAAyB;EAC3D,MAAM,OAAO,IAAI,MAAM;AACvB,OAAK,MAAM;AACX,OAAK,QAAQ;AACb,OAAK,gBAAgB;AACrB,OAAK,OAAO;AACZ,SAAO;;;;;;;;;CAUT,OAAO,cAAc,MAAY,OAAmB;EAClD,MAAM,OAAO,IAAI,MAAM;AAIvB,OAAK,MAAM,MAAM;AAGjB,OAAK,WAAW;AAChB,OAAK,YAAY;AAGjB,OAAK,gBAAgB,IAAI,KAAK,IAAI,KAAK,eAAe,MAAM,cAAc;AAG1E,OAAK,OAAO,KAAK,OAAO,MAAM;AAE9B,SAAO;;;;;;;;CAST,SAAkB;AAChB,SAAO,KAAK,kBAAkB;;;;;;;;;CAUhC,aAAyB;AACvB,MAAI,KAAK,UAAU;AACjB,OAAI,CAAC,KAAK,KACR,OAAM,IAAI,MAAM,6BAA6B;AAE/C,UAAO,KAAK;;AAGd,MAAI,CAAC,KAAK,QACR,OAAM,IAAI,MAAM,yBAAyB;AAG3C,SAAO,KAAK,QAAQ,SAAS;;;;;;;;CAS/B,mBAA2B;AAGzB,UAFmB,KAAK,UAAU,iBAAi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