{"version":3,"file":"importer.cjs","names":["Node","NodeKey"],"sources":["../../src/import/importer.ts"],"sourcesContent":["import type {\n  ExportNode,\n} from \"../export/types.js\";\nimport type {\n  MutableTree,\n} from \"../mutable-tree.js\";\nimport {\n  Node,\n} from \"../node.js\";\nimport {\n  NodeKey,\n} from \"../node-key.js\";\n\n/**\n * Maximum batch size before flushing to database\n * Based on Go IAVL import.go line 12\n */\nconst MAX_BATCH_SIZE = 10000;\n\n/**\n * Error thrown when calling methods on a closed importer\n */\nexport class ErrNoImport extends Error {\n  constructor() {\n    super(\"no import in progress\");\n    this.name = \"ErrNoImport\";\n  }\n}\n\n/**\n * Importer imports data into an empty MutableTree.\n * It is created by MutableTree.import(). Users must call close() when done.\n *\n * ExportNodes must be imported in the order returned by Exporter,\n * i.e. depth-first post-order (LRN).\n *\n * Importer is not concurrency-safe, it is the caller's responsibility to ensure\n * the tree is not modified while performing an import.\n *\n * Based on Go IAVL import.go lines 17-34.\n */\nexport class Importer {\n  private tree: MutableTree | null;\n  private version: bigint;\n  private batchSize: number = 0;\n  private stack: Node[] = [];\n  private nonces: number[] = [];\n\n  /**\n   * Creates a new Importer for an empty MutableTree.\n   *\n   * @param tree - The MutableTree to import into (must be empty)\n   * @param version - The version to import (must match exported version)\n   * @throws Error if version is negative, tree is not empty, or database has existing versions\n   *\n   * Based on Go IAVL import.go lines 36-58.\n   */\n  constructor(tree: MutableTree, version: bigint) {\n    if (version < 0n) {\n      throw new Error(\"imported version cannot be negative\");\n    }\n\n    const latestVersion = tree.getVersion();\n    if (latestVersion > 0n) {\n      throw new Error(`found database at version ${latestVersion}, must be 0`);\n    }\n\n    if (tree.getSize() > 0n) {\n      throw new Error(\"tree must be empty\");\n    }\n\n    this.tree = tree;\n    this.version = version;\n    this.stack = [];\n    // Initialize nonces array with size version+1\n    this.nonces = new Array(Number(version) + 1).fill(0);\n  }\n\n  /**\n   * Writes a node to the database.\n   * Handles batching and flushing when batch size exceeds MAX_BATCH_SIZE.\n   *\n   * Based on Go IAVL import.go lines 60-104.\n   */\n  private async writeNode(node: Node): Promise<void> {\n    if (!this.tree) {\n      throw new ErrNoImport();\n    }\n\n    // Hash the node\n    node.computeHash(node.nodeKey!.version);\n\n    // Validate node structure\n    const validationError = node.validate();\n    if (validationError) {\n      throw new Error(`Node validation failed: ${validationError}`);\n    }\n\n    // Serialize node\n    const bytes = node.toBytes();\n\n    // Write to database\n    const ndb = this.tree.getNodeDB();\n    const nodeKeyBytes = node.nodeKey!.toBytes();\n    const dbKey = ndb.nodeKey(nodeKeyBytes);\n    await ndb.db.set(dbKey, bytes);\n\n    this.batchSize++;\n\n    // Flush if batch size exceeded (in a real implementation we'd batch these)\n    if (this.batchSize >= MAX_BATCH_SIZE) {\n      // In TypeScript we don't have async batch commits like Go\n      // The database handles this internally\n      this.batchSize = 0;\n    }\n  }\n\n  /**\n   * Adds an ExportNode to the import.\n   * ExportNodes must be added in the order returned by Exporter (post-order LRN).\n   * Nodes are periodically flushed to the database, but the imported version\n   * is not visible until commit() is called.\n   *\n   * Based on Go IAVL import.go lines 120-186.\n   *\n   * @param exportNode - The exported node to add\n   * @throws Error if importer is closed, node is nil, or version is invalid\n   */\n  async add(exportNode: ExportNode): Promise<void> {\n    if (!this.tree) {\n      throw new ErrNoImport();\n    }\n\n    if (!exportNode) {\n      throw new Error(\"node cannot be nil\");\n    }\n\n    if (exportNode.version > this.version) {\n      throw new Error(\n        `node version ${exportNode.version} can't be greater than import version ${this.version}`,\n      );\n    }\n\n    // Create node from export data\n    const node = new Node();\n    node.key = exportNode.key;\n    node.value = exportNode.value;\n    node.subtreeHeight = exportNode.height;\n\n    // Note: Branch nodes will have their value cleared below when children are attached\n\n    // Build tree from bottom-left up using a stack.\n    // The stack stores unresolved left children while constructing right children.\n    // When all children are built, the parent can be constructed and resolved\n    // children can be discarded from the stack.\n\n    const stackSize = this.stack.length;\n\n    if (node.subtreeHeight === 0) {\n      // Leaf node\n      node.size = 1n;\n    }\n    else if (\n      stackSize >= 2\n      && this.stack[stackSize - 1].subtreeHeight < node.subtreeHeight\n      && this.stack[stackSize - 2].subtreeHeight < node.subtreeHeight\n    ) {\n      // Branch node: both children are on stack\n      const leftNode = this.stack[stackSize - 2];\n      const rightNode = this.stack[stackSize - 1];\n\n      node.leftNode = leftNode;\n      node.rightNode = rightNode;\n      node.leftNodeKey = leftNode.nodeKey!.toBytes();\n      node.rightNodeKey = rightNode.nodeKey!.toBytes();\n      node.size = leftNode.size + rightNode.size;\n      node.value = null; // Branch nodes have no value\n\n      // Write children to database and remove from stack\n      await this.writeNode(leftNode);\n      await this.writeNode(rightNode);\n      this.stack = this.stack.slice(0, stackSize - 2);\n\n      // Remove recursive references to avoid memory leaks\n      leftNode.leftNode = null;\n      leftNode.rightNode = null;\n      rightNode.leftNode = null;\n      rightNode.rightNode = null;\n    }\n\n    // Assign node key with version and nonce\n    const versionIdx = Number(exportNode.version);\n    this.nonces[versionIdx]++;\n    node.nodeKey = new NodeKey(\n      exportNode.version,\n      // Nonce is 1-indexed, but start at 2 since root has nonce of 1\n      this.nonces[versionIdx] + 1,\n    );\n\n    // Push node onto stack\n    this.stack.push(node);\n  }\n\n  /**\n   * Finalizes the import by flushing outstanding nodes to the database,\n   * making the version visible, and updating tree metadata.\n   * Can only be called once, and calls close() internally.\n   *\n   * Based on Go IAVL import.go lines 188-229.\n   *\n   * @throws Error if importer is closed or stack has invalid state\n   */\n  async commit(): Promise<void> {\n    if (!this.tree) {\n      throw new ErrNoImport();\n    }\n\n    const ndb = this.tree.getNodeDB();\n    const stackSize = this.stack.length;\n\n    switch (stackSize) {\n      case 0: {\n        // Empty tree: save empty root\n        const rootKey = ndb.rootKey(this.version);\n        await ndb.db.set(rootKey, new Uint8Array(0));\n        break;\n      }\n\n      case 1: {\n        // Single node (root)\n        const root = this.stack[0];\n        // Root always has nonce 1 - create new NodeKey\n        root.nodeKey = new NodeKey(root.nodeKey!.version, 1);\n\n        await this.writeNode(root);\n\n        // Save root reference only if root version < import version\n        // When root.version == import.version with nonce=1, the root is implicit\n        // (getRoot will automatically return getRootKey(version) as the nodeKey)\n        if (root.nodeKey!.version < this.version) {\n          const rootKey = ndb.rootKey(this.version);\n          const nodeKeyBytes = root.nodeKey!.toBytes();\n          // IMPORTANT: Must save the PREFIXED nodeKey (13 bytes), not raw nodeKey (12 bytes)\n          // This matches Go: i.batch.Set(nodeKey(GetRootKey(version)), nodeKey(stack[0].nodeKey.GetKey()))\n          const prefixedNodeKey = ndb.nodeKey(nodeKeyBytes);\n          await ndb.db.set(rootKey, prefixedNodeKey);\n        }\n        break;\n      }\n\n      default:\n        throw new Error(\n          `invalid node structure, found stack size ${stackSize} when committing`,\n        );\n    }\n\n    // Update tree metadata\n    ndb.resetLatestVersion(this.version);\n\n    // Load the imported version\n    await this.tree.loadVersion(this.version);\n\n    // Cleanup\n    this.close();\n  }\n\n  /**\n   * Frees all resources. Safe to call multiple times.\n   * Uncommitted nodes may already have been flushed to the database,\n   * but will not be visible.\n   *\n   * Based on Go IAVL import.go lines 106-118.\n   */\n  close(): void {\n    this.tree = null;\n    this.stack = [];\n    this.batchSize = 0;\n  }\n}\n"],"mappings":";;;;;;;;AAiBA,MAAM,iBAAiB;;;;AAKvB,IAAa,cAAb,cAAiC,MAAM;CACrC,cAAc;AACZ,QAAM,wBAAwB;AAC9B,OAAK,OAAO;;;;;;;;;;;;;;;AAgBhB,IAAa,WAAb,MAAsB;CACpB,AAAQ;CACR,AAAQ;CACR,AAAQ,YAAoB;CAC5B,AAAQ,QAAgB,EAAE;CAC1B,AAAQ,SAAmB,EAAE;;;;;;;;;;CAW7B,YAAY,MAAmB,SAAiB;AAC9C,MAAI,UAAU,GACZ,OAAM,IAAI,MAAM,sCAAsC;EAGxD,MAAM,gBAAgB,KAAK,YAAY;AACvC,MAAI,gBAAgB,GAClB,OAAM,IAAI,MAAM,6BAA6B,cAAc,aAAa;AAG1E,MAAI,KAAK,SAAS,GAAG,GACnB,OAAM,IAAI,MAAM,qBAAqB;AAGvC,OAAK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