@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 18.1 kB
Source Map (JSON)
{"version":3,"file":"base-index.cjs","names":["DEFAULT_COMPARE_OPTIONS","makeCheckedComparator","normalizeValue","makeComparator","indexableOperations","deepEquals","compileSingleRowExpression","codedMessage","indexObjectKind","codedWarning","rangeValueDomains","compiledIndexEvaluator"],"sources":["../../../src/indexes/base-index.ts"],"sourcesContent":["import { compileSingleRowExpression } from '../query/compiler/evaluators.js'\nimport {\n comparisonFunctions,\n indexableOperations,\n} from '../query/builder/functions.js'\nimport { DEFAULT_COMPARE_OPTIONS, deepEquals } from '../utils.js'\nimport {\n indexObjectKind,\n makeCheckedComparator,\n makeComparator,\n normalizeValue,\n} from '../utils/comparison.js'\nimport { codedMessage, codedWarning, devBuild } from '../error-message.js'\nimport type { CompiledSingleRowExpression } from '../query/compiler/evaluators.js'\nimport type { RangeQueryOptions } from './btree-index.js'\nimport type { CompareOptions } from '../query/builder/types.js'\nimport type { BasicExpression, OrderByDirection } from '../query/ir.js'\n\nfunction normalizeLocaleOptions(options: object | undefined): object {\n return Object.fromEntries(\n Object.entries(options ?? {}).filter(([, value]) => value !== undefined),\n )\n}\n\nfunction canonicalizeLocale(locale: string | undefined): string | undefined {\n return locale === undefined ? undefined : Intl.getCanonicalLocales(locale)[0]\n}\n\ntype LocaleCompareOptions = CompareOptions & {\n stringSort: `locale`\n locale?: string\n localeOptions?: object\n}\n\nfunction resolveStringSort(\n options: CompareOptions,\n): NonNullable<CompareOptions[`stringSort`]> {\n return options.stringSort ?? DEFAULT_COMPARE_OPTIONS.stringSort!\n}\n\n/**\n * Operations that indexes can support, imported from available comparison functions\n */\nexport const IndexOperation = comparisonFunctions\n\nexport { indexableOperations } from '../query/builder/functions.js'\n\nexport const builtInIndexResolverNames = new WeakMap<object, string>()\n\n/**\n * Type for index operation values\n */\nexport type IndexOperation = (typeof comparisonFunctions)[number]\n\nexport interface IndexComparisonOptions {\n compareFn?: (a: any, b: any) => number\n compareOptions?: CompareOptions\n}\n\n/** The read-side surface consumers use on a resolved (possibly reversed) index. */\nexport type IndexReader<TKey extends string | number = string | number> = Pick<\n IndexInterface<TKey>,\n | `lookup`\n | `rangeQuery`\n | `take`\n | `takeFromStart`\n | `keyCount`\n | `supports`\n | `supportsRangeOptimization`\n | `supportsOrderOptimization`\n | `canOptimizeRangeFor`\n>\n\nexport interface IndexInterface<\n TKey extends string | number = string | number,\n> {\n add: (key: TKey, item: any) => void\n remove: (key: TKey, item: any) => void\n update: (key: TKey, oldItem: any, newItem: any) => void\n\n build: (entries: Iterable<[TKey, any]>) => void\n clear: () => void\n\n lookup: (operation: IndexOperation, value: any) => Set<TKey>\n\n equalityLookup: (value: any) => Set<TKey>\n inArrayLookup: (values: Array<any>) => Set<TKey>\n\n rangeQuery: (options: RangeQueryOptions) => Set<TKey>\n rangeQueryReversed: (options: RangeQueryOptions) => Set<TKey>\n\n take: (\n n: number,\n from: unknown,\n filterFn?: (key: TKey) => boolean,\n ) => Array<TKey>\n takeFromStart: (n: number, filterFn?: (key: TKey) => boolean) => Array<TKey>\n takeReversed: (\n n: number,\n from: unknown,\n filterFn?: (key: TKey) => boolean,\n ) => Array<TKey>\n takeReversedFromEnd: (\n n: number,\n filterFn?: (key: TKey) => boolean,\n ) => Array<TKey>\n\n get keyCount(): number\n supports: (operation: IndexOperation) => boolean\n\n /**\n * Whether range lookups (gt/gte/lt/lte) on this index can be trusted to\n * return every matching key. Range traversal relies on the index ordering, so\n * it is unsafe when the index uses a custom comparator, whose order may not\n * match the WHERE evaluator's relational operators. Callers must fall back to\n * a full scan when this is `false`.\n */\n get supportsRangeOptimization(): boolean\n /** Whether a query can use this index for its declared ordered prefix. */\n readonly supportsOrderOptimization?: boolean\n\n /**\n * Whether the live values in this index share the predicate operand's\n * relational domain. Mixed domains can sort differently in the index and\n * WHERE evaluator, which can make a range lookup omit matching rows.\n */\n canOptimizeRangeFor?: (value: unknown) => boolean\n\n matchesField: (fieldPath: Array<string>) => boolean\n matchesCompareOptions: (compareOptions: CompareOptions) => boolean\n matchesDirection: (direction: OrderByDirection) => boolean\n}\n\n/**\n * Base abstract class that all index types extend\n */\nexport abstract class BaseIndex<\n TKey extends string | number = string | number,\n> implements IndexInterface<TKey> {\n public readonly id: number\n public readonly name?: string\n public readonly expression: BasicExpression\n public readonly supportedOperations: Set<IndexOperation>\n protected readonly compareOptions: CompareOptions\n /**\n * Orders indexed values. Every result is checked, because a custom\n * comparator or custom collation may be supplied by the user.\n */\n protected readonly compareFn: (a: any, b: any) => number\n private compiledIndexEvaluator: CompiledSingleRowExpression | undefined\n /**\n * A user-supplied comparator's ordering may not match the WHERE evaluator's\n * relational operators.\n */\n protected readonly hasCustomComparator: boolean\n private rangeValueDomains = new Map<string, number>()\n\n constructor(\n id: number,\n expression: BasicExpression,\n name?: string,\n options?: any,\n ) {\n this.id = id\n this.expression = expression\n this.compareOptions = options?.compareOptions ?? DEFAULT_COMPARE_OPTIONS\n this.hasCustomComparator = options?.compareFn != null\n this.compareFn = makeCheckedComparator(\n options?.compareFn\n ? (a, b) => options.compareFn(normalizeValue(a), normalizeValue(b))\n : makeComparator(this.compareOptions, `index`),\n )\n this.name = name\n this.supportedOperations = new Set<IndexOperation>(indexableOperations)\n this.initialize(options)\n }\n\n // Abstract methods that each index type must implement\n abstract add(key: TKey, item: any): void\n abstract remove(key: TKey, item: any): void\n abstract update(key: TKey, oldItem: any, newItem: any): void\n abstract build(entries: Iterable<[TKey, any]>): void\n abstract clear(): void\n abstract lookup(operation: IndexOperation, value: any): Set<TKey>\n abstract take(\n n: number,\n from: unknown,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey>\n abstract takeFromStart(\n n: number,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey>\n abstract takeReversed(\n n: number,\n from: unknown,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey>\n abstract takeReversedFromEnd(\n n: number,\n filterFn?: (key: TKey) => boolean,\n ): Array<TKey>\n abstract get keyCount(): number\n abstract equalityLookup(value: any): Set<TKey>\n protected exactBucketKeys(value: any): Iterable<TKey> | undefined {\n return this.equalityLookup(value)\n }\n abstract rangeQuery(options: RangeQueryOptions): Set<TKey>\n\n // Common methods\n protected lookupSupportedOperation(\n operation: IndexOperation,\n value: any,\n ): Set<TKey> | undefined {\n if (operation === `eq`) return this.equalityLookup(value)\n if (operation === `in`) return this.inArrayLookup(value)\n if (operation === `gt` || operation === `gte`)\n return this.rangeQuery({\n from: value,\n fromInclusive: operation === `gte`,\n })\n if (operation === `lt` || operation === `lte`)\n return this.rangeQuery({ to: value, toInclusive: operation === `lte` })\n return undefined\n }\n\n /** Combine exact buckets without copying each bucket first. */\n inArrayLookup(values: Array<any>): Set<TKey> {\n const result = new Set<TKey>()\n for (const value of values) {\n const keys = this.exactBucketKeys(value)\n if (keys) for (const key of keys) result.add(key)\n }\n return result\n }\n\n rangeQueryReversed(options: RangeQueryOptions = {}): Set<TKey> {\n const { from, to, fromInclusive = true, toInclusive = true } = options\n const reversed: RangeQueryOptions = {}\n if (`to` in options) {\n reversed.from = to\n reversed.fromInclusive = toInclusive\n }\n if (`from` in options) {\n reversed.to = from\n reversed.toInclusive = fromInclusive\n }\n return this.rangeQuery(reversed)\n }\n\n supports(operation: IndexOperation): boolean {\n return this.supportedOperations.has(operation)\n }\n\n get supportsRangeOptimization(): boolean {\n return !this.hasCustomComparator\n }\n\n get supportsOrderOptimization(): boolean {\n if (this.hasCustomComparator || this.rangeValueDomains.size > 1)\n return false\n // Within these domains the index orders by a storage key (or lacks a\n // defined query order), rather than by the query's value comparator.\n const domain = this.rangeValueDomains.keys().next().value\n return (\n domain === undefined ||\n ![\n `Array`,\n `Binary`,\n `Temporal.Duration.calendar`,\n `Temporal.PlainMonthDay`,\n `function`,\n ].includes(domain)\n )\n }\n\n protected addRangeValue(value: unknown): void {\n const domain = rangeValueDomain(value)\n if (domain === undefined) return\n this.rangeValueDomains.set(\n domain,\n (this.rangeValueDomains.get(domain) ?? 0) + 1,\n )\n }\n\n protected removeRangeValue(value: unknown): void {\n const domain = rangeValueDomain(value)\n if (domain === undefined) return\n const count = this.rangeValueDomains.get(domain)\n if (count === undefined) return\n if (count === 1) this.rangeValueDomains.delete(domain)\n else this.rangeValueDomains.set(domain, count - 1)\n }\n\n protected clearRangeValues(): void {\n this.rangeValueDomains.clear()\n }\n\n canOptimizeRangeFor(value: unknown): boolean {\n const domain = rangeValueDomain(value)\n if (domain === undefined) return true\n if (!isNativeRangeDomain(domain)) return false\n return (\n this.rangeValueDomains.size === 0 ||\n (this.rangeValueDomains.size === 1 && this.rangeValueDomains.has(domain))\n )\n }\n\n matchesField(fieldPath: Array<string>): boolean {\n return (\n this.expression.type === `ref` &&\n this.expression.path.length === fieldPath.length &&\n this.expression.path.every((part, i) => part === fieldPath[i])\n )\n }\n\n /**\n * Checks if the compare options match the index's compare options.\n * The direction is ignored because the index can be reversed if the direction is different.\n */\n matchesCompareOptions(compareOptions: CompareOptions): boolean {\n const indexCompareOptions = this.compareOptions\n const indexStringSort = resolveStringSort(indexCompareOptions)\n const requestedStringSort = resolveStringSort(compareOptions)\n\n if (\n indexCompareOptions.nulls !== compareOptions.nulls ||\n indexStringSort !== requestedStringSort\n ) {\n return false\n }\n\n if (indexStringSort === `custom` && requestedStringSort === `custom`) {\n return (\n indexCompareOptions.stringSort === `custom` &&\n compareOptions.stringSort === `custom` &&\n indexCompareOptions.compare === compareOptions.compare\n )\n }\n\n if (indexStringSort !== `locale` || requestedStringSort !== `locale`) {\n return true\n }\n\n const indexLocaleOptions = indexCompareOptions as LocaleCompareOptions\n const requestedLocaleOptions = compareOptions as LocaleCompareOptions\n\n return (\n canonicalizeLocale(indexLocaleOptions.locale) ===\n canonicalizeLocale(requestedLocaleOptions.locale) &&\n deepEquals(\n normalizeLocaleOptions(indexLocaleOptions.localeOptions),\n normalizeLocaleOptions(requestedLocaleOptions.localeOptions),\n )\n )\n }\n\n /**\n * Checks if the index matches the provided direction.\n */\n matchesDirection(direction: OrderByDirection): boolean {\n return this.compareOptions.direction === direction\n }\n\n protected initialize(_options?: any): void {}\n\n protected evaluateIndexExpression(item: any): any {\n const evaluator = (this.compiledIndexEvaluator ??=\n compileSingleRowExpression(this.expression))\n return evaluator(item as Record<string, unknown>)\n }\n\n /** The indexed value of a row being added. A throwing expression fails the write. */\n protected evaluateAddedValue(key: TKey, item: any): any {\n try {\n return this.evaluateIndexExpression(item)\n } catch (error) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Failed to evaluate index expression for key ${key}: ${error}`\n : codedMessage(99, { key, error }),\n { cause: error },\n )\n }\n }\n}\n\nfunction rangeValueDomain(value: unknown): string | undefined {\n if (value == null) return undefined\n if (value instanceof Date) return `date`\n if (typeof value === `object`) return indexObjectKind(value)\n return typeof value\n}\n\nfunction isNativeRangeDomain(domain: string): boolean {\n return (\n domain === `number` ||\n domain === `bigint` ||\n domain === `boolean` ||\n domain === `string` ||\n domain === `date`\n )\n}\n\n/**\n * Type for index constructor\n */\nexport type IndexConstructor<TKey extends string | number = string | number> =\n new (\n id: number,\n expression: BasicExpression,\n name?: string,\n options?: any,\n ) => BaseIndex<TKey>\n\n/** A row being removed whose expression throws: warn, and skip the row. */\nexport function warnRemovalFailure(key: unknown, error: unknown): void {\n console.warn(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `Failed to evaluate index expression for key ${key} during removal:`\n : codedWarning(216, { key }),\n error,\n )\n}\n"],"mappings":";;;;;AAkBA,SAAS,uBAAuB,SAAqC;CACnE,OAAO,OAAO,YACZ,OAAO,QAAQ,WAAW,CAAC,CAAC,CAAA,CAAE,QAAQ,GAAG,WAAW,UAAU,KAAA,CAAS,CACzE;AACF;AAEA,SAAS,mBAAmB,QAAgD;CAC1E,OAAO,WAAW,KAAA,IAAY,KAAA,IAAY,KAAK,oBAAoB,MAAM,CAAA,CAAE;AAC7E;AAQA,SAAS,kBACP,SAC2C;CAC3C,OAAO,QAAQ,cAAcA,cAAAA,wBAAwB;AACvD;AASA,IA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