{"version":3,"file":"utils.cjs","names":["collectCollectionSources","requireCollectionSource","codedMessage","isExpressionLike","isRefProxy","buildQuery","getQueryIR","UnsupportedRootScalarSelectError","MultiSet","normalizeOrderByPaths"],"sources":["../../../../src/query/live/utils.ts"],"sourcesContent":["import { MultiSet } from '@tanstack/db-ivm'\nimport { UnsupportedRootScalarSelectError } from '../../errors.js'\nimport { normalizeOrderByPaths } from '../compiler/expressions.js'\nimport { buildQuery, getQueryIR } from '../builder/index.js'\nimport {\n  collectCollectionSources,\n  isExpressionLike,\n  requireCollectionSource,\n} from '../ir.js'\nimport { isRefProxy } from '../builder/ref-proxy-identity.js'\nimport { codedMessage, devBuild } from '../../error-message.js'\nimport type { MultiSetArray, RootStreamBuilder } from '@tanstack/db-ivm'\nimport type { Collection } from '../../collection/index.js'\nimport type { ChangeMessage, StringCollationConfig } from '../../types.js'\nimport type { InitialQueryBuilder, QueryBuilder } from '../builder/index.js'\nimport type { Context } from '../builder/types.js'\nimport type { OrderBy, QueryIR } from '../ir.js'\n\n/**\n * Helper function to extract collections from a compiled query.\n * Traverses the query IR to find all collection references.\n * Maps collections by their ID (not alias) as expected by the compiler.\n */\nexport function extractCollectionsFromQuery(\n  query: QueryIR,\n): Record<string, Collection<any, any, any>> {\n  const collections: Record<string, Collection<any, any, any>> = {}\n  for (const source of collectCollectionSources(query)) {\n    collections[source.collection.id] = source.collection\n  }\n  return collections\n}\n\nexport { collectCollectionSources as extractCollectionSources }\n\n/**\n * Whether a source permits initial-query readiness, which live queries and\n * `skipInitial` Effects share. An on-demand source serves its consumer through\n * subset demand, whose settlement each consumer tracks, so its own Collection\n * readiness does not gate the consumer; that readiness can lag, as a\n * progressive source's background full sync does. An eager source serves no\n * subset demand, so it must reach ready.\n */\nexport function sourcePermitsInitialReadiness(\n  collection: Pick<Collection, `config` | `isReady`>,\n): boolean {\n  return collection.config.syncMode === `on-demand` || collection.isReady()\n}\n\n/**\n * Helper function to extract the collection that is referenced in the query's FROM clause.\n * The FROM clause may refer directly to a collection or indirectly to a subquery.\n */\nexport function extractCollectionFromSource(query: {\n  readonly from: any\n}): Collection<any, any, any> {\n  const from = query.from\n\n  if (from.type === `collectionRef`) {\n    return from.collection\n  } else if (from.type === `descriptorRef`) {\n    return requireCollectionSource(from)\n  } else if (from.type === `queryRef`) {\n    // Recursively extract from subquery\n    return extractCollectionFromSource(from.query)\n  } else if (from.type === `unionFrom`) {\n    return extractCollectionFromSource({ from: from.sources[0] })\n  } else if (from.type === `unionAll`) {\n    return extractCollectionFromSource(from.queries[0])\n  }\n\n  throw new Error(\n    devBuild() && process.env.NODE_ENV !== `production`\n      ? `Failed to extract collection. Invalid FROM clause: ${JSON.stringify(query)}`\n      : codedMessage(160),\n  )\n}\n\n/**\n * Check if a value is a nested select object (plain object, not an expression)\n */\nfunction isNestedSelectObject(obj: any): boolean {\n  if (obj === null || typeof obj !== `object`) return false\n  if (isExpressionLike(obj)) return false\n  // Ref proxies from spread operations\n  if (isRefProxy(obj)) return false\n  return true\n}\n\n/**\n * Builds a query IR from a config object that contains either a query builder\n * function or a QueryBuilder instance.\n */\nexport function buildQueryFromConfig<TContext extends Context>(config: {\n  query:\n    | ((q: InitialQueryBuilder) => QueryBuilder<TContext>)\n    | QueryBuilder<TContext>\n  requireObjectResult?: boolean\n}): QueryIR {\n  // Build the query using the provided query builder function or instance\n  const query =\n    typeof config.query === `function`\n      ? buildQuery<TContext>(config.query)\n      : getQueryIR(config.query)\n\n  if (\n    config.requireObjectResult &&\n    query.select &&\n    !isNestedSelectObject(query.select)\n  ) {\n    throw new UnsupportedRootScalarSelectError()\n  }\n\n  return query\n}\n\n/**\n * Helper function to send changes to a D2 input stream.\n * Converts ChangeMessages to D2 MultiSet data and sends to the input.\n *\n * @returns The number of multiset entries sent\n */\nexport function sendChangesToInput(\n  input: RootStreamBuilder<unknown>,\n  changes: Iterable<ChangeMessage>,\n): number {\n  const multiSetArray: MultiSetArray<unknown> = []\n  for (const change of changes) {\n    const key = change.key\n    if (change.type === `insert`) {\n      multiSetArray.push([[key, change.value], 1])\n    } else if (change.type === `update`) {\n      multiSetArray.push([[key, change.previousValue], -1])\n      multiSetArray.push([[key, change.value], 1])\n    } else {\n      // change.type === `delete`\n      multiSetArray.push([[key, change.value], -1])\n    }\n  }\n\n  if (multiSetArray.length !== 0) {\n    input.sendData(new MultiSet(multiSetArray))\n  }\n\n  return multiSetArray.length\n}\n\n/** Splits updates into a delete of the old value and an insert of the new value */\nexport function* splitUpdates<\n  T extends object = Record<string, unknown>,\n  TKey extends string | number = string | number,\n>(\n  changes: Iterable<ChangeMessage<T, TKey>>,\n): Generator<ChangeMessage<T, TKey>> {\n  for (const change of changes) {\n    if (change.type === `update`) {\n      yield { type: `delete`, key: change.key, value: change.previousValue! }\n      yield { type: `insert`, key: change.key, value: change.value }\n    } else {\n      yield change\n    }\n  }\n}\n\n/** Keep each source key at one exact D2 contribution. */\nexport function reconcileChangesForD2<\n  T extends object,\n  TKey extends string | number,\n>(\n  changes: Array<ChangeMessage<T, TKey>>,\n  sentRows: Map<TKey, T>,\n): Array<ChangeMessage<T, TKey>> {\n  const reconciled: Array<ChangeMessage<T, TKey>> = []\n  for (const change of changes) {\n    const previousValue = sentRows.get(change.key)\n    if (change.type === `insert`) {\n      if (previousValue !== undefined) continue\n      sentRows.set(change.key, change.value)\n      reconciled.push(change)\n    } else if (change.type === `delete`) {\n      if (previousValue === undefined) continue\n      sentRows.delete(change.key)\n      reconciled.push({ ...change, value: previousValue })\n    } else {\n      sentRows.set(change.key, change.value)\n      reconciled.push(\n        previousValue === undefined\n          ? { type: `insert`, key: change.key, value: change.value }\n          : { ...change, previousValue },\n      )\n    }\n  }\n  return reconciled\n}\n\n/**\n * Compute orderBy/limit subscription hints for an alias.\n * Returns normalised orderBy and effective limit suitable for passing to\n * `subscribeChanges`, or `undefined` values when the query's orderBy cannot\n * be scoped to the given alias (e.g. cross-collection refs or aggregates), or\n * when its resolved string collation is a local custom comparator.\n */\nexport function computeSubscriptionOrderByHints(\n  query: { orderBy?: OrderBy; limit?: number; offset?: number },\n  alias: string,\n  queryCompareOptions: StringCollationConfig,\n): { orderBy: OrderBy | undefined; limit: number | undefined } {\n  const { orderBy, limit, offset } = query\n  const effectiveLimit =\n    limit !== undefined && offset !== undefined ? limit + offset : limit\n\n  const normalizedOrderBy = orderBy\n    ? normalizeOrderByPaths(orderBy, alias)\n    : undefined\n\n  const usesCustomLocalOrder =\n    normalizedOrderBy?.some(\n      (clause) =>\n        (clause.compareOptions.stringSort ?? queryCompareOptions.stringSort) ===\n        `custom`,\n    ) ?? false\n\n  // Only pass orderBy when it is scoped to this alias and uses simple refs,\n  // to avoid leaking cross-collection paths into backend-specific compilers.\n  const canPassOrderBy =\n    !usesCustomLocalOrder &&\n    (normalizedOrderBy?.every((clause) => {\n      const exp = clause.expression\n      if (exp.type !== `ref`) return false\n      const path = exp.path\n      return Array.isArray(path) && path.length === 1\n    }) ??\n      false)\n\n  return {\n    orderBy: canPassOrderBy ? normalizedOrderBy : undefined,\n    limit: canPassOrderBy ? effectiveLimit : undefined,\n  }\n}\n"],"mappings":";;;;;;;;AAuBA,SAAgB,4BACd,OAC2C;CAC3C,MAAM,cAAyD,CAAC;CAChE,KAAA,MAAW,UAAUA,WAAAA,yBAAyB,KAAK,GACjD,YAAY,OAAO,WAAW,MAAM,OAAO;CAE7C,OAAO;AACT;AAYA,SAAgB,8BACd,YACS;CACT,OAAO,WAAW,OAAO,aAAa,eAAe,WAAW,QAAQ;AAC1E;AAMA,SAAgB,4BAA4B,OAEd;CAC5B,MAAM,OAAO,MAAM;CAEnB,IAAI,KAAK,SAAS,iBAChB,OAAO,KAAK;MAAA,IACH,KAAK,SAAS,iBACvB,OAAOC,WAAAA,wBAAwB,IAAI;MAAA,IAC1B,KAAK,SAAS,YAEvB,OAAO,4BAA4B,KAAK,KAAK;MAAA,IACpC,KAAK,SAAS,aACvB,OAAO,4BAA4B,EAAE,MAAM,KAAK,QAAQ,GAAG,CAAC;MAAA,IACnD,KAA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