@spooky-sync/client-react 0.0.0-stage → 0.0.1-canary.383
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.
- package/AGENTS.md +93 -0
- package/QUICK_START.md +162 -0
- package/README.md +54 -2
- package/dist/index.cjs +1351 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +623 -0
- package/dist/index.d.cts.map +1 -0
- package/dist/index.d.ts +623 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +1312 -0
- package/dist/index.js.map +1 -0
- package/package.json +71 -4
- package/skills/sp00ky-react/SKILL.md +73 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["Sp00kyClient","RecordId","useLayoutEffect","useEffect"],"sources":["../src/db.ts","../src/provider.tsx","../src/query.ts","../src/status.ts","../src/realtime.ts","../src/files.tsx"],"sourcesContent":["import type { SyncedDbConfig } from './types';\nimport {\n Sp00kyClient,\n type Sp00kyQueryResultPromise,\n type AuthService,\n type BucketHandle,\n type UpdateOptions,\n type RunOptions,\n type SyncHealth,\n type StorageHealth,\n type PreloadOptions,\n type WebPushModule,\n type Sp00kyChannel,\n type ChannelQuery,\n} from '@spooky-sync/core';\nimport type {\n ChannelPeer,\n ChannelTableNames,\n GetTable,\n QueryBuilder,\n SchemaStructure,\n TableModel,\n TableNames,\n FinalQuery,\n InnerQuery,\n BackendNames,\n BackendRoutes,\n RoutePayload,\n BucketNames,\n BucketDefinitionSchema,\n} from '@spooky-sync/query-builder';\nimport { RecordId, type Surreal } from 'surrealdb';\n\n/**\n * SyncedDb - a thin wrapper around the sp00ky core client for React.\n * Delegates all logic to the underlying `Sp00kyClient` instance.\n *\n * NOTE: keep in sync with packages/client-solid/src/index.ts and\n * packages/client-solid2/src/index.ts (SyncedDb). Copied rather than shared so\n * this package's dependency graph never pulls in solid-js. React rows are plain\n * objects (no store proxies), so unlike the Solid 2 copy nothing is unwrapped\n * before a write.\n */\nexport class SyncedDb<S extends SchemaStructure> {\n private config: SyncedDbConfig<S>;\n private sp00ky: Sp00kyClient<S> | null = null;\n private _initialized = false;\n\n constructor(config: SyncedDbConfig<S>) {\n this.config = config;\n }\n\n public getSp00ky(): Sp00kyClient<S> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky;\n }\n\n /** Initialize the core client. */\n async init(): Promise<void> {\n if (this._initialized) return;\n this.sp00ky = new Sp00kyClient<S>(this.config);\n await this.sp00ky.init();\n this._initialized = true;\n }\n\n /**\n * Tear down the client: leaves the tabs broker, closes the local store and\n * remote socket, and frees the wasm circuit.\n */\n async close(): Promise<void> {\n const instance = this.sp00ky;\n this.sp00ky = null;\n this._initialized = false;\n if (instance) await instance.close();\n }\n\n /** Create a new record in the database. */\n async create(id: string, payload: Record<string, unknown>): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.create(id, payload);\n }\n\n /** Update an existing record in the database. */\n async update<TName extends TableNames<S>>(\n tableName: TName,\n recordId: string,\n payload: Partial<TableModel<GetTable<S, TName>>>,\n options?: UpdateOptions\n ): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.update(\n tableName as string,\n recordId,\n payload as Record<string, unknown>,\n options\n );\n }\n\n /** Delete an existing record in the database. */\n async delete<TName extends TableNames<S>>(\n tableName: TName,\n selector: string | RecordId | InnerQuery<GetTable<S, TName>, boolean>\n ): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n // Accept a `\"table:id\"` string OR a RecordId: live-query rows carry their\n // `id` as a RecordId, so callers can pass `db.delete('game', row.id)`\n // directly. Build the canonical string from the raw id part (not\n // `RecordId.toString()`, which escapes special chars) so it round-trips\n // through the engine's `parseRecordIdString`. InnerQuery selectors are not\n // supported yet. (Cross-package RecordId instances match by constructor name.)\n const isRecordId =\n selector instanceof RecordId || (selector as any)?.constructor?.name === 'RecordId';\n let id: string;\n if (typeof selector === 'string') {\n id = selector;\n } else if (isRecordId) {\n id = `${tableName as string}:${(selector as RecordId).id}`;\n } else {\n throw new Error('Only string ID or RecordId selectors are supported currently with core');\n }\n await this.sp00ky.delete(tableName as string, id);\n }\n\n /**\n * Preload/prewarm a built query into the local cache without a component\n * subscribing to it, so a later `useQuery` for the same data paints\n * instantly. Best-effort.\n */\n public async preload(\n finalQuery: FinalQuery<S, any, any, any, any, Sp00kyQueryResultPromise>,\n options?: PreloadOptions\n ): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.preload(finalQuery, options);\n }\n\n /** Start a query on `table`. Finish it with `.build()` and pass it to `useQuery`. */\n public query<TName extends TableNames<S>>(\n table: TName\n ): QueryBuilder<S, TName, Sp00kyQueryResultPromise, {}, false> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.query(table, {});\n }\n\n /**\n * Open a peer to peer channel to `peers` for the rows `query` matches (a\n * query on a `-- @channel` table; only its `where` counts). Prefer the\n * `useChannel` hook, which closes it with the component.\n */\n public channel<T extends ChannelTableNames<S>>(\n query: ChannelQuery<S, T> | ReadonlyArray<ChannelQuery<S, T>>,\n peers: Iterable<ChannelPeer>\n ): Sp00kyChannel<S, T> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.channel(query, peers);\n }\n\n /** Run a backend operation (writes an outbox job row). */\n public async run<B extends BackendNames<S>, R extends BackendRoutes<S, B>>(\n backend: B,\n path: R,\n payload: RoutePayload<S, B, R>,\n options?: RunOptions\n ): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.run(backend, path, payload, options);\n }\n\n /** Authenticate the remote connection with a token. */\n public async authenticate(token: string): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.authenticate(token);\n }\n\n /**\n * Tell the client that this app's own impersonation banner is on screen.\n * Only needed with `impersonationBanner: { mode: 'custom' }`; the\n * `useImpersonation({ rendersBanner: true })` hook calls it for you.\n */\n public acknowledgeImpersonationBanner(): void {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n this.sp00ky.acknowledgeImpersonationBanner();\n }\n\n /** Sign out, clear session and local storage. */\n public async signOut(): Promise<void> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n await this.sp00ky.auth.signOut();\n }\n\n /** Execute a function with direct access to the remote database connection. */\n public async useRemote<T>(fn: (db: Surreal) => T | Promise<T>): Promise<T> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return await this.sp00ky.useRemote(fn);\n }\n\n /**\n * Run one SurrealQL statement against the REMOTE database, results shaped\n * like the SDK's own `.query()` (one entry per statement). Nothing is cached\n * locally. Prefer this over `useRemote(s => s.query(...))` for a plain read:\n * the bare SDK client that callback receives skips the connect gate, so a\n * statement issued while the socket is being rebuilt fails with \"Specify a\n * namespace to use\" instead of waiting for the session.\n */\n public async remoteQuery<T extends unknown[] = unknown[]>(\n sql: string,\n vars?: Record<string, unknown>\n ): Promise<T> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return await this.sp00ky.remoteQuery<T>(sql, vars);\n }\n\n /** Access the remote database service directly. */\n get remote(): Sp00kyClient<S>['remoteClient'] {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.remoteClient;\n }\n\n /** Access the local database service directly. */\n get local(): Sp00kyClient<S>['localClient'] {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.localClient;\n }\n\n /** Access the auth service. */\n get auth(): AuthService<S> {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.auth;\n }\n\n get pendingMutationCount(): number {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.pendingMutationCount;\n }\n\n /** Diagnostic, see `Sp00kyClient.liveRetryCount`. */\n get liveRetryCount(): number {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.liveRetryCount;\n }\n\n subscribeToPendingMutations(cb: (count: number) => void): () => void {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.subscribeToPendingMutations(cb);\n }\n\n /** Queries mid-fetch right now. See {@link useSyncActivity}. */\n get fetchingQueryCount(): number {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.fetchingQueryCount;\n }\n\n /**\n * Observe how many queries are fetching from the server. Fires immediately\n * and on every change. Prefer the `useSyncActivity` hook in components.\n */\n subscribeToFetchActivity(cb: (fetching: number) => void): () => void {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.subscribeToFetchActivity(cb);\n }\n\n /** Current sync-health snapshot. See {@link useSyncStatus}. */\n get syncHealth(): SyncHealth {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.syncHealth;\n }\n\n /**\n * Observe sync health. Fires immediately with the current status and again\n * on every healthy/degraded transition. Prefer the `useSyncStatus` hook in\n * components; this is the imperative escape hatch.\n */\n subscribeToSyncHealth(cb: (health: SyncHealth) => void): () => void {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.subscribeToSyncHealth(cb);\n }\n\n /** Current local-store durability snapshot. See {@link useStorageStatus}. */\n get storageHealth(): StorageHealth {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.storageHealth;\n }\n\n /**\n * Observe local-store durability. Fires immediately with the current\n * snapshot and again on change. Prefer the `useStorageStatus` hook.\n */\n subscribeToStorageHealth(cb: (health: StorageHealth) => void): () => void {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.subscribeToStorageHealth(cb);\n }\n\n /**\n * Web Push for this browser: `support()`, `subscribe()` (from a click),\n * `devices()`, `notify()` / `test()` (push to yourself), `bridge()` for the\n * service worker. See the push-notifications docs page.\n */\n get webPush(): WebPushModule {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.webPush;\n }\n\n bucket<B extends BucketNames<S>>(name: B): BucketHandle {\n if (!this.sp00ky) throw new Error('SyncedDb not initialized');\n return this.sp00ky.bucket(name);\n }\n\n getBucketConfig(name: string): BucketDefinitionSchema | undefined {\n return this.config.schema.buckets?.find((b) => b.name === name);\n }\n}\n","import {\n createContext,\n useContext,\n useEffect,\n useLayoutEffect,\n useRef,\n useState,\n type ReactNode,\n} from 'react';\nimport type { SchemaStructure } from '@spooky-sync/query-builder';\nimport type { SyncedDbConfig } from './types';\nimport { SyncedDb } from './db';\n\n/** `useLayoutEffect` in the browser, `useEffect` on the server (no warning, same order). */\nexport const useIsomorphicLayoutEffect =\n typeof window !== 'undefined' ? useLayoutEffect : useEffect;\n\n/** Ref that always holds the latest value, for callbacks read from async continuations. */\nexport function useLatest<T>(value: T): { readonly current: T } {\n const ref = useRef(value);\n useIsomorphicLayoutEffect(() => {\n ref.current = value;\n });\n return ref;\n}\n\nconst Sp00kyContext = createContext<SyncedDb<any> | null>(null);\n\n/** The provider's `SyncedDb`, or `null` outside one. */\nexport function useOptionalDb(): SyncedDb<any> | null {\n return useContext(Sp00kyContext);\n}\n\n/**\n * The `SyncedDb` the nearest `<Sp00kyProvider>` initialized. Throws outside a\n * provider; every hook in this package goes through it.\n */\nexport function useDb<S extends SchemaStructure>(): SyncedDb<S> {\n const db = useContext(Sp00kyContext);\n if (!db) {\n throw new Error(\n 'useDb must be used within a <Sp00kyProvider>. Wrap your app in <Sp00kyProvider config={...}>.'\n );\n }\n return db as SyncedDb<S>;\n}\n\nexport interface Sp00kyProviderProps<S extends SchemaStructure> {\n /**\n * Client config. Read ONCE, when the provider mounts: changing it later does\n * not rebuild the client. To switch databases, remount the provider with a\n * new `key`.\n */\n config: SyncedDbConfig<S>;\n /** Rendered until the client is initialized (and `preload` resolved). */\n fallback?: ReactNode;\n onError?: (error: Error) => void;\n onReady?: (db: SyncedDb<S>) => void;\n /**\n * Prewarm data into the local cache before revealing the UI. Runs after\n * `init()`; the `fallback` stays visible until it resolves. Use awaitable\n * `db.preload(...)` calls here to gate first-load on essential data (e.g.\n * config). On warm loads preload returns instantly. Best-effort: a rejection\n * is caught and the UI is revealed anyway.\n */\n preload?: (db: SyncedDb<S>) => Promise<void>;\n children?: ReactNode;\n}\n\n/** One client per mounted provider, kept across StrictMode's simulated remount. */\ninterface Boot<S extends SchemaStructure> {\n instance: SyncedDb<S>;\n init: Promise<void>;\n /** Handed to the tree: from here on it is never closed (see the cleanup below). */\n revealed: boolean;\n disposeTimer?: ReturnType<typeof setTimeout>;\n}\n\n/**\n * Initializes a sp00ky client and provides it to `useDb()` and every hook\n * below. Renders `fallback` until the client is ready.\n *\n * The client is created in an effect, never during render, so a server render\n * only produces the fallback and StrictMode's double render creates nothing.\n */\nexport function Sp00kyProvider<S extends SchemaStructure>(props: Sp00kyProviderProps<S>) {\n const [db, setDb] = useState<SyncedDb<S> | null>(null);\n const boot = useRef<Boot<S> | null>(null);\n const callbacks = useLatest({\n onError: props.onError,\n onReady: props.onReady,\n preload: props.preload,\n });\n // Read once, at mount: see the `config` prop docs.\n const config = useRef(props.config).current;\n\n useEffect(() => {\n let active = true;\n let current = boot.current;\n if (current?.disposeTimer !== undefined) {\n // StrictMode re-ran this effect right after its cleanup: keep the client.\n clearTimeout(current.disposeTimer);\n current.disposeTimer = undefined;\n }\n if (!current) {\n const instance = new SyncedDb<S>(config);\n current = boot.current = { instance, init: instance.init(), revealed: false };\n }\n const b = current;\n\n b.init.then(\n async () => {\n if (!active) return;\n // Gate first-load UI on prewarmed data. Best-effort: never let a\n // preload failure keep the app stuck on the fallback.\n const preload = callbacks.current.preload;\n if (preload && !b.revealed) {\n try {\n await preload(b.instance);\n } catch (e) {\n // oxlint-disable-next-line no-console\n console.error('Sp00kyProvider: preload failed; revealing UI anyway', e);\n }\n }\n if (!active) return;\n const first = !b.revealed;\n b.revealed = true;\n setDb(b.instance);\n if (first) callbacks.current.onReady?.(b.instance);\n },\n (e: unknown) => {\n if (!active) return;\n const error = e instanceof Error ? e : new Error(String(e));\n if (callbacks.current.onError) {\n callbacks.current.onError(error);\n } else {\n // oxlint-disable-next-line no-console\n console.error('Sp00kyProvider: Failed to initialize database', error);\n }\n }\n );\n\n return () => {\n active = false;\n // StrictMode runs this cleanup and the effect again in the same commit,\n // so wait a task before deciding the provider is really gone. Only an\n // instance that was never revealed is closed then (init raced the\n // unmount). A revealed client is deliberately NOT closed: that nulls the\n // core client, so any write still in flight from the old tree (an\n // unmount handler, a pending submit) would throw \"SyncedDb not\n // initialized\" while the UI looks fine. The provider normally wraps the\n // whole app and only unmounts with the page, where the browser reclaims\n // the client anyway.\n b.disposeTimer = setTimeout(() => {\n b.disposeTimer = undefined;\n if (boot.current !== b) return;\n boot.current = null;\n if (!b.revealed) {\n b.init.then(\n () => b.instance.close(),\n () => {}\n );\n }\n }, 0);\n };\n // Mount-only by design: config and callbacks are read through refs.\n }, []);\n\n if (!db) return <>{props.fallback ?? null}</>;\n return <Sp00kyContext.Provider value={db}>{props.children}</Sp00kyContext.Provider>;\n}\n","import { useEffect, useState, useSyncExternalStore } from 'react';\nimport type {\n ColumnSchema,\n FinalQuery,\n QueryResult,\n SchemaStructure,\n TableNames,\n} from '@spooky-sync/query-builder';\nimport type {\n PreloadOptions as CorePreloadOptions,\n Sp00kyQueryResultPromise,\n} from '@spooky-sync/core';\nimport { SyncedDb } from './db';\nimport { useDb, useOptionalDb } from './provider';\n\n// ---------------------------------------------------------------------------\n// Pure part: structural sharing and the query state machine.\n// ---------------------------------------------------------------------------\n\nconst isPlainObject = (v: unknown): v is Record<string, unknown> => {\n if (v === null || typeof v !== 'object') return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n};\n\n/**\n * Value equality for the leaves `share` does not descend into. The decoder\n * hands out a fresh RecordId / Date / Uuid / Duration for every record-link\n * and datetime column on every emission, so by identity every such field\n * \"changed\" every time. Two instances of the same class that print alike are\n * the same value. A class whose `toString` is the default `[object X]`\n * (ArrayBuffer, Map, ...) cannot be compared that way and counts as changed.\n */\nexport function sameValue(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a == null || b == null || typeof a !== 'object' || typeof b !== 'object') return false;\n if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n const ctor = (a as object).constructor;\n if (!ctor || ctor !== (b as object).constructor || ctor === Object || ctor === Array)\n return false;\n const text = String(a);\n return !text.startsWith('[object ') && text === String(b);\n}\n\nconst keyOf = (v: unknown): string | undefined => {\n if (!isPlainObject(v)) return undefined;\n const id = v.id;\n return id === undefined || id === null ? undefined : String(id);\n};\n\n/**\n * Structural sharing between two emissions: returns `prev` itself where\n * `next` is deep-equal to it, and a new value that reuses every unchanged\n * subtree otherwise. Array items with an `id` are matched by id, so a row keeps\n * its object identity across reorders, inserts and deletes; `React.memo` rows\n * and `useMemo` deps keyed on a row only re-run when that row changed.\n *\n * Never mutates either argument: the engine may hand the same row objects to\n * several subscribers.\n */\nexport function share<T>(prev: unknown, next: T): T {\n if (prev === next) return next;\n if (Array.isArray(prev) && Array.isArray(next)) {\n const byKey = new Map<string, unknown>();\n for (const item of prev) {\n const k = keyOf(item);\n if (k !== undefined) byKey.set(k, item);\n }\n let same = prev.length === next.length;\n const out = next.map((item, i) => {\n const k = keyOf(item);\n const base = k !== undefined ? byKey.get(k) : prev[i];\n const v = base === undefined ? item : share(base, item);\n if (v !== prev[i]) same = false;\n return v;\n });\n return (same ? prev : out) as T;\n }\n if (isPlainObject(prev) && isPlainObject(next)) {\n const keys = Object.keys(next);\n let same = keys.length === Object.keys(prev).length;\n const out: Record<string, unknown> = {};\n for (const k of keys) {\n const v = k in prev ? share(prev[k], next[k]) : next[k];\n if (v !== prev[k] || !(k in prev)) same = false;\n out[k] = v;\n }\n return (same ? prev : out) as T;\n }\n return (sameValue(prev, next) ? prev : next) as T;\n}\n\n/** What the hook renders from. One immutable value per change. */\nexport interface QueryState {\n /** Last result: rows for a list, a row or `null` for `.one()`, `null` before any. */\n data: unknown;\n error: Error | undefined;\n /** Server membership known and painted for the current identity (core authority). */\n isAuthoritative: boolean;\n /** An emission WITH data was applied for the current identity. */\n hasPainted: boolean;\n isFetching: boolean;\n}\n\nexport type QueryEvent =\n | { type: 'reset' }\n | { type: 'rows'; rows: Record<string, unknown>[]; isOne: boolean }\n | { type: 'status'; fetching: boolean }\n | { type: 'authority'; known: boolean }\n | { type: 'error'; error: Error };\n\nexport const initialQueryState: QueryState = {\n data: null,\n error: undefined,\n isAuthoritative: false,\n hasPainted: false,\n isFetching: false,\n};\n\n/**\n * The query state machine, the same contract as the Solid 2 binding:\n *\n * - `reset` (a new identity) clears authority, the paint latch and the error.\n * The previous `data` stays until the new identity emits, so growing a\n * `.limit()` does not flash an empty list.\n * - `rows` applies every emission as-is (the core only emits what it decided\n * the query holds); one WITH data ends the cold load on its own.\n * - `authority` is the channel that ends a cold load whose honest answer is\n * zero rows. A flip back to false is a bucket switch (another principal):\n * what is painted is the previous one's, so the paint latch goes too.\n *\n * Returns `state` itself when nothing changed, so React skips the render.\n */\nexport function reduceQuery(state: QueryState, event: QueryEvent): QueryState {\n switch (event.type) {\n case 'reset':\n if (!state.isAuthoritative && !state.hasPainted && !state.error && !state.isFetching) {\n return state;\n }\n return {\n ...state,\n isAuthoritative: false,\n hasPainted: false,\n error: undefined,\n isFetching: false,\n };\n case 'rows': {\n const next = event.isOne ? (event.rows[0] ?? null) : event.rows;\n const hasRows = event.isOne ? next !== null && next !== undefined : event.rows.length > 0;\n const data = share(state.data, next);\n const hasPainted = state.hasPainted || hasRows;\n if (data === state.data && hasPainted === state.hasPainted) return state;\n return { ...state, data, hasPainted };\n }\n case 'status':\n return event.fetching === state.isFetching ? state : { ...state, isFetching: event.fetching };\n case 'authority': {\n const hasPainted = event.known ? state.hasPainted : false;\n if (event.known === state.isAuthoritative && hasPainted === state.hasPainted) return state;\n return { ...state, isAuthoritative: event.known, hasPainted };\n }\n case 'error':\n return { ...state, error: event.error };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Imperative shell: one engine subscription per hook, feeding the reducer.\n// ---------------------------------------------------------------------------\n\ntype AnyFinalQuery = FinalQuery<any, any, any, any, any, Sp00kyQueryResultPromise>;\ntype Sp00ky = ReturnType<SyncedDb<any>['getSp00ky']>;\n\nclass QueryStore {\n private state: QueryState = initialQueryState;\n private listeners = new Set<() => void>();\n /** Registered hash of the attached query, for opt-in deregistration on unmount. */\n activeHash: string | undefined;\n\n subscribe = (listener: () => void) => {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n };\n\n getSnapshot = () => this.state;\n\n private dispatch(event: QueryEvent) {\n const next = reduceQuery(this.state, event);\n if (next === this.state) return;\n this.state = next;\n for (const l of this.listeners) l();\n }\n\n /** Clear the identity flags: the query went away or was disabled. */\n reset() {\n this.dispatch({ type: 'reset' });\n }\n\n /**\n * Register `query` and mirror its rows, fetch status and authority until the\n * returned cleanup runs. Registration can fail (canonically the SSP\n * answering 503 NOT_READY while it bootstraps): that surfaces as `error`, and\n * the sync scheduler retries the registration underneath.\n */\n attach(sp00ky: Sp00ky, query: AnyFinalQuery): () => void {\n this.dispatch({ type: 'reset' });\n let disposed = false;\n const cleanups: (() => void)[] = [];\n // `sp00ky.subscribe` resolves its unsubscribe asynchronously; the status\n // and authority subscriptions return one directly. If teardown already\n // happened while the promise was in flight, unsubscribe at once.\n const addCleanup = (c: (() => void) | Promise<() => void>) => {\n if (typeof c === 'function') {\n if (disposed) c();\n else cleanups.push(c);\n return;\n }\n void c.then(\n (fn) => {\n if (disposed) fn();\n else cleanups.push(fn);\n },\n () => {}\n );\n };\n\n query.run().then(\n ({ hash }: { hash: string }) => {\n if (disposed) return;\n this.activeHash = hash;\n addCleanup(\n sp00ky.subscribeQueryStatus(\n hash,\n (status) => {\n if (!disposed) this.dispatch({ type: 'status', fetching: status === 'fetching' });\n },\n { immediate: true }\n )\n );\n addCleanup(\n sp00ky.subscribe(\n hash,\n (rows) => {\n if (disposed) return;\n const t0 = performance.now();\n this.dispatch({ type: 'rows', rows, isOne: query.isOne });\n sp00ky.reportFrontendTiming(hash, performance.now() - t0);\n },\n { immediate: true }\n )\n );\n // Subscribed after the rows, so the immediate deliveries keep the\n // core's order: authority flips only after the rows it covers.\n addCleanup(\n sp00ky.subscribeQueryAuthority(\n hash,\n (known) => {\n if (!disposed) this.dispatch({ type: 'authority', known });\n },\n { immediate: true }\n )\n );\n },\n (err: unknown) => {\n if (disposed) return;\n this.dispatch({\n type: 'error',\n error: err instanceof Error ? err : new Error(String(err)),\n });\n }\n );\n\n return () => {\n disposed = true;\n for (const c of cleanups) c();\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Hooks.\n// ---------------------------------------------------------------------------\n\ntype QueryArg<\n S extends SchemaStructure,\n TableName extends TableNames<S>,\n T extends { columns: Record<string, ColumnSchema> },\n RelatedFields extends Record<string, any>,\n IsOne extends boolean,\n> = FinalQuery<S, TableName, T, RelatedFields, IsOne, Sp00kyQueryResultPromise> | null | undefined;\n\nexport interface QueryOptions {\n /** Only register while true (default `true`). `false` keeps the last data. */\n enabled?: boolean;\n /**\n * Tear down the query (remote `_00_query` view + local WASM view) when this\n * hook unmounts and no other subscriber remains, instead of keeping it\n * resident for cheap re-subscription. Use for viewport-windowed lists that\n * mount and unmount a query per scroll window. Trade-off: scrolling back to\n * a torn-down window re-registers it.\n */\n deregisterOnCleanup?: boolean;\n}\n\nexport interface UseQueryResult<TData> {\n /**\n * The result. `[]` / `null` before the first emission, then each live\n * emission with structural sharing: unchanged rows keep their object\n * identity, so memoized rows only re-render when their own data changed.\n */\n data: TData;\n /** Registration or sync error (e.g. SSP 503 during bootstrap). Never thrown. */\n error: Error | undefined;\n /**\n * True only on a COLD first load: nothing painted for this identity, the\n * server has not answered, and registration has not failed. A paint from the\n * local cache ends it, and so does the server answering with zero rows.\n */\n isLoading: boolean;\n /** A fetch cycle is in flight (registration, a sync round). */\n isFetching: boolean;\n /**\n * `data` holds the rendered rows of a known membership for this identity:\n * the server's answer, or the membership an earlier session left on this\n * device. From here `data` is an answer, not a cache guess.\n */\n isAuthoritative: boolean;\n /** `data` holds something: rows for a list, a row for `.one()`. */\n hasData: boolean;\n /** Authoritative AND no data: the server said \"no rows\". Render empty states on this. */\n isEmpty: boolean;\n /**\n * Authoritative AND idle. The gate for trusting a short window as the end of\n * a list, and for \"create it if it is missing\". Not monotonic: a later sync\n * round re-enters `isFetching`.\n */\n isSettled: boolean;\n}\n\n/**\n * What `data` holds: a list is never null (`[]` until the first emission), a\n * `.one()` row is `null` until it exists.\n */\nexport type QueryData<\n S extends SchemaStructure,\n TableName extends TableNames<S>,\n RelatedFields extends Record<string, any>,\n IsOne extends boolean,\n> = IsOne extends true\n ? QueryResult<S, TableName, RelatedFields, true> | null\n : QueryResult<S, TableName, RelatedFields, false>;\n\nconst EMPTY_LIST: readonly never[] = Object.freeze([]);\n\n/**\n * Live query. Pass a built query (`db.query('post')...build()`), or `null` /\n * `undefined` to skip. The query is re-registered only when its identity hash\n * (surql + vars) changes, so building it inline on every render is fine.\n *\n * ```tsx\n * const posts = useQuery(db.query('post').orderBy('created_at', 'desc').limit(20).build());\n * ```\n */\nexport function useQuery<\n S extends SchemaStructure,\n TableName extends TableNames<S>,\n T extends { columns: Record<string, ColumnSchema> },\n RelatedFields extends Record<string, any>,\n IsOne extends boolean,\n TData = QueryData<S, TableName, RelatedFields, IsOne>,\n>(\n query: QueryArg<S, TableName, T, RelatedFields, IsOne>,\n options?: QueryOptions\n): UseQueryResult<TData>;\nexport function useQuery<\n S extends SchemaStructure,\n TableName extends TableNames<S>,\n T extends { columns: Record<string, ColumnSchema> },\n RelatedFields extends Record<string, any>,\n IsOne extends boolean,\n TData = QueryData<S, TableName, RelatedFields, IsOne>,\n>(\n db: SyncedDb<S>,\n query: QueryArg<S, TableName, T, RelatedFields, IsOne>,\n options?: QueryOptions\n): UseQueryResult<TData>;\nexport function useQuery(\n dbOrQuery: SyncedDb<any> | AnyFinalQuery | null | undefined,\n queryOrOptions?: AnyFinalQuery | QueryOptions | null,\n maybeOptions?: QueryOptions\n): UseQueryResult<unknown> {\n const explicit = dbOrQuery instanceof SyncedDb ? dbOrQuery : null;\n // Hooks run unconditionally; `useContext` is cheap and the explicit db wins.\n const contextDb = useOptionalDb();\n const db = explicit ?? contextDb;\n if (!db) {\n throw new Error(\n 'useQuery: no db argument and no <Sp00kyProvider> above. ' +\n 'Pass a SyncedDb or wrap your app in <Sp00kyProvider>.'\n );\n }\n const query = (explicit ? queryOrOptions : dbOrQuery) as AnyFinalQuery | null | undefined;\n const options = (explicit ? maybeOptions : queryOrOptions) as QueryOptions | undefined;\n\n const [store] = useState(() => new QueryStore());\n const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getSnapshot);\n\n const enabled = options?.enabled ?? true;\n const identity = enabled && query ? query.hash : null;\n\n useEffect(() => {\n if (identity === null || !query) {\n store.reset();\n return;\n }\n return store.attach(db.getSp00ky(), query);\n // `query` is read from the render whose identity changed: same hash, same query.\n }, [store, db, identity]);\n\n const deregister = options?.deregisterOnCleanup ?? false;\n useEffect(() => {\n if (!deregister) return;\n // Declared after the attach effect, so on unmount its cleanup runs second:\n // this hook's callback is already gone and deregisterQuery's refcount guard\n // sees the true remaining-subscriber count.\n return () => {\n if (store.activeHash) db.getSp00ky().deregisterQuery(store.activeHash);\n };\n }, [store, db, deregister]);\n\n const isOne = query?.isOne;\n let data = state.data;\n if (isOne === false && !Array.isArray(data)) data = EMPTY_LIST;\n else if (isOne === true && Array.isArray(data)) data = null;\n\n const hasData = Array.isArray(data) ? data.length > 0 : data !== null && data !== undefined;\n return {\n data,\n error: state.error,\n isLoading: !state.isAuthoritative && !state.hasPainted && state.error === undefined,\n isFetching: state.isFetching,\n isAuthoritative: state.isAuthoritative,\n hasData,\n isEmpty: state.isAuthoritative && !hasData,\n isSettled: state.isAuthoritative && !state.isFetching,\n };\n}\n\nexport type UsePreloadOptions = CorePreloadOptions & {\n /** Only preload while true (default `true`). */\n enabled?: boolean;\n};\n\n/**\n * Fire-and-forget prewarm: registers `query` via `db.preload` (a live query\n * nobody subscribes to, evicted a ttl after registration unless a view mounts\n * it first) whenever its identity changes. Nothing to clean up.\n *\n * Typical use: inside a list row, preload the detail query the user is likely\n * to open next, so navigation paints from cache instead of the network.\n */\nexport function usePreload(\n query: AnyFinalQuery | null | undefined,\n options?: UsePreloadOptions\n): void {\n const db = useDb();\n const enabled = options?.enabled ?? true;\n const identity = enabled && query ? query.hash : null;\n const signal = options?.signal;\n useEffect(() => {\n if (identity === null || !query) return;\n void db\n .getSp00ky()\n .preload(query, { signal })\n .catch(() => {});\n }, [db, identity]);\n}\n","import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from 'react';\nimport {\n semverGt,\n type AppReleaseOptions,\n type AppReleaseSnapshot,\n type ConnectionState,\n type FeatureFlagOptions,\n type ImpersonationInfo,\n type StorageHealth,\n type StorageHealthStatus,\n type SyncHealth,\n type SyncHealthStatus,\n} from '@spooky-sync/core';\nimport type { SchemaStructure } from '@spooky-sync/query-builder';\nimport { SyncedDb } from './db';\nimport { useDb, useLatest, useOptionalDb } from './provider';\n\n/** Shallow equality for the snapshot objects the engine re-creates on every callback. */\nfunction shallowEqual(a: unknown, b: unknown): boolean {\n if (Object.is(a, b)) return true;\n if (!a || !b || typeof a !== 'object' || typeof b !== 'object') return false;\n const ka = Object.keys(a);\n if (ka.length !== Object.keys(b).length) return false;\n return ka.every((k) => Object.is((a as any)[k], (b as any)[k]));\n}\n\n/**\n * React view over an engine subscribe-callback API. The engine's subscribe\n * methods fire immediately with the current value, and `read` seeds the\n * first render so nothing flashes before that lands. `deps` identify the\n * source: a change re-reads and re-subscribes.\n */\nexport function useEngineValue<T>(\n subscribe: (cb: (value: T) => void) => () => void,\n read: () => T,\n deps: readonly unknown[]\n): T {\n const source = useMemo(() => {\n let value = read();\n return {\n subscribe: (onChange: () => void) =>\n subscribe((next) => {\n if (shallowEqual(value, next)) return;\n value = next;\n onChange();\n }),\n getSnapshot: () => value,\n };\n // The caller's deps identify the source.\n }, deps);\n return useSyncExternalStore(source.subscribe, source.getSnapshot, source.getSnapshot);\n}\n\n/**\n * Count of locally committed mutations the server has not acknowledged yet.\n * Drive an \"unsaved changes\" indicator off this.\n */\nexport function usePendingMutations(): number {\n const db = useDb();\n return useEngineValue(\n (cb) => db.subscribeToPendingMutations(cb),\n () => db.pendingMutationCount,\n [db]\n );\n}\n\nexport interface UseSyncStatus {\n /** Full health snapshot. */\n health: SyncHealth;\n /** `'healthy'` | `'degraded'`. */\n status: SyncHealthStatus;\n isHealthy: boolean;\n /** `true` once sync has failed for a sustained run: drive a banner off this. */\n isDegraded: boolean;\n /** `true` once at least one sync round has succeeded this session. */\n everConnected: boolean;\n /**\n * `true` only for a real lost connection: degraded AFTER a first successful\n * sync. Stays `false` during the initial \"connecting\" phase.\n */\n isOffline: boolean;\n /**\n * Transport state of the remote WebSocket. Flips the instant the socket\n * drops, unlike `status`, which only degrades after a sustained run of failed\n * sync rounds: drive a \"reconnecting...\" affordance off this.\n */\n connection: ConnectionState;\n /** `true` while the connection is being re-established. */\n isReconnecting: boolean;\n}\n\n/**\n * Sync health for a \"can't reach the server\" banner. Single sync failures are\n * absorbed by the retry; `isDegraded` only turns on once failures persist for\n * `syncHealth.degradeAfterConsecutiveFailures` rounds (default 3).\n */\nexport function useSyncStatus(): UseSyncStatus {\n const db = useDb();\n const health = useEngineValue<SyncHealth>(\n (cb) => db.subscribeToSyncHealth(cb),\n () => db.syncHealth,\n [db]\n );\n return {\n health,\n status: health.status,\n isHealthy: health.status === 'healthy',\n isDegraded: health.status === 'degraded',\n everConnected: health.everConnected,\n isOffline: health.status === 'degraded' && health.everConnected,\n connection: health.connection,\n isReconnecting: health.connection === 'reconnecting',\n };\n}\n\nexport interface UseSyncActivityOptions {\n /** How long queries must be fetching before `isDownloading` turns on. Default 200 ms. */\n downloadDelayMs?: number;\n /** `isUploading` needs MORE than this many queued mutations. Default 0. */\n uploadThreshold?: number;\n /** How long the outbox must stay above `uploadThreshold`. Default 150 ms. */\n uploadDelayMs?: number;\n}\n\nexport interface UseSyncActivity {\n /** Queries with traffic the user waits on (core `fetchingQueryCount`). */\n fetchingQueries: number;\n /** Locally committed writes the server has not acknowledged yet. */\n pendingMutations: number;\n /** Fetching for longer than `downloadDelayMs`: a \"downloading\" mark. */\n isDownloading: boolean;\n /** More than `uploadThreshold` writes queued for longer than `uploadDelayMs`. */\n isUploading: boolean;\n}\n\n/** `busy` once it has held for `delayMs`; off the same render it clears. */\nfunction useDelayedOn(busy: boolean, delayMs: number): boolean {\n const [on, setOn] = useState(false);\n useEffect(() => {\n if (!busy) {\n setOn(false);\n return;\n }\n if (delayMs <= 0) {\n setOn(true);\n return;\n }\n const timer = setTimeout(() => setOn(true), delayMs);\n return () => clearTimeout(timer);\n }, [busy, delayMs]);\n return busy && on;\n}\n\n/**\n * The two directions of sync traffic, for an indicator in the app chrome. Both\n * flags are debounced ON by their delay and drop at once, so a local-first\n * page that answers from cache and confirms within a few ms never flickers.\n */\nexport function useSyncActivity<S extends SchemaStructure = any>(\n dbOrOptions?: SyncedDb<S> | UseSyncActivityOptions,\n maybeOptions?: UseSyncActivityOptions\n): UseSyncActivity {\n const explicitDb = dbOrOptions instanceof SyncedDb ? dbOrOptions : undefined;\n const options = (explicitDb ? maybeOptions : (dbOrOptions as UseSyncActivityOptions)) ?? {};\n const contextDb = useOptionalDb();\n const db = explicitDb ?? contextDb;\n if (!db)\n throw new Error(\n 'useSyncActivity must be used within a <Sp00kyProvider>, or pass the SyncedDb.'\n );\n\n const fetchingQueries = useEngineValue(\n (cb) => db.subscribeToFetchActivity(cb),\n () => db.fetchingQueryCount,\n [db]\n );\n const pendingMutations = useEngineValue(\n (cb) => db.subscribeToPendingMutations(cb),\n () => db.pendingMutationCount,\n [db]\n );\n const isDownloading = useDelayedOn(fetchingQueries > 0, options.downloadDelayMs ?? 200);\n const isUploading = useDelayedOn(\n pendingMutations > (options.uploadThreshold ?? 0),\n options.uploadDelayMs ?? 150\n );\n return { fetchingQueries, pendingMutations, isDownloading, isUploading };\n}\n\nexport interface UseStorageStatus {\n /** Full durability snapshot. */\n health: StorageHealth;\n /** `'unknown'` | `'persistent'` | `'memory'`. */\n status: StorageHealthStatus;\n /** `true` when the local store survives a reload. */\n isPersistent: boolean;\n /**\n * `true` only when durable storage was requested and could NOT be opened, so\n * local writes die on reload. Drive a warning off this, not off `status`.\n */\n isMemoryFallback: boolean;\n}\n\n/** How durable the LOCAL cache is, for a \"no local storage\" warning. */\nexport function useStorageStatus(): UseStorageStatus {\n const db = useDb();\n const health = useEngineValue<StorageHealth>(\n (cb) => db.subscribeToStorageHealth(cb),\n () => db.storageHealth,\n [db]\n );\n return {\n health,\n status: health.status,\n isPersistent: health.status === 'persistent',\n isMemoryFallback: health.fallback,\n };\n}\n\nexport interface UseImpersonationOptions {\n /**\n * This component renders the app's own impersonation banner. Required with\n * `impersonationBanner: { mode: 'custom' }`: it acknowledges the banner, so\n * the client does not fall back to its built-in one.\n */\n rendersBanner?: boolean;\n}\n\nexport interface UseImpersonation {\n /** The active impersonation, or `null`. */\n impersonation: ImpersonationInfo | null;\n isImpersonating: boolean;\n /** Return to the admin session. */\n stop: () => Promise<void>;\n}\n\n/** Observe admin impersonation (started from the DevTools). */\nexport function useImpersonation(options: UseImpersonationOptions = {}): UseImpersonation {\n const db = useDb();\n const impersonation = useEngineValue<ImpersonationInfo | null>(\n (cb) => db.auth.subscribeImpersonation(cb),\n () => db.auth.impersonation,\n [db]\n );\n // Re-acknowledged per session: a new impersonation restarts the client's\n // fallback timer, and this component is what cancels it.\n useEffect(() => {\n if (options.rendersBanner && impersonation) db.acknowledgeImpersonationBanner();\n }, [db, options.rendersBanner, impersonation]);\n const stop = useCallback(() => db.auth.stopImpersonating(), [db]);\n return { impersonation, isImpersonating: impersonation !== null, stop };\n}\n\nexport interface UseFeatureFlag {\n variant: string | undefined;\n payload: unknown | undefined;\n /** The resolved variant exists and is not `'off'`. */\n enabled: boolean;\n}\n\n/**\n * A feature flag for the signed-in user. Updates live when the assignment in\n * `_00_user_feature` changes (e.g. `spky flag enable <key>`).\n */\nexport function useFeatureFlag(key: string, options?: FeatureFlagOptions): UseFeatureFlag {\n const db = useDb();\n const fallback = options?.fallback;\n const ttl = options?.ttl;\n const state = useEngineValue<{ variant: string | undefined; payload: unknown }>(\n (cb) => {\n // A handle per subscription, closed with it: the module shares one live\n // query across all handles, so this is cheap.\n const handle = db.getSp00ky().feature(key, { fallback, ttl });\n const off = handle.subscribe((s) =>\n cb({ variant: s.variant ?? fallback, payload: s.payload })\n );\n return () => {\n off();\n handle.close();\n };\n },\n () => {\n // Seed the first render from the module's current answer.\n const peek = db.getSp00ky().feature(key, { fallback, ttl });\n const value = { variant: peek.variant(), payload: peek.payload() };\n peek.close();\n return value;\n },\n [db, key, fallback, ttl]\n );\n return {\n variant: state.variant,\n payload: state.payload,\n enabled: state.variant !== undefined && state.variant !== 'off',\n };\n}\n\nexport interface UseAppReleaseOptions extends AppReleaseOptions {\n /** App name from sp00ky.yml, e.g. `web`. */\n app: string;\n /** The running build's version (X.Y.Z), typically baked in at build time. */\n currentVersion: string;\n}\n\nexport interface UseAppRelease {\n /** Latest announced version for the app, or undefined when no row exists. */\n latestVersion: string | undefined;\n /** Announced version is semver-newer than the running build. */\n updateAvailable: boolean;\n /** The newer release asks clients to update/reload without prompting. */\n mandatory: boolean;\n /** The newer release asks reloads to clear service-worker caches first. */\n cacheBust: boolean;\n /**\n * Reload onto the announced release: `location.reload()`, or with cache-bust\n * clear CacheStorage, nudge the service worker to update, and navigate with a\n * `?cb=` token. The service worker is deliberately NOT unregistered.\n */\n reload: () => Promise<void>;\n}\n\nasync function reloadForSnapshot(snapshot: AppReleaseSnapshot): Promise<void> {\n if (typeof window === 'undefined') return;\n if (snapshot.cacheBust) {\n try {\n if (window.caches) {\n const keys = await window.caches.keys();\n await Promise.all(keys.map((k) => window.caches.delete(k)));\n }\n if (navigator.serviceWorker) {\n const regs = await navigator.serviceWorker.getRegistrations();\n for (const r of regs) r.update().catch(() => {});\n }\n window.location.href = window.location.pathname + '?cb=' + Date.now();\n return;\n } catch {\n /* fall through to a plain reload */\n }\n }\n window.location.reload();\n}\n\n/**\n * The app's announced release (`_00_app_release:<app>`, written by\n * `spky deploy` / `spky release`) compared against the running build.\n */\nexport function useAppRelease(options: UseAppReleaseOptions): UseAppRelease {\n const db = useDb();\n const { app, ttl, currentVersion } = options;\n const snapshot = useEngineValue<AppReleaseSnapshot>(\n (cb) => {\n const handle = db.getSp00ky().appRelease(app, { ttl });\n const off = handle.subscribe(cb);\n return () => {\n off();\n handle.close();\n };\n },\n () => {\n const peek = db.getSp00ky().appRelease(app, { ttl });\n const value = peek.snapshot();\n peek.close();\n return value;\n },\n [db, app, ttl]\n );\n const updateAvailable = semverGt(snapshot.version, currentVersion);\n const latest = useLatest(snapshot);\n const reload = useCallback(() => reloadForSnapshot(latest.current), [latest]);\n return {\n latestVersion: snapshot.version,\n updateAvailable,\n mandatory: updateAvailable && snapshot.mandatory,\n cacheBust: snapshot.cacheBust,\n reload,\n };\n}\n\nexport interface Submission<Args extends unknown[], R> {\n /** Run the wrapped async fn. Concurrent submits share the pending flag. Never rejects. */\n submit: (...args: Args) => Promise<R | undefined>;\n /** At least one submit is in flight. */\n pending: boolean;\n /** Error from the most recent settled submit, cleared on the next submit. */\n error: Error | undefined;\n /** Result of the most recent successful submit. */\n result: R | undefined;\n clearError: () => void;\n}\n\n/**\n * Pending/error state around a mutation, for a button spinner. The engine is\n * already optimistic local-first (a write commits locally and re-renders\n * through live queries before it syncs), so there is no optimistic layer here.\n * An error means the LOCAL commit failed; sync failures surface through\n * `useSyncStatus` and `usePendingMutations`.\n *\n * `submit` is stable across renders and always calls the latest `fn`.\n */\nexport function useSubmission<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>\n): Submission<Args, R> {\n const latest = useLatest(fn);\n const [inFlight, setInFlight] = useState(0);\n const [error, setError] = useState<Error | undefined>(undefined);\n const [result, setResult] = useState<R | undefined>(undefined);\n\n const submit = useCallback(\n async (...args: Args): Promise<R | undefined> => {\n setError(undefined);\n setInFlight((n) => n + 1);\n try {\n const r = await latest.current(...args);\n setResult(() => r);\n return r;\n } catch (e) {\n setError(e instanceof Error ? e : new Error(String(e)));\n return undefined;\n } finally {\n setInFlight((n) => n - 1);\n }\n },\n [latest]\n );\n const clearError = useCallback(() => setError(undefined), []);\n return { submit, pending: inFlight > 0, error, result, clearError };\n}\n","import { useCallback, useEffect, useMemo, useRef, useState } from 'react';\nimport type { ChannelPeer, ChannelTableNames, SchemaStructure } from '@spooky-sync/query-builder';\nimport type {\n ChannelQuery,\n ChannelState,\n ChannelStatus,\n CrdtField,\n Sp00kyChannel,\n} from '@spooky-sync/core';\nimport type { SyncedDb } from './db';\nimport { useDb, useLatest } from './provider';\n\n/**\n * Open a `@crdt` field of the record `recordId` names, for an editor to bind\n * to (`field?.getDoc()`). Re-opens when the id changes, closes on unmount.\n *\n * `null` until the field is loaded (`CrdtField.isLoaded`): this device had the\n * document, or the server answered. Until then show the column's text instead\n * of binding an editor to a document still arriving.\n */\nexport function useCrdtField(\n table: string,\n recordId: string | null | undefined,\n field: string\n): CrdtField | null {\n const db = useDb();\n const key = recordId ? `${table}\\u0000${recordId}\\u0000${field}` : null;\n // Tagged with the key it was opened for, so a render after the id changed\n // never hands out the previous record's document.\n const [opened, setOpened] = useState<{ key: string; field: CrdtField } | null>(null);\n\n useEffect(() => {\n if (!key || !recordId) return;\n const sp00ky = db.getSp00ky();\n let superseded = false;\n let isOpen = false;\n let offLoaded = () => {};\n sp00ky\n .openCrdtField(table, recordId, field)\n .then((cf) => {\n isOpen = true;\n if (superseded) {\n void sp00ky.closeCrdtField(table, recordId, field);\n return;\n }\n // Handed out once loaded: an empty document before the server answered\n // is \"not arrived yet\", not \"empty\".\n offLoaded = cf.onLoaded(() => {\n if (!superseded) setOpened({ key, field: cf });\n });\n })\n .catch((err) => {\n // A silent rejection leaves the editor stuck on its fallback with no\n // trail; surface the root cause (missing `@crdt` annotation, codegen\n // drift, a local query failure).\n // oxlint-disable-next-line no-console\n console.error(\n `[useCrdtField] Failed to open CRDT field ${table}.${field} on ${recordId}:`,\n err\n );\n });\n return () => {\n superseded = true;\n offLoaded();\n if (isOpen) void sp00ky.closeCrdtField(table, recordId, field);\n setOpened(null);\n };\n }, [db, key]);\n\n return opened && opened.key === key ? opened.field : null;\n}\n\n/** Who a channel connects to. */\nexport type ChannelPeers = Iterable<ChannelPeer>;\n\n/** What a channel carries: the rows a query (or several) matches. */\nexport type ChannelQueries<S extends SchemaStructure, T extends ChannelTableNames<S>> =\n | ChannelQuery<S, T>\n | ReadonlyArray<ChannelQuery<S, T>>;\n\n/** An open channel, for as long as the component is mounted. */\nexport interface UseChannel<S extends SchemaStructure, T extends string> {\n /** `idle` | `connecting` | `connected` | `failed` | `unsupported`. */\n status: ChannelStatus;\n /** Users with a tab connected. */\n peers: ReadonlyArray<string>;\n /** Writes that go to THIS channel's peers only (when the row matches its query), plus the database as always. */\n update: Sp00kyChannel<S, T>['update'];\n create: Sp00kyChannel<S, T>['create'];\n delete: Sp00kyChannel<S, T>['delete'];\n}\n\nconst IDLE: ChannelState = { status: 'idle', peers: [] };\n\n/** Identity of a channel's queries: their hashes (a builder is built first). */\nfunction queriesKey(q: ChannelQueries<any, any> | null | undefined): string | null {\n if (!q) return null;\n const list = (Array.isArray(q) ? q : [q]) as ReadonlyArray<any>;\n return list\n .map((item) =>\n String('build' in item && typeof item.build === 'function' ? item.build().hash : item.hash)\n )\n .join(',');\n}\n\nconst peersKey = (peers: ChannelPeers): string => [...peers].map((p) => String(p)).join('\\u0000');\n\n/**\n * Open a peer to peer channel to `peers` for the rows `query` matches, while\n * the component is mounted. The query must be on a `-- @channel` table and\n * only its `where` counts; it is checked against each row, never registered.\n * Writes to matching rows (`db.update` / `db.create` / `db.delete`, or the\n * channel's own) reach the peers over WebRTC in tens of ms; `-- @ephemeral`\n * fields travel only this way. A connection forms when both sides list each\n * other; your own id is skipped.\n *\n * ```tsx\n * const ch = useChannel(db.query('message').where({ conversation: convoId }), [me, other]);\n * ```\n *\n * `query` may be `null` (closes the channel until a query is passed again) or\n * a list of queries. Query and peers are compared by value, so building them\n * inline is fine.\n */\nexport function useChannel<S extends SchemaStructure, T extends ChannelTableNames<S>>(\n query: ChannelQueries<S, T> | null | undefined,\n peers: ChannelPeers\n): UseChannel<S, T> {\n const db = useDb();\n const [state, setState] = useState<ChannelState>(IDLE);\n const channel = useRef<Sp00kyChannel<any, any> | null>(null);\n\n const qKey = queriesKey(query as ChannelQueries<any, any> | null | undefined);\n const pKey = peersKey(peers);\n // The latest inputs, for the effects below, which key on their values.\n const latest = useLatest({ query, peers });\n\n const isOpen = qKey !== null;\n useEffect(() => {\n if (!isOpen) return;\n const { query: q, peers: p } = latest.current;\n const ch = (db as SyncedDb<any>).channel(q as any, p);\n channel.current = ch;\n const stop = ch.subscribe(setState);\n return () => {\n stop();\n ch.close();\n if (channel.current === ch) channel.current = null;\n setState(IDLE);\n };\n }, [db, isOpen]);\n\n // Re-scope and re-peer an open channel in place. Their first run repeats\n // what the channel was just opened with, which is harmless.\n useEffect(() => {\n const q = latest.current.query;\n if (q) channel.current?.setQueries(q as ChannelQueries<any, any>);\n }, [qKey]);\n useEffect(() => {\n channel.current?.setPeers(latest.current.peers);\n }, [pKey]);\n\n const open = useCallback(() => {\n if (!channel.current) throw new Error('This channel is closed (no query was passed).');\n return channel.current;\n }, []);\n const writes = useMemo(\n () => ({\n update: ((...args: Parameters<Sp00kyChannel<any, any>['update']>) =>\n open().update(...args)) as UseChannel<S, T>['update'],\n create: ((...args: Parameters<Sp00kyChannel<any, any>['create']>) =>\n open().create(...args)) as UseChannel<S, T>['create'],\n delete: ((...args: Parameters<Sp00kyChannel<any, any>['delete']>) =>\n open().delete(...args)) as UseChannel<S, T>['delete'],\n }),\n [open]\n );\n\n return { status: state.status, peers: state.peers, ...writes };\n}\n","import {\n useCallback,\n useEffect,\n useRef,\n useState,\n type CSSProperties,\n type ReactNode,\n} from 'react';\nimport type { BucketNames, SchemaStructure } from '@spooky-sync/query-builder';\nimport {\n decodeBlurhash,\n fileToUint8Array,\n type BlobUrlLease,\n type BucketPutOptions,\n type BucketPutResult,\n} from '@spooky-sync/core';\nimport { SyncedDb } from './db';\nimport { useIsomorphicLayoutEffect, useOptionalDb } from './provider';\n\nconst toError = (e: unknown) => (e instanceof Error ? e : new Error(String(e)));\n\n/** `(bucket, ...rest)` with the provider's db, or `(db, bucket, ...rest)`. */\nfunction useDbAndArgs<S extends SchemaStructure, Rest extends unknown[]>(\n hook: string,\n args: unknown[]\n): [SyncedDb<S>, BucketNames<S>, ...Rest] {\n const contextDb = useOptionalDb();\n if (args[0] instanceof SyncedDb) return args as [SyncedDb<S>, BucketNames<S>, ...Rest];\n if (!contextDb)\n throw new Error(`${hook} must be used within a <Sp00kyProvider>, or pass the SyncedDb.`);\n return [contextDb as SyncedDb<S>, ...(args as [BucketNames<S>, ...Rest])];\n}\n\n// ---------------------------------------------------------------------------\n// useFileUpload\n// ---------------------------------------------------------------------------\n\nexport interface FileUploadResult {\n isUploading: boolean;\n error: Error | null;\n clearError: () => void;\n upload: (\n path: string,\n file: File | Blob,\n options?: BucketPutOptions\n ) => Promise<BucketPutResult | void>;\n /** Object URL of the file, revoked when the component unmounts. */\n download: (path: string) => Promise<string | null>;\n remove: (path: string) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n}\n\n/**\n * Upload to, read from and delete in a bucket, with `isUploading` / `error`\n * state. Validates `maxSize` and `allowedExtensions` from the schema before\n * uploading. The returned functions are stable across renders.\n */\nexport function useFileUpload<S extends SchemaStructure>(\n bucketName: BucketNames<S>\n): FileUploadResult;\nexport function useFileUpload<S extends SchemaStructure>(\n db: SyncedDb<S>,\n bucketName: BucketNames<S>\n): FileUploadResult;\nexport function useFileUpload(...args: unknown[]): FileUploadResult {\n const [db, bucketName] = useDbAndArgs<any, []>('useFileUpload', args);\n const [uploads, setUploads] = useState(0);\n const [error, setError] = useState<Error | null>(null);\n\n const objectUrls = useRef<string[]>([]);\n useEffect(\n () => () => {\n for (const url of objectUrls.current) URL.revokeObjectURL(url);\n objectUrls.current = [];\n },\n []\n );\n\n const clearError = useCallback(() => setError(null), []);\n\n const upload = useCallback(\n async (path: string, file: File | Blob, options?: BucketPutOptions) => {\n setError(null);\n const config = db.getBucketConfig(bucketName as string);\n if (config?.maxSize !== null && config?.maxSize !== undefined && file.size > config.maxSize) {\n const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);\n setError(new Error(`File exceeds maximum size of ${maxMB} MB.`));\n return;\n }\n const allowed = config?.allowedExtensions;\n const fileName = (file as File).name;\n if (allowed && allowed.length > 0 && fileName) {\n const ext = fileName.split('.').pop()?.toLowerCase();\n if (!ext || !allowed.includes(ext)) {\n setError(new Error(`File type not allowed. Accepted: ${allowed.join(', ')}.`));\n return;\n }\n }\n setUploads((n) => n + 1);\n try {\n const bytes = await fileToUint8Array(file);\n return await db.bucket(bucketName).put(path, bytes, options);\n } catch (e) {\n setError(toError(e));\n } finally {\n setUploads((n) => n - 1);\n }\n },\n [db, bucketName]\n );\n\n const download = useCallback(\n async (path: string) => {\n setError(null);\n try {\n const content = await db.bucket(bucketName).get(path);\n if (!content) return null;\n const url = URL.createObjectURL(new Blob([content as BlobPart]));\n objectUrls.current.push(url);\n return url;\n } catch (e) {\n setError(toError(e));\n return null;\n }\n },\n [db, bucketName]\n );\n\n const remove = useCallback(\n async (path: string) => {\n setError(null);\n try {\n await db.bucket(bucketName).delete(path);\n } catch (e) {\n setError(toError(e));\n }\n },\n [db, bucketName]\n );\n\n const exists = useCallback(\n async (path: string) => {\n setError(null);\n try {\n return await db.bucket(bucketName).exists(path);\n } catch (e) {\n setError(toError(e));\n return false;\n }\n },\n [db, bucketName]\n );\n\n return { isUploading: uploads > 0, error, clearError, upload, download, remove, exists };\n}\n\n// ---------------------------------------------------------------------------\n// useDownloadFile\n// ---------------------------------------------------------------------------\n\nexport interface UseDownloadFileOptions {\n /**\n * Master switch, default `true`. `false` gives every hook instance its own\n * private object URL fetched fresh from the bucket and revoked on unmount.\n */\n cache?: boolean;\n /** Keep the bytes in OPFS so they survive a reload and work offline. Default `true`. */\n persist?: boolean;\n /** Exempt this file from pressure eviction. */\n pin?: boolean;\n /**\n * `'never'` (default) treats a bucket path as immutable. `'head'` spends a\n * remote `head()` to compare sizes first, for paths the app overwrites.\n */\n revalidate?: 'never' | 'head';\n}\n\nexport interface UseDownloadFileResult {\n url: string | null;\n isLoading: boolean;\n error: Error | null;\n /** Bypass every cache layer once and fetch again. */\n refetch: () => void;\n}\n\ninterface DownloadState {\n /** The request this state belongs to; a stale one reads as idle. */\n request: string | null;\n url: string | null;\n isLoading: boolean;\n error: Error | null;\n}\n\n/**\n * Object URL for a bucket file, shared and refcounted across every component\n * showing the same path, persisted to OPFS by default. `null` path is idle.\n */\nexport function useDownloadFile<S extends SchemaStructure>(\n bucketName: BucketNames<S>,\n path: string | null | undefined,\n options?: UseDownloadFileOptions\n): UseDownloadFileResult;\nexport function useDownloadFile<S extends SchemaStructure>(\n db: SyncedDb<S>,\n bucketName: BucketNames<S>,\n path: string | null | undefined,\n options?: UseDownloadFileOptions\n): UseDownloadFileResult;\nexport function useDownloadFile(...args: unknown[]): UseDownloadFileResult {\n const [db, bucketName, path, options = {}] = useDbAndArgs<\n any,\n [string | null | undefined, UseDownloadFileOptions?]\n >('useDownloadFile', args);\n const useCache = options.cache !== false;\n const persist = options.persist !== false;\n const { pin, revalidate } = options;\n\n const [tick, setTick] = useState(0);\n const reloadOnce = useRef(false);\n const request = path ? `${String(bucketName)}\\u0000${path}\\u0000${tick}` : null;\n const [state, setState] = useState<DownloadState>({\n request: null,\n url: null,\n isLoading: false,\n error: null,\n });\n\n useEffect(() => {\n if (!path || !request) return;\n const reload = reloadOnce.current;\n reloadOnce.current = false;\n let cancelled = false;\n // Exactly one of these is held: a refcounted lease on the shared cache\n // entry, or a private URL this effect minted and must revoke itself.\n let lease: BlobUrlLease | null = null;\n let privateUrl: string | null = null;\n setState((s) => ({ request, url: s.url, isLoading: true, error: null }));\n\n const bucket = db.bucket(bucketName);\n const resolve: Promise<string | null> = useCache\n ? bucket.url(path, { persist, pin, revalidate, reload }).then((acquired) => {\n if (!acquired) return null;\n if (cancelled) {\n // Unmounted or the path changed mid-flight: hand the reference\n // straight back, or its object URL leaks for the life of the tab.\n acquired.release();\n return null;\n }\n lease = acquired;\n return acquired.url;\n })\n : bucket.read(path, { persist: false, reload: true }).then((blob) => {\n if (!blob || cancelled) return null;\n privateUrl = URL.createObjectURL(blob);\n return privateUrl;\n });\n\n resolve.then(\n (url) => {\n if (!cancelled) setState({ request, url, isLoading: false, error: null });\n },\n (err) => {\n if (!cancelled) setState({ request, url: null, isLoading: false, error: toError(err) });\n }\n );\n\n return () => {\n cancelled = true;\n lease?.release();\n if (privateUrl) URL.revokeObjectURL(privateUrl);\n };\n }, [db, request, useCache, persist, pin, revalidate]);\n\n const refetch = useCallback(() => {\n reloadOnce.current = true;\n setTick((n) => n + 1);\n }, []);\n\n // A path that went away (or a request not started yet) reads as idle, so a\n // render never shows the previous path's URL under a null path.\n if (!request) return { url: null, isLoading: false, error: null, refetch };\n if (state.request !== request) return { url: state.url, isLoading: true, error: null, refetch };\n return { url: state.url, isLoading: state.isLoading, error: state.error, refetch };\n}\n\n// ---------------------------------------------------------------------------\n// useBlurhash / useBucketImage\n// ---------------------------------------------------------------------------\n\nexport interface UseBlurhashResult {\n /** The stored blurhash for the path, or null while loading / when none exists. */\n hash: string | null;\n isLoading: boolean;\n}\n\n/**\n * The blurhash sidecar for a bucket image (written automatically by\n * `bucket.put`, see `Sp00kyConfig.blurhash`). Resolves from OPFS instantly on\n * warm clients. `useBucketImage` / `BucketImage` bundle it with the download.\n */\nexport function useBlurhash<S extends SchemaStructure>(\n bucketName: BucketNames<S>,\n path: string | null | undefined\n): UseBlurhashResult;\nexport function useBlurhash<S extends SchemaStructure>(\n db: SyncedDb<S>,\n bucketName: BucketNames<S>,\n path: string | null | undefined\n): UseBlurhashResult;\nexport function useBlurhash(...args: unknown[]): UseBlurhashResult {\n const [db, bucketName, path] = useDbAndArgs<any, [string | null | undefined]>(\n 'useBlurhash',\n args\n );\n const request = path ? `${String(bucketName)}\\u0000${path}` : null;\n const [state, setState] = useState<{ request: string | null; hash: string | null }>({\n request: null,\n hash: null,\n });\n\n useEffect(() => {\n if (!path || !request) return;\n let cancelled = false;\n db.bucket(bucketName)\n .blurhash(path)\n .then(\n (hash) => {\n if (!cancelled) setState({ request, hash });\n },\n () => {\n if (!cancelled) setState({ request, hash: null });\n }\n );\n return () => {\n cancelled = true;\n };\n }, [db, request]);\n\n if (!request) return { hash: null, isLoading: false };\n if (state.request !== request) return { hash: null, isLoading: true };\n return { hash: state.hash, isLoading: false };\n}\n\nexport interface UseBucketImageOptions extends UseDownloadFileOptions {\n /** Also resolve the image's blurhash sidecar. Default `true`. */\n blurhash?: boolean;\n}\n\nexport interface UseBucketImageResult extends UseDownloadFileResult {\n /** Blurhash for the same path, or null (off, missing, still loading). */\n blurhash: string | null;\n /** True once the current `url` has been decoded and is safe to paint. */\n ready: boolean;\n /**\n * Ref callback for the `<img>` rendering `url`: flips `ready` once the\n * bitmap is decoded (on failure too, so a broken blob degrades to\n * paint-on-load instead of hiding the image forever). Its identity follows\n * `url`, so React re-runs it when the url changes.\n */\n gate: (img: HTMLImageElement | null) => void;\n}\n\n/**\n * Everything to render a bucket image without a pop-in: the refcounted object\n * URL, the blurhash placeholder, and a decode gate. `BucketImage` wraps this\n * into a drop-in component; use the hook for custom markup.\n */\nexport function useBucketImage<S extends SchemaStructure>(\n bucketName: BucketNames<S>,\n path: string | null | undefined,\n options?: UseBucketImageOptions\n): UseBucketImageResult;\nexport function useBucketImage<S extends SchemaStructure>(\n db: SyncedDb<S>,\n bucketName: BucketNames<S>,\n path: string | null | undefined,\n options?: UseBucketImageOptions\n): UseBucketImageResult;\nexport function useBucketImage(...args: unknown[]): UseBucketImageResult {\n const [db, bucketName, path, options = {}] = useDbAndArgs<\n any,\n [string | null | undefined, UseBucketImageOptions?]\n >('useBucketImage', args);\n // Called BEFORE the download so the sidecar read enters the serialized\n // remote queue first: the placeholder should never wait behind its bytes.\n const { hash } = useBlurhash(db, bucketName, options.blurhash !== false ? path : null);\n const file = useDownloadFile(db, bucketName, path, options);\n\n // The url whose bitmap is decoded. A new url is undecoded until its own\n // gate fires, so `ready` re-arms without an effect.\n const [decodedUrl, setDecodedUrl] = useState<string | null>(null);\n const url = file.url;\n const gate = useCallback(\n (img: HTMLImageElement | null) => {\n if (!img || !url) return;\n const done = () => setDecodedUrl(url);\n if (typeof img.decode === 'function') {\n img.decode().then(done, done);\n } else if (img.complete) {\n done();\n } else {\n img.onload = done;\n img.onerror = done;\n }\n },\n [url]\n );\n\n return { ...file, blurhash: hash, ready: url !== null && decodedUrl === url, gate };\n}\n\n// ---------------------------------------------------------------------------\n// Components\n// ---------------------------------------------------------------------------\n\nexport interface BlurhashProps {\n /** The blurhash string. Nullish paints nothing (transparent canvas). */\n hash: string | null | undefined;\n /** Decode resolution. 32x32 is plenty; size the canvas with CSS. */\n width?: number;\n height?: number;\n /** Contrast punch, see the blurhash reference decoder. Defaults to 1. */\n punch?: number;\n className?: string;\n style?: CSSProperties;\n}\n\n/** A blurhash painted onto a canvas, once per hash change. */\nexport function Blurhash({\n hash,\n width = 32,\n height = 32,\n punch = 1,\n className,\n style,\n}: BlurhashProps) {\n const canvas = useRef<HTMLCanvasElement>(null);\n useEffect(() => {\n const el = canvas.current;\n if (!el) return;\n el.width = width;\n el.height = height;\n if (!hash) return;\n try {\n const pixels = decodeBlurhash(hash, width, height, punch);\n const ctx = el.getContext('2d');\n if (!ctx) return;\n const imageData = ctx.createImageData(width, height);\n imageData.data.set(pixels);\n ctx.putImageData(imageData, 0, 0);\n } catch {\n // An invalid hash paints nothing; the layer below stays visible.\n }\n }, [hash, width, height, punch]);\n return <canvas ref={canvas} className={className} style={style} />;\n}\n\nexport interface BucketImageProps {\n /** Bucket name from the schema. */\n bucket: string;\n /** Path within the bucket. Nullish renders only the fallback layers. */\n path: string | null | undefined;\n alt?: string;\n /** Class for the container (sizing/positioning). */\n className?: string;\n style?: CSSProperties;\n /** Class for the inner `<img>` (the layout styles are inline). */\n imgClassName?: string;\n /** `object-fit` for the image. Defaults to `cover`. */\n fit?: CSSProperties['objectFit'];\n /** Bottom placeholder layer, shown until the image settles. */\n fallback?: ReactNode;\n /** Crossfade duration in ms. Defaults to 300. */\n transition?: number;\n /** Crossfade easing. Defaults to an ease-out-expo curve. */\n easing?: string;\n /** Resolve the blurhash sidecar. Defaults to true. */\n blurhash?: boolean;\n /** Download tuning, forwarded to `useDownloadFile`. */\n options?: UseBucketImageOptions;\n}\n\nconst LAYER: CSSProperties = { position: 'absolute', inset: 0, width: '100%', height: '100%' };\n\nfunction prefersReducedMotion(): boolean {\n return typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;\n}\n\n/**\n * A bucket image that never pops in. Layers, bottom to top: your `fallback`,\n * the stored blurhash, and the real image, which stays transparent until its\n * bitmap is DECODED and then crossfades in. The placeholder layers unmount\n * once the fade settles. Respects prefers-reduced-motion. The container is\n * made `position: relative` unless your class positions it already.\n */\nexport function BucketImage(props: BucketImageProps) {\n const image = useBucketImage(props.bucket as BucketNames<SchemaStructure>, props.path, {\n ...props.options,\n blurhash: props.blurhash !== false,\n });\n const [reducedMotion] = useState(prefersReducedMotion);\n const transition = props.transition ?? 300;\n\n const root = useRef<HTMLDivElement>(null);\n // Layers are absolutely positioned; give them an anchor without stomping on\n // a class that already positions the container.\n useIsomorphicLayoutEffect(() => {\n const el = root.current;\n if (el && getComputedStyle(el).position === 'static') el.style.position = 'relative';\n }, []);\n\n // Placeholders leave the DOM once the fade is over (a shelf of covers should\n // not composite three layers each forever) and come back with a new url.\n const [settledUrl, setSettledUrl] = useState<string | null>(null);\n useEffect(() => {\n if (!image.ready || !image.url) return;\n const url = image.url;\n const timer = setTimeout(() => setSettledUrl(url), (reducedMotion ? 0 : transition) + 120);\n return () => clearTimeout(timer);\n }, [image.ready, image.url, reducedMotion, transition]);\n const settled = image.ready && settledUrl === image.url;\n\n return (\n <div ref={root} className={props.className} style={props.style}>\n {!settled && (\n <div style={LAYER}>\n <div style={LAYER}>{props.fallback}</div>\n <Blurhash hash={image.blurhash} style={LAYER} />\n </div>\n )}\n <img\n ref={image.gate}\n src={image.url ?? undefined}\n alt={props.alt ?? ''}\n decoding=\"async\"\n className={props.imgClassName}\n style={{\n ...LAYER,\n objectFit: props.fit ?? 'cover',\n opacity: image.ready ? 1 : 0,\n transition: reducedMotion\n ? 'none'\n : `opacity ${transition}ms ${props.easing ?? 'cubic-bezier(0.16, 1, 0.3, 1)'}`,\n }}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2CA,IAAa,WAAb,MAAiD;CAK/C,YAAY,QAA2B;OAH/B,SAAiC;OACjC,eAAe;AAGrB,OAAK,SAAS;;CAGhB,AAAO,YAA6B;AAClC,MAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,MAAM,2BAA2B;AAC7D,SAAO,KAAK;;;CAId,MAAM,OAAsB;AAC1B,MAAI,KAAK,aAAc;AACvB,OAAK,SAAS,IAAIA,+BAAgB,KAAK,OAAO;AAC9C,QAAM,KAAK,OAAO,MAAM;AACxB,OAAK,eAAe;;;;;;CAOtB,MAAM,QAAuB;EAC3B,MAAM,WAAW,KAAK;AACtB,OAAK,SAAS;AACd,OAAK,eAAe;AACpB,MAAI,SAAU,OAAM,SAAS,OAAO;;;CAItC,MAAM,OAAO,IAAY,SAAiD;AACxE,MAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,MAAM,2BAA2B;AAC7D,QAAM,KAAK,OAAO,OAAO,IAAI,QAAQ;;;CAIvC,MAAM,OACJ,WACA,UACA,SACA,SACe;AACf,MAAI,CAAC,KAAK,OAAQ,OAAM,IAAI,MAAM,2BAA2B;AAC7D,QAAM,KAAK,OAAO,OAChB,WACA,UACA,SACA,QACD;;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