Open History to see the last commit
1import { getPreparedLiveQuerySources } from '@tanstack/db'
2import type { DbClient } from '@tanstack/db'
3
4export { resumeDeferredLiveQueryCollections as resumeSyncStarts } from '@tanstack/db'
5
6const sourceObjectTokens = new WeakMap<object, number>()
7let nextSourceObjectToken = 0
8
9export function getSourceObjectToken(source: object): number {
10 let id = sourceObjectTokens.get(source)
11 if (id === undefined) {
12 id = ++nextSourceObjectToken
13 sourceObjectTokens.set(source, id)
14 }
15 return id
16}
17
18export function getPreparedSources(
19 preparedValue: unknown,
20 client?: DbClient,
21 hookName?: string,
22): Array<{ id: string }> {
23 return getPreparedLiveQuerySources(
24 preparedValue,
25 !client && hookName
26 ? (alias) => {
27 throw new Error(
28 `[${hookName}] Collection descriptor "${alias}" requires a DbClient when the query is consumed. Wrap this component in <DbProvider client={client}> or use a concrete Collection.`,
29 )
30 }
31 : undefined,
32 )
33}
34
35/** The source object each Collection ID named while one hook is mounted. */
36export type SourceIdBindings = {
37 unscoped: Map<string, number>
38 byClient: WeakMap<DbClient, Map<string, number>>
39}
40
41export function createSourceIdBindings(): SourceIdBindings {
42 return { unscoped: new Map(), byClient: new WeakMap() }
43}
44
45/**
46 * Derived query identity names each source by its Collection ID. While a hook
47 * is mounted, an ID must keep naming one source object in each client scope,
48 * or the hook could reuse a live query that reads the old source. Claims the
49 * prepared value's sources, or calls `release` and throws on a collision so a
50 * rejected render keeps no sync-start deferral.
51 */
52export function claimSourceIds(
53 bindings: SourceIdBindings,
54 preparedValue: unknown,
55 client: DbClient | undefined,
56 hookName: string,
57 release: () => void,
58): void {
59 const prior = client ? bindings.byClient.get(client) : bindings.unscoped
60 const seen = new Map<string, number>()
61 for (const source of getPreparedSources(preparedValue, client, hookName)) {
62 const token = getSourceObjectToken(source)
63 const previous = seen.get(source.id) ?? prior?.get(source.id)
64 if (previous !== undefined && previous !== token) {
65 release()
66 throw new Error(
67 `[${hookName}] Source Collection "${source.id}" was replaced by a different Collection with the same ID while this hook is mounted. Unmount the hook and clean up its previous source and client scope before reusing the ID.`,
68 )
69 }
70 seen.set(source.id, token)
71 }
72 const claimed = prior ?? new Map<string, number>()
73 for (const [id, token] of seen) claimed.set(id, token)
74 if (client) bindings.byClient.set(client, claimed)
75}