@spooky-sync/client-angular 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 +120 -0
- package/QUICK_START.md +199 -0
- package/README.md +78 -2
- package/fesm2022/spooky-sync-client-angular.mjs +1507 -0
- package/fesm2022/spooky-sync-client-angular.mjs.map +1 -0
- package/package.json +48 -3
- package/skills/sp00ky-angular/SKILL.md +97 -0
- package/types/spooky-sync-client-angular.d.ts +758 -0
- package/types/spooky-sync-client-angular.d.ts.map +1 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spooky-sync-client-angular.mjs","sources":["../../src/db.ts","../../src/internal.ts","../../src/provide.ts","../../src/query.ts","../../src/status.ts","../../src/realtime.ts","../../src/files.ts","../../src/blurhash.ts","../../src/image-gate.ts","../../src/bucket-image.ts","../../src/spooky-sync-client-angular.ts"],"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 Angular.\n * Delegates all logic to the underlying `Sp00kyClient` instance.\n *\n * It is also the DI token: `provideSp00ky(config)` provides one instance per\n * application, and `inject(SyncedDb)` / `injectDb()` return it.\n *\n * NOTE: keep in sync with packages/client-react/src/db.ts,\n * packages/client-svelte/src/db.ts and packages/client-solid2/src/index.ts\n * (SyncedDb). Copied rather than shared so each binding's dependency graph\n * stays its own. Angular rows are plain objects (signals never proxy), so\n * unlike the Svelte and Solid 2 copies nothing is unwrapped 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 `injectQuery` 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 `injectQuery`. */\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 * `injectChannel` function, 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 * `injectImpersonation({ rendersBanner: true })` 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 injectSyncActivity}. */\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 `injectSyncActivity` 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 injectSyncStatus}. */\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 `injectSyncStatus` 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 injectStorageStatus}. */\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 `injectStorageStatus`.\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 assertInInjectionContext,\n inject,\n Injector,\n PLATFORM_ID,\n runInInjectionContext,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport { SyncedDb } from './db';\nimport type { MaybeSignal } from './types';\n\n/** Read a `MaybeSignal`, tracking whatever the signal or function reads. */\nexport function read<T>(value: MaybeSignal<T>): T {\n return typeof value === 'function' ? (value as () => T)() : value;\n}\n\nexport function toError(e: unknown): Error {\n return e instanceof Error ? e : new Error(String(e));\n}\n\n/**\n * Run `fn` in the caller's injection context, or in `injector` when one is\n * given. `caller` names the public function in Angular's NG0203 error.\n */\nexport function inContext<T>(caller: Function, injector: Injector | undefined, fn: () => T): T {\n if (injector) return runInInjectionContext(injector, fn);\n assertInInjectionContext(caller);\n return fn();\n}\n\n/** The provided client, or a readable error. Must run in an injection context. */\nexport function providedDb(caller: string): SyncedDb<any> {\n const db = inject(SyncedDb, { optional: true });\n if (!db) {\n throw new Error(\n `${caller}: no SyncedDb is provided. Add provideSp00ky(config) to the application ` +\n 'providers (app.config.ts), or provide a SyncedDb yourself ({ provide: SyncedDb, useValue: db }).'\n );\n }\n return db;\n}\n\n/**\n * The client, for a function that talks to the engine. The engine is\n * browser-only (WebAssembly, IndexedDB / OPFS, workers), and `provideSp00ky`\n * does not start it during a server render, so these functions refuse to run\n * there instead of failing deep inside the engine.\n */\nexport function engineDb(caller: string): SyncedDb<any> {\n const db = providedDb(caller);\n if (!isPlatformBrowser(inject(PLATFORM_ID))) {\n throw new Error(\n `${caller} runs in the browser only: the sp00ky client does not start during a server render. ` +\n 'Render this component on the client: wrap it in a @defer block, or give its route ' +\n 'renderMode: RenderMode.Client.'\n );\n }\n return db;\n}\n","import {\n DestroyRef,\n type EnvironmentProviders,\n inject,\n makeEnvironmentProviders,\n PLATFORM_ID,\n provideAppInitializer,\n} from '@angular/core';\nimport { isPlatformBrowser } from '@angular/common';\nimport type { SchemaStructure } from '@spooky-sync/query-builder';\nimport { SyncedDb } from './db';\nimport { inContext, providedDb } from './internal';\nimport type { InjectOptions, Sp00kyOptions, SyncedDbConfig } from './types';\n\n/**\n * Provide the sp00ky client to the application:\n *\n * ```ts\n * // app.config.ts\n * export const appConfig: ApplicationConfig = {\n * providers: [provideSp00ky(dbConfig)],\n * };\n * ```\n *\n * The client starts in an app initializer, so the app renders once it is\n * ready and every `inject*` function can use it straight away. Whatever is in\n * the root element of `index.html` stays on screen until then. If `init()`\n * fails, bootstrap fails: handle it on `bootstrapApplication(...).catch(...)`.\n *\n * `config` may also be a factory, run in the injection context, to build the\n * config from other providers. During a server render the client is created\n * but never started (see `injectQuery`).\n *\n * The client is closed when the application is destroyed.\n */\nexport function provideSp00ky<S extends SchemaStructure>(\n config: SyncedDbConfig<S> | (() => SyncedDbConfig<S>),\n options: Sp00kyOptions<S> = {}\n): EnvironmentProviders {\n return makeEnvironmentProviders([\n {\n provide: SyncedDb,\n useFactory: () => {\n const db = new SyncedDb<S>(typeof config === 'function' ? config() : config);\n inject(DestroyRef).onDestroy(() => void db.close());\n return db;\n },\n },\n provideAppInitializer(() => {\n if (!isPlatformBrowser(inject(PLATFORM_ID))) return;\n return start(inject(SyncedDb) as SyncedDb<S>, options.preload);\n }),\n ]);\n}\n\nasync function start<S extends SchemaStructure>(\n db: SyncedDb<S>,\n preload: Sp00kyOptions<S>['preload']\n): Promise<void> {\n await db.init();\n if (!preload) return;\n try {\n await preload(db);\n } catch (e) {\n // oxlint-disable-next-line no-console\n console.error('provideSp00ky: preload failed; starting the app anyway', e);\n }\n}\n\n/**\n * The application's `SyncedDb`, typed with your schema:\n * `private readonly db = injectDb<typeof schema>();`. Same instance as\n * `inject(SyncedDb)`.\n */\nexport function injectDb<S extends SchemaStructure>(options?: InjectOptions): SyncedDb<S> {\n return inContext(injectDb, options?.injector, () => providedDb('injectDb') as SyncedDb<S>);\n}\n","import {\n computed,\n DestroyRef,\n effect,\n inject,\n Injector,\n type Signal,\n signal,\n untracked,\n} from '@angular/core';\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 { engineDb, inContext, read, toError } from './internal';\nimport type { InjectOptions, MaybeSignal } from './types';\n\n// ---------------------------------------------------------------------------\n// Pure part: structural sharing between emissions.\n// NOTE: keep in sync with packages/client-react/src/query.ts and\n// packages/client-svelte/src/query.svelte.ts (`share`, `sameValue`).\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.\n *\n * That is what makes one signal per query fine-grained enough: a deep-equal\n * emission is the same value, so the signal (compared with `Object.is`) does\n * not notify at all, and an `@for (...; track row.id)` hands an unchanged row\n * the same object, so its `computed`s and `OnPush` children stay put.\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// ---------------------------------------------------------------------------\n// injectQuery\n// ---------------------------------------------------------------------------\n\ntype AnyFinalQuery = FinalQuery<any, any, any, any, any, Sp00kyQueryResultPromise>;\n\ntype BuiltQuery<\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>;\n\nexport interface QueryOptions extends InjectOptions {\n /** Only register while true (default `true`). `false` keeps the last data. */\n enabled?: MaybeSignal<boolean>;\n /**\n * Tear down the query (remote `_00_query` view + local WASM view) when the\n * injection context is destroyed and no other subscriber remains, instead of\n * keeping it resident for cheap re-subscription. Use for viewport-windowed\n * lists that mount and unmount a query per scroll window. Trade-off:\n * scrolling back to a torn-down window re-registers it.\n */\n deregisterOnCleanup?: boolean;\n}\n\n/** A live query. Every field is a read-only signal: `posts.data()`, `posts.isLoading()`. */\nexport interface QueryState<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, and a deep-equal emission does not notify.\n */\n readonly data: Signal<TData>;\n /** Registration or sync error (e.g. SSP 503 during bootstrap). Never thrown. */\n readonly error: Signal<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 readonly isLoading: Signal<boolean>;\n /** A fetch cycle is in flight (registration, a sync round). */\n readonly isFetching: Signal<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 readonly isAuthoritative: Signal<boolean>;\n /** `data` holds something: rows for a list, a row for `.one()`. */\n readonly hasData: Signal<boolean>;\n /** Authoritative AND no data: the server said \"no rows\". Render empty states on this. */\n readonly isEmpty: Signal<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 readonly isSettled: Signal<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 function that builds the query, so it follows the signals\n * it reads (`() => this.db.query('post').where({ author: this.userId() }).build()`);\n * return `null` / `undefined` to skip. The query is re-registered only when\n * its identity hash (surql + vars) changes, not on every rebuild.\n *\n * Call it in an injection context (a field initializer or constructor), or pass\n * `{ injector }`. The registration ends with that context.\n *\n * ```ts\n * @Component({\n * template: `@for (post of posts.data(); track post.id) { <p>{{ post.title }}</p> }`,\n * })\n * export class PostList {\n * private readonly db = injectDb<typeof schema>();\n * readonly posts = injectQuery(() =>\n * this.db.query('post').orderBy('created_at', 'desc').limit(20).build()\n * );\n * }\n * ```\n */\nexport function injectQuery<\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: MaybeSignal<BuiltQuery<S, TableName, T, RelatedFields, IsOne> | null | undefined>,\n options?: QueryOptions\n): QueryState<TData>;\nexport function injectQuery(\n query: MaybeSignal<AnyFinalQuery | null | undefined>,\n options?: QueryOptions\n): QueryState<unknown> {\n return inContext(injectQuery, options?.injector, () => {\n const sp00ky = engineDb('injectQuery').getSp00ky();\n const injector = inject(Injector);\n\n // Rows stay plain objects: they reach `db.update(...)`, workers and\n // third-party code as the engine produced them.\n const data = signal<unknown>(null);\n const error = signal<Error | undefined>(undefined);\n // Server membership known and painted for the current identity (core authority).\n const isAuthoritative = signal(false);\n // An emission WITH data was applied for the current identity. With\n // `isAuthoritative` this ends the cold load: a cached paint ends it without\n // the server, a server answer ends it without rows.\n const hasPainted = signal(false);\n const isFetching = signal(false);\n // Registered hash of the attached query, for opt-in deregistration.\n let activeHash: string | undefined;\n\n // The built query (a new object whenever what the function reads changes)…\n const resolved = computed(() =>\n read(options?.enabled ?? true) ? (read(query) ?? null) : null\n );\n // …and its identity. A string, so the attach effect below only re-runs\n // when the query really changed, not on every rebuild of the same one.\n const identity = computed(() => {\n const q = resolved();\n return q ? String(q.hash) : null;\n });\n const isOne = computed(() => resolved()?.isOne);\n\n const attach = effect(\n (onCleanup) => {\n const id = identity();\n // A new identity starts clean: authority, the paint latch and a\n // previous identity's error reset. `data` stays until the new identity\n // emits, so growing a `.limit()` does not flash an empty list.\n isAuthoritative.set(false);\n hasPainted.set(false);\n isFetching.set(false);\n error.set(undefined);\n if (id === null) return;\n const q = untracked(resolved);\n if (!q) return;\n\n let disposed = false;\n const cleanups: (() => void)[] = [];\n onCleanup(() => {\n disposed = true;\n for (const c of cleanups) c();\n });\n // `sp00ky.subscribe` resolves its unsubscribe asynchronously; the\n // status and authority subscriptions return one directly. If teardown\n // already 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 // Registration can fail, canonically the SSP answering 503 NOT_READY\n // while it bootstraps. That surfaces as `error`; the sync scheduler\n // retries the registration underneath, so a transient failure still\n // recovers.\n q.run().then(\n ({ hash }: { hash: string }) => {\n if (disposed) return;\n activeHash = hash;\n addCleanup(\n sp00ky.subscribeQueryStatus(\n hash,\n (status) => {\n if (!disposed) isFetching.set(status === 'fetching');\n },\n { immediate: true }\n )\n );\n addCleanup(\n sp00ky.subscribe(\n hash,\n (rows: Record<string, unknown>[]) => {\n if (disposed) return;\n const t0 = performance.now();\n // Every emission is applied as is: the core only emits what\n // it decided the query holds. One WITH data ends the cold load.\n const next = q.isOne ? (rows[0] ?? null) : rows;\n data.set(share(untracked(data), next));\n if (q.isOne ? next !== null && next !== undefined : rows.length > 0) {\n hasPainted.set(true);\n }\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. This\n // is the channel that ends a cold load whose honest answer is zero\n // rows. A flip back to false is a bucket switch (another\n // principal): what is painted is the previous one's, so the paint\n // latch goes with it.\n addCleanup(\n sp00ky.subscribeQueryAuthority(\n hash,\n (known) => {\n if (disposed) return;\n isAuthoritative.set(known);\n if (!known) hasPainted.set(false);\n },\n { immediate: true }\n )\n );\n },\n (err: unknown) => {\n if (!disposed) error.set(toError(err));\n }\n );\n },\n { injector, debugName: 'injectQuery' }\n );\n\n if (options?.deregisterOnCleanup) {\n // Tear the subscriptions down first, so deregisterQuery's refcount guard\n // sees the true remaining-subscriber count.\n inject(DestroyRef).onDestroy(() => {\n attach.destroy();\n if (activeHash) sp00ky.deregisterQuery(activeHash);\n });\n }\n\n const current = computed(() => {\n const v = data();\n const one = isOne();\n if (one === false && !Array.isArray(v)) return EMPTY_LIST;\n if (one === true && Array.isArray(v)) return null;\n return v;\n });\n const hasData = computed(() => {\n const v = current();\n return Array.isArray(v) ? v.length > 0 : v !== null && v !== undefined;\n });\n\n return {\n data: current,\n error: error.asReadonly(),\n isLoading: computed(() => !isAuthoritative() && !hasPainted() && error() === undefined),\n isFetching: isFetching.asReadonly(),\n isAuthoritative: isAuthoritative.asReadonly(),\n hasData,\n isEmpty: computed(() => isAuthoritative() && !hasData()),\n isSettled: computed(() => isAuthoritative() && !isFetching()),\n };\n });\n}\n\nexport interface PreloadOptions extends CorePreloadOptions, InjectOptions {\n /** Only preload while true (default `true`). */\n enabled?: MaybeSignal<boolean>;\n}\n\n/**\n * Fire-and-forget prewarm: registers the 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: in a list row, preload the detail query the user is likely to\n * open next, so navigation paints from cache instead of the network.\n */\nexport function injectPreload(\n query: MaybeSignal<AnyFinalQuery | null | undefined>,\n options?: PreloadOptions\n): void {\n inContext(injectPreload, options?.injector, () => {\n const sp00ky = engineDb('injectPreload').getSp00ky();\n const resolved = computed(() =>\n read(options?.enabled ?? true) ? (read(query) ?? null) : null\n );\n const identity = computed(() => {\n const q = resolved();\n return q ? String(q.hash) : null;\n });\n effect(\n () => {\n if (identity() === null) return;\n const q = untracked(resolved);\n if (!q) return;\n void sp00ky.preload(q, { signal: options?.signal }).catch(() => {});\n },\n { debugName: 'injectPreload' }\n );\n });\n}\n","import { computed, DestroyRef, inject, type Signal, signal } from '@angular/core';\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 { engineDb, inContext, toError } from './internal';\nimport type { InjectOptions } from './types';\n\n/**\n * A signal over an engine value. The engine's subscribe callback only bumps a\n * version; the signal reads the engine's own current value (`db.syncHealth`,\n * ...), so nothing can go stale. `equal: () => false` because the engine may\n * hand back the same snapshot object after changing it; the derived booleans\n * below are compared by value, so readers still only wake on real changes.\n * The subscription ends with the injection context.\n */\nfunction engineSignal<T>(\n current: () => T,\n subscribe: (onChange: () => void) => () => void\n): Signal<T> {\n const version = signal(0);\n inject(DestroyRef).onDestroy(subscribe(() => version.update((v) => v + 1)));\n return computed(\n () => {\n version();\n return current();\n },\n { equal: () => false }\n );\n}\n\n/**\n * Count of locally committed mutations not acknowledged by the server yet.\n * Drive an \"unsaved changes\" indicator off it.\n */\nexport function injectPendingMutations(options?: InjectOptions): Signal<number> {\n return inContext(injectPendingMutations, options?.injector, () => {\n const db = engineDb('injectPendingMutations');\n const count = engineSignal(\n () => db.pendingMutationCount,\n (cb) => db.subscribeToPendingMutations(() => cb())\n );\n return computed(() => count());\n });\n}\n\nexport interface SyncStatus {\n /** Full health snapshot. */\n readonly health: Signal<SyncHealth>;\n /** `'healthy'` | `'degraded'`. */\n readonly status: Signal<SyncHealthStatus>;\n readonly isHealthy: Signal<boolean>;\n /** `true` once sync has failed for a sustained run. Drive a banner off this. */\n readonly isDegraded: Signal<boolean>;\n /** `true` once at least one sync round has succeeded this session. */\n readonly everConnected: Signal<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 readonly isOffline: Signal<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.\n */\n readonly connection: Signal<ConnectionState>;\n /** `true` while the connection is being re-established. Usually still healthy. */\n readonly isReconnecting: Signal<boolean>;\n}\n\n/**\n * Observe sync health for a \"can't reach the server\" banner / indicator.\n * Individual sync failures are absorbed by the retry; `isDegraded` only turns\n * on once failures persist (core `syncHealth.degradeAfterConsecutiveFailures`,\n * default 3) and turns off on the next successful round.\n *\n * Needs no component: in a service (`providedIn: 'root'`) it lives as long as\n * the app.\n */\nexport function injectSyncStatus(options?: InjectOptions): SyncStatus {\n return inContext(injectSyncStatus, options?.injector, () => {\n const db = engineDb('injectSyncStatus');\n const health = engineSignal(\n () => db.syncHealth,\n (cb) => db.subscribeToSyncHealth(() => cb())\n );\n return {\n health,\n status: computed(() => health().status),\n isHealthy: computed(() => health().status === 'healthy'),\n isDegraded: computed(() => health().status === 'degraded'),\n everConnected: computed(() => health().everConnected),\n isOffline: computed(() => {\n const h = health();\n return h.status === 'degraded' && h.everConnected;\n }),\n connection: computed(() => health().connection),\n isReconnecting: computed(() => health().connection === 'reconnecting'),\n };\n });\n}\n\nexport interface StorageStatus {\n /** Full durability snapshot. */\n readonly health: Signal<StorageHealth>;\n /** `'unknown'` | `'persistent'` | `'memory'`. */\n readonly status: Signal<StorageHealthStatus>;\n /** `true` when the local store survives a reload. */\n readonly isPersistent: Signal<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`: a\n * store configured as in-memory reports `'memory'` too, by choice.\n */\n readonly isMemoryFallback: Signal<boolean>;\n}\n\n/**\n * Observe how durable the LOCAL cache is, for a \"no local storage\" warning.\n * Under `localEngine: 'sqlite'` + `store: 'indexeddb'` only one client per\n * bucket can hold the OPFS store open; a second tab runs in memory.\n */\nexport function injectStorageStatus(options?: InjectOptions): StorageStatus {\n return inContext(injectStorageStatus, options?.injector, () => {\n const db = engineDb('injectStorageStatus');\n const health = engineSignal(\n () => db.storageHealth,\n (cb) => db.subscribeToStorageHealth(() => cb())\n );\n return {\n health,\n status: computed(() => health().status),\n isPersistent: computed(() => health().status === 'persistent'),\n isMemoryFallback: computed(() => health().fallback),\n };\n });\n}\n\nexport interface SyncActivityOptions extends InjectOptions {\n /**\n * How long queries must be fetching before `isDownloading` turns on. Filters\n * the sub-frame fetches a warm cache produces. Default 200 ms.\n */\n downloadDelayMs?: number;\n /** `isUploading` turns on once MORE than this many writes are queued. Default 0. */\n uploadThreshold?: number;\n /**\n * How long the outbox must stay above `uploadThreshold` before `isUploading`\n * turns on: a write acknowledged within a round trip never lights it.\n * Default 150 ms.\n */\n uploadDelayMs?: number;\n}\n\nexport interface SyncActivity {\n /** Queries with traffic the user waits on (core `fetchingQueryCount`). */\n readonly fetchingQueries: Signal<number>;\n /** Locally committed writes the server has not acknowledged yet. */\n readonly pendingMutations: Signal<number>;\n /** Fetching for longer than `downloadDelayMs`. Drives a \"downloading\" mark. */\n readonly isDownloading: Signal<boolean>;\n /** More than `uploadThreshold` writes queued for longer than `uploadDelayMs`. */\n readonly isUploading: Signal<boolean>;\n}\n\n/**\n * The two directions of sync traffic, for an indicator in the app chrome.\n * `isDownloading` and `isUploading` are debounced ON by their delay and off at\n * once, so a page that answers from cache and confirms with the server in a few\n * milliseconds never flickers. Timers end with the injection context.\n */\nexport function injectSyncActivity(options: SyncActivityOptions = {}): SyncActivity {\n return inContext(injectSyncActivity, options.injector, () => {\n const db = engineDb('injectSyncActivity');\n const destroyRef = inject(DestroyRef);\n\n const downloading = delayedOn(options.downloadDelayMs ?? 200, destroyRef);\n const uploading = delayedOn(options.uploadDelayMs ?? 150, destroyRef);\n const threshold = options.uploadThreshold ?? 0;\n\n const fetchingQueries = engineSignal(\n () => db.fetchingQueryCount,\n (cb) =>\n db.subscribeToFetchActivity((n) => {\n downloading.set(n > 0);\n cb();\n })\n );\n const pendingMutations = engineSignal(\n () => db.pendingMutationCount,\n (cb) =>\n db.subscribeToPendingMutations((n) => {\n uploading.set(n > threshold);\n cb();\n })\n );\n // Seed both from the current counts, whether or not the engine called back\n // immediately.\n downloading.set(db.fetchingQueryCount > 0);\n uploading.set(db.pendingMutationCount > threshold);\n\n return {\n fetchingQueries: computed(() => fetchingQueries()),\n pendingMutations: computed(() => pendingMutations()),\n isDownloading: downloading.on,\n isUploading: uploading.on,\n };\n });\n}\n\n/**\n * A flag that turns on once `busy` has held for `delayMs` and off the instant\n * it clears. A burst too short to see never flickers, and neither direction can\n * latch on after the work is done. Driven from engine callbacks, not effects,\n * so it works in services too.\n */\nfunction delayedOn(\n delayMs: number,\n destroyRef: DestroyRef\n): { on: Signal<boolean>; set: (busy: boolean) => void } {\n const on = signal(false);\n let busy = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const stop = () => {\n if (timer !== undefined) clearTimeout(timer);\n timer = undefined;\n };\n destroyRef.onDestroy(stop);\n return {\n on: on.asReadonly(),\n set: (next) => {\n // A boolean, so a count moving 1 -> 2 does not restart the timer.\n if (next === busy) return;\n busy = next;\n stop();\n if (!next) on.set(false);\n else if (delayMs <= 0) on.set(true);\n else timer = setTimeout(() => on.set(true), delayMs);\n },\n };\n}\n\nexport interface ImpersonationOptions extends InjectOptions {\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 Impersonation {\n /** The active impersonation, or `null`. */\n readonly impersonation: Signal<ImpersonationInfo | null>;\n readonly isImpersonating: Signal<boolean>;\n /** Return to the admin session. */\n stop: () => Promise<void>;\n}\n\n/**\n * Observe admin impersonation (started from the DevTools). The client already\n * shows its own warning bar with a Stop button; use this for anything extra,\n * such as hiding actions an admin should not take on someone's behalf.\n */\nexport function injectImpersonation(options: ImpersonationOptions = {}): Impersonation {\n return inContext(injectImpersonation, options.injector, () => {\n const db = engineDb('injectImpersonation');\n const impersonation = engineSignal(\n () => db.auth.impersonation,\n (cb) =>\n db.auth.subscribeImpersonation((info) => {\n // Re-acknowledged per session: a new impersonation restarts the\n // client's fallback timer, and this banner is what cancels it.\n if (info && options.rendersBanner) db.acknowledgeImpersonationBanner();\n cb();\n })\n );\n return {\n impersonation,\n isImpersonating: computed(() => impersonation() !== null),\n stop: () => db.auth.stopImpersonating(),\n };\n });\n}\n\nexport interface FeatureFlag {\n /** Resolved variant (`options.fallback` when unassigned). */\n readonly variant: Signal<string | undefined>;\n readonly payload: Signal<unknown>;\n /** The variant is set and not `'off'`. */\n readonly enabled: Signal<boolean>;\n}\n\n/**\n * A feature flag for the signed-in user. Updates whenever the\n * server-materialized assignment in `_00_user_feature` changes, so\n * `spky flag enable <key>` reaches the UI without a refresh. The handle closes\n * with the injection context.\n */\nexport function injectFeatureFlag(\n key: string,\n options: FeatureFlagOptions & InjectOptions = {}\n): FeatureFlag {\n return inContext(injectFeatureFlag, options.injector, () => {\n const { injector: _, ...flagOptions } = options;\n const handle = engineDb('injectFeatureFlag').getSp00ky().feature(key, flagOptions);\n inject(DestroyRef).onDestroy(() => handle.close());\n const snapshot = engineSignal(\n () => handle,\n (cb) => handle.subscribe(() => cb())\n );\n return {\n variant: computed(() => snapshot().variant()),\n payload: computed(() => snapshot().payload()),\n enabled: computed(() => snapshot().enabled()),\n };\n });\n}\n\nexport interface AppReleaseConfig extends AppReleaseOptions, InjectOptions {\n /** App name from sp00ky.yml, e.g. `web`. */\n app: string;\n /**\n * The running build's version (X.Y.Z), typically baked in at build time\n * (e.g. from package.json through an `environment` file).\n */\n currentVersion: string;\n}\n\nexport interface AppRelease {\n /** Latest announced version for the app, or undefined when no row exists. */\n readonly latestVersion: Signal<string | undefined>;\n /** Announced version is semver-newer than the running build. */\n readonly updateAvailable: Signal<boolean>;\n /** The newer release asks clients to update/reload without prompting. */\n readonly mandatory: Signal<boolean>;\n /** The newer release asks reloads to clear service-worker caches first. */\n readonly cacheBust: Signal<boolean>;\n /**\n * Reload onto the announced release. Plain `location.reload()` normally;\n * with cache-bust, CacheStorage is cleared, the service worker is nudged to\n * update (never unregistered) and navigation carries a `?cb=` token.\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 * Observe the app's announced release (`_00_app_release:<app>`, written by\n * `spky deploy` / `spky release`) and compare it with the running build, for a\n * \"new version available, Reload\" notice. Guard an automatic `reload()` on\n * `mandatory` against loops with a per-version marker.\n */\nexport function injectAppRelease(config: AppReleaseConfig): AppRelease {\n return inContext(injectAppRelease, config.injector, () => {\n const handle = engineDb('injectAppRelease')\n .getSp00ky()\n .appRelease(config.app, { ttl: config.ttl });\n inject(DestroyRef).onDestroy(() => handle.close());\n const snapshot = engineSignal(\n () => handle.snapshot(),\n (cb) => handle.subscribe(() => cb())\n );\n const updateAvailable = computed(() => semverGt(snapshot().version, config.currentVersion));\n return {\n latestVersion: computed(() => snapshot().version),\n updateAvailable,\n mandatory: computed(() => updateAvailable() && snapshot().mandatory),\n cacheBust: computed(() => snapshot().cacheBust),\n reload: () => reloadForSnapshot(handle.snapshot()),\n };\n });\n}\n\nexport interface Submission<Args extends unknown[], R> {\n /** Run the wrapped async fn. Never rejects; a failure lands in `error`. */\n submit: (...args: Args) => Promise<R | undefined>;\n /** True while at least one submit is in flight. */\n readonly pending: Signal<boolean>;\n /** Error from the most recent settled submit, cleared on the next submit. */\n readonly error: Signal<Error | undefined>;\n /** Result of the most recent successful submit. */\n readonly result: Signal<R | undefined>;\n clearError: () => void;\n}\n\n/**\n * Button pending / error state around a mutation. Deliberately no optimistic\n * layer: the engine already commits writes locally and re-renders through live\n * queries before it syncs. An `error` here means the LOCAL commit failed; sync\n * failures surface through `injectSyncStatus` and `injectPendingMutations`.\n * Needs no injection context: it only holds signals.\n */\nexport function injectSubmission<Args extends unknown[], R>(\n fn: (...args: Args) => Promise<R>\n): Submission<Args, R> {\n const inFlight = signal(0);\n const error = signal<Error | undefined>(undefined);\n const result = signal<R | undefined>(undefined);\n return {\n submit: async (...args: Args): Promise<R | undefined> => {\n error.set(undefined);\n inFlight.update((n) => n + 1);\n try {\n const r = await fn(...args);\n result.set(r);\n return r;\n } catch (e) {\n error.set(toError(e));\n return undefined;\n } finally {\n inFlight.update((n) => n - 1);\n }\n },\n pending: computed(() => inFlight() > 0),\n error: error.asReadonly(),\n result: result.asReadonly(),\n clearError: () => error.set(undefined),\n };\n}\n","import { computed, effect, type Signal, signal, untracked } from '@angular/core';\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 { engineDb, inContext, read } from './internal';\nimport type { InjectOptions, MaybeSignal } from './types';\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 with the\n * injection context. Pass the id as a signal (an `input()`) or a function to\n * follow state.\n *\n * The signal stays `null` until the field is loaded (`CrdtField.isLoaded`):\n * this device had the document, or the server answered. Until then show the\n * column's text instead of binding an editor to a document still arriving.\n */\nexport function injectCrdtField(\n table: string,\n recordId: MaybeSignal<string | null | undefined>,\n field: string,\n options?: InjectOptions\n): Signal<CrdtField | null> {\n return inContext(injectCrdtField, options?.injector, () => {\n const sp00ky = engineDb('injectCrdtField').getSp00ky();\n const current = signal<CrdtField | null>(null);\n\n effect(\n (onCleanup) => {\n const id = read(recordId);\n if (!id) return;\n let superseded = false;\n let isOpen = false;\n let offLoaded = () => {};\n onCleanup(() => {\n superseded = true;\n offLoaded();\n if (isOpen) void sp00ky.closeCrdtField(table, id, field);\n current.set(null);\n });\n sp00ky\n .openCrdtField(table, id, field)\n .then((cf) => {\n isOpen = true;\n if (superseded) {\n void sp00ky.closeCrdtField(table, id, field);\n return;\n }\n // Handed out once loaded: an empty document before the server\n // answered is \"not arrived yet\", not \"empty\".\n offLoaded = cf.onLoaded(() => {\n if (!superseded) current.set(cf);\n });\n })\n .catch((err) => {\n // A silent rejection leaves the editor stuck on its fallback with\n // no trail; surface the root cause (missing `@crdt` annotation,\n // codegen drift, a local query failure).\n // oxlint-disable-next-line no-console\n console.error(\n `[injectCrdtField] Failed to open CRDT field ${table}.${field} on ${id}:`,\n err\n );\n });\n },\n { debugName: 'injectCrdtField' }\n );\n\n return current.asReadonly();\n });\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 injection context lives. */\nexport interface ChannelRef<S extends SchemaStructure, T extends string> {\n /** `idle` | `connecting` | `connected` | `failed` | `unsupported`. */\n readonly status: Signal<ChannelStatus>;\n /** Users with a tab connected. */\n readonly peers: Signal<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, for the\n * lifetime of the injection context. The query must be on a `-- @channel`\n * table and only its `where` counts; it is checked against each row, never\n * registered. Writes to matching rows (`db.update` / `db.create` /\n * `db.delete`, or the channel's own) reach the peers over WebRTC in tens of\n * ms; `-- @ephemeral` fields travel only this way. A connection forms when both\n * sides list each other; your own id is skipped.\n *\n * ```ts\n * readonly channel = injectChannel(\n * () => this.db.query('message').where({ conversation: this.convoId() }),\n * () => [this.me(), this.other()]\n * );\n * ```\n *\n * Both arguments may be signals or functions and are compared by value, so\n * rebuilding them is free. A `null` query closes the channel until a query\n * comes back.\n */\nexport function injectChannel<S extends SchemaStructure, T extends ChannelTableNames<S>>(\n query: MaybeSignal<ChannelQueries<S, T> | null | undefined>,\n peers: MaybeSignal<ChannelPeers | null | undefined>,\n options?: InjectOptions\n): ChannelRef<S, T> {\n return inContext(injectChannel, options?.injector, () => {\n const db = engineDb('injectChannel');\n const state = signal<ChannelState>(IDLE);\n let channel: Sp00kyChannel<any, any> | null = null;\n\n const readQuery = () => read(query) as ChannelQueries<any, any> | null | undefined;\n const readPeers = () => read(peers) ?? [];\n const qKey = computed(() => queriesKey(readQuery()));\n const pKey = computed(() => peersKey(readPeers()));\n const isOpen = computed(() => qKey() !== null);\n\n effect(\n (onCleanup) => {\n if (!isOpen()) return;\n const ch = untracked(() => db.channel(readQuery()!, readPeers()));\n channel = ch;\n const stop = ch.subscribe((s) => state.set(s));\n onCleanup(() => {\n stop();\n ch.close();\n if (channel === ch) channel = null;\n state.set(IDLE);\n });\n },\n { debugName: 'injectChannel' }\n );\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 effect(() => {\n qKey();\n const q = untracked(readQuery);\n if (q) channel?.setQueries(q);\n });\n effect(() => {\n pKey();\n channel?.setPeers(untracked(readPeers));\n });\n\n const open = () => {\n if (!channel)\n throw new Error('This channel is closed (its query is null, or its context is destroyed).');\n return channel;\n };\n return {\n status: computed(() => state().status),\n peers: computed(() => state().peers),\n update: ((...args: Parameters<Sp00kyChannel<any, any>['update']>) =>\n open().update(...args)) as ChannelRef<S, T>['update'],\n create: ((...args: Parameters<Sp00kyChannel<any, any>['create']>) =>\n open().create(...args)) as ChannelRef<S, T>['create'],\n delete: ((...args: Parameters<Sp00kyChannel<any, any>['delete']>) =>\n open().delete(...args)) as ChannelRef<S, T>['delete'],\n };\n });\n}\n","import { DestroyRef, effect, inject, type Signal, signal, untracked } from '@angular/core';\nimport type { BucketNames, SchemaStructure } from '@spooky-sync/query-builder';\nimport {\n fileToUint8Array,\n type BlobUrlLease,\n type BucketPutOptions,\n type BucketPutResult,\n} from '@spooky-sync/core';\nimport type { SyncedDb } from './db';\nimport { engineDb, inContext, read, toError } from './internal';\nimport type { InjectOptions, MaybeSignal } from './types';\n\ntype PathArg = MaybeSignal<string | null | undefined>;\n\nexport interface FileUpload {\n readonly isUploading: Signal<boolean>;\n readonly error: Signal<Error | null>;\n clearError: () => void;\n /** Validates against the bucket's `maxSize` / `allowedExtensions` first. */\n upload: (\n path: string,\n file: File | Blob,\n options?: BucketPutOptions\n ) => Promise<BucketPutResult | void>;\n /** An object URL for the file (revoked with the injection context), or `null`. */\n download: (path: string) => Promise<string | null>;\n remove: (path: string) => Promise<void>;\n exists: (path: string) => Promise<boolean>;\n}\n\n/**\n * Upload, download, remove and probe files in a bucket, with `isUploading`\n * and `error` signals. `bucket` may be a signal; it is read on each call.\n */\nexport function injectFileUpload<S extends SchemaStructure = any>(\n bucket: MaybeSignal<BucketNames<S>>,\n options?: InjectOptions\n): FileUpload {\n return inContext(injectFileUpload, options?.injector, () => {\n const db = engineDb('injectFileUpload') as SyncedDb<S>;\n const isUploading = signal(false);\n const error = signal<Error | null>(null);\n\n const objectUrls: string[] = [];\n inject(DestroyRef).onDestroy(() => {\n for (const url of objectUrls) URL.revokeObjectURL(url);\n });\n\n const validate = (name: string, file: File | Blob): void => {\n const config = db.getBucketConfig(name);\n if (!config) return;\n if (config.maxSize !== null && config.maxSize !== undefined && file.size > config.maxSize) {\n const maxMB = (config.maxSize / (1024 * 1024)).toFixed(1);\n throw new Error(`File exceeds maximum size of ${maxMB} MB.`);\n }\n if (config.allowedExtensions && config.allowedExtensions.length > 0) {\n const fileName = (file as File).name;\n if (fileName) {\n const ext = fileName.split('.').pop()?.toLowerCase();\n if (!ext || !config.allowedExtensions.includes(ext)) {\n throw new Error(\n `File type not allowed. Accepted: ${config.allowedExtensions.join(', ')}.`\n );\n }\n }\n }\n };\n\n return {\n isUploading: isUploading.asReadonly(),\n error: error.asReadonly(),\n clearError: () => error.set(null),\n upload: async (path, file, putOptions) => {\n const name = untracked(() => read(bucket));\n error.set(null);\n try {\n validate(name as string, file);\n } catch (e) {\n error.set(toError(e));\n return undefined;\n }\n isUploading.set(true);\n try {\n const bytes = await fileToUint8Array(file);\n return await db.bucket(name).put(path, bytes, putOptions);\n } catch (e) {\n error.set(toError(e));\n return undefined;\n } finally {\n isUploading.set(false);\n }\n },\n download: async (path) => {\n error.set(null);\n try {\n const content = await db.bucket(untracked(() => read(bucket))).get(path);\n if (!content) return null;\n const objectUrl = URL.createObjectURL(new Blob([content as BlobPart]));\n objectUrls.push(objectUrl);\n return objectUrl;\n } catch (e) {\n error.set(toError(e));\n return null;\n }\n },\n remove: async (path) => {\n error.set(null);\n try {\n await db.bucket(untracked(() => read(bucket))).delete(path);\n } catch (e) {\n error.set(toError(e));\n }\n },\n exists: async (path) => {\n error.set(null);\n try {\n return await db.bucket(untracked(() => read(bucket))).exists(path);\n } catch (e) {\n error.set(toError(e));\n return false;\n }\n },\n };\n });\n}\n\nexport interface DownloadFileOptions extends InjectOptions {\n /**\n * Master switch, default `true`. `false` gives every caller its own private\n * object URL fetched fresh from the bucket and revoked with its context: no\n * sharing, no persistence, no reuse.\n */\n cache?: boolean;\n /**\n * Keep the bytes in OPFS so they survive a reload and are available offline.\n * Default `true`. The in-tab object URL is still shared between components\n * rendering the same path either way.\n */\n persist?: boolean;\n /** Exempt this file from pressure eviction. Pinned bytes never expire. */\n pin?: boolean;\n /**\n * `'never'` (default) treats a bucket path as immutable, which is how paths\n * are written (`crypto.randomUUID() + ext`). `'head'` spends a remote `head()`\n * to compare sizes before trusting the cached copy, for paths the app\n * overwrites in place.\n */\n revalidate?: 'never' | 'head';\n}\n\nexport interface DownloadFile {\n /** Object URL for the file, `null` while none is resolved (or no path). */\n readonly url: Signal<string | null>;\n readonly isLoading: Signal<boolean>;\n readonly error: Signal<Error | null>;\n /** Bypass every cache layer once and fetch again. */\n refetch: () => void;\n}\n\n/**\n * An object URL for a bucket file that follows `path` (a signal or function).\n * Cached URLs are refcounted and shared between every component showing the\n * same path; the previous URL stays valid until the next one is ready, so an\n * `<img>` never flashes broken on a path change.\n */\nexport function injectDownloadFile<S extends SchemaStructure = any>(\n bucket: MaybeSignal<BucketNames<S>>,\n path: PathArg,\n options: DownloadFileOptions = {}\n): DownloadFile {\n return inContext(injectDownloadFile, options.injector, () =>\n downloadFile(engineDb('injectDownloadFile'), bucket, path, () => options)\n );\n}\n\n/**\n * `injectDownloadFile` without the context check, with options read lazily\n * (on each fetch, untracked), so a component can pass its inputs.\n */\nfunction downloadFile(\n db: SyncedDb<any>,\n bucket: MaybeSignal<string>,\n path: PathArg,\n options: () => DownloadFileOptions\n): DownloadFile {\n const url = signal<string | null>(null);\n const isLoading = signal(false);\n const error = signal<Error | null>(null);\n const refetchTick = signal(0);\n /** Consumed by the next fetch, so `refetch()` bypasses every layer once. */\n let reloadOnce = false;\n\n // What backs the current `url`: a refcounted lease on the shared cache entry,\n // or a private URL this caller minted and must revoke itself.\n let held: { lease?: BlobUrlLease; privateUrl?: string } | null = null;\n const release = () => {\n held?.lease?.release();\n if (held?.privateUrl) URL.revokeObjectURL(held.privateUrl);\n held = null;\n };\n inject(DestroyRef).onDestroy(release);\n\n effect(\n (onCleanup) => {\n refetchTick();\n const name = read(bucket);\n const filePath = read(path);\n if (!filePath) {\n release();\n url.set(null);\n isLoading.set(false);\n error.set(null);\n return;\n }\n\n const opts = untracked(options);\n const reload = reloadOnce;\n reloadOnce = false;\n let cancelled = false;\n onCleanup(() => {\n cancelled = true;\n });\n isLoading.set(true);\n error.set(null);\n\n const handle = db.bucket(name);\n const next: Promise<{ lease?: BlobUrlLease; privateUrl?: string; url: string } | null> =\n opts.cache !== false\n ? handle\n .url(filePath, {\n persist: opts.persist !== false,\n pin: opts.pin,\n revalidate: opts.revalidate,\n reload,\n })\n .then((lease) => (lease ? { lease, url: lease.url } : null))\n : handle.read(filePath, { persist: false, reload: true }).then((blob) => {\n if (!blob) return null;\n const privateUrl = URL.createObjectURL(blob);\n return { privateUrl, url: privateUrl };\n });\n\n next.then(\n (result) => {\n if (cancelled) {\n // Destroyed, or the path changed mid-flight: hand the reference\n // straight back, or the entry never drops to zero and its object\n // URL leaks for the life of the tab.\n result?.lease?.release();\n if (result?.privateUrl) URL.revokeObjectURL(result.privateUrl);\n return;\n }\n release();\n held = result;\n url.set(result?.url ?? null);\n isLoading.set(false);\n },\n (err) => {\n if (cancelled) return;\n error.set(toError(err));\n isLoading.set(false);\n }\n );\n },\n { debugName: 'injectDownloadFile' }\n );\n\n return {\n url: url.asReadonly(),\n isLoading: isLoading.asReadonly(),\n error: error.asReadonly(),\n refetch: () => {\n reloadOnce = true;\n refetchTick.update((n) => n + 1);\n },\n };\n}\n\nexport interface BlurhashResult {\n /** The stored blurhash for the path, `null` while loading or when none exists. */\n readonly hash: Signal<string | null>;\n readonly isLoading: Signal<boolean>;\n}\n\n/**\n * The blurhash sidecar for a bucket image (written by `bucket.put`, see\n * `Sp00kyConfig.blurhash`). Resolves from OPFS instantly on warm clients; a\n * miss is remembered per tab. `injectBucketImage` / `<sp00ky-bucket-image>`\n * bundle it with the download; use this when the hash belongs to another\n * rendition.\n */\nexport function injectBlurhash<S extends SchemaStructure = any>(\n bucket: MaybeSignal<BucketNames<S>>,\n path: PathArg,\n options?: InjectOptions\n): BlurhashResult {\n return inContext(injectBlurhash, options?.injector, () =>\n blurhashOf(engineDb('injectBlurhash'), bucket, path)\n );\n}\n\nfunction blurhashOf(db: SyncedDb<any>, bucket: MaybeSignal<string>, path: PathArg): BlurhashResult {\n const hash = signal<string | null>(null);\n const isLoading = signal(false);\n\n effect(\n (onCleanup) => {\n const name = read(bucket);\n const filePath = read(path);\n if (!filePath) {\n hash.set(null);\n isLoading.set(false);\n return;\n }\n let cancelled = false;\n onCleanup(() => {\n cancelled = true;\n });\n isLoading.set(true);\n db.bucket(name)\n .blurhash(filePath)\n .then(\n (result) => {\n if (cancelled) return;\n hash.set(result);\n isLoading.set(false);\n },\n () => {\n if (cancelled) return;\n hash.set(null);\n isLoading.set(false);\n }\n );\n },\n { debugName: 'injectBlurhash' }\n );\n\n return { hash: hash.asReadonly(), isLoading: isLoading.asReadonly() };\n}\n\nexport interface BucketImageOptions extends DownloadFileOptions {\n /**\n * Also resolve the image's blurhash sidecar (see `Sp00kyConfig.blurhash`).\n * Default `true`; read before the bytes, so the tiny sidecar tends to land\n * first on the serialized remote chain.\n */\n blurhash?: boolean;\n}\n\nexport interface BucketImageRef extends DownloadFile {\n /** Blurhash for the same path, or `null` (off, missing, still loading). */\n readonly blurhash: Signal<string | null>;\n /** True once the current `url` has been decoded and is safe to paint. */\n readonly ready: Signal<boolean>;\n /**\n * Drive an `<img>`: set its `src` to `url` and flip `ready` once that bitmap\n * is DECODED (failures count too, so a broken blob degrades to\n * paint-on-load instead of hiding forever). Reads `url`, so call it inside\n * an effect to re-arm on every new url; returns that run's cleanup. The\n * `sp00kyImageGate` directive does exactly this: prefer it.\n */\n gate: (img: HTMLImageElement) => () => void;\n}\n\n/**\n * Everything needed to render a bucket image without a pop-in: the refcounted\n * object URL, the blurhash placeholder, and a decode gate so the bitmap is only\n * revealed once it can paint in full. `<sp00ky-bucket-image>` wraps it; use\n * this with `<img [sp00kyImageGate]=\"image\">` for custom markup.\n */\nexport function injectBucketImage<S extends SchemaStructure = any>(\n bucket: MaybeSignal<BucketNames<S>>,\n path: PathArg,\n options: BucketImageOptions = {}\n): BucketImageRef {\n return inContext(injectBucketImage, options.injector, () =>\n bucketImage(engineDb('injectBucketImage'), bucket, path, () => options)\n );\n}\n\n/** `injectBucketImage` with options read lazily, for `<sp00ky-bucket-image>`'s inputs. */\nexport function bucketImage(\n db: SyncedDb<any>,\n bucket: MaybeSignal<string>,\n path: PathArg,\n options: () => BucketImageOptions\n): BucketImageRef {\n // Created BEFORE the download so the sidecar read enters the serialized\n // remote queue first: the placeholder should never wait behind the bytes it\n // stands in for.\n const sidecar = blurhashOf(db, bucket, () => (options().blurhash !== false ? read(path) : null));\n const file = downloadFile(db, bucket, path, options);\n const ready = signal(false);\n\n const gate = (img: HTMLImageElement): (() => void) => {\n const src = file.url();\n ready.set(false);\n if (!src) {\n img.removeAttribute('src');\n return () => {};\n }\n img.src = src;\n let cancelled = false;\n const reveal = () => {\n if (!cancelled) ready.set(true);\n };\n if (typeof img.decode === 'function') img.decode().then(reveal, reveal);\n else if (img.complete) reveal();\n else {\n img.onload = reveal;\n img.onerror = reveal;\n }\n return () => {\n cancelled = true;\n };\n };\n\n return {\n ...file,\n blurhash: sidecar.hash,\n ready: ready.asReadonly(),\n gate,\n };\n}\n","import { afterRenderEffect, Directive, ElementRef, inject, input } from '@angular/core';\nimport { decodeBlurhash } from '@spooky-sync/core';\n\n/**\n * Paints a blurhash onto the host `<canvas>`:\n * `<canvas [sp00kyBlurhash]=\"hash\" class=\"absolute inset-0 h-full w-full\"></canvas>`.\n *\n * Size the canvas with CSS; the decode resolution stays tiny (32x32 is plenty:\n * a blurhash carries at most 9x9 DCT components). Repaints once per hash (or\n * size) change, after render, and never during a server render.\n */\n@Directive({\n selector: 'canvas[sp00kyBlurhash]',\n})\nexport class Blurhash {\n /** The blurhash string. Nullish paints nothing (a transparent canvas). */\n readonly hash = input<string | null | undefined>(undefined, { alias: 'sp00kyBlurhash' });\n /** Decode width in pixels. Defaults to 32. */\n readonly blurhashWidth = input(32);\n /** Decode height in pixels. Defaults to 32. */\n readonly blurhashHeight = input(32);\n /** Contrast punch, see the blurhash reference decoder. Defaults to 1. */\n readonly blurhashPunch = input(1);\n\n constructor() {\n const canvas = inject<ElementRef<HTMLCanvasElement>>(ElementRef).nativeElement;\n afterRenderEffect({\n write: () => {\n const width = this.blurhashWidth();\n const height = this.blurhashHeight();\n const hash = this.hash();\n const punch = this.blurhashPunch();\n canvas.width = width;\n canvas.height = height;\n if (!hash) return;\n try {\n const pixels = decodeBlurhash(hash, width, height, punch);\n const ctx = canvas.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 },\n });\n }\n}\n","import { afterRenderEffect, Directive, ElementRef, inject, input } from '@angular/core';\nimport type { BucketImageRef } from './files';\n\n/**\n * Wires an `<img>` to `injectBucketImage`: sets `src` to the image's url and\n * flips its `ready` signal once the bitmap is decoded, re-arming on every new\n * url. Do not also bind `src`.\n *\n * ```html\n * <img [sp00kyImageGate]=\"cover\" alt=\"\" [style.opacity]=\"cover.ready() ? 1 : 0\" />\n * ```\n */\n@Directive({\n selector: 'img[sp00kyImageGate]',\n})\nexport class ImageGate {\n /** The result of `injectBucketImage(...)`. */\n readonly image = input.required<BucketImageRef>({ alias: 'sp00kyImageGate' });\n\n constructor() {\n const img = inject<ElementRef<HTMLImageElement>>(ElementRef).nativeElement;\n afterRenderEffect({\n write: (onCleanup) => onCleanup(this.image().gate(img)),\n });\n }\n}\n","import {\n afterNextRender,\n ChangeDetectionStrategy,\n Component,\n computed,\n DestroyRef,\n effect,\n ElementRef,\n inject,\n input,\n signal,\n} from '@angular/core';\nimport { Blurhash } from './blurhash';\nimport { bucketImage, type BucketImageOptions } from './files';\nimport { ImageGate } from './image-gate';\nimport { engineDb } from './internal';\n\nconst LAYER = 'position:absolute;inset:0;width:100%;height:100%;';\n\n/** `prefers-reduced-motion: reduce`, live. */\nfunction prefersReducedMotion() {\n const reduced = signal(false);\n if (typeof matchMedia !== 'function') return reduced.asReadonly();\n const query = matchMedia('(prefers-reduced-motion: reduce)');\n reduced.set(query.matches);\n const onChange = (e: MediaQueryListEvent) => reduced.set(e.matches);\n query.addEventListener?.('change', onChange);\n inject(DestroyRef).onDestroy(() => query.removeEventListener?.('change', onChange));\n return reduced.asReadonly();\n}\n\n/**\n * A bucket image that never pops in. Bottom to top: the projected content (your\n * own plate or skeleton), the stored blurhash, and the real image, which stays\n * transparent until its bitmap is DECODED and then crossfades over the\n * placeholders. The placeholders leave the DOM once the fade is over and come\n * back when the path changes.\n *\n * ```html\n * <sp00ky-bucket-image bucket=\"avatars\" [path]=\"avatar()\" class=\"h-12 w-12 rounded-full\">\n * <div class=\"h-full w-full bg-neutral-200\"></div>\n * </sp00ky-bucket-image>\n * ```\n *\n * The host is the container: size and position it with `class` / `style`. It\n * becomes `display: block` and `position: relative` unless you set otherwise.\n */\n@Component({\n selector: 'sp00ky-bucket-image',\n imports: [Blurhash, ImageGate],\n changeDetection: ChangeDetectionStrategy.OnPush,\n template: `\n @if (!settled()) {\n <div [style]=\"layer\">\n <div [style]=\"layer\"><ng-content /></div>\n <canvas [sp00kyBlurhash]=\"image.blurhash()\" [style]=\"layer\"></canvas>\n </div>\n }\n <img\n [class]=\"imgClass()\"\n [alt]=\"alt()\"\n decoding=\"async\"\n [style]=\"imgStyle()\"\n [sp00kyImageGate]=\"image\"\n />\n `,\n})\nexport class BucketImage {\n /** Bucket name from the schema. */\n readonly bucket = input.required<string>();\n /** Path within the bucket. Nullish renders only the placeholder layers. */\n readonly path = input<string | null | undefined>(null);\n readonly alt = input('');\n /** Classes for the inner `<img>` (the layout styles are inline). */\n readonly imgClass = input<string>();\n /** `object-fit` for the image. Defaults to `cover`. */\n readonly fit = input<'cover' | 'contain' | 'fill' | 'none' | 'scale-down'>('cover');\n /** Crossfade duration in ms. Defaults to 300. */\n readonly transition = input(300);\n /** Crossfade easing. Defaults to an ease-out-expo curve. */\n readonly easing = input('cubic-bezier(0.16, 1, 0.3, 1)');\n /** Resolve the blurhash sidecar. Defaults to true. */\n readonly blurhash = input(true);\n /** Download tuning, as for `injectDownloadFile`. Read when a fetch starts. */\n readonly options = input<BucketImageOptions>();\n\n protected readonly layer = LAYER;\n protected readonly image = bucketImage(engineDb('BucketImage'), this.bucket, this.path, () => ({\n ...this.options(),\n blurhash: this.blurhash(),\n }));\n protected readonly settled = signal(false);\n private readonly reducedMotion = prefersReducedMotion();\n\n protected readonly imgStyle = computed(() => {\n const fade = this.reducedMotion() ? 'none' : `opacity ${this.transition()}ms ${this.easing()}`;\n return (\n LAYER + `object-fit:${this.fit()};opacity:${this.image.ready() ? 1 : 0};transition:${fade};`\n );\n });\n\n constructor() {\n effect((onCleanup) => {\n if (!this.image.ready()) {\n this.settled.set(false);\n return;\n }\n const wait = (this.reducedMotion() ? 0 : this.transition()) + 120;\n const timer = setTimeout(() => this.settled.set(true), wait);\n onCleanup(() => clearTimeout(timer));\n });\n\n // The layers are absolutely positioned: give them an anchor without\n // stomping on a caller class that already positions or displays the host.\n const host = inject<ElementRef<HTMLElement>>(ElementRef).nativeElement;\n afterNextRender(() => {\n const { display, position } = getComputedStyle(host);\n if (!display || display === 'inline') host.style.display = 'block';\n if (!position || position === 'static') host.style.position = 'relative';\n });\n }\n}\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":";;;;;;;;AAiCA;;;;;;;;;;;;AAYG;MACU,QAAQ,CAAA;AACX,IAAA,MAAM;IACN,MAAM,GAA2B,IAAI;IACrC,YAAY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AAA,EAAA,UAAA,EAAA,KAAA,EAAA,iBAAA,EAAA,IAAA,EAAA,EAAA,QAAA,EAAA,EAAA,iBAAA,EAAA,UAAA,EAAA,UAAA,EAAA,UAAA,EAAA,QAAA,EAAA,IAAA,EAAA,UAAA,EAAA,KAAA,EAAA,iBAAA,EAAA,IAAA,EAAA,EAAA,OAAA,EAAA,EAAA,iBAAA,EAAA,SAAA,EAAA,UAAA,EAAA,SAAA,EAAA,QAAA,EAAA,IAAA,EAAA,UAAA,EAAA,KAAA,EAAA,iBAAA,EAAA,IAAA,EAAA,EAAA,EAAA,QAAA,EAAA,EAAA,EAAA,QAAA,EAhBZ;;;;;;;;;;;;;;GAcT,EAAA,QAAA,EAAA,IAAA,EAAA,YAAA,EAAA,CAAA,EAAA,IAAA,EAAA,WAAA,EAAA,IAAA,EAhBS,QAAQ,mJAAE,SAAS,EAAA,QAAA,EAAA,sBAAA,EAAA,MAAA,EAAA,CAAA,iBAAA,CAAA,EAAA,CAAA,EAAA,eAAA,EAAA,EAAA,CAAA,uBAAA,CAAA,MAAA,EAAA,CAAA;;4FAkBlB,WAAW,EAAA,UAAA,EAAA,CAAA;kBApBvB,SAAS;AAAC,YAAA,IAAA,EAAA,CAAA;AACT,oBAAA,QAAQ,EAAE,qBAAqB;AAC/B,oBAAA,OAAO,EAAE,CAAC,QAAQ,EAAE,SAAS,CAAC;oBAC9B,eAAe,EAAE,uBAAuB,CAAC,MAAM;AAC/C,oBAAA,QAAQ,EAAE;;;;;;;;;;;;;;AAcT,EAAA,CAAA;AACF,iBAAA;;;AClED;;AAEG;;;;"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,51 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spooky-sync/client-angular",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.0.1-canary.383",
|
|
4
|
+
"description": "Angular (signals) bindings for the sp00ky local-first sync client",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"surrealdb",
|
|
7
|
+
"database",
|
|
8
|
+
"browser",
|
|
9
|
+
"offline",
|
|
10
|
+
"sync",
|
|
11
|
+
"angular",
|
|
12
|
+
"signals",
|
|
13
|
+
"local-first",
|
|
14
|
+
"tanstack-intent"
|
|
15
|
+
],
|
|
16
|
+
"author": "",
|
|
17
|
+
"license": "MIT",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "https://github.com/mono424/sp00ky.git",
|
|
21
|
+
"directory": "packages/client-angular"
|
|
22
|
+
},
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"sideEffects": false,
|
|
27
|
+
"packageManager": "pnpm@9.0.0",
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@spooky-sync/core": "0.0.1-canary.383",
|
|
30
|
+
"@spooky-sync/query-builder": "0.0.1-canary.383",
|
|
31
|
+
"@surrealdb/wasm": "^3.1.0",
|
|
32
|
+
"surrealdb": "2.1.0",
|
|
33
|
+
"tslib": "^2.3.0"
|
|
34
|
+
},
|
|
35
|
+
"peerDependencies": {
|
|
36
|
+
"@angular/common": "^21.0.0 || ^22.0.0",
|
|
37
|
+
"@angular/core": "^21.0.0 || ^22.0.0"
|
|
38
|
+
},
|
|
39
|
+
"module": "fesm2022/spooky-sync-client-angular.mjs",
|
|
40
|
+
"typings": "types/spooky-sync-client-angular.d.ts",
|
|
41
|
+
"exports": {
|
|
42
|
+
"./package.json": {
|
|
43
|
+
"default": "./package.json"
|
|
44
|
+
},
|
|
45
|
+
".": {
|
|
46
|
+
"types": "./types/spooky-sync-client-angular.d.ts",
|
|
47
|
+
"default": "./fesm2022/spooky-sync-client-angular.mjs"
|
|
48
|
+
}
|
|
49
|
+
},
|
|
50
|
+
"type": "module"
|
|
6
51
|
}
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: sp00ky-angular
|
|
3
|
+
description: >-
|
|
4
|
+
Angular (signals) integration for the Sp00ky reactive local-first SurrealDB
|
|
5
|
+
framework. Use when an Angular 21+ app uses sp00ky: provideSp00ky in
|
|
6
|
+
app.config.ts, injectQuery with signal inputs for live data, mutations via
|
|
7
|
+
plain db calls or injectSubmission, status functions (sync, storage, feature
|
|
8
|
+
flags, app release), CRDT fields, peer to peer channels, file
|
|
9
|
+
upload/download and sp00ky-bucket-image, plus the Angular CLI build settings
|
|
10
|
+
(worker entry, wasm assets, prebundle exclusions). For React apps use the
|
|
11
|
+
sp00ky-react skill, for Svelte sp00ky-svelte, for Solid sp00ky-solid or
|
|
12
|
+
sp00ky-solid2.
|
|
13
|
+
metadata:
|
|
14
|
+
author: sp00ky-sync
|
|
15
|
+
version: '0.0.1'
|
|
16
|
+
---
|
|
17
|
+
|
|
18
|
+
# Sp00ky Angular Client
|
|
19
|
+
|
|
20
|
+
`@spooky-sync/client-angular` targets Angular 21+ in the browser (zoneless or zone.js). `inject*` functions return read-only signals and run in an injection context; inputs that follow state are signals or functions. `injectQuery` rows are structurally shared between live emissions: rows matched by `id` keep their object identity, a deep-equal emission does not notify.
|
|
21
|
+
|
|
22
|
+
## Setup
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
// app.config.ts
|
|
26
|
+
export const appConfig: ApplicationConfig = {
|
|
27
|
+
providers: [
|
|
28
|
+
provideZonelessChangeDetection(),
|
|
29
|
+
provideSp00ky({
|
|
30
|
+
schema,
|
|
31
|
+
schemaSurql: SURQL_SCHEMA,
|
|
32
|
+
logLevel: 'info',
|
|
33
|
+
database: {
|
|
34
|
+
namespace: 'main',
|
|
35
|
+
database: 'app',
|
|
36
|
+
endpoint: 'ws://localhost:8666/rpc',
|
|
37
|
+
store: 'indexeddb',
|
|
38
|
+
workers: {
|
|
39
|
+
surreal: () =>
|
|
40
|
+
new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
|
|
41
|
+
},
|
|
42
|
+
},
|
|
43
|
+
}),
|
|
44
|
+
],
|
|
45
|
+
};
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The client starts in an app initializer; the app renders once it is ready. Angular CLI apps also need: `src/app/sp00ky-surreal.worker.ts` containing `import '@surrealdb/wasm/worker';` (install `@surrealdb/wasm`), `webWorkerTsConfig`, `assets` copying `ssp_wasm_bg.wasm` (`@spooky-sync/ssp-wasm/pkg`), `index_bg.wasm` (`@surrealdb/wasm-native/dist`), `tabs-broker-worker.js` (`@spooky-sync/core/dist`) and `sqlite3.wasm` + `sqlite3-opfs-async-proxy.js` (`@sqlite.org/sqlite-wasm/dist`) to `/`, and `serve.options.prebundle.exclude` for `@spooky-sync/client-angular`, `@spooky-sync/core`, `@spooky-sync/ssp-wasm`, `@surrealdb/wasm`, `@surrealdb/wasm-native`, `@sqlite.org/sqlite-wasm`. With pnpm, `public-hoist-pattern[]` the wasm packages. Without these, init hangs on a 404 `worker-agent.mjs`.
|
|
49
|
+
|
|
50
|
+
## Queries
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
export class PostList {
|
|
54
|
+
private readonly db = injectDb<typeof schema>();
|
|
55
|
+
readonly authorId = input<string | null>(null);
|
|
56
|
+
protected readonly posts = injectQuery(() => {
|
|
57
|
+
const author = this.authorId();
|
|
58
|
+
return author ? this.db.query('post').where({ author }).limit(20).build() : null;
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```html
|
|
64
|
+
@if (posts.isLoading()) { <app-spinner /> } @else if (posts.isEmpty()) { <app-empty /> } @else {
|
|
65
|
+
@for (p of posts.data(); track p.id) { <app-post-row [post]="p" /> } }
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- Pass a function; it re-runs when the signals it reads change, and the query re-registers only when its identity (surql + vars) changes. Return `null` to skip.
|
|
69
|
+
- Result signals: `data`, `error`, `isLoading` (cold first load only), `isFetching`, `isAuthoritative`, `hasData`, `isEmpty` (server said "no rows"), `isSettled` (authoritative and idle).
|
|
70
|
+
- Options: `{ enabled?, deregisterOnCleanup?, injector? }`. `injectPreload(() => query)` warms the cache for a likely-next screen.
|
|
71
|
+
|
|
72
|
+
## Mutations
|
|
73
|
+
|
|
74
|
+
Plain awaited calls; the engine is optimistic local-first:
|
|
75
|
+
|
|
76
|
+
```ts
|
|
77
|
+
await this.db.create('post:' + crypto.randomUUID(), { title });
|
|
78
|
+
await this.db.update('post', id, { title });
|
|
79
|
+
await this.db.delete('post', row.id);
|
|
80
|
+
await this.db.run('backend', 'route', payload);
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Button state: `save = injectSubmission(fn)` gives `submit`, `pending()`, `error()`, `result()`, `clearError`.
|
|
84
|
+
|
|
85
|
+
## Functions
|
|
86
|
+
|
|
87
|
+
`injectDb`, `injectPendingMutations()`, `injectSyncStatus`, `injectSyncActivity`, `injectStorageStatus`, `injectImpersonation`, `injectFeatureFlag`, `injectAppRelease`, `injectCrdtField(table, this.id, field)()`, `injectChannel(() => query, () => peers)`, `injectFileUpload(bucket)`, `injectDownloadFile(bucket, this.path)`, `injectBlurhash`, `injectBucketImage` (with `<img [sp00kyImageGate]="image">`), plus `<sp00ky-bucket-image>` (projected placeholder) and `<canvas [sp00kyBlurhash]>`. Tests: `{ provide: SyncedDb, useValue: fakeDb }`.
|
|
88
|
+
|
|
89
|
+
## Gotchas
|
|
90
|
+
|
|
91
|
+
- `inject*` run in field initializers / constructors (or pass `{ injector }`), not in `ngOnInit` or handlers.
|
|
92
|
+
- Call the signals: `posts.data()`.
|
|
93
|
+
- Required inputs are read inside the query function, never in a field initializer.
|
|
94
|
+
- SSR: engine-backed components go in `@defer` or on `RenderMode.Client` routes.
|
|
95
|
+
- No suspense mode; branch on `isLoading()`.
|
|
96
|
+
|
|
97
|
+
Full API: `node_modules/@spooky-sync/client-angular/AGENTS.md`.
|