import { assertInInjectionContext, computed, effect, signal, untracked, } from '@angular/core' import { configPool, createLiveQueryObserver, getLiveQueryStatusFlags, getPublicCollection, isCollection, isSingleResultCollection, resolveLiveQueryValue, } from '@tanstack/db' import type { Collection, CollectionStatus, Context, GetResult, InferResultType, InitialQueryBuilder, LiveQueryHookConfig, LiveQuerySnapshot, LiveQueryStatusFlags, NonSingleResult, PooledLiveQueries, QueryBuilder, SingleResult, } from '@tanstack/db' import type { Signal } from '@angular/core' const DEFAULT_GC_TIME_MS = 1 export * from '@tanstack/db' /** * The result of calling `injectLiveQuery`. * Contains reactive signals for the query state and data. */ /** The status and flag signals every `injectLiveQuery` result has. */ export type InjectLiveQueryFlags = { /** A signal containing the current status of the collection */ status: Signal } & { [K in keyof LiveQueryStatusFlags]: Signal } export interface InjectLiveQueryResult< TContext extends Context, > extends InjectLiveQueryFlags { /** A signal containing the complete state map of results keyed by their ID */ state: Signal>> /** A signal containing the results as an array, or single result for findOne queries */ data: Signal> /** A signal containing the underlying collection instance (null for disabled queries) */ collection: Signal, string | number, {} > | null> } type InferConditionalResultType = TContext extends SingleResult ? InferResultType | [] : InferResultType export type InjectConditionalLiveQueryResult = Omit< InjectLiveQueryResult, `data` > & { data: Signal> } export interface InjectLiveQueryResultWithCollection< TResult extends object = any, TKey extends string | number = string | number, TUtils extends Record = {}, > extends InjectLiveQueryFlags { state: Signal> data: Signal> collection: Signal | null> } export interface InjectLiveQueryResultWithSingleResultCollection< TResult extends object = any, TKey extends string | number = string | number, TUtils extends Record = {}, > extends InjectLiveQueryFlags { state: Signal> data: Signal collection: Signal<(Collection & SingleResult) | null> } export function injectLiveQuery< TContext extends Context, TParams extends any, >(options: { params: () => TParams /** Pass `pooledLiveQueries` to share one partition among equal-shape queries. */ pool?: PooledLiveQueries query: (args: { params: TParams q: InitialQueryBuilder }) => QueryBuilder }): InjectLiveQueryResult export function injectLiveQuery< TContext extends Context, TParams extends any, >(options: { params: () => TParams /** Pass `pooledLiveQueries` to share one partition among equal-shape queries. */ pool?: PooledLiveQueries query: (args: { params: TParams q: InitialQueryBuilder }) => QueryBuilder | undefined | null }): InjectConditionalLiveQueryResult export function injectLiveQuery( queryFn: (q: InitialQueryBuilder) => QueryBuilder, ): InjectLiveQueryResult export function injectLiveQuery( queryFn: ( q: InitialQueryBuilder, ) => QueryBuilder | undefined | null, ): InjectConditionalLiveQueryResult export function injectLiveQuery( config: LiveQueryHookConfig, ): InjectLiveQueryResult // Pre-created collection without singleResult export function injectLiveQuery< TResult extends object, TKey extends string | number, TUtils extends Record, >( liveQueryCollection: Collection & NonSingleResult, ): InjectLiveQueryResultWithCollection // Pre-created collection with singleResult export function injectLiveQuery< TResult extends object, TKey extends string | number, TUtils extends Record, >( liveQueryCollection: Collection & SingleResult, ): InjectLiveQueryResultWithSingleResultCollection export function injectLiveQuery(opts: any) { assertInInjectionContext(injectLiveQuery) let pendingWindow: (() => void) | undefined let previousCollection: ReturnType = null const resolveNext = (value: unknown, pool?: PooledLiveQueries) => (previousCollection = resolveLiveQueryValue(value, { gcTime: DEFAULT_GC_TIME_MS, pool, previousCollection, windowOwner: resolveNext, onWindowChange: (move) => { pendingWindow = move }, })) const resolveInput = () => { // Check if it's an existing collection if (isCollection(opts)) { previousCollection = null return opts } if (typeof opts === `function`) { return resolveNext(opts) } // Handle LiveQueryCollectionConfig objects. Default startSync/gcTime to // match the query-fn and reactive-options paths, but let an explicit value // in the config win — otherwise a bare `{ query }` never syncs. if (opts && typeof opts === `object` && typeof opts.query === `function`) { if (typeof opts.params === `function`) { // The pool is checked first, so a disabled query rejects it too. const pool = configPool(opts) return resolveNext( (q: InitialQueryBuilder) => opts.query({ params: opts.params(), q }), pool, ) } return resolveNext(opts) } throw new Error(`Invalid options provided to injectLiveQuery`) } const resolved = computed<{ collection: ReturnType move: (() => void) | undefined }>(() => { pendingWindow = undefined const collection = resolveInput() return { collection, move: pendingWindow } }) const collection = computed(() => resolved().collection) effect(() => { const { move } = resolved() untracked(() => move?.()) }) // The shared observer already captures one coherent view per publication. // Signals project that snapshot instead of copying its rows and health again. const snapshot = signal | null>(null) const state = computed( () => (snapshot()?.state ?? new Map()) as Map, ) const status = computed(() => { const value = snapshot()?.status ?? `idle` return value === `idle` && !collection() ? `disabled` : value }) const health = computed(() => snapshot()?.health) // Every status flag comes from the shared rule; a disabled query is ready. const flags = computed(() => getLiveQueryStatusFlags(status() as CollectionStatus, health()), ) // Between input resolution and observer attachment, the snapshot can belong // to the previous query. Reapply the current query's projection to its rows. const data = computed(() => { // Read the current input even when a snapshot exists: a compile rejection // must propagate instead of exposing the previous query's rows. const currentCollection = collection() const currentSnapshot = snapshot() if ( currentSnapshot && currentSnapshot.collection === getPublicCollection(currentCollection) ) return currentSnapshot.data // Public pooled Collections materialize when their properties are read. // The captured keyed rows let us reproject without inspecting that facade. const rows = Array.from(currentSnapshot?.state?.values() ?? []) return currentCollection && isSingleResultCollection(currentCollection) ? rows[0] : rows }) // The effect owns this observer through reruns and injector destruction. effect((onCleanup) => { const currentCollection = collection() // Handle null collection (disabled query) if (!currentCollection) { snapshot.set(null) return } // Wholesale mode preserves Angular's loading policy: attaching requests no // initial-state snapshot from the source. const observer = createLiveQueryObserver(currentCollection, { mode: `wholesale`, }) const syncSnapshot = () => snapshot.set(observer.getSnapshot()) observer.subscribe(syncSnapshot) // Wholesale attach suppresses listener calls raised by synchronous sync // startup. Read once after subscribe returns to capture that final state. syncSnapshot() onCleanup(() => observer.dispose()) }) return { state, data, // Loosely typed so the impl return stays compatible with every overload // (the shared `isCollection` guard narrows the computed to `Collection | null`). collection: computed(() => getPublicCollection(collection()), ) as Signal, status, isLoading: computed(() => flags().isLoading), isReady: computed(() => flags().isReady || status() === `disabled`), isIdle: computed(() => flags().isIdle), isLoadingError: computed(() => flags().isLoadingError), isCrashed: computed(() => flags().isCrashed), isCleanedUp: computed(() => flags().isCleanedUp), isSyncError: computed(() => flags().isSyncError), health, } }