{"version":3,"file":"mutable-tree.cjs","names":["ChangeTracker","FastNode","Node","updated: boolean","existingRoot: Node | null","ImmutableTree","rootNode: Node | null","newNodes: Node[]"],"sources":["../src/mutable-tree.ts"],"sourcesContent":["/**\n * MutableTree is a persistent tree which keeps track of versions.\n *\n * THREAD SAFETY NOTE:\n * - NOT safe for concurrent use. While Node.js is single-threaded, async operations\n *   can interleave, so callers should serialize mutations (e.g., using a promise queue)\n *   if multiple async operations might modify the tree simultaneously.\n * - An immutable tree at a given version can be returned via getImmutable, which is safe\n *   for concurrent async access (reads only, no modifications).\n *\n * Given and returned key/value byte slices must not be modified, since they may point to data\n * located inside IAVL which would also be modified.\n *\n * The inner ImmutableTree should not be used directly by callers.\n *\n * Corresponds to Go's MutableTree in mutable_tree.go\n */\n\nimport type {\n  Logger,\n} from \"winston\";\n\nimport {\n  ChangeTracker,\n} from \"./change-tracker.js\";\nimport type {\n  ExportNode,\n} from \"./export/types.js\";\nimport type {\n  CommitmentProof,\n} from \"./generated/cosmos/ics23/v1/proofs.js\";\nimport {\n  ImmutableTree,\n} from \"./immutable-tree.js\";\nimport {\n  Node,\n} from \"./node.js\";\nimport {\n  FastNode,\n} from \"./storage/fast-node.js\";\nimport type {\n  NodeDB,\n} from \"./storage/node-db.js\";\nimport type {\n  ChangeSet,\n} from \"./types/index.js\";\n\n/**\n * MutableTree is a persistent tree which keeps track of versions.\n * NOT safe for concurrent mutations - serialize async operations if needed.\n */\nexport class MutableTree {\n  /** Logger for diagnostics */\n  private readonly logger: Logger | null;\n\n  /** Change tracker for recording modifications */\n  private readonly changeTracker: ChangeTracker;\n\n  /** The current working tree (embedded ImmutableTree) */\n  private workingTree: ImmutableTree;\n\n  /** The current working root node (mutable) */\n  private workingRoot: Node | null;\n\n  /** The current working version */\n  private workingVersion: bigint;\n\n  /** The most recently saved tree */\n  private lastSaved: ImmutableTree;\n\n  /** FastNodes that have not yet been saved to disk */\n  private readonly unsavedFastNodeAdditions: Map<string, FastNode>;\n\n  /** FastNodes that have not yet been removed from disk */\n  private readonly unsavedFastNodeRemovals: Map<string, boolean>;\n\n  /** Node database for persistent storage */\n  private readonly ndb: NodeDB;\n\n  /** If true, the tree will work like no fast storage and always not upgrade fast storage */\n  private readonly skipFastStorageUpgrade: boolean;\n\n  /** Whether initialVersion logic should apply (cleared after first save) */\n  private initialVersionSet: boolean;\n\n  /**\n   * Creates a new MutableTree instance.\n   *\n   * @param ndb - Node database for persistent storage\n   * @param workingTree - The current working tree (ImmutableTree)\n   * @param skipFastStorageUpgrade - If true, disable fast storage optimization\n   * @param logger - Optional logger instance\n   * @param enableChangeTracking - If true, enable change tracking (default: false)\n   */\n  constructor(\n    ndb: NodeDB,\n    workingTree: ImmutableTree,\n    skipFastStorageUpgrade: boolean = false,\n    logger: Logger | null = null,\n    enableChangeTracking: boolean = false,\n  ) {\n    this.ndb = ndb;\n    this.workingTree = workingTree;\n    this.workingRoot = workingTree.getRoot();\n    this.workingVersion = workingTree.getVersion();\n    this.skipFastStorageUpgrade = skipFastStorageUpgrade;\n    this.logger = logger;\n\n    // Clone the working tree as lastSaved\n    this.lastSaved = workingTree.clone();\n\n    // Initialize unsaved fast node tracking\n    this.unsavedFastNodeAdditions = new Map<string, FastNode>();\n    this.unsavedFastNodeRemovals = new Map<string, boolean>();\n\n    // Check if initialVersion is set in options\n    const opts = this.ndb.getOptions();\n    this.initialVersionSet = opts.initialVersion !== undefined;\n\n    // Initialize change tracker\n    this.changeTracker = new ChangeTracker(enableChangeTracking);\n  }\n\n  /**\n   * Returns whether the working tree is empty (has no keys).\n   * Only non-empty trees can be saved.\n   *\n   * @returns true if the tree has no keys\n   */\n  isWorkingTreeEmpty(): boolean {\n    return this.workingRoot === null || this.workingRoot.size === 0n;\n  }\n\n  /**\n   * Returns the current working tree (for internal use).\n   *\n   * @returns The working ImmutableTree\n   */\n  getWorkingTree(): ImmutableTree {\n    return this.workingTree;\n  }\n\n  /**\n   * Returns the root node of the working tree.\n   *\n   * @returns The root node, or null if tree is empty\n   */\n  getRoot(): Node | null {\n    return this.workingRoot;\n  }\n\n  /**\n   * Returns the version of the working tree.\n   *\n   * @returns The current version\n   */\n  getVersion(): bigint {\n    return this.workingVersion;\n  }\n\n  /**\n   * Returns the working version (version + 1).\n   * This is the version that will be assigned when SaveVersion is called.\n   *\n   * Matches Go's WorkingVersion() with initialVersion support:\n   * - If calculated version is 1 and initialVersion is set, use initialVersion\n   * - Otherwise return workingVersion + 1\n   *\n   * @returns The working version\n   */\n  getWorkingVersion(): bigint {\n    let version = this.workingVersion + 1n;\n\n    // If this would be version 1 and initialVersionSet is true, use initialVersion instead\n    // This allows first save to be version 0 (or other value) when configured\n    // Note: initialVersionSet is cleared after first save (in saveVersion)\n    if (version === 1n && this.initialVersionSet) {\n      const opts = this.ndb.getOptions();\n      version = BigInt(opts.initialVersion!);\n    }\n\n    return version;\n  }\n\n  /**\n   * Sets the initial version number for a new tree.\n   * Can only be called before any versions are saved.\n   *\n   * Corresponds to Go's MutableTree.SetInitialVersion() (iavl/mutable_tree.go:305)\n   *\n   * @param version - The initial version number to use\n   * @throws Error if tree already has saved versions\n   */\n  setInitialVersion(version: number): void {\n    // Check if tree already has versions\n    if (this.workingVersion !== 0n) {\n      throw new Error(\"tree already has versions, cannot set initial version\");\n    }\n\n    // Set the option in NodeDB\n    const opts = this.ndb.getOptions();\n    opts.initialVersion = version;\n\n    // Set the flag to indicate initialVersion logic should apply\n    this.initialVersionSet = true;\n  }\n\n  /**\n   * Returns the hash of the latest saved version of the tree.\n   * If no versions have been saved, returns null.\n   *\n   * @returns The hash, or null if no versions saved\n   */\n  getHash(): Uint8Array | null {\n    return this.lastSaved.hash();\n  }\n\n  /**\n   * Returns the hash of the current working tree.\n   *\n   * @returns The working tree hash, or null if tree is empty\n   */\n  getWorkingHash(): Uint8Array | null {\n    if (!this.workingRoot) {\n      return null;\n    }\n    // Use computeHashWithDescendants to handle unsaved nodes (nodes without nodeKey)\n    // This recursively computes hashes for all children before computing parent hash\n    return this.workingRoot.computeHashWithDescendants(this.getWorkingVersion());\n  }\n\n  /**\n   * Returns the size (number of leaf nodes) in the working tree.\n   *\n   * @returns The tree size\n   */\n  getSize(): bigint {\n    if (!this.workingRoot) {\n      return 0n;\n    }\n    return this.workingRoot.size;\n  }\n\n  /**\n   * Gets the NodeDB instance (for internal use by Importer)\n   * @internal\n   */\n  getNodeDB(): NodeDB {\n    return this.ndb;\n  }\n\n  /**\n   * Checks if a specific version exists in the tree.\n   * Returns true if the version has been saved, false otherwise.\n   *\n   * Corresponds to Go's MutableTree.VersionExists()\n   *\n   * @param version - Version number to check\n   * @returns True if version exists, false otherwise\n   */\n  async versionExists(version: bigint): Promise<boolean> {\n    return await this.ndb.versionExists(version);\n  }\n\n  /**\n   * Returns the most recent saved version number.\n   * Returns 0n if no versions have been saved.\n   *\n   * Corresponds to Go's MutableTree.GetLatestVersion()\n   *\n   * @returns The latest version number\n   */\n  getLatestVersion(): bigint {\n    return this.ndb.getLatestVersion();\n  }\n\n  /**\n   * Returns an array of all available version numbers in the tree.\n   * Returns empty array if no versions have been saved.\n   *\n   * Corresponds to Go's MutableTree.AvailableVersions()\n   *\n   * @returns Sorted array of all saved version numbers\n   */\n  async availableVersions(): Promise<bigint[]> {\n    return await this.ndb.getVersions();\n  }\n\n  /**\n   * Gets the value for a key in the tree.\n   * Checks unsaved additions first, then falls back to tree traversal.\n   *\n   * IMPORTANT: The returned value must not be modified, since it may point to data\n   * stored within IAVL which would also be modified (reference sharing in JavaScript).\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    // Fast storage optimization: check unsaved changes first\n    // NOTE: Must check before empty tree check, as unsaved additions\n    // may exist even when tree is empty\n    if (!this.skipFastStorageUpgrade) {\n      // Check unsaved additions (new keys not yet persisted)\n      const keyStr = Buffer.from(key).toString(\"hex\");\n      const fastNode = this.unsavedFastNodeAdditions.get(keyStr);\n      if (fastNode) {\n        // Return value from unsaved addition\n        // NOTE: Returning reference to internal data - caller must not modify\n        return fastNode.value;\n      }\n\n      // Check unsaved removals (deleted keys not yet removed from disk)\n      if (this.unsavedFastNodeRemovals.has(keyStr)) {\n        // Key was deleted in this working tree\n        return null;\n      }\n    }\n\n    // Empty tree check (after unsaved checks)\n    if (this.workingRoot === null) {\n      return null;\n    }\n\n    // Fall back to tree traversal\n    const result = await this.workingRoot.get(this.ndb, key);\n    return result.value;\n  }\n\n  /**\n   * Sets a key-value pair in the tree.\n   * Returns true if the key already existed (update), false if it's a new key (insert).\n   *\n   * IMPORTANT: The key and value byte arrays must not be modified after this call,\n   * since they may be stored within IAVL (reference sharing in JavaScript).\n   *\n   * @param key - The key to set\n   * @param value - The value to set\n   * @returns true if key was updated, false if newly inserted\n   * @throws Error if value is null\n   */\n  async set(key: Uint8Array, value: Uint8Array): Promise<boolean> {\n    if (!value) {\n      throw new Error(`Attempt to store nil value at key '${Buffer.from(key).toString(\"hex\")}'`);\n    }\n\n    // Track the change if tracking is enabled\n    this.changeTracker.recordSet(key, value);\n\n    // Empty tree: create root node\n    if (this.workingRoot === null) {\n      if (!this.skipFastStorageUpgrade) {\n        this.addUnsavedAddition(key, new FastNode(key, value, this.getWorkingVersion()));\n      }\n      // Create new root\n      this.workingRoot = Node.newLeafNode(key, value);\n      return false; // New insertion\n    }\n\n    // Recursively set in existing tree\n    const result = await this.recursiveSet(this.workingRoot, key, value);\n    this.workingRoot = result.newNode;\n    return result.updated;\n  }\n\n  /**\n   * Helper to add an unsaved fast node addition.\n   * Removes from unsavedFastNodeRemovals if present.\n   *\n   * @param key - The key\n   * @param fastNode - The fast node to add\n   */\n  private addUnsavedAddition(key: Uint8Array, fastNode: FastNode): void {\n    const keyStr = Buffer.from(key).toString(\"hex\");\n    this.unsavedFastNodeRemovals.delete(keyStr);\n    this.unsavedFastNodeAdditions.set(keyStr, fastNode);\n  }\n\n  /**\n   * Recursively sets a key-value pair in the tree.\n   * Implements copy-on-write semantics by cloning nodes on mutation.\n   *\n   * @param node - Current node\n   * @param key - Key to set\n   * @param value - Value to set\n   * @returns Object with new node and whether key was updated\n   */\n  private async recursiveSet(\n    node: Node,\n    key: Uint8Array,\n    value: Uint8Array,\n  ): Promise<{\n    newNode: Node\n    updated: boolean\n  }> {\n    if (node.isLeaf()) {\n      return this.recursiveSetLeaf(node, key, value);\n    }\n\n    // Clone node for copy-on-write\n    const clonedNode = await node.clone(this.ndb);\n\n    // Compare key to decide left or right subtree\n    const cmp = Buffer.compare(key, node.key!);\n\n    let updated: boolean;\n    if (cmp < 0) {\n      // Go left\n      const result = await this.recursiveSet(clonedNode.leftNode!, key, value);\n      clonedNode.leftNode = result.newNode;\n      updated = result.updated;\n    }\n    else {\n      // Go right\n      const result = await this.recursiveSet(clonedNode.rightNode!, key, value);\n      clonedNode.rightNode = result.newNode;\n      updated = result.updated;\n    }\n\n    if (updated) {\n      // Key already existed, just return cloned node\n      return {\n        newNode: clonedNode,\n        updated: true,\n      };\n    }\n\n    // New insertion: recalculate height/size and rebalance\n    await clonedNode.calcHeightAndSize(this.ndb);\n    const balanced = await this.balance(clonedNode);\n\n    return {\n      newNode: balanced,\n      updated: false,\n    };\n  }\n\n  /**\n   * Handles setting a key-value pair when current node is a leaf.\n   * Three cases:\n   * 1. key < node.key: Create branch with new key on left\n   * 2. key > node.key: Create branch with new key on right\n   * 3. key == node.key: Replace value (update)\n   *\n   * @param node - Current leaf node\n   * @param key - Key to set\n   * @param value - Value to set\n   * @returns Object with new node and whether key was updated\n   */\n  private recursiveSetLeaf(\n    node: Node,\n    key: Uint8Array,\n    value: Uint8Array,\n  ): {\n    newNode: Node\n    updated: boolean\n  } {\n    const version = this.getWorkingVersion();\n\n    if (!this.skipFastStorageUpgrade) {\n      this.addUnsavedAddition(key, new FastNode(key, value, version));\n    }\n\n    const cmp = Buffer.compare(key, node.key!);\n\n    if (cmp < 0) {\n      // setKey < leafKey: new key goes on left\n      const newLeaf = Node.newLeafNode(key, value);\n      const branch = new Node();\n      branch.key = node.key;\n      branch.subtreeHeight = 1;\n      branch.size = 2n;\n      branch.nodeKey = null;\n      branch.leftNode = newLeaf;\n      branch.rightNode = node;\n      return {\n        newNode: branch,\n        updated: false,\n      };\n    }\n    else if (cmp > 0) {\n      // setKey > leafKey: new key goes on right\n      const newLeaf = Node.newLeafNode(key, value);\n      const branch = new Node();\n      branch.key = key;\n      branch.subtreeHeight = 1;\n      branch.size = 2n;\n      branch.nodeKey = null;\n      branch.leftNode = node;\n      branch.rightNode = newLeaf;\n      return {\n        newNode: branch,\n        updated: false,\n      };\n    }\n    else {\n      // setKey == leafKey: replace value (update)\n      return {\n        newNode: Node.newLeafNode(key, value),\n        updated: true,\n      };\n    }\n  }\n\n  /**\n   * Removes a key from the working tree.\n   * The key should not be modified after this call.\n   *\n   * @param key - The key to remove\n   * @returns Object with removed value and whether removal occurred\n   */\n  async remove(key: Uint8Array): Promise<{\n    value: Uint8Array | null\n    removed: boolean\n  }> {\n    if (this.workingRoot === null) {\n      return {\n        value: null,\n        removed: false,\n      };\n    }\n\n    const result = await this.recursiveRemove(this.workingRoot, key);\n    if (!result.removed) {\n      return {\n        value: null,\n        removed: false,\n      };\n    }\n\n    // Track the removal if tracking is enabled\n    this.changeTracker.recordDelete(key, result.value ?? undefined);\n\n    if (!this.skipFastStorageUpgrade) {\n      this.addUnsavedRemoval(key);\n    }\n\n    this.workingRoot = result.newNode;\n    return {\n      value: result.value,\n      removed: true,\n    };\n  }\n\n  /**\n   * Iterates over all keys in the tree, calling a callback function for each key-value pair.\n   * Returns true if iteration was stopped early by the callback returning true.\n   *\n   * Corresponds to Go's MutableTree.Iterate()\n   *\n   * @param fn - Callback function called for each key-value pair. Return true to stop iteration.\n   * @returns True if iteration was stopped early, false if iteration completed\n   */\n  async iterate(fn: (key: Uint8Array, value: Uint8Array) => boolean): Promise<boolean> {\n    if (this.workingRoot === null) {\n      return false;\n    }\n\n    const iter = this.iterator(undefined, undefined);\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   * Returns an iterator over the mutable tree in ascending order.\n   * CONTRACT: no updates should be made to the tree while an iterator is active.\n   *\n   * Corresponds to Go's MutableTree.Iterator()\n   *\n   * @param start - Start key (inclusive), or undefined for beginning\n   * @param end - End key (exclusive), or undefined for end\n   * @returns Iterator over the tree\n   */\n  iterator(\n    start: Uint8Array | undefined,\n    end: Uint8Array | undefined,\n  ) {\n    return this.workingTree.iterator(start ?? null, end ?? null);\n  }\n\n  /**\n   * Returns a reverse iterator over the mutable tree (descending order).\n   * CONTRACT: no updates should be made to the tree while an iterator is active.\n   *\n   * @param start - Start key (inclusive), or undefined for end\n   * @param end - End key (exclusive), or undefined for beginning\n   * @returns Reverse iterator over the tree\n   */\n  reverseIterator(\n    start: Uint8Array | undefined,\n    end: Uint8Array | undefined,\n  ) {\n    return this.workingTree.reverseIterator(start ?? null, end ?? null);\n  }\n\n  /**\n   * Helper to add an unsaved fast node removal.\n   * Removes from unsavedFastNodeAdditions if present.\n   *\n   * @param key - The key to mark as removed\n   */\n  private addUnsavedRemoval(key: Uint8Array): void {\n    const keyStr = Buffer.from(key).toString(\"hex\");\n    this.unsavedFastNodeAdditions.delete(keyStr);\n    this.unsavedFastNodeRemovals.set(keyStr, true);\n  }\n\n  /**\n   * Recursively removes a key from the tree.\n   * Implements copy-on-write semantics by cloning nodes on mutation.\n   *\n   * @param node - Current node\n   * @param key - Key to remove\n   * @returns Object with new node, new key (for branch node key updates), removed value, and whether removal occurred\n   */\n  private async recursiveRemove(\n    node: Node,\n    key: Uint8Array,\n  ): Promise<{\n    newNode: Node | null\n    newKey: Uint8Array | null\n    value: Uint8Array | null\n    removed: boolean\n  }> {\n    // Base case: leaf node\n    if (node.isLeaf()) {\n      if (Buffer.compare(key, node.key!) === 0) {\n        // Found the key to remove\n        return {\n          newNode: null,\n          newKey: null,\n          value: node.value!,\n          removed: true,\n        };\n      }\n      // Key not found\n      return {\n        newNode: node,\n        newKey: null,\n        value: null,\n        removed: false,\n      };\n    }\n\n    // Clone node for copy-on-write\n    const clonedNode = await node.clone(this.ndb);\n\n    // Compare key to decide left or right subtree\n    const cmp = Buffer.compare(key, node.key!);\n\n    if (cmp < 0) {\n      // Go left\n      const result = await this.recursiveRemove(clonedNode.leftNode!, key);\n\n      if (!result.removed) {\n        // Key not found, return unchanged node\n        return {\n          newNode: clonedNode,\n          newKey: null,\n          value: null,\n          removed: false,\n        };\n      }\n\n      if (result.newNode === null) {\n        // Left child was removed, return right child\n        return {\n          newNode: clonedNode.rightNode,\n          newKey: clonedNode.key!,\n          value: result.value,\n          removed: true,\n        };\n      }\n\n      // Update left child, recalculate height/size, and rebalance\n      clonedNode.leftNode = result.newNode;\n      await clonedNode.calcHeightAndSize(this.ndb);\n      const balanced = await this.balance(clonedNode);\n\n      return {\n        newNode: balanced,\n        newKey: result.newKey,\n        value: result.value,\n        removed: true,\n      };\n    }\n    else {\n      // Go right (cmp >= 0)\n      const result = await this.recursiveRemove(clonedNode.rightNode!, key);\n\n      if (!result.removed) {\n        // Key not found, return unchanged node\n        return {\n          newNode: clonedNode,\n          newKey: null,\n          value: null,\n          removed: false,\n        };\n      }\n\n      if (result.newNode === null) {\n        // Right child was removed, return left child\n        return {\n          newNode: clonedNode.leftNode,\n          newKey: null,\n          value: result.value,\n          removed: true,\n        };\n      }\n\n      // Update right child\n      clonedNode.rightNode = result.newNode;\n      // Update branch key if needed (when right child's leftmost key changed)\n      if (result.newKey !== null) {\n        clonedNode.key = result.newKey;\n      }\n      await clonedNode.calcHeightAndSize(this.ndb);\n      const balanced = await this.balance(clonedNode);\n\n      return {\n        newNode: balanced,\n        newKey: null,\n        value: result.value,\n        removed: true,\n      };\n    }\n  }\n\n  /**\n   * Performs a right rotation on the given node.\n   * Used for rebalancing when left subtree is too tall.\n   *\n   * Before:        node                After:      newNode\n   *               /    \\                          /      \\\n   *           left      c          =>         a        node\n   *          /    \\                                   /    \\\n   *         a      b                                 b      c\n   *\n   * @param node - The node to rotate (will be cloned)\n   * @returns The new root of the rotated subtree\n   */\n  private async rotateRight(node: Node): Promise<Node> {\n    // Check if node has left child before rotating\n    if (!node.leftNode) {\n      throw new Error(\"Cannot rotate right: node has no left child\");\n    }\n\n    // Clone the node for copy-on-write\n    const clonedNode = await node.clone(this.ndb);\n\n    // Clone the left child (will become new root)\n    const newNode = await clonedNode.leftNode!.clone(this.ndb);\n\n    // Perform rotation\n    clonedNode.leftNode = newNode.rightNode;\n    newNode.rightNode = clonedNode;\n\n    // Recalculate height and size (only for branch nodes)\n    if (!clonedNode.isLeaf()) {\n      await clonedNode.calcHeightAndSize(this.ndb);\n    }\n    await newNode.calcHeightAndSize(this.ndb);\n\n    return newNode;\n  }\n\n  /**\n   * Performs a left rotation on the given node.\n   * Used for rebalancing when right subtree is too tall.\n   *\n   * Before:     node                   After:         newNode\n   *            /    \\                                /      \\\n   *           a      right            =>          node       c\n   *                 /    \\                       /    \\\n   *                b      c                     a      b\n   *\n   * @param node - The node to rotate (will be cloned)\n   * @returns The new root of the rotated subtree\n   */\n  private async rotateLeft(node: Node): Promise<Node> {\n    // Check if node has right child before rotating\n    if (!node.rightNode) {\n      throw new Error(\"Cannot rotate left: node has no right child\");\n    }\n\n    // Clone the node for copy-on-write\n    const clonedNode = await node.clone(this.ndb);\n\n    // Clone the right child (will become new root)\n    const newNode = await clonedNode.rightNode!.clone(this.ndb);\n\n    // Perform rotation\n    clonedNode.rightNode = newNode.leftNode;\n    newNode.leftNode = clonedNode;\n\n    // Recalculate height and size (only for branch nodes)\n    if (!clonedNode.isLeaf()) {\n      await clonedNode.calcHeightAndSize(this.ndb);\n    }\n    await newNode.calcHeightAndSize(this.ndb);\n\n    return newNode;\n  }\n\n  /**\n   * Balances an AVL tree node by performing rotations if needed.\n   * Assumes node can be modified (not persisted).\n   *\n   * AVL Balance Cases:\n   * - balance > 1 (left-heavy):\n   *   - Left-Left: Single right rotation\n   *   - Left-Right: Left rotation on left child, then right rotation on node\n   * - balance < -1 (right-heavy):\n   *   - Right-Right: Single left rotation\n   *   - Right-Left: Right rotation on right child, then left rotation on node\n   * - -1 <= balance <= 1: Already balanced, no rotation needed\n   *\n   * @param node - The node to balance (must not be persisted)\n   * @returns The new root of the balanced subtree\n   * @throws Error if node is already persisted\n   */\n  private async balance(node: Node): Promise<Node> {\n    // Ensure node hasn't been persisted (can be modified)\n    if (node.nodeKey !== null) {\n      throw new Error(\"unexpected balance() call on persisted node\");\n    }\n\n    // Calculate balance factor (left height - right height)\n    const balance = node.getBalanceFactor();\n\n    // Left-heavy case (balance > 1)\n    if (balance > 1) {\n      // Check left child's balance to determine rotation type\n      const leftBalance = node.leftNode!.getBalanceFactor();\n\n      if (leftBalance >= 0) {\n        // Left-Left Case: Single right rotation\n        const newNode = await this.rotateRight(node);\n        return newNode;\n      }\n\n      // Left-Right Case: Double rotation\n      // First rotate left child left, then rotate node right\n      node.leftNodeKey = null; // Clear cached key\n      node.leftNode = await this.rotateLeft(node.leftNode!);\n\n      const newNode = await this.rotateRight(node);\n      return newNode;\n    }\n\n    // Right-heavy case (balance < -1)\n    if (balance < -1) {\n      // Load right child if needed\n      const rightNode = await node.getRightNode(this.ndb);\n      if (!rightNode) {\n        throw new Error(\"Right node should exist for right-heavy tree\");\n      }\n\n      // Check right child's balance to determine rotation type\n      const rightBalance = rightNode.getBalanceFactor();\n\n      if (rightBalance <= 0) {\n        // Right-Right Case: Single left rotation\n        const newNode = await this.rotateLeft(node);\n        return newNode;\n      }\n\n      // Right-Left Case: Double rotation\n      // First rotate right child right, then rotate node left\n      node.rightNodeKey = null; // Clear cached key\n      node.rightNode = await this.rotateRight(rightNode);\n\n      const newNode = await this.rotateLeft(node);\n      return newNode;\n    }\n\n    // Already balanced (-1 <= balance <= 1)\n    return node;\n  }\n\n  /**\n   * SaveVersion saves a new tree version to disk and returns the hash.\n   *\n   * Steps:\n   * 1. Check if version already exists (idempotent check)\n   * 2. Save fast storage nodes (if not skipped)\n   * 3. Save new tree nodes with assigned node keys\n   * 4. Commit changes to storage\n   * 5. Update version and reset working state\n   *\n   * @returns Object with hash and version number\n   * @throws Error if version already exists with different hash\n   */\n  async saveVersion(): Promise<{\n    hash: Uint8Array | null\n    version: bigint\n  }> {\n    // Check if no changes since last save (idempotent)\n    // Only applies if we've saved at least once (workingVersion was updated by a save)\n    // For fresh trees, workingVersion equals lastSaved version (both from initial ImmutableTree)\n    // After first save, workingVersion is updated to the saved version\n    const hasSavedBefore = await this.ndb.versionExists(this.workingVersion);\n    if (hasSavedBefore && this.workingRoot === this.lastSaved.getRoot()) {\n      // No changes since last save - return the last saved version\n      return {\n        hash: this.lastSaved.hash(),\n        version: this.workingVersion,\n      };\n    }\n\n    const version = this.getWorkingVersion();\n\n    // Clear initialVersionSet after first save (matches Go behavior)\n    this.initialVersionSet = false;\n\n    // Check if version already exists\n    if (await this.ndb.versionExists(version)) {\n      // If version exists, verify it's the same hash (idempotent)\n      const existingNodeKey = await this.ndb.getRoot(version);\n      let existingRoot: Node | null = null;\n\n      if (existingNodeKey !== null) {\n        existingRoot = await this.ndb.getNode(existingNodeKey);\n      }\n\n      const newHash = this.workingHash();\n\n      // If both null or same hash, it's idempotent\n      const existingHash = existingRoot?.hash ?? null;\n      const hashesMatch\n        = (existingHash === null && newHash === null)\n          || (existingHash !== null\n            && newHash !== null\n            && Buffer.from(existingHash).equals(Buffer.from(newHash)));\n\n      if (\n        (existingRoot === null && this.workingRoot === null)\n        || hashesMatch\n      ) {\n        // Update internal state to match saved version\n        this.workingVersion = version;\n        this.workingRoot = existingRoot;\n        const newWorkingTree = this.workingTree.clone();\n        this.lastSaved = newWorkingTree.clone();\n        return {\n          hash: newHash,\n          version,\n        };\n      }\n\n      // Version exists with different hash - error\n      throw new Error(\n        `version ${version} was already saved to different hash `\n        + `(existing: ${existingHash ? Buffer.from(existingHash).toString(\"hex\") : \"null\"}, `\n        + `new: ${newHash ? Buffer.from(newHash).toString(\"hex\") : \"null\"})`,\n      );\n    }\n\n    this.logger?.debug(\"SAVE TREE\", {\n      version: version.toString(),\n    });\n\n    // Save fast storage nodes\n    if (!this.skipFastStorageUpgrade) {\n      await this.saveFastNodeVersion(version);\n    }\n\n    // Save tree nodes\n    if (this.workingRoot === null) {\n      await this.ndb.saveEmptyRoot(version);\n    }\n    else {\n      if (this.workingRoot.nodeKey !== null) {\n        // No updated nodes - just save root reference\n        await this.ndb.saveRoot(version, this.workingRoot.nodeKey.toBytes());\n\n        // Handle legacy nodes\n        if (this.workingRoot.isLegacy) {\n          this.workingRoot.isLegacy = false;\n          await this.ndb.saveNode(this.workingRoot);\n        }\n      }\n      else {\n        // Save all new nodes\n        await this.saveNewNodes(version);\n      }\n    }\n\n    // Mark committing to prevent async pruning interference\n    this.ndb.setCommitting();\n\n    try {\n      // Commit to storage\n      await this.ndb.commit();\n\n      // Update version tracking\n      this.ndb.resetLatestVersion(version);\n    }\n    finally {\n      // Always unset committing flag\n      this.ndb.unsetCommitting();\n    }\n    this.workingVersion = version;\n\n    // Set new working tree - create new ImmutableTree with saved state\n    // This creates a snapshot of what was just saved\n    this.workingTree = new ImmutableTree(\n      this.workingRoot,\n      this.ndb,\n      version,\n      this.skipFastStorageUpgrade,\n    );\n    this.lastSaved = this.workingTree.clone();\n\n    // Clear unsaved fast node maps\n    if (!this.skipFastStorageUpgrade) {\n      this.unsavedFastNodeAdditions.clear();\n      this.unsavedFastNodeRemovals.clear();\n    }\n\n    // Clear change tracker after successful save\n    this.changeTracker.clear();\n\n    // Return hash from the saved tree (matches Go's tree.Hash())\n    return {\n      hash: this.lastSaved.hash(),\n      version,\n    };\n  }\n\n  /**\n   * SaveChangeSet applies a ChangeSet (set of key-value changes) to the tree and saves a new version.\n   *\n   * The method will:\n   * 1. Check for uncommitted changes (returns error if any exist)\n   * 2. Apply all changes in the changeset (set/delete operations)\n   * 3. Save the version\n   * 4. Return the new version number\n   *\n   * Corresponds to Go's MutableTree.SaveChangeSet() (iavl/mutable_tree.go:622)\n   *\n   * @param changeSet - The set of changes to apply\n   * @returns The new version number\n   * @throws Error if there are uncommitted changes\n   * @throws Error if attempting to delete a non-existent key\n   * @throws Error on any set/remove operation failure\n   */\n  async saveChangeSet(changeSet: ChangeSet): Promise<bigint> {\n    // Check for uncommitted changes\n    if (this.workingRoot !== null && this.workingRoot.nodeKey === null) {\n      throw new Error(\"cannot save changeset with uncommitted changes\");\n    }\n\n    // Apply all changes\n    for (const pair of changeSet.pairs) {\n      if (pair.delete) {\n        // For deletes, error if key doesn't exist (matching Go behavior)\n        const result = await this.remove(pair.key);\n        if (!result.removed) {\n          throw new Error(`attempted to remove non-existent key ${Buffer.from(pair.key).toString(\"hex\")}`);\n        }\n      }\n      else {\n        // For sets, just set the value\n        await this.set(pair.key, pair.value);\n      }\n    }\n\n    // Save version and return version number\n    const result = await this.saveVersion();\n    return result.version;\n  }\n\n  /**\n   * LoadVersion loads a specific version of the tree into the working state.\n   * Returns the latest version available in the database.\n   *\n   * If targetVersion is 0 or negative, loads the latest version.\n   * If targetVersion doesn't exist, returns an error.\n   *\n   * @param targetVersion - The version to load (0 or negative for latest)\n   * @returns The latest version number available in the database\n   * @throws Error if version doesn't exist or is invalid\n   */\n  async loadVersion(targetVersion: bigint): Promise<bigint> {\n    const firstVersion = this.ndb.getFirstVersion();\n    const latestVersion = this.ndb.getLatestVersion();\n\n    // Check if initialVersion is set and conflicts with firstVersion\n    const opts = this.ndb.getOptions();\n    if (firstVersion > 0n && opts.initialVersion !== undefined && firstVersion < BigInt(opts.initialVersion)) {\n      throw new Error(\n        `initial version set to ${opts.initialVersion}, but found earlier version ${firstVersion}`,\n      );\n    }\n\n    // Check if any versions exist\n    if (latestVersion === 0n) {\n      if (targetVersion <= 0n) {\n        // No versions saved yet - this is ok for an empty tree\n        // Handle fast storage upgrade if needed\n        if (!this.skipFastStorageUpgrade) {\n          await this.enableFastStorageAndCommitIfNotEnabled();\n        }\n        return 0n;\n      }\n      throw new Error(`no versions found while trying to load ${targetVersion}`);\n    }\n\n    // If targetVersion is 0 or negative, load latest\n    if (targetVersion <= 0n) {\n      targetVersion = latestVersion;\n    }\n\n    // Check if target version is too high\n    if (latestVersion < targetVersion) {\n      throw new Error(\n        `wanted to load target ${targetVersion} but only found up to ${latestVersion}`,\n      );\n    }\n\n    // Check if version exists\n    if (!await this.ndb.versionExists(targetVersion)) {\n      throw new Error(`version ${targetVersion} does not exist`);\n    }\n\n    // Load root node key for target version\n    const rootNodeKey = await this.ndb.getRoot(targetVersion);\n\n    // Load root node if it exists\n    let rootNode: Node | null = null;\n    if (rootNodeKey !== null) {\n      rootNode = await this.ndb.getNode(rootNodeKey);\n      if (rootNode === null) {\n        throw new Error(`root node not found for version ${targetVersion}`);\n      }\n    }\n\n    // Create new ImmutableTree for this version\n    const iTree = new ImmutableTree(\n      rootNode,\n      this.ndb,\n      targetVersion,\n      this.skipFastStorageUpgrade,\n    );\n\n    // Update working tree to loaded version\n    this.workingTree = iTree;\n    this.workingRoot = iTree.getRoot();\n    this.workingVersion = targetVersion;\n    this.lastSaved = iTree.clone();\n\n    // Clear unsaved changes\n    this.unsavedFastNodeAdditions.clear();\n    this.unsavedFastNodeRemovals.clear();\n\n    // Handle fast storage upgrade if needed\n    if (!this.skipFastStorageUpgrade) {\n      await this.enableFastStorageAndCommitIfNotEnabled();\n    }\n\n    return latestVersion;\n  }\n\n  /**\n   * LoadVersionForOverwriting loads a version and allows overwriting it.\n   * This deletes all versions after the target version, preparing the tree for overwriting history.\n   *\n   * Corresponds to Go's MutableTree.LoadVersionForOverwriting() (iavl/mutable_tree.go:266)\n   *\n   * Use case: Rolling back to a previous state and creating a new branch of history.\n   *\n   * @param targetVersion - The version to load (all versions after this will be deleted)\n   * @returns The latest version number available in the database\n   * @throws Error if version doesn't exist or deletion fails\n   */\n  async loadVersionForOverwriting(targetVersion: bigint): Promise<bigint> {\n    // Load the target version\n    const loadedVersion = await this.loadVersion(targetVersion);\n\n    // Delete all versions after this one\n    await this.deleteVersionsFrom(targetVersion + 1n);\n\n    // Commit the deletion\n    await this.ndb.commit();\n\n    // Handle fast storage upgrade if needed\n    if (!this.skipFastStorageUpgrade) {\n      // This will repopulate the fast node index because of version mismatch\n      await this.enableFastStorageAndCommitIfNotEnabled();\n    }\n\n    return loadedVersion;\n  }\n\n  /**\n   * GetImmutable loads an ImmutableTree at a given version for querying.\n   * The returned tree is safe for concurrent access (read-only), provided the\n   * version is not deleted via DeleteVersion().\n   *\n   * This method loads the version from the database and creates a new ImmutableTree\n   * instance. It does NOT return the current working tree or lastSaved tree,\n   * ensuring consistency with the persisted state.\n   *\n   * @param version - The version to load\n   * @returns ImmutableTree at the specified version\n   * @throws Error if version doesn't exist or loading fails\n   */\n  async getImmutable(version: bigint): Promise<ImmutableTree> {\n    // Check if version exists\n    const exists = await this.ndb.versionExists(version);\n    if (!exists) {\n      throw new Error(`version ${version} does not exist`);\n    }\n\n    // Load root node key for the version\n    const rootNodeKey = await this.ndb.getRoot(version);\n\n    // Load root node if it exists\n    let rootNode: Node | null = null;\n    if (rootNodeKey !== null) {\n      rootNode = await this.ndb.getNode(rootNodeKey);\n      if (rootNode === null) {\n        throw new Error(`root node not found for version ${version}`);\n      }\n    }\n\n    // Create and return new ImmutableTree instance\n    return new ImmutableTree(\n      rootNode,\n      this.ndb,\n      version,\n      this.skipFastStorageUpgrade,\n    );\n  }\n\n  /**\n   * Get Versioned gets the value at the specified key and version.\n   * The returned value must not be modified, since it may point to data stored within IAVL.\n   *\n   * Based on Go IAVL v1.3.5 mutable_tree.go GetVersioned (lines 665-695)\n   *\n   * @param key - The key to look up\n   * @param version - The version to query\n   * @returns The value at the key for the specified version, or null if not found\n   */\n  async getVersioned(\n    key: Uint8Array,\n    version: bigint,\n  ): Promise<Uint8Array | null> {\n    const exists = await this.ndb.versionExists(version);\n    if (!exists) {\n      return null;\n    }\n\n    // Fast storage optimization: try to use fast storage if available\n    // This is only applicable when fast storage is enabled\n    if (!this.skipFastStorageUpgrade) {\n      // Check if fast storage can be used\n      // Fast storage is only usable for the latest version\n      const latestVersion = this.ndb.getLatestVersion();\n      const isLatestVersion = version === latestVersion;\n      const hasFastStorage = this.ndb.hasUpgradedToFastStorage();\n\n      if (isLatestVersion && hasFastStorage) {\n        // Try to get from fast storage\n        const fastNode = await this.ndb.getFastNode(key);\n\n        // If no fast node and this is the latest version, key doesn't exist\n        if (!fastNode && version === latestVersion) {\n          return null;\n        }\n\n        // If fast node exists and was last updated at or before the requested version,\n        // return its value\n        if (fastNode && fastNode.versionLastUpdatedAt <= version) {\n          return fastNode.value;\n        }\n      }\n    }\n\n    // Fall back to regular tree traversal\n    const tree = await this.getImmutable(version);\n    return tree.get(key);\n  }\n\n  /**\n   * Get Versioned Proof gets the proof for the given key at the specified version.\n   * Returns either a membership or non-membership proof depending on whether the key exists.\n   *\n   * Based on Go IAVL v1.3.5 proof_ics23.go GetVersionedProof (lines 203-212)\n   *\n   * @param key - The key to generate a proof for\n   * @param version - The version to generate the proof at\n   * @returns CommitmentProof for the key at the specified version\n   * @throws Error if version doesn't exist\n   */\n  async getVersionedProof(\n    key: Uint8Array,\n    version: bigint,\n  ): Promise<CommitmentProof> {\n    const exists = await this.ndb.versionExists(version);\n    if (!exists) {\n      throw new Error(`version ${version} does not exist`);\n    }\n\n    const tree = await this.getImmutable(version);\n    return tree.getProof(key);\n  }\n\n  /**\n   * Rollback resets the working tree to the latest saved version, discarding\n   * any unsaved modifications.\n   *\n   * This is useful when you want to abandon uncommitted changes and return to\n   * the last saved state. After rollback:\n   * - Working tree is restored to lastSaved state\n   * - All unsaved mutations are discarded\n   * - Unsaved fast node additions/removals are cleared\n   *\n   * If no versions have been saved yet (version === 0), rollback creates a\n   * fresh empty tree.\n   */\n  rollback(): void {\n    if (this.workingVersion > 0n) {\n      // Restore to last saved version\n      this.workingTree = this.lastSaved.clone();\n      this.workingRoot = this.workingTree.getRoot();\n    }\n    else {\n      // No versions saved yet, create empty tree\n      this.workingTree = new ImmutableTree(\n        null,\n        this.ndb,\n        0n,\n        this.skipFastStorageUpgrade,\n      );\n      this.workingRoot = null;\n    }\n\n    // Clear unsaved changes\n    if (!this.skipFastStorageUpgrade) {\n      this.unsavedFastNodeAdditions.clear();\n      this.unsavedFastNodeRemovals.clear();\n    }\n\n    // Clear change tracker on rollback\n    this.changeTracker.clear();\n  }\n\n  /**\n   * Deletes a specific version from the tree.\n   * The version must exist and cannot be the latest version.\n   *\n   * Note: This is a simplified implementation. Full orphan node cleanup\n   * will be added when orphan tracking is implemented.\n   *\n   * @param version - Version to delete\n   * @throws Error if version doesn't exist or is the latest version\n   */\n  async deleteVersion(version: bigint): Promise<void> {\n    await this.ndb.deleteVersion(version);\n    await this.ndb.commit();\n  }\n\n  /**\n   * Deletes all versions from the first version up to and including toVersion.\n   * This is useful for pruning old versions to reclaim space.\n   *\n   * After deletion, the first available version will be toVersion + 1.\n   *\n   * @param toVersion - Delete all versions up to and including this (inclusive)\n   * @throws Error if toVersion is invalid or versions have active readers\n   */\n  async deleteVersionsTo(toVersion: bigint): Promise<void> {\n    await this.ndb.deleteVersionsTo(toVersion);\n    await this.ndb.commit();\n  }\n\n  /**\n   * Deletes all versions from fromVersion upwards (including fromVersion).\n   * This effectively \"rewinds\" the tree to an earlier state.\n   *\n   * After deletion, the latest version will be fromVersion-1.\n   *\n   * @param fromVersion - Delete all versions from this onwards (inclusive)\n   * @throws Error if fromVersion is invalid or versions have active readers\n   */\n  async deleteVersionsFrom(fromVersion: bigint): Promise<void> {\n    await this.ndb.deleteVersionsFrom(fromVersion);\n    await this.ndb.commit();\n  }\n\n  /**\n   * Enables fast storage and commits if not already enabled.\n   * This is called after loading versions to ensure fast storage is upgraded.\n   * @returns true if fast storage was enabled, false if already enabled\n   */\n  private async enableFastStorageAndCommitIfNotEnabled(): Promise<boolean> {\n    // TODO: Implement fast storage upgrade in a future item\n    // For now, return false (already enabled/not needed)\n    return false;\n  }\n\n  /**\n   * Returns the hash of the current working tree.\n   * Uses workingRoot since it's kept up-to-date with mutations.\n   * Uses recursive hash computation to handle unsaved nodes.\n   * @returns Hash of working tree, or null if empty\n   */\n  private workingHash(): Uint8Array | null {\n    if (!this.workingRoot) {\n      return null;\n    }\n    // Compute hash recursively to handle unsaved nodes\n    this.workingRoot.computeHashWithDescendants(this.getWorkingVersion());\n    return this.workingRoot.hash;\n  }\n\n  /**\n   * Saves fast storage nodes for a version.\n   * @param version - Version number to save fast nodes for\n   */\n  private async saveFastNodeVersion(version: bigint): Promise<void> {\n    await this.saveFastNodeAdditions();\n    await this.saveFastNodeRemovals();\n    await this.ndb.setFastStorageVersionToBatch(version);\n  }\n\n  /**\n   * Saves all unsaved fast node additions to storage.\n   */\n  private async saveFastNodeAdditions(): Promise<void> {\n    // Sort keys for deterministic order\n    const keys = Array.from(this.unsavedFastNodeAdditions.keys()).sort();\n\n    for (const key of keys) {\n      const node = this.unsavedFastNodeAdditions.get(key);\n      if (node) {\n        await this.ndb.saveFastNode(node);\n      }\n    }\n  }\n\n  /**\n   * Saves all unsaved fast node removals to storage.\n   */\n  private async saveFastNodeRemovals(): Promise<void> {\n    // Sort keys for deterministic order\n    const keys = Array.from(this.unsavedFastNodeRemovals.keys()).sort();\n\n    for (const key of keys) {\n      await this.ndb.deleteFastNode(Buffer.from(key, \"hex\"));\n    }\n  }\n\n  /**\n   * Saves all new nodes recursively, assigning node keys.\n   * @param version - Version number for node keys\n   */\n  private async saveNewNodes(version: bigint): Promise<void> {\n    let nonce = 0;\n    const newNodes: Node[] = [];\n\n    // Recursive function to assign keys to nodes\n    const recursiveAssignKey = async (node: Node): Promise<Uint8Array> => {\n      if (node.nodeKey !== null) {\n        return node.nodeKey.toBytes();\n      }\n\n      nonce++;\n      // Import NodeKey class\n      const {\n        NodeKey,\n      } = await import(\"./node-key.js\");\n      node.nodeKey = new NodeKey(version, nonce);\n\n      // For inner nodes, recursively assign keys to children\n      if (node.subtreeHeight > 0) {\n        if (node.leftNode) {\n          node.leftNodeKey = await recursiveAssignKey(node.leftNode);\n        }\n        if (node.rightNode) {\n          node.rightNodeKey = await recursiveAssignKey(node.rightNode);\n        }\n      }\n\n      // Hash the node with its version\n      node.computeHash(version);\n      newNodes.push(node);\n\n      return node.nodeKey.toBytes();\n    };\n\n    // Assign keys starting from root\n    if (this.workingRoot) {\n      await recursiveAssignKey(this.workingRoot);\n    }\n\n    // Save all nodes and clear references\n    for (const node of newNodes) {\n      await this.ndb.saveNode(node);\n      // Clear child references to free memory\n      node.leftNode = null;\n      node.rightNode = null;\n    }\n\n    // Note: We do NOT call saveRoot here (unlike when root.nodeKey !== null)\n    // The root node is saved directly via SaveNode above, and getRoot() handles\n    // the \"implicit root\" case where a node exists at GetRootKey(version).\n    // Calling saveRoot here would create a self-reference and overwrite the node data.\n    // Matches Go IAVL mutable_tree.go saveNewNodes() which does not call SaveRoot.\n  }\n\n  /**\n   * Import imports nodes from an Exporter into this tree.\n   * The tree must be empty and the database must have no existing versions.\n   * Nodes must be provided in the same order as exported (post-order LRN).\n   *\n   * Based on Go IAVL mutable_tree.go Import method.\n   *\n   * @param exporter - The Exporter to import nodes from\n   * @param version - The version to import as\n   * @throws Error if tree is not empty or version is invalid\n   *\n   * @example\n   * ```typescript\n   * const sourceTree = await MutableTree.create(sourceDb);\n   * await sourceTree.set(str(\"a\"), str(\"1\"));\n   * await sourceTree.saveVersion();\n   *\n   * const exporter = sourceTree.getWorkingTree().export();\n   *\n   * const targetTree = await MutableTree.create(targetDb);\n   * await targetTree.import(exporter, 1n);\n   * ```\n   */\n  async import(\n    exporter: AsyncIterableIterator<ExportNode>,\n    version: bigint,\n  ): Promise<void> {\n    const {\n      Importer,\n    } = await import(\"./import/importer.js\");\n\n    const importer = new Importer(this, version);\n\n    try {\n      for await (const node of exporter) {\n        await importer.add(node);\n      }\n\n      await importer.commit();\n    }\n    catch (error) {\n      importer.close();\n      throw error;\n    }\n  }\n\n  /**\n   * Import compressed nodes into an empty tree from a compressed exporter.\n   * The compressed exporter uses delta encoding to reduce size.\n   *\n   * @param exporter - Async iterator that yields compressed ExportNodes\n   * @param version - The version to import (must match export version)\n   * @throws Error if tree is not empty or import fails\n   *\n   * @example\n   * ```typescript\n   * const sourceTree = await MutableTree.create(sourceDb);\n   * await sourceTree.set(str(\"a\"), str(\"1\"));\n   * await sourceTree.saveVersion();\n   *\n   * const exporter = sourceTree.getWorkingTree().exportCompressed();\n   *\n   * const targetTree = await MutableTree.create(targetDb);\n   * await targetTree.importCompressed(exporter, 1n);\n   * ```\n   */\n  async importCompressed(\n    exporter: AsyncIterable<ExportNode>,\n    version: bigint,\n  ): Promise<void> {\n    const {\n      Importer,\n    } = await import(\"./import/importer.js\");\n    const {\n      CompressImporter,\n    } = await import(\"./export/compress.js\");\n\n    // Import the type separately\n    const baseImporter = new Importer(this, version);\n\n    // Create adapter for the importer interface\n    const importerAdapter = {\n      async add(node: ExportNode): Promise<void> {\n        await baseImporter.add(node);\n      },\n    };\n\n    const decompressor = new CompressImporter(importerAdapter);\n\n    try {\n      for await (const node of exporter) {\n        await decompressor.add(node);\n      }\n\n      await baseImporter.commit();\n    }\n    catch (error) {\n      baseImporter.close();\n      throw error;\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 a convenience method that delegates to the NodeDB.\n   * Based on Go IAVL v1.3.5 mutable_tree.go (though Go has it on ImmutableTree)\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  async traverseStateChanges(\n    startVersion: bigint,\n    endVersion: bigint,\n    fn: (version: bigint, changeSet: ChangeSet) => Promise<boolean | void>,\n  ): Promise<void> {\n    return this.ndb.traverseStateChanges(startVersion, endVersion, fn);\n  }\n\n  /**\n   * Checks if the tree storage format can be upgraded.\n   * In our TypeScript implementation, we already use the latest format,\n   * so this always returns false (no upgrade needed/possible).\n   *\n   * Corresponds to Go's MutableTree.IsUpgradeable()\n   *\n   * @returns false - TypeScript implementation uses latest format\n   */\n  isUpgradeable(): boolean {\n    // In the Go implementation, this checks if fast storage upgrade is needed.\n    // In our TS implementation, we always use the latest format from the start,\n    // so there's nothing to upgrade.\n    return false;\n  }\n\n  /**\n   * Returns a string representation of the tree for debugging.\n   * Shows the current version, size, and root hash.\n   *\n   * Corresponds to Go's MutableTree.String()\n   *\n   * @returns String representation of the tree\n   */\n  toString(): string {\n    const hash = this.workingHash();\n    const hashHex = hash ? Buffer.from(hash).toString(\"hex\").substring(0, 16) : \"null\";\n    const size = this.workingRoot?.size ?? 0n;\n\n    return `MutableTree{version=${this.workingVersion}, size=${size}, hash=${hashHex}...}`;\n  }\n\n  // === Change Tracking Methods ===\n\n  /**\n   * Enable or disable change tracking.\n   * When enabled, the tree tracks all set and remove operations.\n   *\n   * @param enabled - Whether to enable change tracking\n   */\n  setChangeTracking(enabled: boolean): void {\n    this.changeTracker.setEnabled(enabled);\n  }\n\n  /**\n   * Check if change tracking is enabled.\n   *\n   * @returns True if change tracking is enabled\n   */\n  isChangeTrackingEnabled(): boolean {\n    return this.changeTracker.isEnabled();\n  }\n\n  /**\n   * Get the current change set containing all modifications since the last save.\n   * Returns a copy of the change set to prevent external modifications.\n   *\n   * @returns The current change set\n   */\n  getChangeSet(): ChangeSet {\n    return this.changeTracker.getChangeSet();\n  }\n\n  /**\n   * Get the number of changes tracked since the last save.\n   *\n   * @returns Number of tracked changes\n   */\n  getChangeCount(): number {\n    return this.changeTracker.size();\n  }\n\n  /**\n   * Clear the current change set.\n   * This is automatically called after saveVersion() and rollback().\n   */\n  clearChangeSet(): void {\n    this.changeTracker.clear();\n  }\n\n  /**\n   * Get statistics about the current change tracking.\n   *\n   * @returns Change tracking statistics\n   */\n  getChangeStats(): {\n    total: number\n    sets: number\n    deletes: number\n    enabled: boolean\n    maxChanges: number\n  } {\n    return this.changeTracker.getStats();\n  }\n\n  /**\n   * Check if a specific key has been changed since the last save.\n   *\n   * @param key - The key to check\n   * @returns True if the key has been modified\n   */\n  hasChange(key: Uint8Array): boolean {\n    return this.changeTracker.hasChange(key);\n  }\n\n  /**\n   * Apply a change set to the tree.\n   * This applies all changes in the set (sets and deletes) to the current tree.\n   * Note: This does not save the tree - call saveVersion() after to persist.\n   *\n   * @param changeSet - The change set to apply\n   */\n  async applyChangeSet(changeSet: ChangeSet): Promise<void> {\n    for (const pair of changeSet.pairs) {\n      if (pair.delete) {\n        await this.remove(pair.key);\n      }\n      else {\n        await this.set(pair.key, pair.value);\n      }\n    }\n  }\n\n  /**\n   * Serialize the current change set to protobuf bytes.\n   * Useful for network transmission or storage.\n   *\n   * @returns Serialized change set\n   */\n  serializeChangeSet(): Uint8Array {\n    return this.changeTracker.serialize();\n  }\n}\n"],"mappings":";;;;;;;;;;AAmDA,IAAa,cAAb,MAAyB;;CAEvB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAQ;;CAGR,AAAQ;;CAGR,AAAQ;;CAGR,AAAQ;;CAGR,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAiB;;CAGjB,AAAQ;;;;;;;;;;CAWR,YACE,KACA,aACA,yBAAkC,OAClC,SAAwB,MACxB,uBAAgC,OAChC;AACA,OAAK,MAAM;AACX,OAAK,cAAc;AACnB,OAAK,cAAc,YAAY,SAAS;AACxC,OAAK,iBAAiB,YAAY,YAAY;AAC9C,OAAK,yBAAyB;AAC9B,OAAK,SAAS;AAGd,OAAK,YAAY,YAAY,OAAO;AAGpC,OAAK,2CAA2B,IAAI,KAAuB;AAC3D,OAAK,0CAA0B,IAAI,KAAsB;AAIzD,OAAK,oBADQ,KAAK,IAAI,YAAY,CACJ,mBAAmB;AAGjD,OAAK,gBAAgB,IAAIA,qCAAc,qBAAqB;;;;;;;;CAS9D,qBAA8B;AAC5B,SAAO,KAAK,gBAAgB,QAAQ,KAAK,YAAY,SAAS;;;;;;;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