@tanstack/db
Version:
A reactive client store for building super fast apps on sync
1 lines • 40.3 kB
Source Map (JSON)
{"version":3,"file":"live-query-observer.cjs","names":["codedMessage","isFailedStatus","isSingleResultCollection","getPublicCollection","getLiveQueryStatusFlags","LiveQueryObserverDisposedError","runAllCallbacks","describeProblem","snapshotDirty","cachedServerView","cachedSnapshot","publicationQueue","dispatching","blockDelivery","attached","collectionUnsub","clientBinding","getVisibleEntries","preloadCollection","refreshDetachedState","visibleStatus","cachedRows","publishedHealth","readEntries","cachedEntries","captureEntries","cachedCollectionRevision","cachedCollectionLayoutRevision","updateCachedEntries","detach","attach","deliveredLayoutRevision","flushPublications"],"sources":["../../src/live-query-observer.ts"],"sourcesContent":["import { LiveQueryObserverDisposedError } from './errors.js'\nimport { codedMessage, devBuild } from './error-message.js'\nimport { runAllCallbacks } from './utils/callbacks.js'\nimport {\n getLiveQueryStatusFlags,\n getPublicCollection,\n isFailedStatus,\n isSingleResultCollection,\n} from './live-query-primitives.js'\nimport { describeProblem } from './collection/lifecycle.js'\nimport type { Collection } from './collection/index.js'\nimport type { LiveQueryObserverClient } from './live-query-observer-client.js'\nimport type { DbClient, DehydratedLiveQueryResult } from './client.js'\nimport type { ChangeMessage, CollectionStatus, HealthNode } from './types.js'\n\n/**\n * The canonical, adapter-agnostic view of a live query at a point in time.\n *\n * `getSnapshot()` returns a stable object identity that only changes when the\n * query changes, so `useSyncExternalStore`-style consumers can compare by\n * reference. Each snapshot retains a captured view of `state`/`data`, so\n * reading an older snapshot cannot expose rows from a later revision.\n * Within one row revision, metadata-only changes retain the row containers.\n * Cleanup/reset may discard that revision even when its rows were empty.\n */\nexport interface LiveQuerySnapshot<\n T extends object,\n TKey extends string | number,\n> {\n /** Keyed results, or `undefined` for a disabled query. */\n state: ReadonlyMap<TKey, T> | undefined\n /** Ordered results (single row for `findOne`), or `undefined` when disabled. */\n data: T | ReadonlyArray<T> | undefined\n /** The underlying collection, or `undefined` when disabled. */\n collection: Collection<T, TKey, any> | undefined\n /**\n * Monotonic counter bumped whenever the visible layout (the ordered key\n * sequence) changes — membership, ordering, or an order-only move. Lets\n * consumers detect a reorder that changed no row value (which `data`/`state`\n * identity alone can't express once row values are structurally shared).\n *\n * It is NOT in lockstep with snapshot identity: a value-only update produces a\n * new snapshot while `layoutRevision` stays put. A `layoutRevision` change\n * always accompanies a new snapshot, but not vice versa.\n */\n layoutRevision: number\n status: CollectionStatus | `disabled`\n isLoading: boolean\n isReady: boolean\n isIdle: boolean\n /** The first load failed: there is nothing to show. */\n isLoadingError: boolean\n /** Local storage or an invariant broke. Only a cascade cleanup and a fresh start recover. */\n isCrashed: boolean\n isCleanedUp: boolean\n isEnabled: boolean\n /**\n * The data is shown, and something keeps it from staying current: a sync\n * problem or a failed request somewhere in `health`.\n */\n isSyncError: boolean\n /**\n * The health tree for the query and every Collection it depends on, or\n * `undefined` for a disabled query. After the first ready, a source\n * problem shows here and the data stays.\n */\n health: HealthNode | undefined\n}\n\n/**\n * Listener payload: changes, `[]` for an internal layout-only publication, or\n * `undefined` for a synthetic status/ready notification.\n */\nexport type LiveQueryObserverListener<\n T extends object,\n TKey extends string | number,\n> = (changes: Array<ChangeMessage<T, TKey>> | undefined) => void\n\n/**\n * Wraps a resolved live-query `Collection` (or `null` for a disabled query) with\n * the shared lifecycle every framework adapter needs: start sync on first\n * subscribe, subscribe to changes and status transitions, expose a stable\n * snapshot for wholesale consumers, and deliver the raw change set for\n * granular consumers.\n *\n * Input resolution (query fn / config / collection / disabled) stays in the\n * adapter — it is framework-reactive. The observer owns everything after the\n * input is resolved to a concrete collection.\n *\n * @internal Unstable contract for TanStack DB's official framework adapters —\n * not a public extension point yet; may change in any release.\n */\nexport interface LiveQueryObserver<\n T extends object,\n TKey extends string | number,\n> {\n /** Stable per-revision snapshot for wholesale materialization. */\n getSnapshot: () => LiveQuerySnapshot<T, TKey>\n /** Server snapshot. preloadRequested marks an explicit streaming Suspense load. */\n getServerSnapshot: (preloadRequested?: boolean) => LiveQuerySnapshot<T, TKey>\n /**\n * Subscribe to changes. The listener receives the change set (or `undefined`\n * for the synthetic notify a ready collection emits on attach). Granular\n * adapters apply the changes; wholesale adapters can ignore them and re-read\n * `getSnapshot()`. Raw changes can carry fresh equal row objects while a\n * snapshot retains its capture for the unchanged revision. Returns an\n * unsubscribe function.\n */\n subscribe: (listener: LiveQueryObserverListener<T, TKey>) => () => void\n /** Resolve once the collection has loaded its first data. */\n preload: () => Promise<void>\n /** The transport or preload error for this query, if it has not produced data. */\n getError: () => unknown\n /** Capture the ordered query result without serializing its source collections. */\n dehydrate: () => DehydratedLiveQueryResult<T, TKey>\n /** Idempotent teardown. */\n dispose: () => void\n}\n\n/**\n * One logical subscription. Records — not raw callbacks — identify\n * subscriptions, so the same listener function can be subscribed twice and\n * each subscription tears down independently.\n */\ninterface SubscriptionRecord<T extends object, TKey extends string | number> {\n listener: LiveQueryObserverListener<T, TKey>\n active: boolean\n}\n\ninterface Publication<T extends object, TKey extends string | number> {\n changes: Array<ChangeMessage<T, TKey>> | undefined\n targets: Array<SubscriptionRecord<T, TKey>>\n entries?: Array<[TKey, T]>\n status: CollectionStatus\n collectionRevision?: number\n collectionLayoutRevision?: number\n layoutChanged: boolean\n}\n\nconst DISABLED_SNAPSHOT: LiveQuerySnapshot<any, any> = {\n state: undefined,\n data: undefined,\n collection: undefined,\n layoutRevision: 0,\n status: `disabled`,\n isLoading: false,\n isReady: true,\n isIdle: false,\n isLoadingError: false,\n isCrashed: false,\n isCleanedUp: false,\n isEnabled: false,\n isSyncError: false,\n health: undefined,\n}\n\nclass LiveQueryObserverImpl<\n T extends object,\n TKey extends string | number,\n> implements LiveQueryObserver<T, TKey> {\n private readonly collection: Collection<T, TKey, any> | null\n private readonly wholesale: boolean\n private readonly clientBinding: LiveQueryObserverClient<T, TKey> | undefined\n private readonly onPreload: (() => void) | undefined\n private visibleStatus: CollectionStatus | undefined\n private cachedEntries: Array<[TKey, T]> | undefined\n private cachedCollectionRevision: number | undefined\n private cachedCollectionLayoutRevision: number | undefined\n private snapshotDirty = true\n // While attached, the tree from the last status or health change. Every\n // tree change is announced, so a snapshot reuses it instead of rebuilding.\n private publishedHealth: { tree: HealthNode | undefined } | undefined\n // Whether the cached snapshot was built for the hydration read.\n private cachedServerView = false\n private cachedSnapshot: LiveQuerySnapshot<T, TKey> = DISABLED_SNAPSHOT\n // Last materialized visible capture, which can be a hydration seed or lag\n // the live capture until getSnapshot() runs. These are array references.\n private cachedRows:\n | {\n entries: Array<[TKey, T]>\n data: Array<T>\n state?: Map<TKey, T>\n }\n | undefined\n private layoutRevision = 0\n private deliveredLayoutRevision: number | undefined\n private readonly subscriptions = new Set<SubscriptionRecord<T, TKey>>()\n // Publications are dispatched FIFO: an emit that happens while another\n // publication is being delivered (a listener mutating the collection\n // synchronously) is queued, never delivered reentrantly.\n private readonly publicationQueue: Array<Publication<T, TKey>> = []\n private dispatching = false\n private blockDelivery = false\n private attached = false\n private collectionUnsub: (() => void) | null = null\n private preloadPromise: Promise<void> | undefined\n private disposed = false\n\n // Sync activation belongs to the first subscription (attach), so building\n // an observer cannot activate collection resources on its own. Server\n // request clients still record ownership here because React may render an\n // observer without ever subscribing to it.\n constructor(\n collection: Collection<T, TKey, any> | null,\n wholesale: boolean,\n client: DbClient | undefined,\n queryHash: string | undefined,\n onPreload: (() => void) | undefined,\n suspendUntilReady: boolean,\n ) {\n if (\n collection &&\n (!Number.isFinite(collection._stateRevision) ||\n !Number.isFinite(collection._layoutRevision))\n ) {\n throw new Error(\n devBuild() && process.env.NODE_ENV !== `production`\n ? `LiveQueryObserver requires finite Collection row and layout revision clocks`\n : codedMessage(262),\n )\n }\n this.collection = collection\n this.wholesale = wholesale\n this.onPreload = onPreload\n this.clientBinding = client?._bindLiveQueryObserver(\n collection,\n queryHash,\n suspendUntilReady,\n {\n observer: this,\n read: (server) => this.getSnapshot(server),\n entries: () => (collection ? this.getVisibleEntries(collection) : []),\n isAttached: () => this.attached,\n isDisposed: () => this.disposed,\n dirty: () => {\n this.snapshotDirty = true\n },\n publish: (changes, entries) => {\n const revision =\n entries && collection ? collection._stateRevision : undefined\n const layoutRevision =\n entries && collection ? collection._layoutRevision : undefined\n this.emit(\n this.wholesale ? undefined : changes,\n undefined,\n entries,\n collection?.status,\n revision,\n layoutRevision,\n entries !== undefined,\n )\n },\n preload: () => this.preloadCollection(),\n },\n )\n this.clientBinding?.registerResource()\n }\n\n getSnapshot(forServerSnapshot = false): LiveQuerySnapshot<T, TKey> {\n const collection = this.collection\n if (!collection) return DISABLED_SNAPSHOT\n\n this.clientBinding?.sync(forServerSnapshot)\n if (!this.attached) this.refreshDetachedState(collection)\n\n // The hydration read and an ordinary read differ only while a seed\n // stands in front of a failure.\n if (\n this.cachedServerView !== forServerSnapshot &&\n this.clientBinding?.seed &&\n isFailedStatus(this.visibleStatus ?? collection.status)\n ) {\n this.snapshotDirty = true\n }\n\n if (this.snapshotDirty) {\n const entries = this.getVisibleEntries(collection)\n // Capture each row revision once. Sharing this value across metadata\n // snapshots keeps rows lazy and avoids retaining a chain of old snapshots.\n let rows = this.cachedRows\n if (!rows || rows.entries !== entries) {\n // Captured entries already contain the previous ordered keys. Compare\n // keys directly: serialized signatures can collide for string keys.\n const previous = rows?.entries\n if (\n previous?.length !== entries.length ||\n entries.some(([key], index) => previous[index]![0] !== key)\n ) {\n this.layoutRevision++\n }\n rows = this.cachedRows = {\n entries,\n data: entries.map(([, value]) => value),\n }\n }\n const singleResult = isSingleResultCollection(collection)\n const liveStatus = this.visibleStatus ?? collection.status\n // The seed stands in only for a result that is still coming, so an\n // ordinary read never hides a failure behind it. The hydration read\n // keeps the server's view: it must reproduce what the server rendered.\n const status = this.clientBinding?.failed\n ? (`error` as const)\n : this.clientBinding?.seed &&\n (forServerSnapshot || !isFailedStatus(liveStatus))\n ? (this.clientBinding.seed.snapshot.status ?? `ready`)\n : liveStatus\n this.cachedServerView = forServerSnapshot\n\n const health = this.publishedHealth\n ? this.publishedHealth.tree\n : (collection as { health?: HealthNode }).health\n this.cachedSnapshot = {\n get state() {\n return (rows.state ??= new Map(rows.entries))\n },\n data: singleResult ? rows.data[0] : rows.data,\n collection: getPublicCollection(collection),\n layoutRevision: this.layoutRevision,\n status,\n ...getLiveQueryStatusFlags(status, health),\n isEnabled: true,\n }\n this.snapshotDirty = false\n }\n return this.cachedSnapshot\n }\n\n getServerSnapshot(preloadRequested = false): LiveQuerySnapshot<T, TKey> {\n return (\n this.clientBinding?.getServerSnapshot(preloadRequested) ??\n this.getSnapshot()\n )\n }\n\n getError(): unknown {\n this.clientBinding?.sync()\n return this.clientBinding?.error\n }\n\n dehydrate(): DehydratedLiveQueryResult<T, TKey> {\n const collection = this.collection\n if (!collection) return { rows: [] }\n\n const entries =\n this.clientBinding?.seed &&\n this.clientBinding.seed.snapshot.status === undefined\n ? this.clientBinding.seed.entries\n : this.readEntries(collection).entries\n\n return {\n rows: entries.map(([key, value]) => ({\n key,\n value,\n })),\n }\n }\n\n private getVisibleEntries(\n collection: Collection<T, TKey, any>,\n ): Array<[TKey, T]> {\n if (this.clientBinding?.seed) return this.clientBinding.seed.entries\n return this.cachedEntries ?? this.captureEntries(collection)\n }\n\n private readEntries(collection: Collection<T, TKey, any>): {\n entries: Array<[TKey, T]>\n revision: number\n layoutRevision: number\n } {\n const revision = collection._stateRevision\n const layoutRevision = collection._layoutRevision\n // Reuse the last delivered capture only when both clocks match. A queued\n // newer publication must still capture its own rows before reentrant writes.\n const entries =\n this.cachedEntries &&\n revision === this.cachedCollectionRevision &&\n layoutRevision === this.cachedCollectionLayoutRevision\n ? this.cachedEntries\n : (Array.from(collection.entries()) as Array<[TKey, T]>)\n return { entries, revision, layoutRevision }\n }\n\n private captureEntries(\n collection: Collection<T, TKey, any>,\n ): Array<[TKey, T]> {\n const { entries, revision, layoutRevision } = this.readEntries(collection)\n this.updateCachedEntries(entries, revision, layoutRevision)\n return this.cachedEntries!\n }\n\n private updateCachedEntries(\n entries: Array<[TKey, T]>,\n revision: number | undefined,\n layoutRevision: number | undefined,\n ): void {\n // Collection clocks are authoritative; equal writes may re-enrich a row\n // without changing its value. Keep that revision's captured identities.\n if (\n this.cachedEntries === undefined ||\n revision !== this.cachedCollectionRevision ||\n layoutRevision !== this.cachedCollectionLayoutRevision\n ) {\n this.cachedEntries = entries\n this.snapshotDirty = true\n }\n this.cachedCollectionRevision = revision\n this.cachedCollectionLayoutRevision = layoutRevision\n }\n\n /**\n * A detached read catches up from the Collection's row and layout clocks.\n * Supported inputs are Collections and pooled views from this DB instance.\n */\n private refreshDetachedState(collection: Collection<T, TKey, any>): void {\n const status = collection.status\n this.captureEntries(collection)\n\n // A health-only change moves no row or status. Trees keep their identity\n // until their content changes, so identity tells whether it went stale.\n if (\n this.visibleStatus !== status ||\n this.cachedSnapshot.health !==\n (collection as { health?: HealthNode }).health\n ) {\n this.visibleStatus = status\n this.snapshotDirty = true\n }\n }\n\n subscribe(listener: LiveQueryObserverListener<T, TKey>): () => void {\n if (this.disposed) throw new LiveQueryObserverDisposedError()\n if (this.subscriptions.size === 0) this.clientBinding?.assertSources()\n\n const record: SubscriptionRecord<T, TKey> = { listener, active: true }\n const release = () => {\n if (!record.active) return\n record.active = false\n this.subscriptions.delete(record)\n if (this.subscriptions.size === 0) this.detach()\n }\n this.subscriptions.add(record)\n const attaching = !this.attached\n try {\n if (attaching) {\n this.attach()\n } else {\n // Seed only this late granular listener; a failed seed releases its\n // record without detaching peers that already own subscriptions.\n if (!this.wholesale) this.seed(record)\n }\n } catch (error) {\n // Setup returned no ownership handle. Release every acquired channel\n // and the logical record, so a later explicit subscription can attach.\n if (attaching) this.detach()\n release()\n throw error\n }\n return release\n }\n\n /** Deliver the collection's current rows to one late subscription as inserts. */\n private seed(record: SubscriptionRecord<T, TKey>): void {\n const collection = this.collection\n if (!collection) return\n\n const seedChanges: Array<ChangeMessage<T, TKey>> = []\n for (const [key, value] of this.getVisibleEntries(collection)) {\n seedChanges.push({ type: `insert`, key, value })\n }\n if (seedChanges.length === 0) return\n\n this.emit(seedChanges, [record])\n }\n\n private attach(): void {\n const collection = this.collection\n if (!collection || this.disposed) return\n // Install ownership before any registration can call back or throw.\n const releases: Array<() => void> = []\n const release = () => runAllCallbacks(releases.splice(0))\n this.collectionUnsub = release\n const ownRelease = (unsubscribe: () => void) => {\n if (this.collectionUnsub === release) releases.push(unsubscribe)\n else unsubscribe()\n }\n this.clientBinding?.registerResource()\n this.clientBinding?.sync()\n this.refreshDetachedState(collection)\n this.attached = true\n this.visibleStatus ??= collection.status\n this.deliveredLayoutRevision = collection._layoutRevision\n const attachedWithHydrationSeed = !!this.clientBinding?.seed\n this.blockDelivery = this.wholesale || attachedWithHydrationSeed\n\n // Sync activation happens inside subscribeChanges (addSubscriber starts\n // an idle/cleaned-up collection) — the same startSync path the old\n // constructor-time startSyncImmediate() took, but now owned by the first\n // committed subscription and observed by the status listener below.\n\n // Granular consumers subscribe with initial state so they receive the\n // current rows as inserts followed by deltas through one consistent\n // channel (the collection's per-subscriber change stream requires this to\n // align deltas). Wholesale consumers subscribe WITHOUT initial state —\n // preserving their pre-observer loading policy: no snapshot request means\n // no unfiltered loadSubset({ where: undefined }) against on-demand\n // collections. The explicit `false` marks all state as seen so deletes\n // still flow through as notifies.\n const notify = (\n changes: Array<ChangeMessage<T, TKey>> | undefined,\n status: CollectionStatus = collection.status,\n explicitLayoutChange = false,\n ) => {\n if (this.disposed || this.subscriptions.size === 0) return\n\n if (this.clientBinding?.seed) {\n // Startup remains behind the hydration cut. A later failure ends the\n // sync run whose result the seed stood in for, and is already an\n // owned publication, so it must be visible synchronously.\n if (isFailedStatus(status) && !this.blockDelivery)\n this.clientBinding.handoff()\n else if (status === `ready` || isFailedStatus(status))\n this.clientBinding.scheduleHandoff()\n return\n }\n\n if (status === `ready` && !collection.isLoadingSubset) {\n this.clientBinding?.markAuthoritative()\n }\n\n const layoutRevision = collection._layoutRevision\n let layoutChanged = explicitLayoutChange\n if (\n !explicitLayoutChange &&\n changes !== undefined &&\n changes.length === 0\n ) {\n // Empty ready events predate the explicit layout signal and share its\n // empty-array payload. Only forward an empty batch when the collection\n // confirms that a new layout-only publication occurred.\n if (layoutRevision === this.deliveredLayoutRevision) {\n return\n }\n layoutChanged = true\n }\n if (changes !== undefined) {\n this.deliveredLayoutRevision = layoutRevision\n }\n const captured =\n changes !== undefined || status === `cleaned-up`\n ? this.readEntries(collection)\n : undefined\n this.emit(\n changes,\n undefined,\n captured?.entries,\n status,\n captured?.revision,\n layoutRevision,\n layoutChanged,\n )\n }\n\n // Status transitions that carry no change events (loading→ready with no\n // rows, error, cleaned-up) are part of the canonical publication path:\n // any status change publishes a synthetic notify so consumers re-read the\n // snapshot. Unlike onFirstReady, `on` returns a real unsubscribe, so a\n // detached attachment leaves nothing behind.\n // A health change below the query changes its health tree, not its rows.\n // Each status change is followed by a health change; tree identity\n // tells whether the health change has anything left to publish.\n const healthOf = () => (collection as { health?: HealthNode }).health\n this.publishedHealth = { tree: healthOf() }\n ownRelease(() => {\n this.publishedHealth = undefined\n })\n ownRelease(\n collection.on(`status:change`, ({ status }) => {\n this.publishedHealth = { tree: healthOf() }\n notify(undefined, status)\n }),\n )\n ownRelease(\n collection.on(`health:change`, () => {\n const health = healthOf()\n if (health === this.publishedHealth?.tree) return\n this.publishedHealth = { tree: health }\n // No rows or status changed, so only this marks the snapshot stale.\n this.snapshotDirty = true\n notify(undefined, collection.status)\n }),\n )\n // Pooled views carry layout changes in their ordinary change stream.\n if (\n (collection as Partial<Collection<T, TKey, any>>)._subscribeLayoutChanges\n ) {\n ownRelease(\n collection._subscribeLayoutChanges(() =>\n notify([], collection.status, true),\n ),\n )\n }\n // `subscribeChanges` delivers the initial state synchronously, so a\n // listener can dispose the observer while the collection subscription is\n // still being created. Register the release hook up front; if detach()\n // ran during that replay (collectionUnsub no longer points at our hook),\n // undo the subscription as soon as the call returns.\n if (this.clientBinding) {\n ownRelease(this.clientBinding.subscribe())\n // A retained ready Collection can settle subset work without another\n // row or status change. That settlement must release its hydration seed.\n ownRelease(\n collection.on(`loadingSubset:change`, () => {\n if (this.clientBinding?.seed) this.clientBinding.scheduleHandoff()\n }),\n )\n }\n const subscription = collection.subscribeChanges(\n (changes) => notify(changes as Array<ChangeMessage<T, TKey>>),\n {\n includeInitialState: !this.wholesale && !attachedWithHydrationSeed,\n // The `cleaned-up` snapshot shows no rows, so the observer keeps none\n // of the last sync run's rows for the next one.\n discardsRowsOnCleanup: true,\n },\n )\n ownRelease(() => subscription.unsubscribe())\n this.blockDelivery = false\n if (this.collectionUnsub !== release) return\n if (this.wholesale || attachedWithHydrationSeed) {\n // Publications raised while subscribeChanges starts sync are part of the\n // subscribe handshake. Apply their final snapshot state now, but suppress\n // listener delivery: useSyncExternalStore performs its consistency read\n // immediately after subscribe returns.\n this.flushPublications(!this.wholesale)\n // The render-time read is still current unless the handshake published.\n this.captureEntries(collection)\n }\n if (this.clientBinding?.seed) {\n if (!this.wholesale) this.seed(Array.from(this.subscriptions)[0]!)\n if (collection.status === `ready` || isFailedStatus(collection.status)) {\n this.clientBinding.scheduleHandoff()\n }\n }\n }\n\n private detach(): void {\n const release = this.collectionUnsub\n const unregister = this.clientBinding?.takeResourceRelease()\n this.collectionUnsub = null\n this.attached = false\n this.blockDelivery = false\n this.publicationQueue.length = 0\n runAllCallbacks([() => release?.(), () => unregister?.()])\n }\n\n private emit(\n changes: Array<ChangeMessage<T, TKey>> | undefined,\n targets = Array.from(this.subscriptions),\n entries?: Array<[TKey, T]>,\n status = this.collection?.status ?? `cleaned-up`,\n collectionRevision?: number,\n collectionLayoutRevision?: number,\n layoutChanged = false,\n ): void {\n this.publicationQueue.push({\n changes,\n targets,\n entries,\n status,\n collectionRevision,\n collectionLayoutRevision,\n layoutChanged,\n })\n if (this.dispatching || this.blockDelivery) return\n\n this.flushPublications()\n }\n\n private flushPublications(deliver = true): void {\n if (this.dispatching) return\n\n let failure: { error: unknown } | undefined\n this.dispatching = true\n try {\n // A dispose() during dispatch empties the queue, ending this loop.\n while (this.publicationQueue.length > 0) {\n const publication = this.publicationQueue.shift()!\n if (publication.entries) {\n this.updateCachedEntries(\n publication.entries,\n publication.collectionRevision,\n publication.collectionLayoutRevision,\n )\n }\n if (publication.layoutChanged) {\n this.snapshotDirty = true\n }\n if (this.visibleStatus !== publication.status) {\n this.visibleStatus = publication.status\n this.snapshotDirty = true\n }\n // Targets are captured when the publication is queued: a subscription\n // removed mid-delivery still receives the in-flight publication, and\n // one added later does not. Late-subscriber seeds use the same queue.\n if (deliver) {\n for (const subRecord of publication.targets) {\n if (this.disposed) break\n try {\n subRecord.listener(publication.changes)\n } catch (error) {\n failure ??= { error }\n }\n }\n }\n }\n } finally {\n this.dispatching = false\n }\n if (failure) throw failure.error\n }\n\n preload(): Promise<void> {\n return this.clientBinding?.preload() ?? this.preloadCollection()\n }\n\n private preloadCollection(): Promise<void> {\n if (this.preloadPromise) return this.preloadPromise\n this.onPreload?.()\n const promise = this.collection?.preload() ?? Promise.resolve()\n this.preloadPromise = promise\n const clear = () => {\n if (this.preloadPromise === promise) this.preloadPromise = undefined\n }\n void promise.then(clear, clear)\n return promise\n }\n\n dispose(): void {\n if (this.disposed) return\n this.disposed = true\n this.detach()\n for (const subRecord of this.subscriptions) subRecord.active = false\n this.subscriptions.clear()\n this.publicationQueue.length = 0\n }\n}\n\nexport interface CreateLiveQueryObserverOptions {\n /**\n * How subscribers consume the observer:\n *\n * - `granular` (default): subscribers apply the delivered `ChangeMessage[]`\n * deltas to their own keyed state (Vue/Svelte/Solid). The observer\n * subscribes with initial state and seeds late subscribers, so every\n * subscriber converges from deltas alone.\n * - `wholesale`: subscribers treat notifications as a wake-up and re-read\n * `getSnapshot()` (React/Angular). The observer subscribes WITHOUT initial\n * state, preserving those adapters' loading policy — no snapshot request,\n * so no unfiltered `loadSubset` against on-demand collections. Nothing is\n * delivered synchronously during `subscribe`, which keeps\n * `useSyncExternalStore`-style consumers safe by construction.\n */\n mode?: `granular` | `wholesale`\n /** DbClient cache that owns SSR snapshots for this query identity. */\n client?: DbClient\n /** Stable live-query identity used for dehydration and hydration. */\n queryHash?: string\n /** Resume framework-deferred query sources before a server preload. */\n onPreload?: () => void\n /** Read the completed stream rather than an earlier ordinary loading view. */\n suspendUntilReady?: boolean\n}\n\n/**\n * The Error an adapter sends to an error boundary for a failed first load or\n * a crash: the cause itself when it is an Error, otherwise an Error with the\n * problem's message (as in `health.error.message`) whose `cause` is the value\n * the sync adapter reported.\n *\n * @internal Shared by TanStack DB's official framework adapters.\n */\nexport const toBoundaryError = (cause: unknown): Error =>\n cause instanceof Error\n ? cause\n : new Error(describeProblem(cause).message, { cause })\n\n/**\n * Create a {@link LiveQueryObserver} for a resolved live-query collection, or a\n * disabled observer when `collection` is `null`/`undefined`.\n *\n * @internal This is an unstable contract shared by TanStack DB's official\n * framework adapters. It is exported so the adapter packages can use it, but\n * it is not a public extension point yet: its API may change in any release\n * without a semver major.\n */\nexport function createLiveQueryObserver<\n T extends object,\n TKey extends string | number,\n>(\n collection: Collection<T, TKey, any> | null | undefined,\n options: CreateLiveQueryObserverOptions = {},\n): LiveQueryObserver<T, TKey> {\n return new LiveQueryObserverImpl<T, TKey>(\n collection ?? null,\n options.mode === `wholesale`,\n options.client,\n options.queryHash,\n options.onPreload,\n options.suspendUntilReady === true,\n )\n}\n"],"mappings":";;;;;AA2IA,IAAM,oBAAiD;CACrD,OAAO,KAAA;CACP,MAAM,KAAA;CACN,YAAY,KAAA;CACZ,gBAAgB;CAChB,QAAQ;CACR,WAAW;CACX,SAAS;CACT,QAAQ;CACR,gBAAgB;CAChB,WAAW;CACX,aAAa;CACb,WAAW;CACX,aAAa;CACb,QAAQ,KAAA;AACV;AAEA,IAAM,wBAAN,MAGwC;CA2CtC,YACE,YACA,WACA,QACA,WACA,WACA,mBACA;EAzCsB,KAAAQ,KAAA;EAKG,KAAAC,KAAA;EAC0B,KAAAC,KAAA;EAU5B,KAAA,iBAAA;EAEQ,KAAA,gCAAA,IAAI,IAAiC;EAIL,KAAAC,KAAA,CAAC;EAC5C,KAAAC,KAAA;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