{"version":3,"file":"btree-index.cjs","names":["BaseIndex","BTree","normalizeValue","areSameValueZeroEqual","codedMessage","compareKeysReversed","compareKeys","builtInIndexResolverNames","orderedEntries","valueMap","indexedKeys","addToBucket","removeFromBucket","takeInternal"],"sources":["../../../src/indexes/btree-index.ts"],"sourcesContent":["import { compareKeys } from '@tanstack/db-ivm'\nimport { compareKeysReversed } from '../utils/array-utils.js'\nimport { BTree } from '../utils/btree.js'\nimport { areSameValueZeroEqual, normalizeValue } from '../utils/comparison.js'\nimport { codedMessage, devBuild } from '../error-message.js'\nimport {\n  BaseIndex,\n  builtInIndexResolverNames,\n  warnRemovalFailure,\n} from './base-index.js'\nimport type { IndexComparisonOptions, IndexOperation } from './base-index.js'\n\nexport type BTreeIndexOptions = IndexComparisonOptions\nexport interface RangeQueryOptions {\n  from?: any\n  to?: any\n  fromInclusive?: boolean\n  toInclusive?: boolean\n}\n\ntype SortKey = { value: any }\ntype Group<TKey> = SortKey & {\n  keys: Map<TKey, any>\n  buckets?: Map<unknown, Set<TKey>>\n  representativeKey: TKey\n  nextRepresentative?: IterableIterator<[TKey, any]>\n}\nexport class BTreeIndex<\n  TKey extends string | number = string | number,\n> extends BaseIndex<TKey> {\n  private orderedEntries = new BTree<SortKey, Group<TKey>>((a, b) =>\n    this.compareFn(a.value, b.value),\n  )\n  private valueMap = new Map<any, Group<TKey>>()\n  private indexedKeys = new Set<TKey>()\n\n  add(key: TKey, item: any): void {\n    const value = this.evaluateAddedValue(key, item)\n    const exact = normalizeValue(value)\n    this.addToBucket(key, value, exact)\n    this.addRangeValue(value)\n    this.indexedKeys.add(key)\n  }\n\n  private addToBucket(key: TKey, value: any, exact: unknown): void {\n    const group = this.valueMap.get(exact)\n    if (group) {\n      group.keys.set(key, value)\n      group.buckets?.get(exact)!.add(key)\n      return\n    }\n    const ordered = this.orderedEntries.get({ value })\n    if (ordered) {\n      ordered.buckets ??= new Map([\n        [normalizeValue(ordered.value), new Set(ordered.keys.keys())],\n      ])\n      ordered.buckets.set(exact, new Set([key]))\n      ordered.keys.set(key, value)\n      this.valueMap.set(exact, ordered)\n    } else {\n      const created = {\n        value,\n        keys: new Map([[key, value]]),\n        representativeKey: key,\n      }\n      // The tree compares before the exact lookup map changes.\n      this.orderedEntries.set(created, created)\n      this.valueMap.set(exact, created)\n    }\n  }\n\n  remove(key: TKey, item: any): void {\n    let value: any\n    try {\n      value = this.evaluateIndexExpression(item)\n    } catch (error) {\n      warnRemovalFailure(key, error)\n      return\n    }\n    const exact = normalizeValue(value)\n    this.removeFromBucket(key, exact)\n    this.removeRangeValue(value)\n    this.indexedKeys.delete(key)\n  }\n\n  private removeFromBucket(key: TKey, exact: unknown): void {\n    const group = this.valueMap.get(exact)\n    if (!group?.keys.has(key)) return\n    const bucket = group.buckets?.get(exact)\n    if (group.buckets && !bucket?.has(key)) return\n    if (group.keys.size === 1) {\n      this.orderedEntries.delete(group)\n    }\n    bucket?.delete(key)\n    group.keys.delete(key)\n    if (bucket?.size === 0 || group.keys.size === 0) {\n      this.valueMap.delete(exact)\n      group.buckets?.delete(exact)\n    }\n    if (group.keys.size && group.representativeKey === key) {\n      // Advancing one iterator skips each removed Map slot at most once.\n      const [nextKey, nextValue] = (group.nextRepresentative ??=\n        group.keys.entries()).next().value as [TKey, any]\n      group.representativeKey = nextKey\n      group.value = nextValue\n    }\n  }\n\n  update(key: TKey, oldItem: any, newItem: any): void {\n    let oldValue: any\n    let newValue: any\n    try {\n      oldValue = this.evaluateIndexExpression(oldItem)\n      newValue = this.evaluateIndexExpression(newItem)\n    } catch {\n      this.remove(key, oldItem)\n      this.add(key, newItem)\n      return\n    }\n    const oldExact = normalizeValue(oldValue)\n    const newExact = normalizeValue(newValue)\n    const group = this.valueMap.get(newExact)\n    const containsKey = group?.buckets\n      ? group.buckets.get(newExact)?.has(key)\n      : group?.keys.has(key)\n    if (areSameValueZeroEqual(oldExact, newExact) && containsKey) {\n      group!.keys.set(key, newValue)\n      if (group!.representativeKey === key) group!.value = newValue\n      this.removeRangeValue(oldValue)\n      this.addRangeValue(newValue)\n      return\n    }\n    this.removeFromBucket(key, oldExact)\n    this.removeRangeValue(oldValue)\n    this.addToBucket(key, newValue, newExact)\n    this.addRangeValue(newValue)\n    this.indexedKeys.add(key)\n  }\n\n  build(entries: Iterable<[TKey, any]>): void {\n    this.clear()\n    for (const [key, item] of entries) this.add(key, item)\n  }\n\n  clear(): void {\n    this.orderedEntries.clear()\n    this.valueMap.clear()\n    this.indexedKeys.clear()\n    this.clearRangeValues()\n  }\n\n  lookup(operation: IndexOperation, value: any): Set<TKey> {\n    const result = this.lookupSupportedOperation(operation, value)\n    if (result !== undefined) return result\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `Operation ${operation} not supported by BTreeIndex`\n        : codedMessage(101, { operation }),\n    )\n  }\n\n  get keyCount(): number {\n    return this.indexedKeys.size\n  }\n\n  equalityLookup(value: any): Set<TKey> {\n    return new Set(this.exactBucketKeys(value))\n  }\n\n  protected exactBucketKeys(value: any): Iterable<TKey> | undefined {\n    const exact = normalizeValue(value)\n    const group = this.valueMap.get(exact)\n    return group?.buckets ? group.buckets.get(exact) : group?.keys.keys()\n  }\n\n  rangeQuery(options: RangeQueryOptions = {}): Set<TKey> {\n    const result = new Set<TKey>()\n    if (this.orderedEntries.size === 0) return result\n    const { from, to, fromInclusive = true, toInclusive = true } = options\n    const low =\n      'from' in options ? { value: from } : this.orderedEntries.minKey()!\n    const high = 'to' in options ? { value: to } : this.orderedEntries.maxKey()!\n    this.orderedEntries.forRange(\n      low,\n      high,\n      !('to' in options) || toInclusive,\n      (sortKey, group) => {\n        if (\n          'from' in options &&\n          !fromInclusive &&\n          this.compareFn(sortKey.value, from) === 0\n        )\n          return\n        for (const key of group.keys.keys()) result.add(key)\n      },\n    )\n    return result\n  }\n\n  private takeInternal(\n    n: number,\n    from: SortKey | undefined,\n    filterFn: ((key: TKey) => boolean) | undefined,\n    reversed: boolean,\n  ): Array<TKey> {\n    const result: Array<TKey> = []\n    let pair = reversed\n      ? this.orderedEntries.nextLowerPair(from)\n      : this.orderedEntries.nextHigherPair(from)\n    while (pair && result.length < n) {\n      for (const key of [...pair[1].keys.keys()].sort(\n        reversed ? compareKeysReversed : compareKeys,\n      )) {\n        if (filterFn?.(key) ?? true) result.push(key)\n        if (result.length >= n) break\n      }\n      if (result.length >= n) break\n      pair = reversed\n        ? this.orderedEntries.nextLowerPair(pair[0])\n        : this.orderedEntries.nextHigherPair(pair[0])\n    }\n    return result\n  }\n\n  take(n: number, from: any, filterFn?: (key: TKey) => boolean): Array<TKey> {\n    return this.takeInternal(n, { value: from }, filterFn, false)\n  }\n\n  takeFromStart(n: number, filterFn?: (key: TKey) => boolean): Array<TKey> {\n    return this.takeInternal(n, undefined, filterFn, false)\n  }\n\n  takeReversed(\n    n: number,\n    from: any,\n    filterFn?: (key: TKey) => boolean,\n  ): Array<TKey> {\n    return this.takeInternal(n, { value: from }, filterFn, true)\n  }\n\n  takeReversedFromEnd(\n    n: number,\n    filterFn?: (key: TKey) => boolean,\n  ): Array<TKey> {\n    return this.takeInternal(n, undefined, filterFn, true)\n  }\n}\n\nbuiltInIndexResolverNames.set(BTreeIndex, 'BTreeIndex')\n"],"mappings":";;;;;;AA2BA,IAAa,aAAb,cAEUA,mBAAAA,UAAgB;;;EACC,KAAAQ,KAAA,IAAIP,cAAAA,OAA6B,GAAG,MAC3D,KAAK,UAAU,EAAE,OAAO,EAAE,KAAK,CACjC;EACmB,KAAAQ,qBAAA,IAAI,IAAsB;EACvB,KAAAC,qBAAA,IAAI,IAAU;;CAEpC,IAAI,KAAW,MAAiB;EAC9B,MAAM,QAAQ,KAAK,mBAAmB,KAAK,IAAI;EAC/C,MAAM,QAAQR,mBAAAA,eAAe,KAAK;EAClC,KAAKS,GAAY,KAAK,OAAO,KAAK;EAClC,KAAK,cAAc,KAAK;EACxB,KAAKD,GAAY,IAAI,GAAG;CAC1B;CAEAC,GAAoB,KAAW,OAAY,OAAsB;EAC/D,MAAM,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