@bkbdev/plugin-react-query 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts", "../src/hub.ts", "../src/actions.ts", "../src/key.ts", "../src/snapshot.ts", "../src/commands.ts", "../src/provider.ts", "../src/track.ts", "../src/mutations.ts", "../src/errors.ts", "../src/watcher.ts"],
4
+ "sourcesContent": ["import type { BkbPlugin } from '@bkbdev/core/register';\nimport { queryCacheProvider } from './provider';\n\nexport { trackQueryClient } from './track';\nexport { onCacheEvent, droppedCacheEvents, trackedClients } from './hub';\nexport type { TrackMeta } from '@bkbdev/core/plugin';\n\n// React Query for the BKB desktop: the cache as it is now, and what happened to it. Listing this\n// package in the `bkbPlugins` option of `@bkbdev/core/babel` makes the Babel plugin wrap the app's\n// `new QueryClient(...)` calls with `trackQueryClient`; release builds never load it.\nconst plugin: BkbPlugin = {\n name: 'react-query',\n extend: () => ({ pluginProviders: [queryCacheProvider()] }),\n};\n\nexport default plugin;\n", "import { createEventHub } from '@bkbdev/core/plugin';\nimport type { QueryClientLike } from './types';\nimport type { QueryWatcher } from './watcher';\nimport type { CacheEvent } from '../../../protocol/src/query-cache-provider';\n\n// Like the Zustand plugin, the clients and the events live on the global object: Metro can load\n// the package once for the project's own import and once for the registration.\nconst REGISTRY_KEY = '__BKB_QUERY_CLIENTS_V1__';\n\nexport interface TrackedClient {\n clientId: string;\n client: QueryClientLike;\n watcher: QueryWatcher;\n}\n\ninterface Registry {\n clients: Map<string, TrackedClient>;\n labelCounts: Map<string, number>;\n}\n\ndeclare const global: { __BKB_QUERY_CLIENTS_V1__?: Registry };\n\nconst events = createEventHub<CacheEvent>('__BKB_QUERY_CACHE_EVENTS_V1__');\n\nfunction registry(): Registry {\n const existing = global[REGISTRY_KEY];\n if (existing) return existing;\n const created: Registry = { clients: new Map(), labelCounts: new Map() };\n global[REGISTRY_KEY] = created;\n return created;\n}\n\n// A client is named after its variable (`queryClient`); one made without a variable is named by\n// the place that creates it. Two with the same name are numbered.\nexport function clientLabel(\n variable: string | null,\n file: string | null,\n line: number | null,\n): string {\n const base =\n variable ?? (file !== null && line !== null ? file.slice(-120) + ':' + line : 'client');\n return base.slice(0, 128);\n}\n\nexport function reserveClientId(label: string): string {\n const state = registry();\n const count = (state.labelCounts.get(label) ?? 0) + 1;\n state.labelCounts.set(label, count);\n return count === 1 ? label : label + '#' + count;\n}\n\nexport function rememberClient(tracked: TrackedClient): void {\n registry().clients.set(tracked.clientId, tracked);\n}\n\nexport function trackedClients(): TrackedClient[] {\n return [...registry().clients.values()];\n}\n\nexport const publishCacheEvent = events.publish;\nexport const onCacheEvent = events.subscribe;\nexport const droppedCacheEvents = events.droppedCount;\n", "import { snapshotValue } from '@bkbdev/core/plugin';\nimport { formatQueryKey } from './key';\nimport { isFetching, isRefetchable } from './snapshot';\nimport type { JsonValue } from '../../../protocol/src/wire';\nimport type { QueryClientLike, QueryLike } from './types';\nimport type {\n CacheEvent,\n QueryAction,\n QueryActionResult,\n} from '../../../protocol/src/query-cache-provider';\n\nexport type QueryDataReply =\n { outcome: 'data'; data: JsonValue; truncated: boolean } | { outcome: 'refused'; reason: string };\n\nfunction refused(reason: string): { outcome: 'refused'; reason: string } {\n return { outcome: 'refused', reason };\n}\n\n// Why a refetch must not run now, or undefined when it may. The rules come from measuring\n// React Query 3, 4 and 5: a query without a queryFn ends in the error state when refetched,\n// a disabled one is ignored by 4 and 5 but refetched by 3, and a second refetch cancels the\n// fetch in flight unless told otherwise.\nfunction refetchBlocker(client: QueryClientLike, query: QueryLike): string | undefined {\n if (isFetching(query)) return 'The query is already fetching.';\n if (!isRefetchable(client, query))\n return 'The query has no query function, or every component using it has it disabled.';\n return undefined;\n}\n\nfunction find(client: QueryClientLike, queryId: string): QueryLike | undefined {\n return client\n .getQueryCache()\n .getAll()\n .find((query) => query.queryHash === queryId);\n}\n\n// Refetches or invalidates exactly one query, the one with this id. The request is reported on\n// the timeline first so the fetch that follows has a visible cause. React Query starts the\n// fetch synchronously, so whether one began is read straight afterwards; the promise itself is\n// not awaited, because a slow request must not hold the reply to the desktop.\nexport function runQueryAction(\n client: QueryClientLike,\n clientId: string,\n action: QueryAction,\n queryId: string,\n emit: (event: CacheEvent) => void,\n now: () => number = Date.now,\n): QueryActionResult {\n const query = find(client, queryId);\n if (!query) return refused('The query no longer exists.');\n if (action === 'refetch') {\n const blocker = refetchBlocker(client, query);\n if (blocker) return refused(blocker);\n }\n emit({\n kind: 'request',\n clientId,\n action,\n queryId,\n key: formatQueryKey(query.queryKey),\n timestamp: now(),\n });\n const filters = { queryKey: query.queryKey, exact: true };\n const pending =\n action === 'refetch'\n ? client.refetchQueries(filters, { cancelRefetch: false })\n : client.invalidateQueries(filters);\n pending.catch(() => undefined);\n return { outcome: 'done', fetchStarted: isFetching(query) };\n}\n\n// The data a query holds, for the desktop to browse. Nothing is read from the network and the\n// query is not touched; a large value is cut.\nexport function readQueryData(client: QueryClientLike, queryId: string): QueryDataReply {\n const query = find(client, queryId);\n if (!query) return refused('The query no longer exists.');\n if (query.state.dataUpdatedAt === 0 && (query.state as { data?: unknown }).data === undefined)\n return refused('The query has no data yet.');\n const { data, truncated } = snapshotValue((query.state as { data?: unknown }).data);\n return { outcome: 'data', data, truncated };\n}\n", "// A query key printed the way it is written in code: ['todos', { page: 2 }]. Bounded in depth,\n// width and length, because keys can embed large objects.\n\nconst MAX_DEPTH = 4;\nconst MAX_ITEMS = 8;\nconst MAX_CHARACTERS = 200;\n\nfunction quote(text: string): string {\n const clipped = text.length > 60 ? text.slice(0, 60) + '\u2026' : text;\n return \"'\" + clipped.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\").replace(/\\n/g, '\\\\n') + \"'\";\n}\n\nfunction propertyName(name: string): string {\n return /^[A-Za-z_$][\\w$]*$/.test(name) ? name : quote(name);\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction scalar(value: unknown): string {\n if (typeof value === 'string') return quote(value);\n if (value === null || typeof value === 'number' || typeof value === 'boolean')\n return String(value);\n if (value === undefined) return 'undefined';\n if (typeof value === 'bigint') return String(value) + 'n';\n if (typeof value === 'function') return '[Function]';\n return '[' + typeof value + ']';\n}\n\nfunction list(items: string[], total: number, open: string, close: string): string {\n const more = total > items.length ? ['\u2026'] : [];\n if (!items.length && !more.length) return open + close;\n const body = [...items, ...more].join(', ');\n return open === '{' ? '{ ' + body + ' }' : open + body + close;\n}\n\nfunction render(value: unknown, depth: number, seen: Set<object>): string {\n if (typeof value !== 'object' || value === null) return scalar(value);\n if (seen.has(value)) return '[Circular]';\n if (depth >= MAX_DEPTH) return Array.isArray(value) ? '[\u2026]' : '{\u2026}';\n seen.add(value);\n try {\n if (Array.isArray(value))\n return list(\n value.slice(0, MAX_ITEMS).map((item) => render(item, depth + 1, seen)),\n value.length,\n '[',\n ']',\n );\n if (!isRecord(value)) return '[object]';\n const names = Object.keys(value);\n return list(\n names\n .slice(0, MAX_ITEMS)\n .map((name) => propertyName(name) + ': ' + render(value[name], depth + 1, seen)),\n names.length,\n '{',\n '}',\n );\n } finally {\n seen.delete(value);\n }\n}\n\nexport function formatQueryKey(key: unknown): string {\n let text: string;\n try {\n text = render(key, 0, new Set());\n } catch {\n return '[unreadable key]';\n }\n return text.length > MAX_CHARACTERS ? text.slice(0, MAX_CHARACTERS - 1) + '\u2026' : text;\n}\n", "import { formatQueryKey } from './key';\nimport type { QueryClientLike, QueryLike } from './types';\nimport type { QueryRow, QueryStatus } from '../../../protocol/src/query-cache-provider';\n\nexport function isFetching(query: QueryLike): boolean {\n const state = query.state;\n return state.fetchStatus === undefined\n ? state.isFetching === true\n : state.fetchStatus === 'fetching';\n}\n\nfunction isPaused(query: QueryLike): boolean {\n return query.state.fetchStatus === 'paused';\n}\n\n// `enabled` can be a function in newer versions; it cannot be evaluated here without running\n// application code, so only an explicit `false` counts as disabled.\nfunction hasActiveObserver(query: QueryLike): boolean {\n if (typeof query.isActive === 'function') return query.isActive();\n const observers = query.observers ?? [];\n return observers.some((observer) => observer.options?.enabled !== false);\n}\n\nfunction hasQueryFunction(client: QueryClientLike, query: QueryLike): boolean {\n if (typeof query.options?.queryFn === 'function') return true;\n const defaults = client.getDefaultOptions ? client.getDefaultOptions() : undefined;\n return typeof defaults?.queries?.queryFn === 'function';\n}\n\n// Whether a refetch is safe and meaningful. Without a query function a refetch leaves the query\n// in the error state; when every observer is disabled React Query 4 and 5 ignore it while 3\n// would run it, so BKB refuses in all versions.\nexport function isRefetchable(client: QueryClientLike, query: QueryLike): boolean {\n if (!hasQueryFunction(client, query)) return false;\n const observers = query.observers ?? [];\n return observers.length === 0 || hasActiveObserver(query);\n}\n\nexport function queryStatus(query: QueryLike): QueryStatus {\n if (isFetching(query)) return 'fetching';\n if (isPaused(query)) return 'paused';\n if (query.state.status === 'error') return 'error';\n if (!(query.observers ?? []).length) return 'inactive';\n if (query.state.dataUpdatedAt === 0) return 'idle';\n return typeof query.isStale === 'function' && !query.isStale() ? 'fresh' : 'stale';\n}\n\nexport function queryRow(\n client: QueryClientLike,\n clientId: string,\n query: QueryLike,\n fetchCount: number,\n source: QueryRow['source'],\n): QueryRow {\n return {\n clientId,\n queryId: query.queryHash,\n key: formatQueryKey(query.queryKey),\n status: queryStatus(query),\n observers: (query.observers ?? []).length,\n fetchCount,\n updatedAt: query.state.dataUpdatedAt > 0 ? query.state.dataUpdatedAt : null,\n refetchable: isRefetchable(client, query),\n source,\n };\n}\n", "import { publishCacheEvent, trackedClients } from './hub';\nimport { readQueryData, runQueryAction } from './actions';\n\ntype Operation = 'refetch' | 'invalidate' | 'read-data';\n\ninterface Command {\n operation: Operation;\n clientId: string;\n queryId: string;\n}\n\n// Sends every query row again. It needs only the client.\ninterface Resync {\n operation: 'resync';\n clientId: string;\n}\n\nfunction field(value: unknown, key: string): unknown {\n if (typeof value !== 'object' || value === null) return undefined;\n try {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n return descriptor && 'value' in descriptor ? (descriptor.value as unknown) : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction parseCommand(command: unknown): Command | Resync | undefined {\n const operation = field(command, 'operation');\n const clientId = field(command, 'clientId');\n const queryId = field(command, 'queryId');\n if (operation === 'resync' && typeof clientId === 'string' && clientId && clientId.length <= 256)\n return { operation, clientId };\n if (operation !== 'refetch' && operation !== 'invalidate' && operation !== 'read-data')\n return undefined;\n if (typeof clientId !== 'string' || !clientId || clientId.length > 256) return undefined;\n if (typeof queryId !== 'string' || !queryId || queryId.length > 512) return undefined;\n return { operation, clientId, queryId };\n}\n\n// Serves the requests BKB makes to the plugin: refetch or invalidate one query of one client,\n// read its data, or send all rows again. Anything else, or a client that is not tracked, is refused.\nexport function handleQueryCommand(command: unknown): unknown {\n const parsed = parseCommand(command);\n if (!parsed) return { outcome: 'refused', reason: 'The request was not understood.' };\n const tracked = trackedClients().find((candidate) => candidate.clientId === parsed.clientId);\n if (!tracked) return { outcome: 'refused', reason: 'That query client is not tracked.' };\n if (parsed.operation === 'resync') {\n tracked.watcher.resend();\n return { outcome: 'done', fetchStarted: false };\n }\n if (parsed.operation === 'read-data') return readQueryData(tracked.client, parsed.queryId);\n return runQueryAction(\n tracked.client,\n tracked.clientId,\n parsed.operation,\n parsed.queryId,\n publishCacheEvent,\n );\n}\n", "import type { PluginProvider } from '@bkbdev/core/register';\nimport { handleQueryCommand } from './commands';\nimport { droppedCacheEvents, onCacheEvent } from './hub';\n\n// Hands the cache events to the logger: it sends each one on the `bkb.query-cache` channel and\n// reports the plugin to BKB in its hello message.\nexport function queryCacheProvider(): PluginProvider {\n return {\n capability: 'queryCache',\n instanceId: 'react-query-' + Date.now().toString(36) + Math.random().toString(36).slice(2, 8),\n subscribe: (listener) => onCacheEvent((event) => listener(event)),\n handleCommand: handleQueryCommand,\n droppedCount: droppedCacheEvents,\n };\n}\n", "import { trackSource } from '@bkbdev/core/plugin';\nimport type { TrackMeta } from '@bkbdev/core/plugin';\nimport { clientLabel, publishCacheEvent, rememberClient, reserveClientId } from './hub';\nimport { MutationWatcher } from './mutations';\nimport type { QueryCacheLike, QueryClientLike } from './types';\nimport { QueryWatcher } from './watcher';\n\ndeclare const __DEV__: boolean | undefined;\nconst tracked = new WeakSet<object>();\n\n// React Query calls `onFocus` and `onOnline` on the cache when the window regains focus or the\n// network returns: the moments it refetches on. The calls are reported, then carried out.\nfunction reportWakeups(cache: QueryCacheLike, clientId: string): void {\n for (const [method, kind] of [\n ['onFocus', 'focus'],\n ['onOnline', 'online'],\n ] as const) {\n const original = cache[method];\n if (typeof original !== 'function') continue;\n cache[method] = () => {\n publishCacheEvent({ kind, clientId, timestamp: Date.now() });\n original.call(cache);\n };\n }\n}\n\n// Reports the queries, mutations, focus and online events of the client to BKB and returns the\n// same client. Calling it again for a client it already tracks does nothing, and in a release\n// build it does nothing at all.\nexport function trackQueryClient<T extends QueryClientLike>(client: T, meta?: TrackMeta): T {\n if (typeof __DEV__ !== 'undefined' && !__DEV__) return client;\n if (tracked.has(client)) return client;\n tracked.add(client);\n const clientId = reserveClientId(\n clientLabel(meta?.variable ?? null, meta?.file ?? null, meta?.line ?? null),\n );\n const watcher = new QueryWatcher(\n client,\n clientId,\n publishCacheEvent,\n Date.now,\n trackSource(meta),\n );\n watcher.start();\n new MutationWatcher(client.getMutationCache(), clientId, publishCacheEvent).start();\n reportWakeups(client.getQueryCache(), clientId);\n rememberClient({ clientId, client, watcher });\n return client;\n}\n", "import { previewValue } from '@bkbdev/core/plugin';\nimport { describeError } from './errors';\nimport { formatQueryKey } from './key';\nimport type { MutationCacheLike, MutationLike } from './types';\nimport type { CacheEvent } from '../../../protocol/src/query-cache-provider';\n\n// `loading` in React Query 3 and 4, `pending` in 5.\nfunction isRunning(status: string): boolean {\n return status === 'loading' || status === 'pending';\n}\n\ninterface Seen {\n status: string;\n startedAt: number | null;\n}\n\nfunction isMutation(value: unknown): value is MutationLike {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { mutationId?: unknown }).mutationId === 'number'\n );\n}\n\nfunction mutationOf(event: unknown): MutationLike | undefined {\n if (isMutation(event)) return event;\n const inner = (event as { mutation?: unknown } | null)?.mutation;\n return isMutation(inner) ? inner : undefined;\n}\n\nfunction nameOf(mutation: MutationLike): string {\n const key = mutation.options?.mutationKey;\n return key === undefined ? 'mutation' : formatQueryKey(key);\n}\n\n// Reports when a mutation starts and how it ends. The variables are shown through the shared\n// preview.\nexport class MutationWatcher {\n private readonly seen = new Map<number, Seen>();\n private stopSubscription: (() => void) | undefined;\n\n constructor(\n private readonly cache: MutationCacheLike,\n private readonly clientId: string,\n private readonly emit: (event: CacheEvent) => void,\n private readonly now: () => number = Date.now,\n ) {}\n\n start(): void {\n for (const mutation of this.cache.getAll())\n this.seen.set(mutation.mutationId, { status: mutation.state.status, startedAt: null });\n this.stopSubscription = this.cache.subscribe((event) => {\n const mutation = mutationOf(event);\n if (mutation) this.observe(mutation);\n });\n }\n\n stop(): void {\n this.stopSubscription?.();\n this.stopSubscription = undefined;\n }\n\n private observe(mutation: MutationLike): void {\n const id = mutation.mutationId;\n const entry = this.seen.get(id) ?? { status: 'idle', startedAt: null };\n this.seen.set(id, entry);\n const status = mutation.state.status;\n const wasRunning = isRunning(entry.status);\n if (isRunning(status) && !wasRunning) {\n entry.startedAt = this.now();\n this.send(mutation, 'started', null, null);\n } else if (wasRunning && (status === 'success' || status === 'error')) {\n const durationMs = entry.startedAt === null ? 0 : this.now() - entry.startedAt;\n const error = status === 'error' ? describeError(mutation.state.error) : null;\n this.send(mutation, status === 'error' ? 'failed' : 'succeeded', durationMs, error);\n }\n entry.status = status;\n }\n\n private send(\n mutation: MutationLike,\n phase: 'started' | 'succeeded' | 'failed',\n durationMs: number | null,\n error: string | null,\n ): void {\n this.emit({\n kind: 'mutation',\n clientId: this.clientId,\n mutationId: mutation.mutationId,\n name: nameOf(mutation),\n phase,\n variables: phase === 'started' ? previewValue(mutation.state.variables) : null,\n durationMs,\n error,\n timestamp: this.now(),\n });\n }\n}\n", "// A short, safe description of whatever a query or mutation failed with. Never `[object Object]`.\nexport function describeError(error: unknown): string | null {\n if (error === null || error === undefined) return null;\n if (error instanceof Error) return error.message.slice(0, 200);\n if (typeof error === 'string') return error.slice(0, 200);\n return 'Unknown error';\n}\n", "import { describeError } from './errors';\nimport { formatQueryKey } from './key';\nimport { isFetching, queryRow } from './snapshot';\nimport type { QueryCacheLike, QueryClientLike, QueryLike } from './types';\nimport type { CacheEvent, QueryRow } from '../../../protocol/src/query-cache-provider';\n\n// What was seen of a query at its previous notification. Transitions are read from the\n// differences, not from the library's event types, because React Query 3 reports no action.\ninterface Seen {\n key: string;\n fetching: boolean;\n invalidated: boolean;\n dataUpdatedAt: number;\n errorUpdatedAt: number;\n startedAt: number | null;\n fetchCount: number;\n // The last row sent for the query, to send another only when something in it changed.\n rowSignature: string;\n}\n\nfunction isQuery(value: unknown): value is QueryLike {\n return (\n typeof value === 'object' &&\n value !== null &&\n typeof (value as { queryHash?: unknown }).queryHash === 'string'\n );\n}\n\n// React Query 4 and 5 notify `{ type, query }`; 3 notifies the query itself.\nfunction queryOf(event: unknown): QueryLike | undefined {\n if (isQuery(event)) return event;\n const inner = (event as { query?: unknown } | null)?.query;\n return isQuery(inner) ? inner : undefined;\n}\n\nexport class QueryWatcher {\n private readonly seen = new Map<string, Seen>();\n private stopSubscription: (() => void) | undefined;\n\n constructor(\n private readonly client: QueryClientLike,\n private readonly clientId: string,\n private readonly emit: (event: CacheEvent) => void,\n private readonly now: () => number = Date.now,\n private readonly source: QueryRow['source'] = null,\n ) {}\n\n // Records the queries that already exist without reporting them, then follows the cache.\n start(): void {\n const cache: QueryCacheLike = this.client.getQueryCache();\n for (const query of cache.getAll()) this.sendRow(query, this.remember(query));\n this.stopSubscription = cache.subscribe((event) => {\n const query = queryOf(event);\n if (query) this.observe(query);\n this.reconcile(cache);\n });\n }\n\n stop(): void {\n this.stopSubscription?.();\n this.stopSubscription = undefined;\n }\n\n // Sends the state of every query again, even if it did not change since the last time.\n resend(): void {\n for (const query of this.client.getQueryCache().getAll()) {\n const entry = this.seen.get(query.queryHash) ?? this.remember(query);\n entry.rowSignature = '';\n this.sendRow(query, entry);\n }\n }\n\n fetchCount(queryId: string): number {\n return this.seen.get(queryId)?.fetchCount ?? 0;\n }\n\n rows(): QueryRow[] {\n return this.client\n .getQueryCache()\n .getAll()\n .map((query) =>\n queryRow(this.client, this.clientId, query, this.fetchCount(query.queryHash), this.source),\n );\n }\n\n private remember(query: QueryLike): Seen {\n const seen: Seen = {\n key: formatQueryKey(query.queryKey),\n fetching: isFetching(query),\n invalidated: query.state.isInvalidated,\n dataUpdatedAt: query.state.dataUpdatedAt,\n errorUpdatedAt: query.state.errorUpdatedAt,\n startedAt: null,\n fetchCount: 0,\n rowSignature: '',\n };\n this.seen.set(query.queryHash, seen);\n return seen;\n }\n\n private event(\n query: string,\n key: string,\n phase: 'fetch-started' | 'succeeded' | 'failed' | 'invalidated' | 'removed',\n extra: { durationMs?: number; error?: string | null } = {},\n ): void {\n this.emit({\n kind: 'query',\n clientId: this.clientId,\n queryId: query,\n key,\n phase,\n durationMs: extra.durationMs ?? null,\n error: extra.error ?? null,\n timestamp: this.now(),\n });\n }\n\n private observe(query: QueryLike): void {\n const id = query.queryHash;\n const state = query.state;\n const fetching = isFetching(query);\n let entry = this.seen.get(id);\n if (!entry) {\n // First time this query is seen: it counts as not fetching and not invalid before, so a\n // fetch that is already running is reported. The stored entry is the one that is updated.\n entry = this.remember(query);\n entry.fetching = false;\n entry.invalidated = false;\n }\n const key = entry.key;\n let failed = false;\n if (fetching && !entry.fetching) {\n entry.startedAt = this.now();\n entry.fetchCount += 1;\n this.event(id, key, 'fetch-started');\n } else if (!fetching && entry.fetching) failed = this.settle(id, entry, query);\n // React Query 5 flags a query invalid when its fetch fails; that is the failure, not an\n // invalidation anyone asked for, and the timeline already says \"Failed\".\n if (state.isInvalidated && !entry.invalidated && !failed) this.event(id, key, 'invalidated');\n entry.fetching = fetching;\n entry.invalidated = state.isInvalidated;\n entry.dataUpdatedAt = state.dataUpdatedAt;\n entry.errorUpdatedAt = state.errorUpdatedAt;\n this.sendRow(query, entry);\n }\n\n // Reports the query's state, but only when it differs from the one reported last.\n private sendRow(query: QueryLike, entry: Seen): void {\n const row = queryRow(this.client, this.clientId, query, entry.fetchCount, this.source);\n const signature = JSON.stringify(row);\n if (signature === entry.rowSignature) return;\n entry.rowSignature = signature;\n this.emit({ kind: 'row', clientId: this.clientId, row, timestamp: this.now() });\n }\n\n // A fetch ended: failed, succeeded, or was cancelled (reported as neither). True when failed.\n private settle(id: string, entry: Seen, query: QueryLike): boolean {\n const state = query.state;\n const durationMs = entry.startedAt === null ? 0 : this.now() - entry.startedAt;\n entry.startedAt = null;\n if (state.errorUpdatedAt > entry.errorUpdatedAt) {\n this.event(id, entry.key, 'failed', { durationMs, error: describeError(state.error) });\n return true;\n }\n if (state.dataUpdatedAt > entry.dataUpdatedAt)\n this.event(id, entry.key, 'succeeded', { durationMs });\n return false;\n }\n\n private reconcile(cache: QueryCacheLike): void {\n const live = cache.getAll();\n if (live.length === this.seen.size) return;\n const present = new Set(live.map((query) => query.queryHash));\n for (const [id, entry] of [...this.seen]) {\n if (present.has(id)) continue;\n this.seen.delete(id);\n this.event(id, entry.key, 'removed');\n }\n }\n}\n"],
5
+ "mappings": ";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,oBAA+B;AAO/B,IAAM,eAAe;AAerB,IAAM,aAAS,8BAA2B,+BAA+B;AAEzE,SAAS,WAAqB;AAC5B,QAAM,WAAW,OAAO,YAAY;AACpC,MAAI,SAAU,QAAO;AACrB,QAAM,UAAoB,EAAE,SAAS,oBAAI,IAAI,GAAG,aAAa,oBAAI,IAAI,EAAE;AACvE,SAAO,YAAY,IAAI;AACvB,SA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ChC,UAAQ,IAAI,MAAM;AAClB,QAAM,WAAW;AAAA,IACf,aAAY,kCAAM,aAAN,YAAkB,OAAM,kCAAM,SAAN,YAAc,OAAM,kCAAM,SAAN,YAAc,IAAI;AAAA,EAC5E;AACA,QAAM,UAAU,IAAI;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA,KAAK;AAAA,QACL,4BAAY,IAAI;AAAA,EAClB;AACA,UAAQ,MAAM;AACd,MAAI,gBAAgB,OAAO,iBAAiB,GAAG,UAAU,iBAAiB,EAAE,MAAM;AAClF,gBAAc,OAAO,cAAc,GAAG,QAAQ;AAC9C,iBAAe,EAAE,UAAU,QAAQ,QAAQ,CAAC;AAC5C,SAAO;AACT;;;APtCA,IAAM,SAAoB;AAAA,EACxB,MAAM;AAAA,EACN,QAAQ,OAAO,EAAE,iBAAiB,CAAC,mBAAmB,CAAC,EAAE;AAC3D;AAEA,IAAO,cAAQ;",
6
+ "names": ["tracked", "import_plugin", "_a", "tracked", "import_plugin", "import_plugin"]
7
+ }
package/dist/index.js ADDED
@@ -0,0 +1,516 @@
1
+ // packages/plugins/react-query/src/hub.ts
2
+ import { createEventHub } from "@bkbdev/core/plugin";
3
+ var REGISTRY_KEY = "__BKB_QUERY_CLIENTS_V1__";
4
+ var events = createEventHub("__BKB_QUERY_CACHE_EVENTS_V1__");
5
+ function registry() {
6
+ const existing = global[REGISTRY_KEY];
7
+ if (existing) return existing;
8
+ const created = { clients: /* @__PURE__ */ new Map(), labelCounts: /* @__PURE__ */ new Map() };
9
+ global[REGISTRY_KEY] = created;
10
+ return created;
11
+ }
12
+ function clientLabel(variable, file, line) {
13
+ const base = variable != null ? variable : file !== null && line !== null ? file.slice(-120) + ":" + line : "client";
14
+ return base.slice(0, 128);
15
+ }
16
+ function reserveClientId(label) {
17
+ var _a;
18
+ const state = registry();
19
+ const count = ((_a = state.labelCounts.get(label)) != null ? _a : 0) + 1;
20
+ state.labelCounts.set(label, count);
21
+ return count === 1 ? label : label + "#" + count;
22
+ }
23
+ function rememberClient(tracked2) {
24
+ registry().clients.set(tracked2.clientId, tracked2);
25
+ }
26
+ function trackedClients() {
27
+ return [...registry().clients.values()];
28
+ }
29
+ var publishCacheEvent = events.publish;
30
+ var onCacheEvent = events.subscribe;
31
+ var droppedCacheEvents = events.droppedCount;
32
+
33
+ // packages/plugins/react-query/src/actions.ts
34
+ import { snapshotValue } from "@bkbdev/core/plugin";
35
+
36
+ // packages/plugins/react-query/src/key.ts
37
+ var MAX_DEPTH = 4;
38
+ var MAX_ITEMS = 8;
39
+ var MAX_CHARACTERS = 200;
40
+ function quote(text) {
41
+ const clipped = text.length > 60 ? text.slice(0, 60) + "\u2026" : text;
42
+ return "'" + clipped.replace(/\\/g, "\\\\").replace(/'/g, "\\'").replace(/\n/g, "\\n") + "'";
43
+ }
44
+ function propertyName(name) {
45
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : quote(name);
46
+ }
47
+ function isRecord(value) {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
50
+ function scalar(value) {
51
+ if (typeof value === "string") return quote(value);
52
+ if (value === null || typeof value === "number" || typeof value === "boolean")
53
+ return String(value);
54
+ if (value === void 0) return "undefined";
55
+ if (typeof value === "bigint") return String(value) + "n";
56
+ if (typeof value === "function") return "[Function]";
57
+ return "[" + typeof value + "]";
58
+ }
59
+ function list(items, total, open, close) {
60
+ const more = total > items.length ? ["\u2026"] : [];
61
+ if (!items.length && !more.length) return open + close;
62
+ const body = [...items, ...more].join(", ");
63
+ return open === "{" ? "{ " + body + " }" : open + body + close;
64
+ }
65
+ function render(value, depth, seen) {
66
+ if (typeof value !== "object" || value === null) return scalar(value);
67
+ if (seen.has(value)) return "[Circular]";
68
+ if (depth >= MAX_DEPTH) return Array.isArray(value) ? "[\u2026]" : "{\u2026}";
69
+ seen.add(value);
70
+ try {
71
+ if (Array.isArray(value))
72
+ return list(
73
+ value.slice(0, MAX_ITEMS).map((item) => render(item, depth + 1, seen)),
74
+ value.length,
75
+ "[",
76
+ "]"
77
+ );
78
+ if (!isRecord(value)) return "[object]";
79
+ const names = Object.keys(value);
80
+ return list(
81
+ names.slice(0, MAX_ITEMS).map((name) => propertyName(name) + ": " + render(value[name], depth + 1, seen)),
82
+ names.length,
83
+ "{",
84
+ "}"
85
+ );
86
+ } finally {
87
+ seen.delete(value);
88
+ }
89
+ }
90
+ function formatQueryKey(key) {
91
+ let text;
92
+ try {
93
+ text = render(key, 0, /* @__PURE__ */ new Set());
94
+ } catch (e) {
95
+ return "[unreadable key]";
96
+ }
97
+ return text.length > MAX_CHARACTERS ? text.slice(0, MAX_CHARACTERS - 1) + "\u2026" : text;
98
+ }
99
+
100
+ // packages/plugins/react-query/src/snapshot.ts
101
+ function isFetching(query) {
102
+ const state = query.state;
103
+ return state.fetchStatus === void 0 ? state.isFetching === true : state.fetchStatus === "fetching";
104
+ }
105
+ function isPaused(query) {
106
+ return query.state.fetchStatus === "paused";
107
+ }
108
+ function hasActiveObserver(query) {
109
+ var _a;
110
+ if (typeof query.isActive === "function") return query.isActive();
111
+ const observers = (_a = query.observers) != null ? _a : [];
112
+ return observers.some((observer) => {
113
+ var _a2;
114
+ return ((_a2 = observer.options) == null ? void 0 : _a2.enabled) !== false;
115
+ });
116
+ }
117
+ function hasQueryFunction(client, query) {
118
+ var _a, _b;
119
+ if (typeof ((_a = query.options) == null ? void 0 : _a.queryFn) === "function") return true;
120
+ const defaults = client.getDefaultOptions ? client.getDefaultOptions() : void 0;
121
+ return typeof ((_b = defaults == null ? void 0 : defaults.queries) == null ? void 0 : _b.queryFn) === "function";
122
+ }
123
+ function isRefetchable(client, query) {
124
+ var _a;
125
+ if (!hasQueryFunction(client, query)) return false;
126
+ const observers = (_a = query.observers) != null ? _a : [];
127
+ return observers.length === 0 || hasActiveObserver(query);
128
+ }
129
+ function queryStatus(query) {
130
+ var _a;
131
+ if (isFetching(query)) return "fetching";
132
+ if (isPaused(query)) return "paused";
133
+ if (query.state.status === "error") return "error";
134
+ if (!((_a = query.observers) != null ? _a : []).length) return "inactive";
135
+ if (query.state.dataUpdatedAt === 0) return "idle";
136
+ return typeof query.isStale === "function" && !query.isStale() ? "fresh" : "stale";
137
+ }
138
+ function queryRow(client, clientId, query, fetchCount, source) {
139
+ var _a;
140
+ return {
141
+ clientId,
142
+ queryId: query.queryHash,
143
+ key: formatQueryKey(query.queryKey),
144
+ status: queryStatus(query),
145
+ observers: ((_a = query.observers) != null ? _a : []).length,
146
+ fetchCount,
147
+ updatedAt: query.state.dataUpdatedAt > 0 ? query.state.dataUpdatedAt : null,
148
+ refetchable: isRefetchable(client, query),
149
+ source
150
+ };
151
+ }
152
+
153
+ // packages/plugins/react-query/src/actions.ts
154
+ function refused(reason) {
155
+ return { outcome: "refused", reason };
156
+ }
157
+ function refetchBlocker(client, query) {
158
+ if (isFetching(query)) return "The query is already fetching.";
159
+ if (!isRefetchable(client, query))
160
+ return "The query has no query function, or every component using it has it disabled.";
161
+ return void 0;
162
+ }
163
+ function find(client, queryId) {
164
+ return client.getQueryCache().getAll().find((query) => query.queryHash === queryId);
165
+ }
166
+ function runQueryAction(client, clientId, action, queryId, emit, now = Date.now) {
167
+ const query = find(client, queryId);
168
+ if (!query) return refused("The query no longer exists.");
169
+ if (action === "refetch") {
170
+ const blocker = refetchBlocker(client, query);
171
+ if (blocker) return refused(blocker);
172
+ }
173
+ emit({
174
+ kind: "request",
175
+ clientId,
176
+ action,
177
+ queryId,
178
+ key: formatQueryKey(query.queryKey),
179
+ timestamp: now()
180
+ });
181
+ const filters = { queryKey: query.queryKey, exact: true };
182
+ const pending = action === "refetch" ? client.refetchQueries(filters, { cancelRefetch: false }) : client.invalidateQueries(filters);
183
+ pending.catch(() => void 0);
184
+ return { outcome: "done", fetchStarted: isFetching(query) };
185
+ }
186
+ function readQueryData(client, queryId) {
187
+ const query = find(client, queryId);
188
+ if (!query) return refused("The query no longer exists.");
189
+ if (query.state.dataUpdatedAt === 0 && query.state.data === void 0)
190
+ return refused("The query has no data yet.");
191
+ const { data, truncated } = snapshotValue(query.state.data);
192
+ return { outcome: "data", data, truncated };
193
+ }
194
+
195
+ // packages/plugins/react-query/src/commands.ts
196
+ function field(value, key) {
197
+ if (typeof value !== "object" || value === null) return void 0;
198
+ try {
199
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
200
+ return descriptor && "value" in descriptor ? descriptor.value : void 0;
201
+ } catch (e) {
202
+ return void 0;
203
+ }
204
+ }
205
+ function parseCommand(command) {
206
+ const operation = field(command, "operation");
207
+ const clientId = field(command, "clientId");
208
+ const queryId = field(command, "queryId");
209
+ if (operation === "resync" && typeof clientId === "string" && clientId && clientId.length <= 256)
210
+ return { operation, clientId };
211
+ if (operation !== "refetch" && operation !== "invalidate" && operation !== "read-data")
212
+ return void 0;
213
+ if (typeof clientId !== "string" || !clientId || clientId.length > 256) return void 0;
214
+ if (typeof queryId !== "string" || !queryId || queryId.length > 512) return void 0;
215
+ return { operation, clientId, queryId };
216
+ }
217
+ function handleQueryCommand(command) {
218
+ const parsed = parseCommand(command);
219
+ if (!parsed) return { outcome: "refused", reason: "The request was not understood." };
220
+ const tracked2 = trackedClients().find((candidate) => candidate.clientId === parsed.clientId);
221
+ if (!tracked2) return { outcome: "refused", reason: "That query client is not tracked." };
222
+ if (parsed.operation === "resync") {
223
+ tracked2.watcher.resend();
224
+ return { outcome: "done", fetchStarted: false };
225
+ }
226
+ if (parsed.operation === "read-data") return readQueryData(tracked2.client, parsed.queryId);
227
+ return runQueryAction(
228
+ tracked2.client,
229
+ tracked2.clientId,
230
+ parsed.operation,
231
+ parsed.queryId,
232
+ publishCacheEvent
233
+ );
234
+ }
235
+
236
+ // packages/plugins/react-query/src/provider.ts
237
+ function queryCacheProvider() {
238
+ return {
239
+ capability: "queryCache",
240
+ instanceId: "react-query-" + Date.now().toString(36) + Math.random().toString(36).slice(2, 8),
241
+ subscribe: (listener) => onCacheEvent((event) => listener(event)),
242
+ handleCommand: handleQueryCommand,
243
+ droppedCount: droppedCacheEvents
244
+ };
245
+ }
246
+
247
+ // packages/plugins/react-query/src/track.ts
248
+ import { trackSource } from "@bkbdev/core/plugin";
249
+
250
+ // packages/plugins/react-query/src/mutations.ts
251
+ import { previewValue } from "@bkbdev/core/plugin";
252
+
253
+ // packages/plugins/react-query/src/errors.ts
254
+ function describeError(error) {
255
+ if (error === null || error === void 0) return null;
256
+ if (error instanceof Error) return error.message.slice(0, 200);
257
+ if (typeof error === "string") return error.slice(0, 200);
258
+ return "Unknown error";
259
+ }
260
+
261
+ // packages/plugins/react-query/src/mutations.ts
262
+ function isRunning(status) {
263
+ return status === "loading" || status === "pending";
264
+ }
265
+ function isMutation(value) {
266
+ return typeof value === "object" && value !== null && typeof value.mutationId === "number";
267
+ }
268
+ function mutationOf(event) {
269
+ if (isMutation(event)) return event;
270
+ const inner = event == null ? void 0 : event.mutation;
271
+ return isMutation(inner) ? inner : void 0;
272
+ }
273
+ function nameOf(mutation) {
274
+ var _a;
275
+ const key = (_a = mutation.options) == null ? void 0 : _a.mutationKey;
276
+ return key === void 0 ? "mutation" : formatQueryKey(key);
277
+ }
278
+ var MutationWatcher = class {
279
+ constructor(cache, clientId, emit, now = Date.now) {
280
+ this.cache = cache;
281
+ this.clientId = clientId;
282
+ this.emit = emit;
283
+ this.now = now;
284
+ this.seen = /* @__PURE__ */ new Map();
285
+ }
286
+ start() {
287
+ for (const mutation of this.cache.getAll())
288
+ this.seen.set(mutation.mutationId, { status: mutation.state.status, startedAt: null });
289
+ this.stopSubscription = this.cache.subscribe((event) => {
290
+ const mutation = mutationOf(event);
291
+ if (mutation) this.observe(mutation);
292
+ });
293
+ }
294
+ stop() {
295
+ var _a;
296
+ (_a = this.stopSubscription) == null ? void 0 : _a.call(this);
297
+ this.stopSubscription = void 0;
298
+ }
299
+ observe(mutation) {
300
+ var _a;
301
+ const id = mutation.mutationId;
302
+ const entry = (_a = this.seen.get(id)) != null ? _a : { status: "idle", startedAt: null };
303
+ this.seen.set(id, entry);
304
+ const status = mutation.state.status;
305
+ const wasRunning = isRunning(entry.status);
306
+ if (isRunning(status) && !wasRunning) {
307
+ entry.startedAt = this.now();
308
+ this.send(mutation, "started", null, null);
309
+ } else if (wasRunning && (status === "success" || status === "error")) {
310
+ const durationMs = entry.startedAt === null ? 0 : this.now() - entry.startedAt;
311
+ const error = status === "error" ? describeError(mutation.state.error) : null;
312
+ this.send(mutation, status === "error" ? "failed" : "succeeded", durationMs, error);
313
+ }
314
+ entry.status = status;
315
+ }
316
+ send(mutation, phase, durationMs, error) {
317
+ this.emit({
318
+ kind: "mutation",
319
+ clientId: this.clientId,
320
+ mutationId: mutation.mutationId,
321
+ name: nameOf(mutation),
322
+ phase,
323
+ variables: phase === "started" ? previewValue(mutation.state.variables) : null,
324
+ durationMs,
325
+ error,
326
+ timestamp: this.now()
327
+ });
328
+ }
329
+ };
330
+
331
+ // packages/plugins/react-query/src/watcher.ts
332
+ function isQuery(value) {
333
+ return typeof value === "object" && value !== null && typeof value.queryHash === "string";
334
+ }
335
+ function queryOf(event) {
336
+ if (isQuery(event)) return event;
337
+ const inner = event == null ? void 0 : event.query;
338
+ return isQuery(inner) ? inner : void 0;
339
+ }
340
+ var QueryWatcher = class {
341
+ constructor(client, clientId, emit, now = Date.now, source = null) {
342
+ this.client = client;
343
+ this.clientId = clientId;
344
+ this.emit = emit;
345
+ this.now = now;
346
+ this.source = source;
347
+ this.seen = /* @__PURE__ */ new Map();
348
+ }
349
+ // Records the queries that already exist without reporting them, then follows the cache.
350
+ start() {
351
+ const cache = this.client.getQueryCache();
352
+ for (const query of cache.getAll()) this.sendRow(query, this.remember(query));
353
+ this.stopSubscription = cache.subscribe((event) => {
354
+ const query = queryOf(event);
355
+ if (query) this.observe(query);
356
+ this.reconcile(cache);
357
+ });
358
+ }
359
+ stop() {
360
+ var _a;
361
+ (_a = this.stopSubscription) == null ? void 0 : _a.call(this);
362
+ this.stopSubscription = void 0;
363
+ }
364
+ // Sends the state of every query again, even if it did not change since the last time.
365
+ resend() {
366
+ var _a;
367
+ for (const query of this.client.getQueryCache().getAll()) {
368
+ const entry = (_a = this.seen.get(query.queryHash)) != null ? _a : this.remember(query);
369
+ entry.rowSignature = "";
370
+ this.sendRow(query, entry);
371
+ }
372
+ }
373
+ fetchCount(queryId) {
374
+ var _a, _b;
375
+ return (_b = (_a = this.seen.get(queryId)) == null ? void 0 : _a.fetchCount) != null ? _b : 0;
376
+ }
377
+ rows() {
378
+ return this.client.getQueryCache().getAll().map(
379
+ (query) => queryRow(this.client, this.clientId, query, this.fetchCount(query.queryHash), this.source)
380
+ );
381
+ }
382
+ remember(query) {
383
+ const seen = {
384
+ key: formatQueryKey(query.queryKey),
385
+ fetching: isFetching(query),
386
+ invalidated: query.state.isInvalidated,
387
+ dataUpdatedAt: query.state.dataUpdatedAt,
388
+ errorUpdatedAt: query.state.errorUpdatedAt,
389
+ startedAt: null,
390
+ fetchCount: 0,
391
+ rowSignature: ""
392
+ };
393
+ this.seen.set(query.queryHash, seen);
394
+ return seen;
395
+ }
396
+ event(query, key, phase, extra = {}) {
397
+ var _a, _b;
398
+ this.emit({
399
+ kind: "query",
400
+ clientId: this.clientId,
401
+ queryId: query,
402
+ key,
403
+ phase,
404
+ durationMs: (_a = extra.durationMs) != null ? _a : null,
405
+ error: (_b = extra.error) != null ? _b : null,
406
+ timestamp: this.now()
407
+ });
408
+ }
409
+ observe(query) {
410
+ const id = query.queryHash;
411
+ const state = query.state;
412
+ const fetching = isFetching(query);
413
+ let entry = this.seen.get(id);
414
+ if (!entry) {
415
+ entry = this.remember(query);
416
+ entry.fetching = false;
417
+ entry.invalidated = false;
418
+ }
419
+ const key = entry.key;
420
+ let failed = false;
421
+ if (fetching && !entry.fetching) {
422
+ entry.startedAt = this.now();
423
+ entry.fetchCount += 1;
424
+ this.event(id, key, "fetch-started");
425
+ } else if (!fetching && entry.fetching) failed = this.settle(id, entry, query);
426
+ if (state.isInvalidated && !entry.invalidated && !failed) this.event(id, key, "invalidated");
427
+ entry.fetching = fetching;
428
+ entry.invalidated = state.isInvalidated;
429
+ entry.dataUpdatedAt = state.dataUpdatedAt;
430
+ entry.errorUpdatedAt = state.errorUpdatedAt;
431
+ this.sendRow(query, entry);
432
+ }
433
+ // Reports the query's state, but only when it differs from the one reported last.
434
+ sendRow(query, entry) {
435
+ const row = queryRow(this.client, this.clientId, query, entry.fetchCount, this.source);
436
+ const signature = JSON.stringify(row);
437
+ if (signature === entry.rowSignature) return;
438
+ entry.rowSignature = signature;
439
+ this.emit({ kind: "row", clientId: this.clientId, row, timestamp: this.now() });
440
+ }
441
+ // A fetch ended: failed, succeeded, or was cancelled (reported as neither). True when failed.
442
+ settle(id, entry, query) {
443
+ const state = query.state;
444
+ const durationMs = entry.startedAt === null ? 0 : this.now() - entry.startedAt;
445
+ entry.startedAt = null;
446
+ if (state.errorUpdatedAt > entry.errorUpdatedAt) {
447
+ this.event(id, entry.key, "failed", { durationMs, error: describeError(state.error) });
448
+ return true;
449
+ }
450
+ if (state.dataUpdatedAt > entry.dataUpdatedAt)
451
+ this.event(id, entry.key, "succeeded", { durationMs });
452
+ return false;
453
+ }
454
+ reconcile(cache) {
455
+ const live = cache.getAll();
456
+ if (live.length === this.seen.size) return;
457
+ const present = new Set(live.map((query) => query.queryHash));
458
+ for (const [id, entry] of [...this.seen]) {
459
+ if (present.has(id)) continue;
460
+ this.seen.delete(id);
461
+ this.event(id, entry.key, "removed");
462
+ }
463
+ }
464
+ };
465
+
466
+ // packages/plugins/react-query/src/track.ts
467
+ var tracked = /* @__PURE__ */ new WeakSet();
468
+ function reportWakeups(cache, clientId) {
469
+ for (const [method, kind] of [
470
+ ["onFocus", "focus"],
471
+ ["onOnline", "online"]
472
+ ]) {
473
+ const original = cache[method];
474
+ if (typeof original !== "function") continue;
475
+ cache[method] = () => {
476
+ publishCacheEvent({ kind, clientId, timestamp: Date.now() });
477
+ original.call(cache);
478
+ };
479
+ }
480
+ }
481
+ function trackQueryClient(client, meta) {
482
+ var _a, _b, _c;
483
+ if (typeof __DEV__ !== "undefined" && !__DEV__) return client;
484
+ if (tracked.has(client)) return client;
485
+ tracked.add(client);
486
+ const clientId = reserveClientId(
487
+ clientLabel((_a = meta == null ? void 0 : meta.variable) != null ? _a : null, (_b = meta == null ? void 0 : meta.file) != null ? _b : null, (_c = meta == null ? void 0 : meta.line) != null ? _c : null)
488
+ );
489
+ const watcher = new QueryWatcher(
490
+ client,
491
+ clientId,
492
+ publishCacheEvent,
493
+ Date.now,
494
+ trackSource(meta)
495
+ );
496
+ watcher.start();
497
+ new MutationWatcher(client.getMutationCache(), clientId, publishCacheEvent).start();
498
+ reportWakeups(client.getQueryCache(), clientId);
499
+ rememberClient({ clientId, client, watcher });
500
+ return client;
501
+ }
502
+
503
+ // packages/plugins/react-query/src/index.ts
504
+ var plugin = {
505
+ name: "react-query",
506
+ extend: () => ({ pluginProviders: [queryCacheProvider()] })
507
+ };
508
+ var src_default = plugin;
509
+ export {
510
+ src_default as default,
511
+ droppedCacheEvents,
512
+ onCacheEvent,
513
+ trackQueryClient,
514
+ trackedClients
515
+ };
516
+ //# sourceMappingURL=index.js.map