@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 19.4 kB
Source Map (JSON)
{"version":3,"file":"change-events.cjs","names":["equalityConjunct","getPropRefPropertyPath","equalityKey","readPath","codedMessage","optimizeExpressionWithIndexes","codedWarning","compileSingleRowExpression","toBooleanPredicate","propRef","buildCompareOptions","supportsOrderedIndexStructure","findIndexForField","supportsOrderedRange","makeComparator"],"sources":["../../../src/collection/change-events.ts"],"sourcesContent":["import {\n compileSingleRowExpression,\n toBooleanPredicate,\n} from '../query/compiler/evaluators.js'\nimport {\n findIndexForField,\n optimizeExpressionWithIndexes,\n supportsOrderedIndexStructure,\n supportsOrderedRange,\n} from '../utils/index-optimization.js'\nimport { ensureIndexForField } from '../indexes/auto-index.js'\nimport { getPropRefPropertyPath } from '../query/ir.js'\nimport {\n equalityConjunct,\n equalityKey,\n readPath,\n} from '../query/equality-conjunct.js'\nimport { makeComparator } from '../utils/comparison.js'\nimport { buildCompareOptions } from '../query/compiler/order-by'\nimport { codedMessage, codedWarning, devBuild } from '../error-message.js'\nimport type {\n ChangeMessage,\n CollectionLike,\n CurrentStateAsChangesOptions,\n SubscribeChangesOptions,\n} from '../types'\nimport type { CollectionImpl } from './index.js'\nimport type { BasicExpression, OrderBy } from '../query/ir.js'\nimport type { WithVirtualProps } from '../virtual-props.js'\n\n/**\n * Yields visible entries, enriched with virtual properties, whose stored row\n * passes `prefilter`.\n */\nexport type StoredRowScan<T extends object, TKey extends string | number> = (\n prefilter: (row: object) => boolean,\n) => Iterable<[TKey, WithVirtualProps<T, TKey>]>\n\n/**\n * A test on a stored row that is false only when `expression` must be false\n * on the row's enriched copy, so a scan can skip enriching rows that fail.\n * It reads one `eq(field, literal)` conjunct. The copy holds each enumerable\n * own root field of the stored row and lacks the others, so its field is the\n * stored value or `undefined`, which matches no literal.\n */\nexport function compileStoredRowPrefilter(\n expression: BasicExpression<boolean>,\n): ((row: object) => boolean) | undefined {\n const conjuncts =\n expression.type === `func` && expression.name === `and`\n ? expression.args\n : [expression]\n for (const conjunct of conjuncts) {\n const eq = equalityConjunct(conjunct, getPropRefPropertyPath)\n if (eq) {\n return (row) =>\n equalityKey(readPath(row as Record<string, unknown>, eq.path)) ===\n eq.literalKey\n }\n }\n return undefined\n}\n\n/**\n * Returns the current state of the collection as an array of changes\n * @param collection - The collection to get changes from\n * @param options - Options including optional where filter, orderBy, and limit\n * @returns An array of changes\n * @example\n * // Get all items as changes\n * const allChanges = currentStateAsChanges(collection)\n *\n * // Get only items matching a condition\n * const activeChanges = currentStateAsChanges(collection, {\n * where: (row) => row.status === 'active'\n * })\n *\n * // Get only items using a pre-compiled expression\n * const activeChanges = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active')\n * })\n *\n * // Get items ordered by name with limit\n * const topUsers = currentStateAsChanges(collection, {\n * orderBy: [{ expression: row.name, compareOptions: { direction: 'asc' } }],\n * limit: 10\n * })\n *\n * // Get active users ordered by score (highest score first)\n * const topActiveUsers = currentStateAsChanges(collection, {\n * where: eq(row.status, 'active'),\n * orderBy: [{ expression: row.score, compareOptions: { direction: 'desc' } }],\n * })\n */\nexport function currentStateAsChanges<\n T extends object,\n TKey extends string | number,\n>(\n collection: CollectionLike<WithVirtualProps<T, TKey>, TKey>,\n options: CurrentStateAsChangesOptions = {},\n scanStoredRows?: StoredRowScan<T, TKey>,\n): Array<ChangeMessage<WithVirtualProps<T, TKey>, TKey>> | void {\n // Helper function to collect filtered results\n const collectFilteredResults = (\n filterFn?: (value: WithVirtualProps<T, TKey>) => boolean,\n ): Array<ChangeMessage<WithVirtualProps<T, TKey>, TKey>> => {\n const result: Array<ChangeMessage<WithVirtualProps<T, TKey>, TKey>> = []\n // Reject rows by a stored field before enriching them; survivors still\n // pass through the full predicate.\n const prefilter =\n filterFn && scanStoredRows && options.where\n ? compileStoredRowPrefilter(options.where)\n : undefined\n const rows = prefilter ? scanStoredRows!(prefilter) : collection.entries()\n for (const [key, value] of rows) {\n // If no filter function is provided, include all items\n if (filterFn?.(value) ?? true) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // Validate that limit without orderBy doesn't happen\n if (options.limit !== undefined && !options.orderBy) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `limit cannot be used without orderBy`\n : codedMessage(94),\n )\n }\n\n // First check if orderBy is present (optionally with limit)\n if (options.orderBy) {\n // Create where filter function if present\n const whereFilter = options.where\n ? createFilterFunctionFromExpression(options.where)\n : undefined\n\n // Get ordered keys using index optimization when possible\n const orderedKeys = getOrderedKeys(\n collection,\n options.orderBy,\n options.limit,\n whereFilter,\n options.optimizedOnly,\n )\n\n if (orderedKeys === undefined) {\n // `getOrderedKeys` returned undefined because we asked for `optimizedOnly` and there was no index to use\n return\n }\n\n // Convert keys to change messages\n const result: Array<ChangeMessage<WithVirtualProps<T, TKey>, TKey>> = []\n for (const key of orderedKeys) {\n const value = collection.get(key)\n if (value !== undefined) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n }\n\n // If no orderBy OR orderBy optimization failed, use where clause optimization\n if (!options.where) {\n // No filtering, return all items\n return collectFilteredResults()\n }\n\n // There's a where clause, let's see if we can use an index\n try {\n const expression: BasicExpression<boolean> = options.where\n\n // Try to optimize the query using indexes\n const optimizationResult = optimizeExpressionWithIndexes(\n expression,\n collection,\n )\n\n if (optimizationResult.canOptimize) {\n // Use index optimization. When the index lookup is inexact, the keys\n // are a superset of the true result (some conditions could not be\n // served by an index), so re-check each row against the full expression.\n const filterFn = optimizationResult.isExact\n ? undefined\n : createFilterFunctionFromExpression(expression)\n const result: Array<ChangeMessage<WithVirtualProps<T, TKey>, TKey>> = []\n for (const key of optimizationResult.matchingKeys) {\n const value = collection.get(key)\n if (value !== undefined && (filterFn?.(value) ?? true)) {\n result.push({\n type: `insert`,\n key,\n value,\n })\n }\n }\n return result\n } else {\n if (options.optimizedOnly) {\n return\n }\n\n const filterFn = createFilterFunctionFromExpression(expression)\n return collectFilteredResults(filterFn)\n }\n } catch (error) {\n // If anything goes wrong with the where clause, fall back to full scan\n console.warn(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `${collection.id ? `[${collection.id}] ` : ``}Error processing where clause, falling back to full scan:`\n : codedWarning(213, { id: collection.id }),\n error,\n )\n\n const filterFn = createFilterFunctionFromExpression(options.where)\n\n if (options.optimizedOnly) {\n return\n }\n\n return collectFilteredResults(filterFn)\n }\n}\n\n/**\n * Creates a filter function from a pre-compiled expression\n * @param expression - The pre-compiled expression to evaluate\n * @returns A function that takes an item and returns true if it matches the filter\n */\nexport function createFilterFunctionFromExpression<T extends object>(\n expression: BasicExpression<boolean>,\n): (item: T) => boolean {\n // Compile expression once when filter function is created, not on every invocation\n const evaluator = compileSingleRowExpression(expression)\n\n return (item: T): boolean => {\n try {\n const result = evaluator(item as Record<string, unknown>)\n return toBooleanPredicate(result)\n } catch {\n // If evaluation fails, exclude the item\n return false\n }\n }\n}\n\n/**\n * Creates a filtered callback that only calls the original callback with changes that match the where clause\n * @param originalCallback - The original callback to filter\n * @param options - The subscription options containing the where clause\n * @returns A filtered callback function\n */\nexport function createFilteredCallback<\n T extends object,\n TKey extends string | number = string | number,\n>(\n originalCallback: (changes: Array<ChangeMessage<T>>) => void,\n options: SubscribeChangesOptions<T, TKey>,\n): (changes: Array<ChangeMessage<T>>) => boolean {\n const filterFn = createFilterFunctionFromExpression(options.whereExpression!)\n\n return (changes: Array<ChangeMessage<T>>) => {\n const filteredChanges: Array<ChangeMessage<T>> = []\n\n for (const change of changes) {\n if (change.type === `insert`) {\n // For inserts, check if the new value matches the filter\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n } else if (change.type === `update`) {\n // For updates, we need to check both old and new values\n const newValueMatches = filterFn(change.value)\n const oldValueMatches = change.previousValue\n ? filterFn(change.previousValue)\n : false\n\n if (newValueMatches && oldValueMatches) {\n // Both old and new match: emit update\n filteredChanges.push(change)\n } else if (newValueMatches && !oldValueMatches) {\n // New matches but old didn't: emit insert\n filteredChanges.push({\n ...change,\n type: `insert`,\n })\n } else if (!newValueMatches && oldValueMatches) {\n // Old matched but new doesn't: emit delete\n filteredChanges.push({\n ...change,\n type: `delete`,\n value: change.previousValue!, // Use the previous value for the delete\n })\n }\n // If neither matches, don't emit anything\n } else {\n // For deletes, include if the previous value would have matched\n // (so subscribers know something they were tracking was deleted)\n if (filterFn(change.value)) {\n filteredChanges.push(change)\n }\n }\n }\n\n // Always call the original callback if we have filtered changes OR\n // if the original changes array was empty (which indicates a ready signal)\n if (filteredChanges.length > 0 || changes.length === 0) {\n originalCallback(filteredChanges)\n return true\n }\n return false\n }\n}\n\n/**\n * Gets ordered keys from a collection using index optimization when possible\n * @param collection - The collection to get keys from\n * @param orderBy - The order by clause\n * @param limit - Optional limit on number of keys to return\n * @param whereFilter - Optional filter function to apply while traversing\n * @returns Array of keys in sorted order\n */\nfunction getOrderedKeys<T extends object, TKey extends string | number>(\n collection: CollectionLike<T, TKey>,\n orderBy: OrderBy,\n limit?: number,\n whereFilter?: (item: T) => boolean,\n optimizedOnly?: boolean,\n): Array<TKey> | undefined {\n // For single-column orderBy on a ref expression, try index optimization\n if (orderBy.length === 1) {\n const clause = orderBy[0]!\n const orderByExpression = clause.expression\n\n if (orderByExpression.type === `ref`) {\n const propRef = orderByExpression\n const fieldPath = propRef.path\n const compareOpts = buildCompareOptions(clause, collection)\n\n // Ensure index exists for this field\n ensureIndexForField(\n fieldPath[0]!,\n fieldPath,\n collection as CollectionImpl<T, TKey>,\n compareOpts,\n supportsOrderedIndexStructure,\n )\n\n // Find the index\n const index = findIndexForField(\n collection,\n fieldPath,\n compareOpts,\n supportsOrderedRange,\n )\n\n if (index) {\n // Use index optimization\n const filterFn = (key: TKey): boolean => {\n const value = collection.get(key)\n if (value === undefined) {\n return false\n }\n return whereFilter?.(value) ?? true\n }\n\n // Take the keys that match the filter and limit\n // if no limit is provided `index.keyCount` is used,\n // i.e. we will take all keys that match the filter\n return index.takeFromStart(limit ?? index.keyCount, filterFn)\n }\n }\n }\n\n if (optimizedOnly) {\n return\n }\n\n // Fallback: collect all items and sort in memory\n const allItems: Array<{ key: TKey; value: T }> = []\n for (const [key, value] of collection.entries()) {\n if (whereFilter?.(value) ?? true) {\n allItems.push({ key, value })\n }\n }\n\n const clauses = orderBy.map((clause) => ({\n expression: clause.expression,\n compare: makeComparator(buildCompareOptions(clause, collection)),\n }))\n const compare = (a: { key: TKey; value: T }, b: { key: TKey; value: T }) => {\n for (const clause of clauses) {\n // Extract values for comparison\n const aValue = extractValueFromItem(a.value, clause.expression)\n const bValue = extractValueFromItem(b.value, clause.expression)\n\n const result = clause.compare(aValue, bValue)\n if (result !== 0) {\n return result\n }\n }\n return 0\n }\n\n allItems.sort(compare)\n const sortedKeys = allItems.map((item) => item.key)\n\n // Apply limit if provided\n if (limit !== undefined) {\n return sortedKeys.slice(0, limit)\n }\n\n // if no limit is provided, we will return all keys\n return sortedKeys\n}\n\n/**\n * Helper function to extract a value from an item based on an expression\n */\nfunction extractValueFromItem(item: any, expression: BasicExpression): any {\n if (expression.type === `ref`) {\n const propRef = expression\n let value = item\n for (const pathPart of propRef.path) {\n value = value?.[pathPart]\n }\n return value\n } else if (expression.type === `val`) {\n return expression.value\n } else {\n // It must be a function\n const evaluator = compileSingleRowExpression(expression)\n return evaluator(item as Record<string, unknown>)\n }\n}\n"],"mappings":";;;;;;;;AA6CA,SAAgB,0BACd,YACwC;CACxC,MAAM,YACJ,WAAW,SAAS,UAAU,WAAW,SAAS,QAC9C,WAAW,OACX,CAAC,UAAU;CACjB,KAAA,MAAW,YAAY,WAAW;EAChC,MAAM,KAAKA,0BAAAA,iBAAiB,UAAUC,WAAAA,sBAAsB;EAC5D,IAAI,IACF,QAAQ,QACNC,0BAAAA,YAAYC,0BAAAA,SAAS,KAAgC,GAAG,IAAI,CAAC,MAC7D,GAAG;CAET;AAEF;AAiCA,SAAgB,sBAId,YACA,UAAwC,CAAC,GACzC,gBAC8D;CAE9D,MAAM,0BACJ,aAC0D;EAC1D,MAAM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