{"version":3,"file":"node-db.cjs","names":["AsyncBatchWithFlusher","LRUCache","startFormatted: Uint8Array","endFormatted: Uint8Array","fastKeyFormat","versions: bigint[]","getRootKey","metadataKeyFormat","orgNode: Node | null","ImmutableTree","nodes: Node[]","prevRoot: Uint8Array | null","pairs: KVPair[]","sharedNode: Node | null","newLeaves: Node[]","currentShared: Node","start: Uint8Array | undefined","end: Uint8Array | undefined","lines: string[]"],"sources":["../../src/storage/node-db.ts"],"sourcesContent":["/**\n * NodeDB handles persistent storage of IAVL tree nodes.\n * It manages both regular nodes (tree structure) and fast nodes (flat key-value index).\n *\n * Key Prefixes:\n * - 's': Regular node keys (format: s<version><nonce>)\n * - 'f': Fast node keys (format: f<key>)\n * - 'm': Metadata keys (format: m<key>)\n * - 'o': Legacy orphan keys (format: o<lastVersion><firstVersion><hash>)\n * - 'n': Legacy node keys (format: n<hash>)\n * - 'r': Legacy root keys (format: r<version>)\n *\n * Corresponds to Go's nodeDB in nodedb.go\n */\n\nimport type {\n  Logger,\n} from \"winston\";\n\nimport {\n  AsyncBatchWithFlusher,\n} from \"../db/batch-with-flusher.js\";\nimport type {\n  Database,\n  Iterator,\n} from \"../db/types.js\";\nimport {\n  ImmutableTree,\n} from \"../immutable-tree.js\";\nimport {\n  fastKeyFormat,\n  metadataKeyFormat,\n} from \"../keyformat/index.js\";\nimport type {\n  Node,\n  NodeGetter,\n} from \"../node.js\";\nimport {\n  getRootKey,\n} from \"../node-key.js\";\nimport type {\n  ChangeSet,\n  KVPair,\n} from \"../types/index.js\";\nimport type {\n  Options,\n  Statistics,\n} from \"../types/options.js\";\nimport {\n  incCacheHitCnt,\n  incCacheMissCnt,\n  incFastCacheHitCnt,\n  incFastCacheMissCnt,\n} from \"../types/options.js\";\nimport type {\n  Cache,\n} from \"./cache.js\";\nimport {\n  LRUCache,\n} from \"./cache.js\";\nimport type {\n  FastNode,\n} from \"./fast-node.js\";\n\n// Storage version constants\nconst STORAGE_VERSION_KEY = \"storage_version\";\nconst DEFAULT_STORAGE_VERSION = \"1.0.0\";\nconst FAST_STORAGE_VERSION = \"1.1.0\";\nconst _FAST_STORAGE_VERSION_DELIMITER = \"-\"; // Will be used for fast storage upgrades\n\n// Key prefixes for different data types\nconst NODE_KEY_PREFIX = 0x73; // 's' - regular nodes\nconst _FAST_NODE_KEY_PREFIX = 0x66; // 'f' - fast nodes (unused, using fastKeyFormat)\nconst _METADATA_KEY_PREFIX = 0x6D; // 'm' - metadata (unused, using metadataKeyFormat)\nconst LEGACY_ORPHAN_KEY_PREFIX = 0x6F; // 'o' - legacy orphans\nconst LEGACY_NODE_KEY_PREFIX = 0x6E; // 'n' - legacy nodes (hash-based)\nconst LEGACY_ROOT_KEY_PREFIX = 0x72; // 'r' - legacy roots\n\n// Default cache size for fast nodes\nconst FAST_NODE_CACHE_SIZE = 100000;\n\n/**\n * NodeDB manages persistent storage of IAVL nodes.\n * Implements the NodeGetter interface for node retrieval.\n */\nexport class NodeDB implements NodeGetter {\n  /** Underlying database for persistent storage */\n  /**\n   * The underlying database\n   * @internal - exposed for Importer use\n   */\n  readonly db: Database;\n\n  /** Batch for buffering writes with auto-flush */\n  private batch: AsyncBatchWithFlusher;\n\n  /** Cache for regular tree nodes */\n  private readonly nodeCache: Cache<string, Node>;\n\n  /** Cache for fast storage nodes */\n  private readonly fastNodeCache: Cache<string, FastNode>;\n\n  /** Configuration options */\n  private readonly opts: Options;\n\n  /** Storage version string */\n  private storageVersion: string;\n\n  /** First version stored in this DB */\n  private firstVersion: bigint;\n\n  /** Latest version stored in this DB */\n  private latestVersion: bigint;\n\n  /** Latest version in legacy format (hash-based keys), 0 if none */\n  private legacyLatestVersion: bigint;\n\n  /** Optional logger for diagnostics */\n  private readonly logger: Logger | null;\n\n  /** Version to prune up to (for async pruning) */\n  private pruneVersion: bigint;\n\n  /** Flag indicating if NodeDB is in the middle of committing */\n  private _isCommitting: boolean;\n\n  /** Resolve function for commit completion promise */\n  private commitCompleteResolve: (() => void) | null;\n\n  /** Promise that resolves when commit is complete */\n  private commitCompletePromise: Promise<void> | null;\n\n  /** Abort controller for async pruning worker */\n  private pruningAbortController: AbortController | null;\n\n  /** Map tracking number of active readers per version */\n  private readonly versionReaders: Map<bigint, number>;\n\n  /**\n   * Creates a new NodeDB instance.\n   *\n   * @param db - Underlying database for persistent storage\n   * @param cacheSize - Size of the regular node cache (default: from options)\n   * @param opts - Configuration options\n   * @param logger - Optional logger instance\n   */\n  constructor(\n    db: Database,\n    cacheSize: number,\n    opts: Options,\n    logger: Logger | null = null,\n  ) {\n    this.db = db;\n    this.opts = opts;\n    this.logger = logger;\n\n    // Initialize batch with auto-flush capability\n    this.batch = new AsyncBatchWithFlusher(db, opts.flushThreshold);\n\n    // Initialize caches\n    this.nodeCache = new LRUCache<string, Node>(cacheSize);\n    this.fastNodeCache = new LRUCache<string, FastNode>(FAST_NODE_CACHE_SIZE);\n\n    // Initialize versions\n    this.firstVersion = 0n;\n    this.latestVersion = 0n;\n    this.legacyLatestVersion = 0n;\n\n    // Initialize storage version (will be loaded from DB in async init)\n    this.storageVersion = DEFAULT_STORAGE_VERSION;\n\n    // Initialize async pruning state\n    this.pruneVersion = 0n;\n    this._isCommitting = false;\n    this.commitCompleteResolve = null;\n    this.commitCompletePromise = null;\n    this.pruningAbortController = null;\n\n    // Initialize version readers tracking\n    this.versionReaders = new Map<bigint, number>();\n  }\n\n  /**\n   * Asynchronously initializes the NodeDB by loading storage version from database.\n   * Should be called after construction.\n   *\n   * @returns Promise that resolves when initialization is complete\n   */\n  async initialize(): Promise<void> {\n    // Load storage version from database\n    const versionKey = this.metadataKey(stringToBytes(STORAGE_VERSION_KEY));\n    const storedVersion = await this.db.get(versionKey);\n\n    if (storedVersion) {\n      this.storageVersion = bytesToString(storedVersion);\n      this.logger?.debug(\"Loaded storage version\", {\n        version: this.storageVersion,\n      });\n    }\n    else {\n      this.storageVersion = DEFAULT_STORAGE_VERSION;\n      this.logger?.debug(\"Using default storage version\", {\n        version: this.storageVersion,\n      });\n    }\n\n    // Start async pruning worker if enabled\n    if (this.opts.asyncPruning) {\n      this.startPruningWorker();\n    }\n  }\n\n  /**\n   * Gets a node from cache or database.\n   * Implements the NodeGetter interface.\n   *\n   * @param nodeKey - The node key (version + nonce encoded)\n   * @returns The node, or null if not found\n   */\n  async getNode(nodeKey: Uint8Array): Promise<Node | null> {\n    if (!nodeKey || nodeKey.length === 0) {\n      throw new Error(\"NodeDB.getNode() requires nodeKey\");\n    }\n\n    // Check cache first\n    const cacheKey = Buffer.from(nodeKey).toString(\"hex\");\n    const cachedNode = this.nodeCache.get(cacheKey);\n    if (cachedNode) {\n      this.logger?.debug(\"Node cache hit\", {\n        nodeKey: cacheKey,\n      });\n      incCacheHitCnt(this.opts.statistics);\n      return cachedNode;\n    }\n\n    this.logger?.debug(\"Node cache miss\", {\n      nodeKey: cacheKey,\n    });\n    incCacheMissCnt(this.opts.statistics);\n\n    // Load from database\n    const dbKey = this.nodeKey(nodeKey);\n    let bytes = await this.db.get(dbKey);\n\n    // If not found and nodeKey is a hash (32 bytes), try legacy format\n    if (!bytes && nodeKey.length === 32) {\n      const legacyKey = this.legacyNodeKey(nodeKey);\n      bytes = await this.db.get(legacyKey);\n    }\n\n    if (!bytes) {\n      return null;\n    }\n\n    // Deserialize node\n    const {\n      Node: NodeClass,\n    } = await import(\"../node.js\");\n    const node = NodeClass.fromBytes(nodeKey, bytes);\n\n    // Add to cache\n    this.nodeCache.add(cacheKey, node);\n\n    return node;\n  }\n\n  /**\n   * Saves a node to the database.\n   *\n   * @param node - The node to save\n   */\n  async saveNode(node: Node): Promise<void> {\n    const nodeKeyBytes = node.getNodeKey();\n    if (!nodeKeyBytes || nodeKeyBytes.length === 0) {\n      throw new Error(\"NodeDB.saveNode() requires node to have nodeKey\");\n    }\n\n    // Serialize node\n    const bytes = node.toBytes();\n\n    // Save to database via batch\n    const dbKey = this.nodeKey(nodeKeyBytes);\n    await this.batch.set(dbKey, bytes);\n\n    // Add to cache\n    const cacheKey = Buffer.from(nodeKeyBytes).toString(\"hex\");\n    this.nodeCache.add(cacheKey, node);\n\n    this.logger?.debug(\"Saved node\", {\n      nodeKey: cacheKey,\n      size: bytes.length,\n    });\n  }\n\n  /**\n   * Saves a fast node to the database.\n   *\n   * @param fastNode - The fast node to save\n   */\n  async saveFastNode(fastNode: FastNode): Promise<void> {\n    if (!fastNode.key || fastNode.key.length === 0) {\n      throw new Error(\"NodeDB.saveFastNode() requires fastNode to have key\");\n    }\n\n    if (!this.hasUpgradedToFastStorage()) {\n      throw new Error(\"Fast storage not enabled - storage version < 1.1.0\");\n    }\n\n    // Serialize fast node\n    const bytes = fastNode.toBytes();\n\n    // Save to database via batch\n    const dbKey = this.fastNodeKey(fastNode.key);\n    await this.batch.set(dbKey, bytes);\n\n    // Add to cache\n    const cacheKey = Buffer.from(fastNode.key).toString(\"hex\");\n    this.fastNodeCache.add(cacheKey, fastNode);\n\n    this.logger?.debug(\"Saved fast node\", {\n      key: cacheKey,\n      version: fastNode.versionLastUpdatedAt,\n      size: bytes.length,\n    });\n  }\n\n  /**\n   * Gets a fast node from cache or database.\n   *\n   * @param key - The key to look up\n   * @returns The fast node, or null if not found\n   */\n  async getFastNode(key: Uint8Array): Promise<FastNode | null> {\n    if (!key || key.length === 0) {\n      throw new Error(\"NodeDB.getFastNode() requires key\");\n    }\n\n    if (!this.hasUpgradedToFastStorage()) {\n      throw new Error(\"Fast storage not enabled - storage version < 1.1.0\");\n    }\n\n    // Check cache first\n    const cacheKey = Buffer.from(key).toString(\"hex\");\n    const cachedFastNode = this.fastNodeCache.get(cacheKey);\n    if (cachedFastNode) {\n      this.logger?.debug(\"Fast node cache hit\", {\n        key: cacheKey,\n      });\n      incFastCacheHitCnt(this.opts.statistics);\n      return cachedFastNode;\n    }\n\n    this.logger?.debug(\"Fast node cache miss\", {\n      key: cacheKey,\n    });\n    incFastCacheMissCnt(this.opts.statistics);\n\n    // Load from database\n    const dbKey = this.fastNodeKey(key);\n    const bytes = await this.db.get(dbKey);\n\n    if (!bytes) {\n      return null;\n    }\n\n    // Deserialize fast node\n    const {\n      FastNode: FastNodeClass,\n    } = await import(\"./fast-node.js\");\n    const fastNode = FastNodeClass.fromBytes(key, bytes);\n\n    // Add to cache\n    this.fastNodeCache.add(cacheKey, fastNode);\n\n    return fastNode;\n  }\n\n  /**\n   * Get iterator for fast prefix and error, if any.\n   * Creates a database iterator over the fast node key range.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go getFastIterator (lines 1031-1052)\n   *\n   * @param start - Start key (inclusive), null for beginning\n   * @param end - End key (exclusive), null for end\n   * @param ascending - True for forward iteration, false for reverse\n   * @returns Database iterator\n   * @internal\n   */\n  getFastIterator(\n    start: Uint8Array | null,\n    end: Uint8Array | null,\n    ascending: boolean,\n  ): Promise<Iterator> {\n    let startFormatted: Uint8Array;\n    let endFormatted: Uint8Array;\n\n    if (start !== null) {\n      startFormatted = this.fastNodeKey(start);\n    }\n    else {\n      // Start from beginning of fast node prefix\n      startFormatted = fastKeyFormat.key(new Uint8Array(0));\n    }\n\n    if (end !== null) {\n      endFormatted = this.fastNodeKey(end);\n    }\n    else {\n      // End at next prefix ('f' = 0x66, next is 'g' = 0x67)\n      endFormatted = new Uint8Array([\"g\".charCodeAt(0)]);\n    }\n\n    if (ascending) {\n      return this.db.iterator(startFormatted, endFormatted);\n    }\n\n    return this.db.reverseIterator(startFormatted, endFormatted);\n  }\n\n  /**\n   * Returns whether fast storage has been enabled.\n   *\n   * @returns true if storage version >= 1.1.0 (fast storage)\n   */\n  hasUpgradedToFastStorage(): boolean {\n    return this.storageVersion >= FAST_STORAGE_VERSION;\n  }\n\n  /**\n   * Gets the storage version string.\n   *\n   * @returns Storage version\n   */\n  getStorageVersion(): string {\n    return this.storageVersion;\n  }\n\n  /**\n   * Gets the first version stored in this database.\n   *\n   * @returns First version number\n   */\n  getFirstVersion(): bigint {\n    return this.firstVersion;\n  }\n\n  /**\n   * Gets the latest version stored in this database.\n   *\n   * @returns Latest version number\n   */\n  getLatestVersion(): bigint {\n    return this.latestVersion;\n  }\n\n  /**\n   * Returns all available version numbers in the tree.\n   * Scans the database for all saved root keys.\n   * Returns empty array if no versions have been saved.\n   *\n   * Corresponds to Go's NodeDB getVersions() (used by MutableTree.AvailableVersions())\n   *\n   * @returns Sorted array of all saved version numbers\n   */\n  async getVersions(): Promise<bigint[]> {\n    const versions: bigint[] = [];\n\n    // Root keys are stored as node keys with format: 's' + version (8 bytes) + nonce (4 bytes = 1)\n    // For roots, nonce is always 1\n    const prefix = Buffer.from([NODE_KEY_PREFIX]); // 's' prefix\n\n    // Create an iterator starting from the node key prefix\n    const iter = await this.db.iterator(prefix, undefined);\n\n    try {\n      while (iter.valid()) {\n        const key = iter.key();\n\n        // Check if this is a node key (starts with NODE_KEY_PREFIX='s')\n        if (key.length > 0 && key[0] === NODE_KEY_PREFIX) {\n          // Node keys are: 's' + version (8 bytes) + nonce (4 bytes)\n          // Root keys have nonce = 1\n          if (key.length === 13) {\n            // Check if nonce is 1 (root key)\n            const nonceView = new DataView(key.buffer, key.byteOffset + 9, 4);\n            const nonce = nonceView.getUint32(0, false); // big-endian\n\n            if (nonce === 1) {\n              // This is a root key, extract version\n              const versionBytes = key.slice(1, 9);\n              const versionView = new DataView(versionBytes.buffer, versionBytes.byteOffset, 8);\n              const version = versionView.getBigUint64(0, false); // big-endian\n              versions.push(version);\n            }\n          }\n        }\n        else {\n          // No longer in node key range\n          break;\n        }\n\n        iter.next();\n      }\n    }\n    finally {\n      iter.close();\n    }\n\n    // Sort versions in ascending order\n    versions.sort((a, b) => Number(a - b));\n\n    return versions;\n  }\n\n  /**\n   * Gets the latest version in legacy (hash-based) format.\n   * Returns 0n if not yet loaded, -1n if no legacy versions exist.\n   *\n   * @returns Latest legacy version number\n   */\n  async getLegacyLatestVersion(): Promise<bigint> {\n    // Return cached value if already loaded\n    if (this.legacyLatestVersion !== 0n) {\n      return this.legacyLatestVersion;\n    }\n\n    // Scan for the highest legacy root version\n    // Legacy roots use prefix 'r' + version (8 bytes big-endian)\n    const startKey = this.legacyRootKey(1n);\n    const endKey = this.legacyRootKey(BigInt(Number.MAX_SAFE_INTEGER));\n\n    const iter = await this.db.reverseIterator(startKey, endKey);\n    try {\n      if (iter.valid()) {\n        const key = iter.key();\n        const view = new DataView(key.buffer, key.byteOffset, key.byteLength);\n        const version = view.getBigInt64(1, false); // Read big-endian int64\n        this.resetLegacyLatestVersion(version);\n        return version;\n      }\n\n      // No legacy versions found\n      this.resetLegacyLatestVersion(-1n);\n      return -1n;\n    }\n    finally {\n      iter.close();\n    }\n  }\n\n  /**\n   * Sets the cached legacy latest version.\n   *\n   * @param version - Version to set\n   */\n  private resetLegacyLatestVersion(version: bigint): void {\n    this.legacyLatestVersion = version;\n  }\n\n  /**\n   * Gets the configuration options for this NodeDB.\n   *\n   * @returns Options object\n   */\n  getOptions(): Options {\n    return this.opts;\n  }\n\n  /**\n   * Checks if a version exists in the database.\n   *\n   * @param version - Version number to check\n   * @returns True if version exists\n   */\n  async versionExists(version: bigint): Promise<boolean> {\n    const rootKey = this.rootKey(version);\n    return await this.db.has(rootKey);\n  }\n\n  /**\n   * Gets the root node key for a specific version.\n   * Returns null if version doesn't exist or has empty root.\n   *\n   * Based on Go IAVL nodedb.go GetRoot() - handles both stored references\n   * and implicit root keys (when root version == stored version with nonce=1).\n   *\n   * @param version - Version number\n   * @returns Root node key or null\n   */\n  async getRoot(version: bigint): Promise<Uint8Array | null> {\n    const rootKey = this.rootKey(version);\n    let value = await this.db.get(rootKey);\n    let isLegacy = false;\n\n    // If not found in new format, check legacy format\n    if (!value) {\n      const legacyKey = this.legacyRootKey(version);\n      value = await this.db.get(legacyKey);\n      isLegacy = true;\n    }\n\n    if (!value) {\n      // No value stored - check if implicit root exists\n      // If root node has version==version and nonce==1, it's implicitly the root\n      const implicitRootKey = getRootKey(version);\n      const nodeKey = this.nodeKey(implicitRootKey);\n      const nodeExists = await this.db.has(nodeKey);\n      if (nodeExists) {\n        return implicitRootKey;\n      }\n      return null;\n    }\n\n    // Empty root is stored as empty bytes\n    if (value.length === 0) {\n      return null;\n    }\n\n    // If value came from legacy location, return it as-is (legacy hash)\n    // Matches Go IAVL nodedb.go GetRoot() legacy handling\n    if (isLegacy) {\n      return value;\n    }\n\n    // Value from new format location could be:\n    // 1. A reference to another node (starts with 's' prefix = 0x73)\n    // 2. Anything else (should not happen in normal operation)\n    //\n    // References are detected by checking if first byte is NODE_KEY_PREFIX ('s' = 0x73).\n    // If it's a reference, strip the prefix and return the nodeKey.\n    // If it's NOT a reference, the root IS at the implicit location GetRootKey(version).\n    //\n    // Matches Go IAVL nodedb.go GetRoot() and isReferenceRoot() logic.\n    const NODE_KEY_PREFIX_LENGTH = 1;\n\n    // Check if value is a reference (starts with node key prefix 's')\n    if (value[0] === NODE_KEY_PREFIX) {\n      // It's a prefixed reference - strip the prefix to get nodeKey\n      return value.slice(NODE_KEY_PREFIX_LENGTH);\n    }\n\n    // Not a reference - root node IS stored at the implicit root key\n    // This handles edge cases and malformed data\n    return getRootKey(version);\n  }\n\n  /**\n   * Saves an empty root for a version.\n   *\n   * @param version - Version number\n   */\n  async saveEmptyRoot(version: bigint): Promise<void> {\n    const rootKey = this.rootKey(version);\n    await this.batch.set(rootKey, new Uint8Array(0));\n  }\n\n  /**\n   * Saves a root reference for a version.\n   * Stores the prefixed nodeKey as the value, matching Go IAVL's SaveRoot.\n   *\n   * @param version - Version number\n   * @param nodeKey - Node key of the root node (unprefixed)\n   */\n  async saveRoot(version: bigint, nodeKey: Uint8Array): Promise<void> {\n    const rootKey = this.rootKey(version);\n    // Store prefixed nodeKey, matching Go: nodeKeyFormat.Key(nk.GetKey())\n    const prefixedNodeKey = this.nodeKey(nodeKey);\n    await this.batch.set(rootKey, prefixedNodeKey);\n  }\n\n  /**\n   * Commits any pending batch operations to the database.\n   * Writes all buffered operations and starts a new batch.\n   *\n   * If sync option is enabled, performs a synchronous write with fsync\n   * to ensure data is flushed to disk (matching Go implementation).\n   */\n  async commit(): Promise<void> {\n    // Write the current batch to database\n    // Use sync write if enabled (ensures data is flushed to disk)\n    if (this.opts.sync) {\n      await this.batch.writeSync();\n    }\n    else {\n      await this.batch.write();\n    }\n\n    // Create a new batch for subsequent operations\n    this.batch = new AsyncBatchWithFlusher(this.db, this.opts.flushThreshold);\n  }\n\n  /**\n   * Resets the latest version tracker.\n   * Called after successfully saving a version.\n   * If this is the first version (firstVersion is 0), also sets firstVersion.\n   *\n   * @param version - New latest version\n   */\n  resetLatestVersion(version: bigint): void {\n    this.latestVersion = version;\n\n    // If this is the first version being saved, set firstVersion\n    if (this.firstVersion === 0n) {\n      this.firstVersion = version;\n    }\n  }\n\n  /**\n   * Sets the fast storage version in the batch.\n   * Updates storage version metadata with fast storage version.\n   *\n   * @param version - Latest version for fast storage\n   */\n  async setFastStorageVersionToBatch(version: bigint): Promise<void> {\n    // Get current storage version\n    const parts = this.storageVersion.split(\"-\");\n    const baseVersion = parts[0];\n\n    // Format: \"1.1.0-{version}\"\n    const newVersion = `${baseVersion}-${version}`;\n\n    // Save to metadata\n    const versionKey = this.metadataKey(stringToBytes(\"version\"));\n    await this.batch.set(versionKey, stringToBytes(newVersion));\n\n    this.storageVersion = newVersion;\n  }\n\n  /**\n   * Deletes a fast node from storage.\n   *\n   * @param key - Key to delete\n   */\n  async deleteFastNode(key: Uint8Array): Promise<void> {\n    const dbKey = this.fastNodeKey(key);\n    await this.batch.delete(dbKey);\n\n    // Remove from cache if present\n    const keyStr = Buffer.from(key).toString(\"hex\");\n    this.fastNodeCache.remove(keyStr);\n  }\n\n  /**\n   * Closes the database connection.\n   */\n  async close(): Promise<void> {\n    await this.db.close();\n  }\n\n  // ==================== Key Formatting Methods ====================\n\n  /**\n   * Formats a node key for storage.\n   * Format: 's' + nodeKey bytes (version + nonce)\n   *\n   * @param _nodeKey - The node key bytes\n   * @returns Database key\n   */\n  /**\n   * Constructs a database key for a node\n   * @internal\n   */\n  nodeKey(_nodeKey: Uint8Array): Uint8Array {\n    // For regular node keys, just add 's' prefix\n    // Node keys are already formatted as <version><nonce>\n    const key = new Uint8Array(1 + _nodeKey.length);\n    key[0] = NODE_KEY_PREFIX;\n    key.set(_nodeKey, 1);\n    return key;\n  }\n\n  /**\n   * Formats a fast node key for storage.\n   * Format: 'f' + key bytes\n   *\n   * @param _key - The key bytes\n   * @returns Database key\n   */\n  private fastNodeKey(_key: Uint8Array): Uint8Array {\n    return fastKeyFormat.key(_key);\n  }\n\n  /**\n   * Formats a metadata key for storage.\n   * Format: 'm' + key bytes\n   *\n   * @param key - The metadata key bytes\n   * @returns Database key\n   */\n  private metadataKey(key: Uint8Array): Uint8Array {\n    return metadataKeyFormat.key(key);\n  }\n\n  /**\n   * Creates a root key for a given version.\n   * Root keys are node keys with nonce = 1.\n   *\n   * @param version - Version number\n   * @returns Database key for the root\n   */\n  /**\n   * Constructs a database key for a root at a given version\n   * @internal\n   */\n  rootKey(version: bigint): Uint8Array {\n    return this.nodeKey(getRootKey(version));\n  }\n\n  /**\n   * Deletes a specific version from the database.\n   * This removes the root reference and all nodes unique to this version.\n   *\n   * Uses traverseOrphans to identify and delete all nodes that existed in the\n   * deleted version but don't exist in the next version (orphaned nodes).\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    // Check version exists\n    const exists = await this.versionExists(version);\n    if (!exists) {\n      throw new Error(`version ${version} does not exist`);\n    }\n\n    // Cannot delete the latest version\n    if (version === this.latestVersion) {\n      throw new Error(`cannot delete latest version ${version}`);\n    }\n\n    // Traverse and delete all orphaned nodes\n    // Orphans are nodes that exist in version but not in version+1\n    await this.traverseOrphans(version, version + 1n, async (orphan) => {\n      try {\n        const nodeKey = orphan.getNodeKey();\n        // Delete the node from storage\n        await this.deleteFromPruning(this.nodeKey(nodeKey));\n      }\n      catch (err) {\n        // Skip nodes without valid keys\n        if (err instanceof Error && err.message.includes(\"must have\")) {\n          return;\n        }\n        throw err;\n      }\n    });\n\n    // Delete the root reference for this version\n    const rootKey = this.rootKey(version);\n    await this.batch.delete(rootKey);\n  }\n\n  /**\n   * Deletes all versions from firstVersion up to and including toVersion.\n   * Updates firstVersion to toVersion + 1 after deletion.\n   *\n   * If asyncPruning is enabled, this queues the deletion for background processing.\n   * Otherwise, performs synchronous deletion.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go DeleteVersionsTo (lines 653-663)\n   *\n   * @param toVersion - Delete all versions up to and including this (inclusive)\n   * @throws Error if toVersion >= latestVersion or if versions have active readers\n   */\n  async deleteVersionsTo(toVersion: bigint): Promise<void> {\n    // If async pruning is enabled, queue the request\n    if (this.opts.asyncPruning) {\n      this.pruneVersion = toVersion;\n      return;\n    }\n\n    // Otherwise, perform synchronous deletion\n    await this.deleteVersionsToSync(toVersion);\n  }\n\n  /**\n   * Performs synchronous deletion of versions.\n   * This is the actual deletion logic, used by both sync and async modes.\n   *\n   * @param toVersion - Delete all versions up to and including this (inclusive)\n   * @throws Error if toVersion >= latestVersion or if versions have active readers\n   */\n  private async deleteVersionsToSync(toVersion: bigint): Promise<void> {\n    const first = this.firstVersion;\n    const latest = this.latestVersion;\n\n    // Validate bounds\n    if (toVersion >= latest) {\n      throw new Error(\n        `toVersion ${toVersion} must be less than latest version ${latest}`,\n      );\n    }\n\n    if (toVersion < first) {\n      // Nothing to delete\n      return;\n    }\n\n    // Delete each version from first to toVersion (inclusive)\n    for (let v = first; v <= toVersion; v++) {\n      try {\n        await this.deleteVersion(v);\n      }\n      catch (err) {\n        // If version doesn't exist, skip it (may have been deleted already)\n        if (err instanceof Error && err.message.includes(\"does not exist\")) {\n          continue;\n        }\n        throw err;\n      }\n    }\n\n    // Update first version to the next version after deleted ones\n    this.firstVersion = toVersion + 1n;\n  }\n\n  /**\n   * Deletes all versions from fromVersion upwards (including fromVersion).\n   * Updates latestVersion to fromVersion-1 after deletion.\n   *\n   * @param fromVersion - Delete all versions from this onwards (inclusive)\n   * @throws Error if versions have active readers\n   */\n  async deleteVersionsFrom(fromVersion: bigint): Promise<void> {\n    const latest = this.latestVersion;\n\n    // Validate bounds\n    if (fromVersion > latest) {\n      // Nothing to delete\n      return;\n    }\n\n    // Delete all nodes in the version range [fromVersion, latest+1)\n    // Node keys have format: 's' + version (8 bytes) + nonce (4 bytes)\n    // We can safely delete all nodes in this range because:\n    // 1. We're deleting future history\n    // 2. Nodes can only reference nodes from same or earlier versions\n    // 3. Earlier versions cannot reference nodes created in later versions\n\n    // Create start key: 's' + fromVersion (8 bytes)\n    const startKey = new Uint8Array(1 + 8);\n    const startView = new DataView(startKey.buffer);\n    startKey[0] = NODE_KEY_PREFIX;\n    startView.setBigUint64(1, fromVersion, false); // big-endian\n\n    // Create end key: 's' + (latest+1) (8 bytes)\n    const endKey = new Uint8Array(1 + 8);\n    const endView = new DataView(endKey.buffer);\n    endKey[0] = NODE_KEY_PREFIX;\n    endView.setBigUint64(1, latest + 1n, false); // big-endian\n\n    // Delete all node keys in range\n    const iter = await this.db.iterator(startKey, endKey);\n    try {\n      while (iter.valid()) {\n        const key = iter.key();\n        await this.batch.delete(key);\n        iter.next();\n      }\n    }\n    finally {\n      iter.close();\n    }\n\n    // Delete root keys for all versions in range\n    for (let v = fromVersion; v <= latest; v++) {\n      const rootKey = this.rootKey(v);\n      try {\n        await this.batch.delete(rootKey);\n      }\n      catch {\n        // Ignore if root doesn't exist\n      }\n    }\n\n    // Update latest version\n    this.latestVersion = fromVersion - 1n;\n  }\n\n  /**\n   * Resets the first version number.\n   * Used internally after version deletion.\n   *\n   * @param version - New first version\n   */\n  private resetFirstVersion(version: bigint): void {\n    this.firstVersion = version;\n  }\n\n  /**\n   * Creates a legacy orphan key.\n   * Format: 'o'<lastVersion><firstVersion><hash>\n   *\n   * @param lastVersion - Last version this node existed in\n   * @param firstVersion - First version this node existed in\n   * @param hash - Node hash\n   * @returns Orphan key bytes\n   */\n  private legacyOrphanKey(\n    lastVersion: bigint,\n    firstVersion: bigint,\n    hash: Uint8Array,\n  ): Uint8Array {\n    // Calculate total size: prefix (1) + lastVersion (8) + firstVersion (8) + hash\n    const key = new Uint8Array(1 + 8 + 8 + hash.length);\n    const view = new DataView(key.buffer);\n\n    // Set prefix\n    key[0] = LEGACY_ORPHAN_KEY_PREFIX;\n\n    // Set lastVersion (big-endian)\n    view.setBigUint64(1, lastVersion, false);\n\n    // Set firstVersion (big-endian)\n    view.setBigUint64(9, firstVersion, false);\n\n    // Set hash\n    key.set(hash, 17);\n\n    return key;\n  }\n\n  /**\n   * Creates a legacy node key (hash-based format).\n   * Format: 'n'<hash>\n   *\n   * @param hash - Node hash (32 bytes)\n   * @returns Legacy node key bytes\n   */\n  private legacyNodeKey(hash: Uint8Array): Uint8Array {\n    const key = new Uint8Array(1 + hash.length);\n    key[0] = LEGACY_NODE_KEY_PREFIX;\n    key.set(hash, 1);\n    return key;\n  }\n\n  /**\n   * Creates a legacy root key.\n   * Format: 'r'<version>\n   *\n   * @param version - Tree version\n   * @returns Legacy root key bytes\n   */\n  private legacyRootKey(version: bigint): Uint8Array {\n    const key = new Uint8Array(1 + 8);\n    const view = new DataView(key.buffer);\n    key[0] = LEGACY_ROOT_KEY_PREFIX;\n    view.setBigInt64(1, BigInt.asIntN(64, version), false);\n    return key;\n  }\n\n  /**\n   * Saves a node during pruning/cleanup operations.\n   * This is used to track nodes that need to be deleted when cleaning up old versions.\n   *\n   * Note: In Go, this method handles commit synchronization. In our single-threaded\n   * JS environment, we don't need that complexity.\n   *\n   * @param node - Node to save for pruning\n   */\n  async saveNodeFromPruning(node: Node): Promise<void> {\n    // Encode and save the node\n    const nodeKey = node.getNodeKey();\n    const nodeBytes = node.toBytes();\n    await this.batch.set(this.nodeKey(nodeKey), nodeBytes);\n  }\n\n  /**\n   * Deletes a key during pruning/cleanup operations.\n   *\n   * Note: In Go, this method handles commit synchronization. In our single-threaded\n   * JS environment, we don't need that complexity.\n   *\n   * @param key - Key to delete\n   */\n  async deleteFromPruning(key: Uint8Array): Promise<void> {\n    await this.batch.delete(key);\n  }\n\n  /**\n   * Traverses orphaned nodes between two versions.\n   *\n   * An orphaned node is one that exists in prevVersion but not in curVersion.\n   * This is determined by comparing the tree structures using parallel iterators.\n   *\n   * The algorithm:\n   * 1. Create iterators for both prevVersion and curVersion trees\n   * 2. For each node in prevVersion tree:\n   *    a. Find matching \"original\" node in curVersion (node.version <= prevVersion)\n   *    b. If hashes match, both trees share this node - skip it\n   *    c. If no match or different hash, node is orphaned - call callback\n   *\n   * This is used during DeleteVersion to identify nodes that need cleanup.\n   *\n   * @param prevVersion - Previous version to compare from\n   * @param curVersion - Current version to compare to\n   * @param fn - Callback function for each orphaned node\n   */\n  async traverseOrphans(\n    prevVersion: bigint,\n    curVersion: bigint,\n    fn: (node: Node) => Promise<void>,\n  ): Promise<void> {\n    // Import NodeIterator here to avoid circular dependency\n    const {\n      NodeIterator,\n    } = await import(\"./node-iterator.js\");\n\n    // Get root keys for both versions\n    const curKey = await this.getRoot(curVersion);\n    const prevKey = await this.getRoot(prevVersion);\n\n    // Create iterators\n    const curIter = await NodeIterator.create(curKey, this);\n    const prevIter = await NodeIterator.create(prevKey, this);\n\n    // Track the current \"original\" node from curVersion tree\n    // (original = node with version <= prevVersion)\n    let orgNode: Node | null = null;\n\n    // Iterate through all nodes in prevVersion tree\n    while (prevIter.valid()) {\n      // Find the next original node in curVersion tree\n      // Original nodes are those that existed at or before prevVersion\n      while (orgNode === null && curIter.valid()) {\n        const node = curIter.getNode();\n        const nodeVersion = node.nodeKey?.version;\n\n        if (nodeVersion !== undefined && nodeVersion <= prevVersion) {\n          // This is an original node (existed in prevVersion)\n          await curIter.next(true); // Skip its children (we found it)\n          orgNode = node;\n        }\n        else {\n          // This is a new node (created after prevVersion)\n          await curIter.next(false); // Continue traversing\n        }\n      }\n\n      const pNode = prevIter.getNode();\n\n      // Compare hashes to see if this node is orphaned\n      if (\n        orgNode !== null\n        && pNode.hash\n        && orgNode.hash\n        && this.hashesEqual(pNode.hash, orgNode.hash)\n      ) {\n        // Hashes match - this node exists in both versions\n        // Skip the subtree (it's shared between versions)\n        await prevIter.next(true);\n        orgNode = null;\n      }\n      else {\n        // Node is orphaned (doesn't exist in curVersion or has different hash)\n        await fn(pNode);\n        await prevIter.next(false);\n      }\n    }\n\n    // Check for errors\n    if (curIter.error()) {\n      throw curIter.error()!;\n    }\n    if (prevIter.error()) {\n      throw prevIter.error()!;\n    }\n  }\n\n  /**\n   * Helper to compare two hash arrays for equality.\n   *\n   * @param a - First hash\n   * @param b - Second hash\n   * @returns true if hashes are equal\n   */\n  private hashesEqual(a: Uint8Array, b: Uint8Array): boolean {\n    if (a.length !== b.length) {\n      return false;\n    }\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] !== b[i]) {\n        return false;\n      }\n    }\n    return true;\n  }\n\n  /**\n   * Helper method to get an empty ImmutableTree at a given version.\n   * Used primarily for testing to create initial tree instances.\n   *\n   * @param version - Version number for the tree\n   * @returns Promise resolving to empty ImmutableTree instance\n   */\n  async getImmutableTree(version: bigint): Promise<ImmutableTree> {\n    return new ImmutableTree(\n      null,\n      this,\n      version,\n      this.opts.skipFastStorageUpgrade ?? false,\n    );\n  }\n\n  // ==================== Async Pruning Methods ====================\n\n  /**\n   * Sets the committing flag to indicate that a commit is in progress.\n   * This prevents the async pruning worker from interfering with the commit.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go SetCommitting (lines 275-284)\n   */\n  setCommitting(): void {\n    // Wait for any pending commit to complete\n    if (this.commitCompletePromise) {\n      // Drain the promise by resetting it\n      this.commitCompletePromise = null;\n      this.commitCompleteResolve = null;\n    }\n\n    // Set committing flag\n    this._isCommitting = true;\n  }\n\n  /**\n   * Unsets the committing flag to indicate that the commit is complete.\n   * This signals the async pruning worker that it can continue.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go UnsetCommitting (lines 286-293)\n   */\n  unsetCommitting(): void {\n    // Clear committing flag\n    this._isCommitting = false;\n\n    // Signal commit complete\n    if (this.commitCompleteResolve) {\n      this.commitCompleteResolve();\n    }\n  }\n\n  /**\n   * Returns true if a commit is currently in progress.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go IsCommitting (lines 295-299)\n   */\n  isCommitting(): boolean {\n    return this._isCommitting;\n  }\n\n  /**\n   * Starts the async pruning worker.\n   * The worker runs in the background and processes pruning requests.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go startPruning (lines 621-651)\n   */\n  private startPruningWorker(): void {\n    this.pruningAbortController = new AbortController();\n    const signal = this.pruningAbortController.signal;\n\n    // Run the pruning loop asynchronously\n    (async () => {\n      while (!signal.aborted) {\n        try {\n          // Check if there's a version to prune\n          const toVersion = this.pruneVersion;\n\n          if (toVersion === 0n) {\n            // No pruning needed, wait a bit\n            await sleep(100, signal);\n            continue;\n          }\n\n          // Wait for commit to complete if in progress\n          if (this.isCommitting()) {\n            await this.waitForCommitComplete(signal);\n          }\n\n          // Perform the pruning (bypassing async mode)\n          await this.deleteVersionsToSync(toVersion);\n\n          // Commit the batch after pruning\n          await this.commit();\n\n          // Clear the prune version if it hasn't been updated\n          if (this.pruneVersion <= toVersion) {\n            this.pruneVersion = 0n;\n          }\n        }\n        catch (err) {\n          // Check if error is due to abort\n          if (signal.aborted) {\n            break;\n          }\n\n          // Log error and wait before retrying\n          this.logger?.error(\"Error during async pruning\", {\n            error: err,\n          });\n          await sleep(1000, signal);\n        }\n      }\n    })().catch((err) => {\n      // Only log if not aborted\n      if (!signal.aborted) {\n        this.logger?.error(\"Pruning worker crashed\", {\n          error: err,\n        });\n      }\n    });\n  }\n\n  /**\n   * Waits for the current commit to complete.\n   *\n   * @param signal - Abort signal to cancel the wait\n   */\n  private async waitForCommitComplete(signal: AbortSignal): Promise<void> {\n    if (!this.commitCompletePromise) {\n      this.commitCompletePromise = new Promise((resolve) => {\n        this.commitCompleteResolve = resolve;\n      });\n    }\n\n    // Race between commit complete and abort signal\n    await Promise.race([\n      this.commitCompletePromise,\n      new Promise((_, reject) => {\n        signal.addEventListener(\"abort\", () => reject(new Error(\"Aborted\")));\n      }),\n    ]);\n  }\n\n  /**\n   * Stops the async pruning worker.\n   * Should be called when closing the database.\n   */\n  stopPruningWorker(): void {\n    if (this.pruningAbortController) {\n      this.pruningAbortController.abort();\n      this.pruningAbortController = null;\n    }\n  }\n\n  // ==================== Statistics Methods ====================\n\n  /**\n   * Gets the current statistics for this NodeDB.\n   * Returns undefined if statistics tracking is not enabled.\n   *\n   * Based on Go IAVL v1.3.5 options.go Statistics getters\n   *\n   * @returns Statistics object or undefined\n   */\n  getStatistics(): Statistics | undefined {\n    return this.opts.statistics;\n  }\n\n  // ==================== Legacy Migration Methods ====================\n\n  /**\n   * Gets all legacy nodes (hash-based format) from the database.\n   * Used for migration and verification purposes.\n   *\n   * @returns Array of legacy nodes\n   */\n  async legacyNodes(): Promise<Node[]> {\n    const nodes: Node[] = [];\n    const prefix = new Uint8Array([LEGACY_NODE_KEY_PREFIX]);\n    const iter = await this.db.iterator(prefix, new Uint8Array([LEGACY_NODE_KEY_PREFIX + 1]));\n\n    try {\n      while (iter.valid()) {\n        const key = iter.key();\n        const value = iter.value();\n\n        // Skip the prefix byte to get the hash\n        const hash = key.slice(1);\n\n        // Import Node.fromBytes to parse legacy nodes\n        const {\n          Node: NodeClass,\n        } = await import(\"../node.js\");\n        const node = NodeClass.fromBytes(hash, value);\n\n        nodes.push(node);\n        iter.next();\n      }\n    }\n    finally {\n      iter.close();\n    }\n\n    return nodes;\n  }\n\n  /**\n   * Traverses state changes between a range of versions.\n   * For each version in the range, it extracts the changes from the previous version\n   * and calls the callback function with the version number and the ChangeSet.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go traverseStateChanges\n   *\n   * @param startVersion - First version to extract changes for\n   * @param endVersion - Last version to extract changes for\n   * @param fn - Callback function to receive changes\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    // Get first version\n    const firstVersion = this.getFirstVersion();\n    if (startVersion < firstVersion) {\n      startVersion = firstVersion;\n    }\n\n    // Get latest version\n    const latestVersion = this.latestVersion;\n    if (endVersion > latestVersion) {\n      endVersion = latestVersion;\n    }\n\n    // Get previous version root (may not exist)\n    let prevVersion = startVersion - 1n;\n    let prevRoot: Uint8Array | null = null;\n    if (prevVersion >= 0n) {\n      try {\n        prevRoot = await this.getRoot(prevVersion);\n      }\n      catch {\n        // Previous version doesn't exist, that's ok\n        prevRoot = null;\n      }\n    }\n\n    // Iterate through each version\n    for (let version = startVersion; version <= endVersion; version++) {\n      const root = await this.getRoot(version);\n\n      // Collect changes for this version\n      const pairs: KVPair[] = [];\n      const receiveKVPair = async (pair: KVPair): Promise<void> => {\n        pairs.push(pair);\n      };\n\n      // Extract state changes between prevRoot and current root\n      if (root) {\n        await this.extractStateChanges(prevVersion, prevRoot, root, receiveKVPair);\n      }\n\n      // Call callback with the changeset\n      const changeSet: ChangeSet = {\n        pairs,\n      };\n\n      const stop = await fn(version, changeSet);\n      if (stop === true) {\n        return;\n      }\n\n      // Move to next version\n      prevVersion = version;\n      prevRoot = root;\n    }\n  }\n\n  /**\n   * Extracts state changes between two tree versions.\n   * This implements the diff algorithm from Go IAVL v1.3.5 diff.go\n   *\n   * The algorithm traverses both trees simultaneously:\n   * 1. Advances through the current tree until reaching a shared node\n   * 2. Records new leaf nodes during traversal\n   * 3. Traverses the previous tree to find orphaned nodes\n   * 4. Compares orphaned and new nodes to generate KVPair stream\n   *\n   * @param prevVersion - Previous version number\n   * @param prevRoot - Root node key of previous version (null if no previous version)\n   * @param root - Root node key of current version\n   * @param receiver - Callback to receive KVPair changes\n   * @returns Promise that resolves when extraction is complete\n   */\n  private async extractStateChanges(\n    prevVersion: bigint,\n    prevRoot: Uint8Array | null,\n    root: Uint8Array,\n    receiver: (pair: KVPair) => Promise<void>,\n  ): Promise<void> {\n    const {\n      NodeIterator,\n    } = await import(\"./node-iterator.js\");\n\n    // Create iterators for both trees\n    const curIter = await NodeIterator.create(root, this);\n    const prevIter = await NodeIterator.create(prevRoot, this);\n\n    // Current shared node between two versions\n    let sharedNode: Node | null = null;\n\n    // New leaf nodes found during traversal to shared node\n    const newLeaves: Node[] = [];\n\n    /**\n     * Consumes remaining newLeaves nodes and produces insertion KVPairs\n     */\n    const consumeNewLeaves = async (): Promise<void> => {\n      for (const node of newLeaves) {\n        if (!node.key || !node.value) {\n          throw new Error(\"Leaf node must have key and value\");\n        }\n        await receiver({\n          delete: false,\n          key: node.key,\n          value: node.value,\n        });\n      }\n      newLeaves.length = 0;\n    };\n\n    /**\n     * Advances curIter until the next shared node.\n     * Records new leaf nodes during traversal.\n     * Sets sharedNode to null if current version is exhausted.\n     */\n    const advanceSharedNode = async (): Promise<void> => {\n      await consumeNewLeaves();\n\n      sharedNode = null;\n      while (curIter.valid()) {\n        const node = curIter.getNode();\n        const shared = (node.nodeKey?.version ?? 0n) <= prevVersion;\n\n        await curIter.next(shared);\n\n        if (shared) {\n          sharedNode = node;\n          break;\n        }\n        else if (node.isLeaf()) {\n          newLeaves.push(node);\n        }\n      }\n    };\n\n    // Initialize by finding first shared node\n    await advanceSharedNode();\n\n    /**\n     * Processes an orphaned leaf node from the previous version.\n     * Compares with newLeaves to produce KVPair changes.\n     */\n    const addOrphanedLeaf = async (orphaned: Node): Promise<void> => {\n      if (!orphaned.key) {\n        throw new Error(\"Orphaned leaf node must have key\");\n      }\n\n      while (newLeaves.length > 0) {\n        const newLeaf = newLeaves[0];\n\n        if (!newLeaf.key || !newLeaf.value) {\n          throw new Error(\"New leaf node must have key and value\");\n        }\n\n        // Compare keys\n        const cmp = Buffer.compare(\n          Buffer.from(orphaned.key),\n          Buffer.from(newLeaf.key),\n        );\n\n        if (cmp > 0) {\n          // New key is smaller - it's an insertion\n          newLeaves.shift();\n          await receiver({\n            delete: false,\n            key: newLeaf.key,\n            value: newLeaf.value,\n          });\n          continue;\n        }\n        else if (cmp < 0) {\n          // Orphaned key is smaller - it's a deletion\n          await receiver({\n            delete: true,\n            key: orphaned.key,\n            value: new Uint8Array(0),\n          });\n          return;\n        }\n        else {\n          // Keys are equal - it's an update\n          newLeaves.shift();\n          await receiver({\n            delete: false,\n            key: newLeaf.key,\n            value: newLeaf.value,\n          });\n          return;\n        }\n      }\n\n      // No more new leaves - this is a deletion\n      await receiver({\n        delete: true,\n        key: orphaned.key,\n        value: new Uint8Array(0),\n      });\n    };\n\n    /**\n     * Traverse previous tree to find orphaned nodes\n     */\n    while (prevIter.valid()) {\n      const node = prevIter.getNode();\n\n      // Check if this node is shared\n      let shared = false;\n\n      if (sharedNode) {\n        // TypeScript has control-flow narrowing issues here, so we explicitly type the variable\n        const currentShared: Node = sharedNode;\n\n        // Check for reference equality\n        shared = (node === currentShared);\n\n        // If not the same reference, check hash equality\n        if (!shared && node.hash !== null && currentShared.hash !== null) {\n          shared = Buffer.compare(Buffer.from(node.hash), Buffer.from(currentShared.hash)) === 0;\n        }\n      }\n\n      // Skip subtree of shared nodes\n      await prevIter.next(shared);\n\n      if (shared) {\n        // Advance to next shared node in current tree\n        await advanceSharedNode();\n      }\n      else if (node.isLeaf()) {\n        // Process orphaned leaf\n        await addOrphanedLeaf(node);\n      }\n    }\n\n    // Consume any remaining new leaves\n    await consumeNewLeaves();\n\n    // Check for errors\n    if (curIter.error()) {\n      throw curIter.error();\n    }\n    if (prevIter.error()) {\n      throw prevIter.error();\n    }\n  }\n\n  /**\n   * Traverse all keys with a certain prefix.\n   * Calls the provided function for each key-value pair matching the prefix.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go traversePrefix (lines 1000-1014)\n   *\n   * @param prefix - The key prefix to search for\n   * @param fn - Callback function receiving key and value for each match\n   * @throws Error if callback returns error or iterator fails\n   */\n  async traversePrefix(\n    prefix: Uint8Array,\n    fn: (key: Uint8Array, value: Uint8Array) => Promise<void>,\n  ): Promise<void> {\n    const itr = await this.getPrefixIterator(prefix);\n\n    try {\n      while (itr.valid()) {\n        await fn(itr.key(), itr.value());\n        itr.next();\n      }\n    }\n    finally {\n      itr.close();\n    }\n  }\n\n  /**\n   * Get the iterator for a given prefix.\n   * Creates a database iterator that yields all keys starting with the prefix.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go getPrefixIterator (lines 1017-1028)\n   *\n   * @param prefix - The key prefix to iterate over\n   * @returns Promise resolving to database iterator over keys with the prefix\n   * @internal\n   */\n  getPrefixIterator(prefix: Uint8Array): Promise<Iterator> {\n    let start: Uint8Array | undefined;\n    let end: Uint8Array | undefined;\n\n    if (prefix.length === 0) {\n      // Empty prefix means iterate everything\n      start = undefined;\n      end = undefined;\n    }\n    else {\n      // Copy the prefix for start\n      start = new Uint8Array(prefix);\n      // Increment the prefix for end (exclusive upper bound)\n      end = incrementBytes(prefix);\n    }\n\n    return this.db.iterator(start, end);\n  }\n\n  /**\n   * Increments the number of active readers for a version.\n   * This prevents the version from being deleted while readers are active.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go incrVersionReaders (lines 1072-1076)\n   *\n   * Note: JavaScript is single-threaded, so no mutex is needed for this operation.\n   * The Go implementation uses a mutex because Go is multi-threaded.\n   *\n   * @param version - The version to increment readers for\n   */\n  incrVersionReaders(version: bigint): void {\n    const count = this.versionReaders.get(version) ?? 0;\n    this.versionReaders.set(version, count + 1);\n  }\n\n  /**\n   * Decrements the number of active readers for a version.\n   * When the count reaches zero, the version can be safely deleted.\n   *\n   * Based on Go IAVL v1.3.5 nodedb.go decrVersionReaders (lines 1078-1087)\n   *\n   * Note: JavaScript is single-threaded, so no mutex is needed for this operation.\n   * The Go implementation uses a mutex because Go is multi-threaded.\n   *\n   * @param version - The version to decrement readers for\n   */\n  decrVersionReaders(version: bigint): void {\n    const count = this.versionReaders.get(version) ?? 0;\n    if (count > 0) {\n      const newCount = count - 1;\n      if (newCount === 0) {\n        // Remove from map when count reaches zero (same as Go's delete)\n        this.versionReaders.delete(version);\n      }\n      else {\n        this.versionReaders.set(version, newCount);\n      }\n    }\n  }\n\n  /**\n   * Checks if a version has any active readers.\n   * Versions with active readers should not be deleted.\n   *\n   * @param version - The version to check\n   * @returns True if the version has active readers\n   */\n  hasVersionReaders(version: bigint): boolean {\n    return (this.versionReaders.get(version) ?? 0) > 0;\n  }\n\n  /**\n   * Returns a string representation of the NodeDB for debugging purposes.\n   * Shows metadata about the database including version range, storage version,\n   * and cache statistics.\n   *\n   * Corresponds to Go's nodeDB.String() but simplified version.\n   * The full Go implementation dumps all nodes which requires traverseNodes().\n   * This simplified version provides useful debug information without the full dump.\n   *\n   * @returns String representation of the database state\n   */\n  toString(): string {\n    const lines: string[] = [];\n    lines.push(\"----- NodeDB State -----\");\n    lines.push(`Storage Version: ${this.storageVersion}`);\n    lines.push(`Latest Version: ${this.latestVersion}`);\n    lines.push(`First Version: ${this.firstVersion}`);\n    lines.push(`Version Range: [${this.firstVersion}, ${this.latestVersion}]`);\n    lines.push(`Has Fast Storage: ${this.hasUpgradedToFastStorage()}`);\n\n    // Cache stats\n    const stats = this.opts.statistics;\n    if (stats) {\n      lines.push(\"\");\n      lines.push(\"Cache Statistics:\");\n      lines.push(`  Node Cache Hits: ${stats.cacheHitCnt}`);\n      lines.push(`  Node Cache Misses: ${stats.cacheMissCnt}`);\n      lines.push(`  Fast Cache Hits: ${stats.fastCacheHitCnt}`);\n      lines.push(`  Fast Cache Misses: ${stats.fastCacheMissCnt}`);\n\n      const totalNodeAccess = stats.cacheHitCnt + stats.cacheMissCnt;\n      const totalFastAccess = stats.fastCacheHitCnt + stats.fastCacheMissCnt;\n\n      if (totalNodeAccess > 0) {\n        const nodeHitRate = ((stats.cacheHitCnt / totalNodeAccess) * 100).toFixed(2);\n        lines.push(`  Node Cache Hit Rate: ${nodeHitRate}%`);\n      }\n\n      if (totalFastAccess > 0) {\n        const fastHitRate = ((stats.fastCacheHitCnt / totalFastAccess) * 100).toFixed(2);\n        lines.push(`  Fast Cache Hit Rate: ${fastHitRate}%`);\n      }\n    }\n\n    lines.push(\"-----------------------\");\n    return lines.join(\"\\n\");\n  }\n}\n\n// ==================== Helper Functions ====================\n\n/**\n * Increments a byte array by one, treating it as a big-endian number.\n * Returns undefined if the increment would overflow (all bytes are 0xFF).\n * This is used to create an exclusive upper bound for prefix iteration.\n *\n * Based on Go IAVL v1.3.5 internal/bytes/bytes.go CpIncr\n *\n * @param bz - The byte array to increment\n * @returns Incremented copy, or undefined on overflow\n */\nfunction incrementBytes(bz: Uint8Array): Uint8Array | undefined {\n  if (bz.length === 0) {\n    throw new Error(\"incrementBytes expects non-zero length\");\n  }\n\n  // Create a copy\n  const ret = new Uint8Array(bz);\n\n  // Increment from right to left (big-endian)\n  for (let i = ret.length - 1; i >= 0; i--) {\n    if (ret[i] < 0xFF) {\n      ret[i]++;\n      return ret;\n    }\n    // Set to 0 and continue carry\n    ret[i] = 0x00;\n    if (i === 0) {\n      // Overflow - all bytes were 0xFF\n      return undefined;\n    }\n  }\n\n  return ret;\n}\n\n/**\n * Converts a string to Uint8Array.\n *\n * @param str - The string to convert\n * @returns Uint8Array representation\n */\nfunction stringToBytes(str: string): Uint8Array {\n  return new TextEncoder().encode(str);\n}\n\n/**\n * Converts a Uint8Array to string.\n *\n * @param bytes - The bytes to convert\n * @returns String representation\n */\nfunction bytesToString(bytes: Uint8Array): string {\n  return new TextDecoder().decode(bytes);\n}\n\n/**\n * Sleeps for the specified duration or until the signal is aborted.\n *\n * @param ms - Duration in milliseconds\n * @param signal - Abort signal to cancel the sleep\n */\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n  return new Promise((resolve, reject) => {\n    if (signal.aborted) {\n      reject(new Error(\"Aborted\"));\n      return;\n    }\n\n    const timeout = setTimeout(() => {\n      signal.removeEventListener(\"abort\", onAbort);\n      resolve();\n    }, ms);\n\n    const onAbort = () => {\n      clearTimeout(timeout);\n      reject(new Error(\"Aborted\"));\n    };\n\n    signal.addEventListener(\"abort\", onAbort);\n  });\n}\n"],"mappings":";;;;;;;;;AAiEA,MAAM,sBAAsB;AAC5B,MAAM,0BAA0B;AAChC,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