@spooky-sync/client-angular 0.0.0-stage → 0.0.1-canary.384
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
package/AGENTS.md
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
# `@spooky-sync/client-angular`: agent guide
|
|
2
|
+
|
|
3
|
+
## What this package is
|
|
4
|
+
|
|
5
|
+
The **Angular** binding for sp00ky, built on signals (peer `@angular/core` / `@angular/common` `^21 || ^22`; zoneless and zone.js both work). Same `SyncedDb` and the same function set as `@spooky-sync/client-react` / `client-svelte` / `client-solid2`, written the Angular way:
|
|
6
|
+
|
|
7
|
+
- `provideSp00ky(config, { preload? })` in the application providers (`app.config.ts`). It provides `SyncedDb` (also the DI token) and starts it in an app initializer, so components render once the client is ready. No wrapper component.
|
|
8
|
+
- `inject*` functions return **read-only signals**: `posts.data()`, `posts.isLoading()`. Call them in templates, `computed()` and `effect()`.
|
|
9
|
+
- An input that should follow state is a **signal or a function**: `injectQuery(() => this.db.query('post').where({ author: this.authorId() }).build())`, `injectCrdtField('post', this.postId, 'body')` (an `input()` is a signal), `injectDownloadFile('covers', this.path)`. A plain value is fixed.
|
|
10
|
+
- A function with a single value returns that signal: `injectPendingMutations()`, `injectCrdtField(...)`.
|
|
11
|
+
- Every `inject*` function must run in an **injection context** (field initializer, constructor, factory, `providedIn: 'root'` service) and ends with it via `DestroyRef`. Pass `{ injector }` to call one anywhere else (like Angular's `effect()` / `toSignal()`). `injectSubmission` needs no context.
|
|
12
|
+
|
|
13
|
+
Browser only. The core client runs SurrealDB / SQLite as WebAssembly in web workers with IndexedDB / OPFS. During a server render `provideSp00ky` never starts the client and the engine-backed `inject*` functions throw ("runs in the browser only"); render such components in `@defer` blocks or on `renderMode: RenderMode.Client` routes.
|
|
14
|
+
|
|
15
|
+
Internals: `injectQuery` keeps rows in a `signal` and structurally shares each live emission with the previous one (`share` in `src/query.ts`): rows matched by `id` keep their object identity, and a deep-equal emission returns the previous value so the signal does not notify. Registrations, CRDT fields, channels and file leases live in `effect()` and end with the injection context. Status functions subscribe to the engine on creation (no effects, so they work in services) and read the engine's own current value. DOM work (`Blurhash`, `ImageGate`) runs in `afterRenderEffect`, never on the server.
|
|
16
|
+
|
|
17
|
+
Built with ng-packagr (Angular Package Format, partial compilation); published from `dist/`.
|
|
18
|
+
|
|
19
|
+
## Setup pattern
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
// src/app/db.ts
|
|
23
|
+
import type { SyncedDbConfig } from '@spooky-sync/client-angular';
|
|
24
|
+
import { schema, SURQL_SCHEMA } from './schema.gen'; // generated by `spky generate`
|
|
25
|
+
|
|
26
|
+
export const dbConfig: SyncedDbConfig<typeof schema> = {
|
|
27
|
+
schema,
|
|
28
|
+
schemaSurql: SURQL_SCHEMA,
|
|
29
|
+
database: {
|
|
30
|
+
namespace: 'main',
|
|
31
|
+
database: 'app',
|
|
32
|
+
endpoint: 'ws://localhost:8666/rpc',
|
|
33
|
+
store: 'indexeddb',
|
|
34
|
+
// Angular CLI only: the app bundles the engine's worker (see below).
|
|
35
|
+
workers: {
|
|
36
|
+
surreal: () =>
|
|
37
|
+
new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// src/app/app.config.ts
|
|
43
|
+
export const appConfig: ApplicationConfig = {
|
|
44
|
+
providers: [provideZonelessChangeDetection(), provideRouter(routes), provideSp00ky(dbConfig)],
|
|
45
|
+
};
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`config` may be a factory run in the injection context. `preload` is awaited before the first render, best-effort. A failed `init()` fails bootstrap (`bootstrapApplication(...).catch(...)`); put a splash inside `<app-root>` in `index.html`. The client is closed when the app is destroyed. Without `provideSp00ky` (tests, a self-made client): `{ provide: SyncedDb, useValue: db }`.
|
|
49
|
+
|
|
50
|
+
### Angular CLI build settings (required)
|
|
51
|
+
|
|
52
|
+
The Angular CLI (`@angular/build:application`) does not bundle a `new Worker(new URL(...))` inside a dependency and does not copy `.wasm` files referenced via `new URL(..., import.meta.url)`. So the app:
|
|
53
|
+
|
|
54
|
+
1. Installs `@surrealdb/wasm` directly and adds `src/app/sp00ky-surreal.worker.ts` = `import '@surrealdb/wasm/worker';` (and, for `localEngine: 'sqlite'`, `sp00ky-sqlite.worker.ts` = `import '@spooky-sync/core/sqlite-worker';` plus `workers.sqlite`).
|
|
55
|
+
2. Sets `"webWorkerTsConfig": "tsconfig.worker.json"` (lib `webworker`, includes `src/**/*.worker.ts`; exclude those from `tsconfig.app.json`).
|
|
56
|
+
3. Copies to the output root with `assets`: `@spooky-sync/ssp-wasm/pkg/ssp_wasm_bg.wasm`, `@surrealdb/wasm-native/dist/index_bg.wasm`, `@spooky-sync/core/dist/tabs-broker-worker.js`, `@sqlite.org/sqlite-wasm/dist/{sqlite3.wasm,sqlite3-opfs-async-proxy.js}`. With pnpm, hoist the first, second and fourth package via `public-hoist-pattern[]` in `.npmrc`.
|
|
57
|
+
4. Excludes `@spooky-sync/client-angular`, `@spooky-sync/core`, `@spooky-sync/ssp-wasm`, `@surrealdb/wasm`, `@surrealdb/wasm-native`, `@sqlite.org/sqlite-wasm` from the dev server's `prebundle`.
|
|
58
|
+
5. Optionally `"allowedCommonJsDependencies": ["pino"]`.
|
|
59
|
+
|
|
60
|
+
Missing any of these shows as a 404 on `worker-agent.mjs` / a `.wasm` file and an app that never bootstraps (init waits on the worker).
|
|
61
|
+
|
|
62
|
+
## Key API
|
|
63
|
+
|
|
64
|
+
- **`provideSp00ky(config, options?)`**: `EnvironmentProviders`. `options.preload?: (db) => Promise<void>`.
|
|
65
|
+
- **`injectDb<typeof schema>(options?)`**: the `SyncedDb<S>` (same instance as `inject(SyncedDb)`). `create`, `update`, `delete`, `query`, `preload`, `run`, `channel`, `bucket`, `remoteQuery`, `useRemote`, `auth` / `signOut`, `pendingMutationCount`, `syncHealth` / `storageHealth` and their subscribe methods. Throws a readable error without a provider.
|
|
66
|
+
- **`injectQuery(query, options?)`**: live query. `query` is a function (or signal) returning a BUILT query (`.build()`, `.one().build()`) or `null` / `undefined` to skip; a fixed built query can be passed directly. Re-registration keys on the identity hash (surql + vars), not on rebuilds. Result signals:
|
|
67
|
+
- `data`: rows, or the row / `null` for `.one()`. `[]` / `null` before the first result. Structurally shared.
|
|
68
|
+
- `error`: registration / sync failure (e.g. SSP 503 NOT_READY). Never thrown; the scheduler retries.
|
|
69
|
+
- `isLoading`: cold first load only (nothing painted for this identity, server not heard, no error).
|
|
70
|
+
- `isFetching`: a fetch cycle is in flight.
|
|
71
|
+
- `isAuthoritative`: `data` holds the rendered rows of a known membership. Latched until the identity changes.
|
|
72
|
+
- `hasData`: rows for a list, a row for `.one()`.
|
|
73
|
+
- `isEmpty`: authoritative AND no data. Empty states go on this, never on `!hasData()`.
|
|
74
|
+
- `isSettled`: authoritative AND idle. Gate windowed-list end detection and create-if-missing on it. Not monotonic.
|
|
75
|
+
- Options: `enabled?: boolean | Signal<boolean> | (() => boolean)`, `deregisterOnCleanup?: boolean`, `injector?: Injector`.
|
|
76
|
+
- On an identity change the previous `data` stays until the new identity emits (flags reset), so growing `.limit()` never flashes empty.
|
|
77
|
+
- **`injectPreload(query, options?)`**: fire-and-forget prewarm of a likely-next query, keyed on its identity. Options: `enabled?`, `signal?`, `injector?`.
|
|
78
|
+
- **`injectSubmission(fn)`**: `{ submit, pending, error, result, clearError }`. `submit` never rejects. No injection context needed.
|
|
79
|
+
- **`injectPendingMutations(options?)`**: `Signal<number>`.
|
|
80
|
+
- **`injectSyncStatus(options?)`**: `{ health, status, isHealthy, isDegraded, everConnected, isOffline, connection, isReconnecting }`.
|
|
81
|
+
- **`injectSyncActivity(options?)`**: `{ fetchingQueries, pendingMutations, isDownloading, isUploading }`, debounced on (`downloadDelayMs` 200, `uploadDelayMs` 150, `uploadThreshold` 0), off at once.
|
|
82
|
+
- **`injectStorageStatus(options?)`**: `{ health, status, isPersistent, isMemoryFallback }`.
|
|
83
|
+
- **`injectImpersonation({ rendersBanner?, injector? })`**: `{ impersonation, isImpersonating, stop }`.
|
|
84
|
+
- **`injectFeatureFlag(key, { fallback?, ttl?, injector? })`**: `{ variant, payload, enabled }`. The handle closes with the context.
|
|
85
|
+
- **`injectAppRelease({ app, currentVersion, ttl?, injector? })`**: `{ latestVersion, updateAvailable, mandatory, cacheBust, reload }`.
|
|
86
|
+
- **`injectCrdtField(table, recordId, field, options?)`**: `Signal<CrdtField | null>`, `null` until loaded. `recordId` is a signal, function or value.
|
|
87
|
+
- **`injectChannel(query, peers, options?)`** (experimental): WebRTC channel for the context's lifetime for the rows `query` matches (a builder, built query, or list, on a `-- @channel` table; only its `where` counts; `null` closes it). Both arguments may be signals / functions, compared by value. Returns `{ status, peers, update, create, delete }` (status / peers are signals). See `/docs/client/channels`.
|
|
88
|
+
- **Files**: `injectFileUpload(bucket, options?)` (`{ upload, download, remove, exists, isUploading, error, clearError }`, validates `maxSize` / `allowedExtensions`), `injectDownloadFile(bucket, path, options?)` (`{ url, isLoading, error, refetch }`, refcounted shared object URL, OPFS-persisted by default, previous URL kept until the next is ready), `injectBlurhash(bucket, path, options?)`, `injectBucketImage(bucket, path, options?)` (adds `blurhash`, `ready` and `gate`). `bucket` and `path` may be signals. Name the schema for typed bucket names: `injectFileUpload<typeof schema>('avatars')`.
|
|
89
|
+
- **Components / directives** (standalone, import them in `imports`): `<sp00ky-bucket-image bucket path alt imgClass fit transition easing blurhash options>` (projected content = placeholder plate; host is the container), `<canvas [sp00kyBlurhash]="hash" [blurhashWidth] [blurhashHeight] [blurhashPunch]>` (`Blurhash`), `<img [sp00kyImageGate]="image">` (`ImageGate`; sets `src`, flips `image.ready()` on decode; do not bind `src` too).
|
|
90
|
+
- **`share(prev, next)`**, **`sameValue(a, b)`**: the pure helpers above, exported for tests and custom stores.
|
|
91
|
+
|
|
92
|
+
## Mutations
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
await this.db.create('post:' + crypto.randomUUID(), { title: 'Hi' });
|
|
96
|
+
await this.db.update('post', 'post:xyz', { title: 'Edited' });
|
|
97
|
+
await this.db.delete('post', row.id); // a row's RecordId works directly
|
|
98
|
+
await this.db.run('backend', 'sendMail', { to });
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
Track a backend job by querying its outbox row: `injectQuery(() => this.db.query('job_outbox').where({ id: this.jobId() }).one().build())`.
|
|
102
|
+
|
|
103
|
+
## Common gotchas
|
|
104
|
+
|
|
105
|
+
- **Queries need `.build()`** (or `.one().build()`). A bare `db.query('post')` is a builder.
|
|
106
|
+
- **Pass a function**, not a value, when the query depends on inputs or signals; `injectQuery(this.db.query('post').where({ id: this.id() }).build())` reads `id` once (and a required input throws NG0950 in a field initializer).
|
|
107
|
+
- **Call the signals**: `posts.data()`, not `posts.data`.
|
|
108
|
+
- **Injection context**: call `inject*` in field initializers or the constructor, not in `ngOnInit`, event handlers or after `await` (or pass `{ injector }`).
|
|
109
|
+
- **Field order**: declare `private readonly db = injectDb()` before the fields whose query functions use `this.db`.
|
|
110
|
+
- **No suspense / resource mode.** Branch on `isLoading()` / `isEmpty()`.
|
|
111
|
+
- **Angular CLI build settings** (worker entry, assets, prebundle) are required; see above.
|
|
112
|
+
- **SSR**: engine-backed components inside `@defer` or on `RenderMode.Client` routes.
|
|
113
|
+
- **`track post.id`** works: row ids are `RecordId` instances with stable identity per row under structural sharing.
|
|
114
|
+
|
|
115
|
+
## Pointers
|
|
116
|
+
|
|
117
|
+
- Walkthrough: `QUICK_START.md` (same content as the docs' [Angular guide](https://mono424.github.io/sp00ky/docs/guide/angular))
|
|
118
|
+
- Skill for coding agents: `skills/sp00ky-angular/SKILL.md`
|
|
119
|
+
- Sync engine: `node_modules/@spooky-sync/core/AGENTS.md`
|
|
120
|
+
- Query builder DSL: `node_modules/@spooky-sync/query-builder/AGENTS.md`
|
package/QUICK_START.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# Quick start: Sp00ky with Angular
|
|
2
|
+
|
|
3
|
+
The same content as the docs' [Angular guide](https://mono424.github.io/sp00ky/docs/guide/angular).
|
|
4
|
+
|
|
5
|
+
## 1. Install
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pnpm add @spooky-sync/core @spooky-sync/client-angular @surrealdb/wasm
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
With pnpm, hoist the packages whose `.wasm` files the build copies (step 2), so their paths exist:
|
|
12
|
+
|
|
13
|
+
```ini
|
|
14
|
+
# .npmrc
|
|
15
|
+
public-hoist-pattern[]=@spooky-sync/ssp-wasm
|
|
16
|
+
public-hoist-pattern[]=@surrealdb/wasm-native
|
|
17
|
+
public-hoist-pattern[]=@sqlite.org/sqlite-wasm
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## 2. Configure the Angular CLI
|
|
21
|
+
|
|
22
|
+
The core client starts web workers and loads `.wasm` files relative to its own modules. The Angular
|
|
23
|
+
CLI's builder does not bundle a worker started inside a dependency, and does not copy a `.wasm`
|
|
24
|
+
file a dependency references, so the app does both.
|
|
25
|
+
|
|
26
|
+
A worker entry for the local database engine:
|
|
27
|
+
|
|
28
|
+
```ts
|
|
29
|
+
// src/app/sp00ky-surreal.worker.ts
|
|
30
|
+
import '@surrealdb/wasm/worker';
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
Using `localEngine: 'sqlite'`? Add a second one, `src/app/sp00ky-sqlite.worker.ts`, containing
|
|
34
|
+
`import '@spooky-sync/core/sqlite-worker';`.
|
|
35
|
+
|
|
36
|
+
A TypeScript config for workers (exclude `src/**/*.worker.ts` from `tsconfig.app.json`):
|
|
37
|
+
|
|
38
|
+
```json
|
|
39
|
+
// tsconfig.worker.json
|
|
40
|
+
{
|
|
41
|
+
"extends": "./tsconfig.json",
|
|
42
|
+
"compilerOptions": { "outDir": "./out-tsc/worker", "lib": ["es2022", "webworker"], "types": [] },
|
|
43
|
+
"include": ["src/**/*.worker.ts"]
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`angular.json`, under `projects.<app>.architect`:
|
|
48
|
+
|
|
49
|
+
```json
|
|
50
|
+
"build": {
|
|
51
|
+
"builder": "@angular/build:application",
|
|
52
|
+
"options": {
|
|
53
|
+
"webWorkerTsConfig": "tsconfig.worker.json",
|
|
54
|
+
"allowedCommonJsDependencies": ["pino"],
|
|
55
|
+
"assets": [
|
|
56
|
+
{ "glob": "**/*", "input": "public" },
|
|
57
|
+
{ "glob": "ssp_wasm_bg.wasm", "input": "node_modules/@spooky-sync/ssp-wasm/pkg", "output": "/" },
|
|
58
|
+
{ "glob": "index_bg.wasm", "input": "node_modules/@surrealdb/wasm-native/dist", "output": "/" },
|
|
59
|
+
{ "glob": "tabs-broker-worker.js", "input": "node_modules/@spooky-sync/core/dist", "output": "/" },
|
|
60
|
+
{ "glob": "{sqlite3.wasm,sqlite3-opfs-async-proxy.js}", "input": "node_modules/@sqlite.org/sqlite-wasm/dist", "output": "/" }
|
|
61
|
+
]
|
|
62
|
+
}
|
|
63
|
+
},
|
|
64
|
+
"serve": {
|
|
65
|
+
"builder": "@angular/build:dev-server",
|
|
66
|
+
"options": {
|
|
67
|
+
"prebundle": {
|
|
68
|
+
"exclude": [
|
|
69
|
+
"@spooky-sync/client-angular", "@spooky-sync/core", "@spooky-sync/ssp-wasm",
|
|
70
|
+
"@surrealdb/wasm", "@surrealdb/wasm-native", "@sqlite.org/sqlite-wasm"
|
|
71
|
+
]
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Pre-bundled by the dev server, those packages look for their `.wasm` files in the wrong folder.
|
|
78
|
+
|
|
79
|
+
## 3. Generate types
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
spky generate
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
## 4. Configure the client
|
|
86
|
+
|
|
87
|
+
```ts
|
|
88
|
+
// src/app/db.ts
|
|
89
|
+
import type { SyncedDbConfig } from '@spooky-sync/client-angular';
|
|
90
|
+
import { schema, SURQL_SCHEMA } from './schema.gen';
|
|
91
|
+
|
|
92
|
+
export const dbConfig: SyncedDbConfig<typeof schema> = {
|
|
93
|
+
logLevel: 'info',
|
|
94
|
+
schema,
|
|
95
|
+
schemaSurql: SURQL_SCHEMA,
|
|
96
|
+
database: {
|
|
97
|
+
namespace: 'main',
|
|
98
|
+
database: 'main',
|
|
99
|
+
endpoint: 'ws://localhost:8666/rpc',
|
|
100
|
+
store: 'indexeddb',
|
|
101
|
+
workers: {
|
|
102
|
+
surreal: () =>
|
|
103
|
+
new Worker(new URL('./sp00ky-surreal.worker', import.meta.url), { type: 'module' }),
|
|
104
|
+
// localEngine: 'sqlite' only:
|
|
105
|
+
// sqlite: () => new Worker(new URL('./sp00ky-sqlite.worker', import.meta.url), { type: 'module' }),
|
|
106
|
+
},
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## 5. Provide the client
|
|
112
|
+
|
|
113
|
+
```ts
|
|
114
|
+
// src/app/app.config.ts
|
|
115
|
+
export const appConfig: ApplicationConfig = {
|
|
116
|
+
providers: [
|
|
117
|
+
provideBrowserGlobalErrorListeners(),
|
|
118
|
+
provideZonelessChangeDetection(),
|
|
119
|
+
provideRouter(routes),
|
|
120
|
+
provideSp00ky(dbConfig, {
|
|
121
|
+
preload: (db) => db.preload(db.query('config').build()), // optional, best-effort
|
|
122
|
+
}),
|
|
123
|
+
],
|
|
124
|
+
};
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
The client starts in an app initializer; the app renders once it is ready, and the root element
|
|
128
|
+
of `index.html` keeps its content until then (`<app-root>Initializing…</app-root>`). If it cannot
|
|
129
|
+
start, bootstrap fails: handle it on `bootstrapApplication(...).catch(...)`.
|
|
130
|
+
|
|
131
|
+
## 6. Query
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
@Component({
|
|
135
|
+
selector: 'app-post-list',
|
|
136
|
+
templateUrl: './post-list.html',
|
|
137
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
138
|
+
})
|
|
139
|
+
export class PostList {
|
|
140
|
+
private readonly db = injectDb<typeof schema>();
|
|
141
|
+
readonly authorId = input<string | null>(null);
|
|
142
|
+
|
|
143
|
+
protected readonly posts = injectQuery(() => {
|
|
144
|
+
const author = this.authorId();
|
|
145
|
+
return author
|
|
146
|
+
? this.db.query('post').where({ author }).orderBy('created_at', 'desc').limit(20).build()
|
|
147
|
+
: null; // skip until the input exists
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
```html
|
|
153
|
+
@if (posts.isLoading()) {
|
|
154
|
+
<p>Loading…</p>
|
|
155
|
+
} @else if (posts.isEmpty()) {
|
|
156
|
+
<p>No posts yet.</p>
|
|
157
|
+
} @else { @for (post of posts.data(); track post.id) { <app-post-row [post]="post" /> } }
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
Result signals: `data`, `error`, `isLoading` (cold first load only), `isFetching`,
|
|
161
|
+
`isAuthoritative`, `hasData`, `isEmpty` (server said "no rows"), `isSettled` (authoritative and
|
|
162
|
+
idle). Options: `{ enabled?, deregisterOnCleanup?, injector? }`. `injectPreload(() => query)` warms
|
|
163
|
+
the cache for a likely-next screen.
|
|
164
|
+
|
|
165
|
+
## 7. Mutate
|
|
166
|
+
|
|
167
|
+
```ts
|
|
168
|
+
await this.db.create('post:' + crypto.randomUUID(), { title });
|
|
169
|
+
await this.db.update('post', id, { title });
|
|
170
|
+
await this.db.delete('post', row.id);
|
|
171
|
+
await this.db.run('backend', 'sendMail', { to });
|
|
172
|
+
|
|
173
|
+
protected readonly save = injectSubmission((title: string) =>
|
|
174
|
+
this.db.create('post:' + crypto.randomUUID(), { title })
|
|
175
|
+
);
|
|
176
|
+
// <button [disabled]="save.pending()" (click)="save.submit(title())">Save</button>
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
## 8. Status, files, realtime
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
readonly sync = injectSyncStatus(); // sync.isDegraded(), sync.isOffline()
|
|
183
|
+
readonly pending = injectPendingMutations(); // pending()
|
|
184
|
+
readonly flag = injectFeatureFlag('new-checkout'); // flag.enabled()
|
|
185
|
+
readonly body = injectCrdtField('post', this.postId, 'body'); // body()?.getDoc()
|
|
186
|
+
readonly files = injectFileUpload('avatars'); // files.upload(path, file)
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
```html
|
|
190
|
+
<sp00ky-bucket-image bucket="avatars" [path]="avatar()" class="h-12 w-12 rounded-full">
|
|
191
|
+
<div class="h-full w-full bg-neutral-200"></div>
|
|
192
|
+
</sp00ky-bucket-image>
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
## Server-side rendering
|
|
196
|
+
|
|
197
|
+
During a server render `provideSp00ky` never starts the client and the engine-backed `inject*`
|
|
198
|
+
functions throw. Wrap sp00ky-backed components in `@defer { ... } @placeholder { ... }`, or give
|
|
199
|
+
their routes `renderMode: RenderMode.Client`.
|
package/README.md
CHANGED
|
@@ -1,3 +1,79 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spooky-sync/client-angular
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Angular bindings for the Sp00ky reactive local-first SurrealDB framework, built on signals. Needs
|
|
4
|
+
Angular 21 or newer; zoneless and zone.js apps both work. Browser only: the core client runs its
|
|
5
|
+
engines as WebAssembly in web workers with IndexedDB / OPFS storage, so during a server render the
|
|
6
|
+
client is never started (render sp00ky-backed components in `@defer` or on `RenderMode.Client`
|
|
7
|
+
routes).
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pnpm add @spooky-sync/core @spooky-sync/client-angular @surrealdb/wasm
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
```ts
|
|
14
|
+
// app.config.ts
|
|
15
|
+
export const appConfig: ApplicationConfig = {
|
|
16
|
+
providers: [provideZonelessChangeDetection(), provideSp00ky(dbConfig)],
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
// post-list.ts
|
|
20
|
+
@Component({
|
|
21
|
+
selector: 'app-post-list',
|
|
22
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
23
|
+
templateUrl: './post-list.html',
|
|
24
|
+
})
|
|
25
|
+
export class PostList {
|
|
26
|
+
private readonly db = injectDb<typeof schema>();
|
|
27
|
+
protected readonly posts = injectQuery(() =>
|
|
28
|
+
this.db.query('post').orderBy('created_at', 'desc').limit(20).build()
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
```html
|
|
34
|
+
<!-- post-list.html -->
|
|
35
|
+
@if (posts.isLoading()) {
|
|
36
|
+
<p>Loading…</p>
|
|
37
|
+
} @else if (posts.isEmpty()) {
|
|
38
|
+
<p>No posts yet.</p>
|
|
39
|
+
} @else { @for (post of posts.data(); track post.id) {
|
|
40
|
+
<p>{{ post.title }}</p>
|
|
41
|
+
} }
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
What "native" means here:
|
|
45
|
+
|
|
46
|
+
- Signals, no RxJS. Every result field is a read-only `Signal` (`posts.data()`,
|
|
47
|
+
`posts.isLoading()`); inputs that follow state are signals or functions
|
|
48
|
+
(`() => this.db.query(...).build()`, an `input()`).
|
|
49
|
+
- `provideSp00ky(config)` is an environment provider: it starts the client in an app initializer,
|
|
50
|
+
so the app renders once the client is ready. `SyncedDb` is the DI token (`injectDb()`,
|
|
51
|
+
`inject(SyncedDb)`).
|
|
52
|
+
- `inject*` functions run in an injection context and end with it through `DestroyRef`; each takes
|
|
53
|
+
`{ injector }` to run anywhere else. Status functions need no component, so they also live in
|
|
54
|
+
`providedIn: 'root'` services.
|
|
55
|
+
- `injectQuery` structurally shares each live emission with the previous one: rows matched by `id`
|
|
56
|
+
keep their object identity, and a deep-equal emission does not notify.
|
|
57
|
+
- `<sp00ky-bucket-image>`, `canvas[sp00kyBlurhash]` and `img[sp00kyImageGate]` are standalone,
|
|
58
|
+
`OnPush`, signal-input components / directives doing their DOM work in `afterRenderEffect`.
|
|
59
|
+
- Mutations stay plain `await db.create(...)` calls: the engine is already optimistic local-first.
|
|
60
|
+
`injectSubmission` only adds button pending and error state.
|
|
61
|
+
|
|
62
|
+
The query flags (`isLoading`, `isFetching`, `isAuthoritative`, `hasData`, `isEmpty`, `isSettled`)
|
|
63
|
+
follow the same contract as `@spooky-sync/client-react`, `client-svelte` and `client-solid2`.
|
|
64
|
+
|
|
65
|
+
**Angular CLI apps need a few build settings**: the CLI does not bundle a worker started inside a
|
|
66
|
+
dependency, nor copy the `.wasm` files a dependency references. The app bundles a one-line worker
|
|
67
|
+
entry (`import '@surrealdb/wasm/worker';`) and hands it to the client through
|
|
68
|
+
`database.workers.surreal`, copies four `.wasm` / worker files with `assets`, and excludes the
|
|
69
|
+
client's packages from the dev server's `prebundle`. `QUICK_START.md` has every line.
|
|
70
|
+
|
|
71
|
+
The package is built with ng-packagr (Angular Package Format, partial compilation). See
|
|
72
|
+
`QUICK_START.md` for a walkthrough, `AGENTS.md` for the full API, and the
|
|
73
|
+
[Angular guide](https://mono424.github.io/sp00ky/docs/guide/angular).
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
pnpm --filter @spooky-sync/client-angular test # builds, then runs vitest on the build
|
|
77
|
+
pnpm --filter @spooky-sync/client-angular type-check # ngc strict templates + test types
|
|
78
|
+
pnpm --filter @spooky-sync/client-angular build # ng-packagr -> dist/ (published from there)
|
|
79
|
+
```
|