UNPKG

@tanstack/react-db

Version:

React integration for @tanstack/db

1 lines • 35.3 kB
{"version":3,"file":"useLiveQuery.cjs","names":["useEffect","useLayoutEffect","shouldWarnInDevelopment","getUnboundDescriptorReporter","prepareLiveQueryValue","identifyLiveQuery","useOptionalDbClient","isCollection","useRef","createLiveQuerySourceIdClaims","getLiveQueryKey","deepEquals","getLiveQueryHash","getStableValueHash","resolveLiveQueryValue","releaseDeferredOnReclaim","createLiveQueryObserver","useSyncExternalStore","rejectLiveQueryInput"],"sources":["../../src/useLiveQuery.ts"],"sourcesContent":["'use client'\n\nimport { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from 'react'\nimport {\n createLiveQueryObserver,\n createLiveQuerySourceIdClaims,\n deepEquals,\n getLiveQueryHash,\n getLiveQueryKey,\n getStableValueHash,\n identifyLiveQuery,\n isCollection,\n prepareLiveQueryValue,\n rejectLiveQueryInput,\n releaseDeferredOnReclaim,\n resolveLiveQueryValue,\n resumeDeferredLiveQueryCollections,\n} from '@tanstack/db'\nimport { useOptionalDbClient } from './DbProvider'\nimport { shouldWarnInDevelopment } from './development'\nimport {\n getPreparedSources,\n getUnboundDescriptorReporter,\n} from './source-id-bindings'\nimport type { SuspenseBinding } from './useLiveSuspenseQuery'\nimport type {\n Collection,\n CollectionImpl,\n CollectionStatus,\n Context,\n DbClient,\n DeferredLiveQueryCollections,\n GetResult,\n InferResultType,\n InitialQueryBuilder,\n LiveQueryCollectionConfig,\n LiveQueryIdentityScope,\n LiveQueryKey,\n LiveQueryObserver,\n LiveQuerySourceIdClaims,\n LiveQueryStatusFlags,\n NonSingleResult,\n PooledLiveQueries,\n QueryBuilder,\n SingleResult,\n} from '@tanstack/db'\n\n// Use the client layout commit to schedule window moves. Server rendering has\n// no commit; React18 diagnoses a layout effect there even when it is empty.\nconst useWindowCommitEffect =\n typeof window === `undefined` ? useEffect : useLayoutEffect\n\nconst DEFAULT_GC_TIME_MS = 1 // Live queries created by useLiveQuery are cleaned up immediately (0 disables GC)\n// Suspense can discard refs before the first commit. Unclaimed preloads live\n// briefly across retries; a successful binding takes exclusive ownership.\nconst DEFAULT_SUSPENSE_GC_TIME_MS = 5000\nconst DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS = 16\nconst DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD = 10\nconst DERIVED_IDENTITY_TOTAL_WARN_MS = 50\nconst warnedDerivedIdentityCallsites = new Set<string>()\nconst unpreparedQueryValue = Symbol(`unpreparedQueryValue`)\n\nexport type DerivedIdentityProfiler = {\n renderCount: number\n totalMs: number\n maxMs: number\n warned: boolean\n}\n\n/** Identity timing and warning state have no work to do in production. */\nexport function createDerivedIdentityProfiler():\n DerivedIdentityProfiler | undefined {\n try {\n if (process.env.NODE_ENV !== `production`) {\n return { renderCount: 0, totalMs: 0, maxMs: 0, warned: false }\n }\n } catch {\n // Unbundled browsers may omit process; the warning policy handles that.\n }\n return undefined\n}\n\nexport type UseLiveQueryStatus = CollectionStatus | `disabled`\nexport type { LiveQueryKey }\ntype UseLiveQueryConfigOptions<TContext extends Context> = Omit<\n LiveQueryCollectionConfig<TContext>,\n `query`\n> & {\n /**\n * Explicit identity for queries that contain opaque functional variants or\n * are hot enough that deriving identity from structured IR is too expensive.\n * Structured queries should omit this so DB can derive identity directly.\n */\n queryKey?: LiveQueryKey\n /** Override the nearest DbProvider for this query. */\n client?: DbClient\n /**\n * Pass `pooledLiveQueries` to share one partition among equality-filtered\n * queries of one shape. Suspense and DbClient queries never pool.\n */\n pool?: PooledLiveQueries\n}\n\ntype ConfiguredQueryBuilder<TContext extends Context> = Extract<\n LiveQueryCollectionConfig<TContext>[`query`],\n QueryBuilder<TContext>\n>\n\nexport type UseLiveQueryConfig<TContext extends Context> =\n UseLiveQueryConfigOptions<TContext> &\n Pick<LiveQueryCollectionConfig<TContext>, `query`>\n\nexport type ConditionalUseLiveQueryConfig<TContext extends Context> =\n UseLiveQueryConfigOptions<TContext> & {\n query:\n | ConfiguredQueryBuilder<TContext>\n | ((\n q: InitialQueryBuilder,\n ) => ConfiguredQueryBuilder<TContext> | undefined | null)\n }\n\nfunction getCurrentTime(): number {\n return typeof performance !== `undefined` &&\n typeof performance.now === `function`\n ? performance.now()\n : Date.now()\n}\n\nfunction getWarningCallsite(stackIndex: number): string {\n const stack = new Error().stack ?? `unknown`\n const lines = stack.split(`\\n`)\n const userFrame = lines\n .slice(1)\n .find(\n (line) =>\n !line.includes(`useLiveQuery.ts`) &&\n !line.includes(`useLiveSuspenseQuery.ts`) &&\n !line.includes(`useLiveInfiniteQuery.ts`),\n )\n return userFrame?.trim() ?? lines[stackIndex]?.trim() ?? stack\n}\n\nfunction warnDerivedIdentityHotPath(\n profiler: DerivedIdentityProfiler,\n durationMs: number,\n): void {\n if (\n profiler.warned ||\n !(\n shouldWarnInDevelopment(`TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`) &&\n process.env.NODE_ENV !== `production`\n )\n ) {\n return\n }\n\n const isSlowSingleRender =\n durationMs >= DERIVED_IDENTITY_SINGLE_RENDER_WARN_MS\n const isHotRenderPath =\n profiler.renderCount >= DERIVED_IDENTITY_RENDER_COUNT_WARN_THRESHOLD &&\n profiler.totalMs >= DERIVED_IDENTITY_TOTAL_WARN_MS\n\n if (!isSlowSingleRender && !isHotRenderPath) {\n return\n }\n\n const callsite = getWarningCallsite(5)\n if (warnedDerivedIdentityCallsites.has(callsite)) {\n profiler.warned = true\n return\n }\n\n warnedDerivedIdentityCallsites.add(callsite)\n profiler.warned = true\n\n const reason = isSlowSingleRender\n ? `one render took ${durationMs.toFixed(1)}ms`\n : `${profiler.renderCount} renders took ${profiler.totalMs.toFixed(1)}ms`\n\n console.warn(\n `[useLiveQuery] Deriving live query identity from structured query IR is running on a hot render path (${reason}, max ${profiler.maxMs.toFixed(1)}ms). ` +\n `Provide an explicit queryKey to skip rebuilding and hashing the IR on every render: useLiveQuery({ queryKey: [...], query }).`,\n )\n}\n\nexport { prepareLiveQueryValue as prepareQueryValue }\n\ntype DerivedQueryPreparation = {\n value: unknown\n identityDeps: Array<unknown>\n}\n\n/** How a hook checks a prepared query whose identity it compares. */\nexport function getIdentityScope(\n claims: LiveQuerySourceIdClaims,\n dbClient: DbClient | undefined,\n hookName: string,\n): LiveQueryIdentityScope {\n return {\n claims,\n client: dbClient,\n bindingName: hookName,\n onUnboundDescriptor: getUnboundDescriptorReporter(dbClient, hookName),\n }\n}\n\n/**\n * Prepare a query without `queryKey`, derive its identity, and claim its\n * source Collection IDs. A query whose IR has no stable identity throws\n * `UnhashableQueryIRError`. The hook's render boundary releases the sync\n * starts a rejected render deferred.\n */\nexport function prepareDerivedQuery(\n value: unknown,\n profiler: DerivedIdentityProfiler | undefined,\n scope: LiveQueryIdentityScope,\n deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>,\n): DerivedQueryPreparation {\n const shouldProfile =\n profiler !== undefined &&\n /* @__PURE__ */ shouldWarnInDevelopment(\n `TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`,\n )\n // Keep literal build guards at both timing sites so production bundlers can\n // erase the timer and warning machinery, as well as the profiler initializer.\n const start =\n shouldProfile && process.env.NODE_ENV !== `production`\n ? getCurrentTime()\n : 0\n const preparedValue = prepareLiveQueryValue(\n value,\n scope.client,\n deferredCollections,\n )\n\n try {\n return {\n value: preparedValue,\n identityDeps: [`derived`, identifyLiveQuery(preparedValue, scope)],\n }\n } finally {\n if (shouldProfile && process.env.NODE_ENV !== `production`) {\n const durationMs = getCurrentTime() - start\n profiler.renderCount += 1\n profiler.totalMs += durationMs\n profiler.maxMs = Math.max(profiler.maxMs, durationMs)\n warnDerivedIdentityHotPath(profiler, durationMs)\n }\n }\n}\n\n/**\n * Create a live query using a query function.\n * @param queryFn - Query function that defines what data to fetch\n * @returns Object with reactive data, state, and status information\n * @example\n * // Prefer config object syntax\n * const { data, isLoading } = useLiveQuery({\n * query: (q) =>\n * q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.completed, false))\n * .select(({ todos }) => ({ id: todos.id, text: todos.text }))\n * })\n *\n * @example\n * // Single result query\n * const { data } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.id, 1))\n * .findOne()\n * })\n *\n * @example\n * // Structured captured values are included in derived query identity\n * const { data, state } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection })\n * .where(({ todos }) => gt(todos.priority, minPriority)),\n * })\n *\n * @example\n * // Return undefined or null to disable a query\n * const { data, isEnabled } = useLiveQuery({\n * query: (q) => {\n * if (!userId) return undefined\n * return q.from({ todos: todosCollection })\n * .where(({ todos }) => eq(todos.userId, userId))\n * },\n * })\n *\n * @example\n * // Join pattern\n * const { data } = useLiveQuery({\n * query: (q) =>\n * q.from({ issues: issueCollection })\n * .join({ persons: personCollection }, ({ issues, persons }) =>\n * eq(issues.userId, persons.id)\n * )\n * .select(({ issues, persons }) => ({\n * id: issues.id,\n * title: issues.title,\n * userName: persons.name\n * }))\n * })\n *\n * @example\n * // Handle loading and error states\n * const { data, isLoading, isLoadingError, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todoCollection })\n * })\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isLoadingError) return <div>Error: {status}</div>\n *\n * return (\n * <ul>\n * {data.map(todo => <li key={todo.id}>{todo.text}</li>)}\n * </ul>\n * )\n */\n// Overload 1: Accept query function that always returns QueryBuilder\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (q: InitialQueryBuilder) => QueryBuilder<TContext>,\n): {\n state: Map<string | number, GetResult<TContext>>\n data: InferResultType<TContext>\n collection: Collection<GetResult<TContext>, string | number, {}>\n status: CollectionStatus // Can't be disabled if always returns QueryBuilder\n isEnabled: true // Always true if always returns QueryBuilder\n} & LiveQueryStatusFlags\n\n// Overload 2: Accept query function that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => QueryBuilder<TContext> | undefined | null,\n): {\n state: Map<string | number, GetResult<TContext>> | undefined\n data: InferResultType<TContext> | undefined\n collection: Collection<GetResult<TContext>, string | number, {}> | undefined\n status: UseLiveQueryStatus\n isEnabled: boolean\n} & LiveQueryStatusFlags\n\n// Overload 3: Accept query function that can return LiveQueryCollectionConfig\nexport function useLiveQuery<TContext extends Context>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => LiveQueryCollectionConfig<TContext> | undefined | null,\n): {\n state: Map<string | number, GetResult<TContext>> | undefined\n data: InferResultType<TContext> | undefined\n collection: Collection<GetResult<TContext>, string | number, {}> | undefined\n status: UseLiveQueryStatus\n isEnabled: boolean\n} & LiveQueryStatusFlags\n\n// Overload 4: Accept query function that can return Collection\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n queryFn: (\n q: InitialQueryBuilder,\n ) => Collection<TResult, TKey, TUtils> | undefined | null,\n): {\n state: Map<TKey, TResult> | undefined\n data: Array<TResult> | undefined\n collection: Collection<TResult, TKey, TUtils> | undefined\n status: UseLiveQueryStatus\n isEnabled: boolean\n} & LiveQueryStatusFlags\n\n// Overload 5: Accept query function that can return all types\nexport function useLiveQuery<\n TContext extends Context,\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n queryFn: (\n q: InitialQueryBuilder,\n ) =>\n | QueryBuilder<TContext>\n | LiveQueryCollectionConfig<TContext>\n | Collection<TResult, TKey, TUtils>\n | undefined\n | null,\n): {\n state:\n Map<string | number, GetResult<TContext>> | Map<TKey, TResult> | undefined\n data: InferResultType<TContext> | Array<TResult> | undefined\n collection:\n | Collection<GetResult<TContext>, string | number, {}>\n | Collection<TResult, TKey, TUtils>\n | undefined\n status: UseLiveQueryStatus\n isEnabled: boolean\n} & LiveQueryStatusFlags\n\n/**\n * Create a live query using configuration object\n * @param config - Configuration object with query and options\n * @returns Object with reactive data, state, and status information\n * @example\n * // Basic config object usage\n * const { data, status } = useLiveQuery({\n * query: (q) => q.from({ todos: todosCollection }),\n * gcTime: 60000\n * })\n *\n * @example\n * // With query builder and options\n * const queryBuilder = new Query()\n * .from({ persons: collection })\n * .where(({ persons }) => gt(persons.age, 30))\n * .select(({ persons }) => ({ id: persons.id, name: persons.name }))\n *\n * const { data, isReady } = useLiveQuery({\n * query: queryBuilder,\n * })\n *\n * @example\n * // Handle all states uniformly\n * const { data, isLoading, isReady, isLoadingError } = useLiveQuery({\n * query: (q) => q.from({ items: itemCollection })\n * })\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isLoadingError) return <div>Something went wrong</div>\n * if (!isReady) return <div>Preparing...</div>\n *\n * return <div>{data.length} items loaded</div>\n */\n// Overload 6: Accept config object\nexport function useLiveQuery<TContext extends Context>(\n config: UseLiveQueryConfig<TContext>,\n): {\n state: Map<string | number, GetResult<TContext>>\n data: InferResultType<TContext>\n collection: Collection<GetResult<TContext>, string | number, {}>\n status: CollectionStatus // Can't be disabled when query always returns a builder\n isEnabled: true // Always true when query always returns a builder\n} & LiveQueryStatusFlags\n\n// Overload 7: Accept config object with a query that can return undefined/null\nexport function useLiveQuery<TContext extends Context>(\n config: ConditionalUseLiveQueryConfig<TContext>,\n): {\n state: Map<string | number, GetResult<TContext>> | undefined\n data: InferResultType<TContext> | undefined\n collection: Collection<GetResult<TContext>, string | number, {}> | undefined\n status: UseLiveQueryStatus\n isEnabled: boolean\n} & LiveQueryStatusFlags\n\n/**\n * Subscribe to an existing live query collection\n * @param liveQueryCollection - Pre-created live query collection to subscribe to\n * @returns Object with reactive data, state, and status information\n * @example\n * // Using pre-created live query collection\n * const myLiveQuery = createLiveQueryCollection((q) =>\n * q.from({ todos: todosCollection }).where(({ todos }) => eq(todos.active, true))\n * )\n * const { data, collection } = useLiveQuery(myLiveQuery)\n *\n * @example\n * // Access collection methods directly\n * const { data, collection, isReady } = useLiveQuery(existingCollection)\n *\n * // Use collection for mutations\n * const handleToggle = (id) => {\n * collection.update(id, draft => { draft.completed = !draft.completed })\n * }\n *\n * @example\n * // Handle states consistently\n * const { data, isLoading, isLoadingError } = useLiveQuery(sharedCollection)\n *\n * if (isLoading) return <div>Loading...</div>\n * if (isLoadingError) return <div>Error loading data</div>\n *\n * return <div>{data.map(item => <Item key={item.id} {...item} />)}</div>\n */\n// Overload 10: Accept pre-created live query collection\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: Collection<TResult, TKey, TUtils> & NonSingleResult,\n): {\n state: Map<TKey, TResult>\n data: Array<TResult>\n collection: Collection<TResult, TKey, TUtils>\n status: CollectionStatus // Can't be disabled for pre-created live query collections\n isEnabled: true // Always true for pre-created live query collections\n} & LiveQueryStatusFlags\n\n// Overload 10: Accept pre-created live query collection with singleResult: true\nexport function useLiveQuery<\n TResult extends object,\n TKey extends string | number,\n TUtils extends Record<string, any>,\n>(\n liveQueryCollection: Collection<TResult, TKey, TUtils> & SingleResult,\n): {\n state: Map<TKey, TResult>\n data: TResult | undefined\n collection: Collection<TResult, TKey, TUtils> & SingleResult\n status: CollectionStatus // Can't be disabled for pre-created live query collections\n isEnabled: true // Always true for pre-created live query collections\n} & LiveQueryStatusFlags\n\n// Implementation - use function overloads to infer the actual collection type\nexport function useLiveQuery(configOrQueryOrCollection: any) {\n return useLiveQueryImpl(configOrQueryOrCollection) as any\n}\n\n// What one hook instance keeps across renders. Fields produced by resolution\n// are installed with their first value, rather than initialized and overwritten\n// in the same render.\ntype HookInstance = {\n collection: Collection<object, string | number, {}> | null\n identityDeps: Array<unknown> | null\n deferredCollections: Set<CollectionImpl<any, string | number, any, any, any>>\n sourceIds: LiveQuerySourceIdClaims\n config?: unknown\n client?: DbClient\n derivedIdentityProfiler?: DerivedIdentityProfiler\n cancelReclaimRelease?: () => void\n observer?: LiveQueryObserver<object, string | number>\n queryHash?: string\n subscribe?: (onStoreChange: () => void) => () => void\n}\n\ntype LiveQueryResult = ReturnType<\n LiveQueryObserver<object, string | number>[`getSnapshot`]\n>\n\n/** @internal Shared implementation for ordinary and Suspense bindings. */\nexport function useLiveQueryImpl(\n configOrQueryOrCollection: unknown,\n): LiveQueryResult\nexport function useLiveQueryImpl(\n configOrQueryOrCollection: unknown,\n suspense: SuspenseBinding,\n): {\n result: LiveQueryResult\n client: DbClient | undefined\n queryHash: string | undefined\n observer: LiveQueryObserver<object, string | number>\n /** Sync starts this render deferred, released if the render throws. */\n deferredCollections: DeferredLiveQueryCollections\n}\nexport function useLiveQueryImpl(\n configOrQueryOrCollection: any,\n suspense?: SuspenseBinding,\n) {\n const forSuspense = suspense !== undefined\n const contextDbClient = useOptionalDbClient()\n // Check if it's already a collection\n const inputIsCollection = isCollection(configOrQueryOrCollection)\n const dbClient: DbClient | undefined =\n (inputIsCollection || typeof configOrQueryOrCollection !== `object`\n ? undefined\n : configOrQueryOrCollection?.client) ?? contextDbClient\n\n const instanceRef = useRef<HookInstance | null>(null)\n const instance: HookInstance = (instanceRef.current ??= {\n collection: null,\n identityDeps: null,\n derivedIdentityProfiler: createDerivedIdentityProfiler(),\n deferredCollections: new Set(),\n sourceIds: createLiveQuerySourceIdClaims(),\n })\n // A commit releases the starts itself, so it drops the reclaim listener.\n const resumeDeferredCollections = () => {\n instance.cancelReclaimRelease?.()\n instance.cancelReclaimRelease = undefined\n resumeDeferredLiveQueryCollections(instance.deferredCollections)\n }\n\n // The render boundary: a render that throws anywhere after preparation\n // never commits, so it releases the sync starts it deferred here.\n try {\n const queryKey = !inputIsCollection\n ? getLiveQueryKey(configOrQueryOrCollection)\n : undefined\n let preparedQueryValue: unknown | typeof unpreparedQueryValue =\n unpreparedQueryValue\n let identityDeps: ReadonlyArray<unknown>\n\n if (queryKey) {\n identityDeps = queryKey\n } else if (inputIsCollection) {\n identityDeps = []\n } else {\n const preparation = prepareDerivedQuery(\n configOrQueryOrCollection,\n instance.derivedIdentityProfiler,\n getIdentityScope(instance.sourceIds, dbClient, `useLiveQuery`),\n instance.deferredCollections,\n )\n preparedQueryValue = preparation.value\n identityDeps = preparation.identityDeps\n }\n\n // Check if we need to create/recreate the collection\n let needsNewCollection =\n suspense?.needsOwnCollection ||\n !instance.collection ||\n (inputIsCollection\n ? instance.config !== configOrQueryOrCollection\n : instance.client !== dbClient ||\n !deepEquals(instance.identityDeps, identityDeps))\n\n if (\n needsNewCollection &&\n !inputIsCollection &&\n preparedQueryValue === unpreparedQueryValue\n ) {\n preparedQueryValue = prepareLiveQueryValue(\n configOrQueryOrCollection,\n dbClient,\n instance.deferredCollections,\n )\n }\n\n let queryHash = instance.queryHash\n let commitWindow: (() => void) | undefined\n let compile:\n | ((\n ownsCollection: boolean,\n windowOwner: object,\n ) => Collection<object, string | number, {}> | null)\n | undefined\n if (needsNewCollection) {\n // Preparation rejects unhashable derived inputs; keyed inputs must hash.\n queryHash = queryKey\n ? getLiveQueryHash(preparedQueryValue, queryKey)\n : getStableValueHash(\n inputIsCollection\n ? [`collection`, configOrQueryOrCollection.id]\n : identityDeps,\n `queryKey`,\n )\n if (inputIsCollection) {\n // Warn when passing a collection directly with on-demand sync mode\n // In on-demand mode, data is only loaded when queries with predicates request it\n // Passing the collection directly doesn't provide any predicates, so no data loads\n if (\n /* @__PURE__ */ shouldWarnInDevelopment(\n `TANSTACK_DB_DISABLE_QUERY_IDENTITY_WARNINGS`,\n ) &&\n process.env.NODE_ENV !== `production` &&\n (configOrQueryOrCollection as { config?: { syncMode?: string } })\n .config?.syncMode === `on-demand`\n ) {\n console.warn(\n `[useLiveQuery] Warning: Passing a collection with syncMode \"on-demand\" directly to useLiveQuery ` +\n `will not load any data. In on-demand mode, data is only loaded when queries with predicates request it.\\n\\n` +\n `Instead, use a query builder function:\\n` +\n ` const { data } = useLiveQuery({ query: (q) => q.from({ c: myCollection }).select(({ c }) => c) })\\n\\n` +\n `Or switch to syncMode \"eager\" if you want all data to sync automatically.`,\n )\n }\n // It's already a collection, ensure sync is started for React hooks\n configOrQueryOrCollection.startSyncImmediate()\n instance.collection = configOrQueryOrCollection\n } else {\n compile = (ownsCollection: boolean, windowOwner: object) => {\n // A keyed query claims nothing, so it reports an unbound descriptor\n // here; the other forms reported it when they claimed.\n if (!dbClient && queryKey !== undefined) {\n getPreparedSources(preparedQueryValue, dbClient, `useLiveQuery`)\n }\n const collection = resolveLiveQueryValue(preparedQueryValue, {\n gcTime: forSuspense\n ? DEFAULT_SUSPENSE_GC_TIME_MS\n : DEFAULT_GC_TIME_MS,\n // Suspense and client observers have distinct preload/snapshot\n // policies, so neither uses equality-partition pooling.\n pool: forSuspense || dbClient ? false : undefined,\n previousCollection:\n ownsCollection && instance.client === dbClient\n ? instance.collection\n : null,\n windowOwner,\n onWindowChange: (move) => {\n commitWindow = move\n },\n // Without a DbClient, Suspense starts it through a preload below.\n startSync: !forSuspense || dbClient !== undefined,\n })\n // A render that never commits releases its deferred sync starts\n // when garbage collection reclaims the live query it built. A\n // Collection the callback returned is not this render's to reclaim.\n if (collection && !isCollection(preparedQueryValue)) {\n instance.cancelReclaimRelease?.()\n instance.cancelReclaimRelease = releaseDeferredOnReclaim(\n collection,\n instance.deferredCollections,\n )\n }\n return collection\n }\n instance.collection = suspense\n ? suspense.resolve(preparedQueryValue, queryHash, dbClient, compile)\n : compile(true, instance)\n // An abandoned render must leave invalidation pending. Its retry or\n // urgent replacement still prepares and commits the requested move.\n if (!commitWindow) instance.identityDeps = [...identityDeps]\n }\n instance.config = configOrQueryOrCollection\n instance.client = dbClient\n if (!commitWindow) instance.queryHash = queryHash\n }\n\n // A client-backed move retains the graph but binds a fresh observer to the\n // requested page's transport hash. Peers keep their own snapshots/observers.\n if (commitWindow && !dbClient) needsNewCollection = false\n let observer = instance.observer!\n let subscribe = instance.subscribe!\n const watchCollection = () => {\n // Recreate the observer when the underlying collection changes. The observer\n // is not disposed explicitly here or on unmount: `useSyncExternalStore`\n // unsubscribes it when the subscribe changes or the component unmounts, which\n // detaches the collection subscription; the observer is then GC'd. (An unmount\n // effect that disposed it would misfire under StrictMode/offscreen effect\n // replay, leaving a disposed observer in the ref.)\n // Defer the initial notify: useSyncExternalStore must not be notified\n // synchronously during subscribe.\n // Wholesale mode: React re-reads getSnapshot() on notify, keeps the\n // hook's pre-observer loading policy, and — because wholesale delivers\n // nothing synchronously during subscribe — never notifies\n // useSyncExternalStore inside its own subscribe call.\n observer = createLiveQueryObserver(instance.collection, {\n mode: `wholesale`,\n client: dbClient,\n queryHash,\n onPreload: resumeDeferredCollections,\n suspendUntilReady: forSuspense,\n })\n // The subscribe function stays bound to the observer that created it.\n subscribe = (onStoreChange: () => void) => {\n const unsubscribe = observer.subscribe(onStoreChange)\n resumeDeferredCollections()\n return unsubscribe\n }\n }\n if (needsNewCollection) watchCollection()\n // Until commit, a proposed page's observer and transport identity belong\n // only to this render. Cancellation must leave the committed seed intact.\n useWindowCommitEffect(() => {\n if (commitWindow) {\n instance.identityDeps = [...identityDeps]\n instance.queryHash = queryHash\n instance.observer = observer\n instance.subscribe = subscribe\n commitWindow()\n }\n claim?.()\n })\n // A Suspense render asks for its data. Preloading starts the sync run, so a\n // source that already holds the rows makes it ready before the snapshot is\n // read instead of suspending once. useLiveSuspenseQuery surfaces failures.\n // A DbClient defers source starts past render and owns its streamed query.\n if (\n forSuspense &&\n !dbClient &&\n (instance.collection?.status === `idle` ||\n instance.collection?.status === `cleaned-up`)\n ) {\n observer.preload().catch(() => {})\n }\n\n const privateCollection = compile && suspense?.forkReady(observer, compile)\n if (privateCollection) {\n instance.collection = privateCollection\n watchCollection()\n }\n if (!commitWindow) {\n instance.observer = observer\n instance.subscribe = subscribe\n }\n const returned = useSyncExternalStore(\n subscribe,\n () => {\n const snapshot = observer.getSnapshot()\n return suspense ? suspense.read(snapshot) : snapshot\n },\n () => {\n const snapshot = observer.getServerSnapshot(forSuspense)\n return suspense ? suspense.read(snapshot) : snapshot\n },\n )\n const claim = returned.isReady ? suspense?.claim() : undefined\n // Pass render-local metadata directly to the Suspense wrapper. The public\n // hook returns the observer's stable snapshot without a wrapper allocation.\n if (forSuspense) {\n return {\n result: returned,\n client: dbClient,\n queryHash,\n observer,\n deferredCollections: instance.deferredCollections,\n }\n }\n return returned\n } catch (error) {\n return rejectLiveQueryInput(instance.deferredCollections, error)\n }\n}\n"],"mappings":";;;;;;;AAiDA,IAAM,wBACJ,OAAO,WAAW,cAAcA,MAAAA,YAAYC,MAAAA;AAE9C,IAAM,qBAAqB;AAG3B,IAAM,8BAA8B;AACpC,IAAM,yCAAyC;AAC/C,IAAM,+CAA+C;AACrD,IAAM,iCAAiC;AACvC,IAAM,iDAAiC,IAAI,IAAY;AACvD,IAAM,uBAAuB,OAAO,sBAAsB;;AAU1D,SAAgB,gCACsB;CACpC,IAAI;EACF,IAAA,QAAA,IAAA,aAA6B,cAC3B,OAAO;GAAE,aAAa;GAAG,SAAS;GAAG,OAAO;GAAG,QAAQ;EAAM;CAEjE,QAAQ,CAER;AAEF;AAyCA,SAAS,iBAAyB;CAChC,OAAO,OAAO,gBAAgB,eAC5B,OAAO,YAAY,QAAQ,aACzB,YAAY,IAAI,IAChB,KAAK,IAAI;AACf;AAEA,SAAS,mBAAmB,YAA4B;CACtD,MAAM,yBAAQ,IAAI,MAAM,EAAA,CAAE,SAAS;CACnC,MAAM,QAAQ,MAAM,MAAM,IAAI;CAS9B,OARkB,MACf,MAAM,CAAC,CAAC,CACR,MACE,SACC,CAAC,KAAK,SAAS,iBAAiB,KAChC,CAAC,KAAK,SAAS,yBAAyB,KACxC,CAAC,KAAK,SAAS,yBAAyB,CAEvC,CAAA,EAAW,KAAK,KAAK,MAAM,WAAW,EAAE,KAAK,KAAK;AAC3D;AAEA,SAAS,2BACP,UACA,YACM;CACN,IACE,SAAS,UACT,EACEC,oBAAAA,wBAAwB,6CAA6C,KAAA,QAAA,IAAA,aAC5C,eAG3B;CAGF,MAAM,qBACJ,cAAc;CAChB,MAAM,kBACJ,SAAS,eAAe,gDACxB,SAAS,WAAW;CAEtB,IAAI,CAAC,sBAAsB,CAAC,iBAC1B;CAGF,MAAM,WAAW,mBAAmB,CAAC;CACrC,IAAI,+BAA+B,IAAI,QAAQ,GAAG;EAChD,S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