{"version":3,"file":"iterator.cjs","names":["afterStart: boolean","startOrAfter: boolean","compareBytes","beforeEnd: boolean","withinEnd: boolean"],"sources":["../../src/iterator/iterator.ts"],"sourcesContent":["/**\n * TreeIterator implements iteration over an ImmutableTree.\n * Uses delayed node traversal with a stack-based approach.\n *\n * Corresponds to Go's Iterator in iterator.go\n */\n\nimport type {\n  ImmutableTree,\n} from \"../immutable-tree.js\";\nimport type {\n  Node,\n} from \"../node.js\";\nimport {\n  compareBytes,\n} from \"../utils/bytes.js\";\n\n/**\n * Delayed node represents a node that may need to be expanded.\n * When delayed is true, the node's children should be traversed.\n * When delayed is false, the node can be immediately returned.\n */\ninterface DelayedNode {\n  node: Node\n  delayed: boolean\n}\n\n/**\n * Traversal manages the stack-based depth-first traversal of the tree.\n */\nclass Traversal {\n  private readonly tree: ImmutableTree;\n  private start: Uint8Array | null;\n  private end: Uint8Array | null;\n  private readonly ascending: boolean;\n  private readonly inclusive: boolean;\n  private readonly delayedNodes: DelayedNode[];\n\n  constructor(\n    tree: ImmutableTree,\n    start: Uint8Array | null,\n    end: Uint8Array | null,\n    ascending: boolean,\n    inclusive: boolean,\n    initialNode: Node,\n  ) {\n    this.tree = tree;\n    this.start = start;\n    this.end = end;\n    this.ascending = ascending;\n    this.inclusive = inclusive;\n    this.delayedNodes = [\n      {\n        node: initialNode,\n        delayed: true,\n      },\n    ];\n  }\n\n  /**\n   * Gets the next node in the traversal.\n   * Returns null when traversal is complete.\n   */\n  async next(): Promise<Node | null> {\n    // End of traversal\n    if (this.delayedNodes.length === 0) {\n      return null;\n    }\n\n    const delayedNode = this.delayedNodes.pop()!;\n    const {\n      node, delayed,\n    } = delayedNode;\n\n    // Already expanded, immediately return\n    if (!delayed || node === null) {\n      return node;\n    }\n\n    // All nodes in the tree should have keys\n    if (node.key === null) {\n      throw new Error(\"Iterator encountered node without key\");\n    }\n\n    // Check if node is within range\n    let afterStart: boolean;\n    let startOrAfter: boolean;\n    if (this.start === null) {\n      afterStart = true;\n      startOrAfter = true;\n    }\n    else {\n      const cmp = compareBytes(this.start, node.key);\n      afterStart = cmp < 0;\n      startOrAfter = afterStart || cmp === 0;\n    }\n\n    let beforeEnd: boolean;\n    let withinEnd: boolean;\n    if (this.end === null) {\n      beforeEnd = true;\n      withinEnd = true;\n    }\n    else {\n      const cmp = compareBytes(node.key, this.end);\n      beforeEnd = cmp < 0;\n      withinEnd = this.inclusive ? (beforeEnd || cmp === 0) : beforeEnd;\n    }\n\n    // If node is a branch node, traverse children\n    if (!node.isLeaf()) {\n      // Ascending: left first, then right\n      if (this.ascending) {\n        // Push right child (will be processed after left)\n        if (withinEnd) {\n          const rightNode = await node.getRightNode(this.tree.ndb);\n          if (rightNode) {\n            this.delayedNodes.push({\n              node: rightNode,\n              delayed: true,\n            });\n          }\n        }\n        // Push left child (will be processed first)\n        if (afterStart) {\n          const leftNode = await node.getLeftNode(this.tree.ndb);\n          if (leftNode) {\n            this.delayedNodes.push({\n              node: leftNode,\n              delayed: true,\n            });\n          }\n        }\n      }\n      // Descending: right first, then left\n      else {\n        // Push left child (will be processed after right)\n        if (afterStart) {\n          const leftNode = await node.getLeftNode(this.tree.ndb);\n          if (leftNode) {\n            this.delayedNodes.push({\n              node: leftNode,\n              delayed: true,\n            });\n          }\n        }\n        // Push right child (will be processed first)\n        if (withinEnd) {\n          const rightNode = await node.getRightNode(this.tree.ndb);\n          if (rightNode) {\n            this.delayedNodes.push({\n              node: rightNode,\n              delayed: true,\n            });\n          }\n        }\n      }\n    }\n\n    // If node is a leaf and within range, return it\n    // If node is a branch, skip it (we only want leaves)\n    if (node.isLeaf() && startOrAfter && withinEnd) {\n      return node;\n    }\n\n    // Continue traversing\n    return this.next();\n  }\n}\n\n/**\n * TreeIterator iterates over key-value pairs in an ImmutableTree.\n *\n * Usage:\n * ```typescript\n * const iter = new TreeIterator(tree, start, end, true);\n * while (iter.valid()) {\n *   console.log(iter.key(), iter.value());\n *   await iter.next();\n * }\n * iter.close();\n * ```\n */\nexport class TreeIterator {\n  private readonly tree: ImmutableTree;\n  private readonly start: Uint8Array | null;\n  private readonly end: Uint8Array | null;\n  private readonly ascending: boolean;\n  private readonly inclusive: boolean;\n\n  private currentKey: Uint8Array | null = null;\n  private currentValue: Uint8Array | null = null;\n  private currentVersion: bigint | null = null;\n  private isValid = false;\n  private traversal: Traversal | null = null;\n\n  /**\n   * Creates a new TreeIterator.\n   * The iterator is positioned before the first element.\n   * Call next() to move to the first element.\n   *\n   * @param tree - The immutable tree to iterate over\n   * @param start - Start key (null for beginning)\n   * @param end - End key (null for no limit)\n   * @param ascending - True for ascending order, false for descending\n   * @param inclusive - True to include end key, false to exclude\n   */\n  constructor(\n    tree: ImmutableTree,\n    start: Uint8Array | null = null,\n    end: Uint8Array | null = null,\n    ascending = true,\n    inclusive = false,\n  ) {\n    this.tree = tree;\n    this.start = start;\n    this.end = end;\n    this.ascending = ascending;\n    this.inclusive = inclusive;\n\n    // Initialize traversal if tree has a root\n    const root = tree.getRoot();\n    if (root) {\n      this.isValid = true;\n      this.traversal = new Traversal(\n        tree,\n        start,\n        end,\n        ascending,\n        inclusive,\n        root,\n      );\n    }\n    else {\n      // Empty tree\n      this.isValid = false;\n    }\n  }\n\n  /**\n   * Checks if the iterator is currently valid.\n   * Returns false when iteration is complete or tree is empty.\n   */\n  valid(): boolean {\n    return this.isValid;\n  }\n\n  /**\n   * Gets the current key.\n   * Only valid when valid() returns true.\n   */\n  key(): Uint8Array {\n    if (!this.isValid || this.currentKey === null) {\n      throw new Error(\"Iterator is not valid\");\n    }\n    return this.currentKey;\n  }\n\n  /**\n   * Gets the current value.\n   * Only valid when valid() returns true.\n   */\n  value(): Uint8Array {\n    if (!this.isValid || this.currentValue === null) {\n      throw new Error(\"Iterator is not valid\");\n    }\n    return this.currentValue;\n  }\n\n  /**\n   * Gets the current node's version.\n   * Only valid when valid() returns true.\n   */\n  version(): bigint {\n    if (!this.isValid || this.currentVersion === null) {\n      throw new Error(\"Iterator is not valid\");\n    }\n    return this.currentVersion;\n  }\n\n  /**\n   * Advances the iterator to the next key-value pair.\n   * After the last element, valid() will return false.\n   */\n  async next(): Promise<void> {\n    if (!this.traversal) {\n      this.isValid = false;\n      return;\n    }\n\n    const node = await this.traversal.next();\n    if (node === null) {\n      this.isValid = false;\n      this.currentKey = null;\n      this.currentValue = null;\n      this.currentVersion = null;\n      this.traversal = null;\n      return;\n    }\n\n    // Only leaf nodes have values\n    if (node.isLeaf()) {\n      this.currentKey = node.key;\n      this.currentValue = node.value;\n      this.currentVersion = node.nodeKey?.version ?? null;\n    }\n    else {\n      // Branch node, continue to next\n      await this.next();\n    }\n  }\n\n  /**\n   * Closes the iterator and releases resources.\n   * The iterator becomes invalid after calling close().\n   */\n  close(): void {\n    this.isValid = false;\n    this.currentKey = null;\n    this.currentValue = null;\n    this.currentVersion = null;\n    this.traversal = null;\n  }\n\n  /**\n   * Gets the iteration domain (start and end keys).\n   */\n  domain(): [Uint8Array | null, Uint8Array | null] {\n    return [this.start, this.end];\n  }\n}\n"],"mappings":";;;;;;AA8BA,IAAM,YAAN,MAAgB;CACd,AAAiB;CACjB,AAAQ;CACR,AAAQ;CACR,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAEjB,YACE,MACA,OACA,KACA,WACA,WACA,aACA;AACA,OAAK,OAAO;AACZ,OAAK,QAAQ;AACb,OAAK,MAAM;AACX,OAAK,YAAY;AACjB,OAAK,YAAY;AACjB,OAAK,eAAe,CAClB;GACE,MAAM;GACN,SAAS;GACV,CACF;;;;;;CAOH,MAAM,OAA6B;AAEjC,MAAI,KAAK,aAAa,WAAW,EAC/B,QAAO;EAIT,MAAM,EACJ,MAAM,YAFY,KAAK,aAAa,KAAK;AAM3C,MAAI,CAAC,WAAW,SAAS,KACvB,QAAO;AAIT,MAAI,KAAK,QAAQ,KACf,OAAM,IAAI,MAAM,wCAAwC;EAI1D,IAAIA;EACJ,IAAIC;AACJ,MAAI,KAAK,UAAU,MAAM;AACvB,gBAAa;AACb,kBAAe;SAEZ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