@gusto/create-baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-LICENSES.txt +204 -0
- package/dist/index.js +1537 -145
- package/dist/index.js.map +1 -1
- package/dist/templates/addons/docker/Dockerfile +13 -11
- package/dist/templates/minimal-cloudflare/AGENTS.md +77 -399
- package/dist/templates/minimal-cloudflare/README.md +33 -97
- package/dist/templates/minimal-cloudflare/package.json +12 -9
- package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +13 -7
- package/dist/templates/minimal-cloudflare/tsconfig.app.json +2 -3
- package/dist/templates/minimal-cloudflare/tsconfig.worker.json +2 -3
- package/dist/templates/minimal-cloudflare/vitest.config.ts +1 -1
- package/dist/templates/minimal-cloudflare/wrangler.jsonc +4 -2
- package/dist/templates/minimal-node/AGENTS.md +80 -380
- package/dist/templates/minimal-node/README.md +37 -135
- package/dist/templates/minimal-node/package.json +11 -9
- package/dist/templates/minimal-node/pnpm-workspace.yaml +14 -9
- package/dist/templates/minimal-node/tsconfig.app.json +2 -3
- package/dist/templates/minimal-node/tsconfig.server.json +2 -3
- package/dist/templates/react-cloudflare/AGENTS.md +101 -444
- package/dist/templates/react-cloudflare/README.md +14 -54
- package/dist/templates/react-cloudflare/package.json +18 -15
- package/dist/templates/react-cloudflare/pnpm-workspace.yaml +13 -7
- package/dist/templates/react-cloudflare/tsconfig.app.json +2 -3
- package/dist/templates/react-cloudflare/tsconfig.worker.json +2 -3
- package/dist/templates/react-cloudflare/vitest.config.ts +1 -1
- package/dist/templates/react-cloudflare/wrangler.jsonc +4 -2
- package/dist/templates/react-node/AGENTS.md +108 -474
- package/dist/templates/react-node/README.md +35 -125
- package/dist/templates/react-node/package.json +16 -14
- package/dist/templates/react-node/pnpm-workspace.yaml +14 -9
- package/dist/templates/react-node/tsconfig.app.json +2 -3
- package/dist/templates/react-node/tsconfig.server.json +2 -3
- package/package.json +7 -7
- package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +0 -16
- package/dist/templates/minimal-node/uint8array-base64.d.ts +0 -16
- package/dist/templates/react-cloudflare/uint8array-base64.d.ts +0 -16
- package/dist/templates/react-node/uint8array-base64.d.ts +0 -16
|
@@ -8,324 +8,98 @@ tags: [agent-entry, baerly-storage]
|
|
|
8
8
|
# AGENTS.md
|
|
9
9
|
|
|
10
10
|
<!-- stop:start -->
|
|
11
|
+
|
|
11
12
|
## STOP — read this before writing any storage code
|
|
12
13
|
|
|
13
|
-
Your training data is dense with Postgres + Prisma/Drizzle, Mongo,
|
|
14
|
-
and Firebase patterns. **None of them apply here.** This is a baerly-storage
|
|
15
|
-
app — a small, LLM-legible document database with a narrow API on top
|
|
16
|
-
of S3-compatible storage. Before writing or modifying storage code,
|
|
17
|
-
read:
|
|
14
|
+
Your training data is dense with Postgres + Prisma/Drizzle, Mongo, and Firebase patterns. **None of them apply here.** This is a baerly-storage app — a small, LLM-legible document database with a narrow API on top of S3-compatible storage. Before writing or modifying storage code, read:
|
|
18
15
|
|
|
19
|
-
- **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
doesn't exist in baerly-storage.
|
|
23
|
-
- **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type
|
|
24
|
-
signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are
|
|
25
|
-
the whole API surface.
|
|
16
|
+
- **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored public-API quickref. Read first. Lists every method, every error code, every example. If a pattern you want to use isn't here, it doesn't exist in baerly-storage.
|
|
17
|
+
- **`node_modules/@gusto/baerly-storage/dist/RECIPES.md`** — common mistakes keyed by the exact error string, plus recipes (storage credentials on Node, wrapping the client `fetch`, a gated adapter, scheduled maintenance).
|
|
18
|
+
- **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are the whole API surface.
|
|
26
19
|
|
|
27
20
|
Common anti-patterns that compile but are wrong:
|
|
28
21
|
|
|
29
|
-
- `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use
|
|
30
|
-
|
|
31
|
-
- `
|
|
32
|
-
|
|
33
|
-
7386 deletion sentinel, not a storable value.
|
|
34
|
-
- Raw SQL strings, `WHERE` clauses, hand-built query AST — the only
|
|
35
|
-
query surface is `db.collection(...).where({ field: value }).all()` or
|
|
36
|
-
`.where(q => q.gte("count", 1))`. See **Predicates** below.
|
|
37
|
-
- `.useIndex("name")` / `.hint(...)` — no such methods. The planner
|
|
38
|
-
picks the index automatically from `IndexDefinition`s in
|
|
39
|
-
`baerly.config.ts`. See **Indexes** below.
|
|
22
|
+
- `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use `db.collection(name).insert(row)` and `.where({ ... }).all()`.
|
|
23
|
+
- `z.string().nullable()` in a schema — `DocumentValue` excludes `null`. Use `.optional()`; `null` in an update patch is the RFC 7386 deletion sentinel, not a storable value.
|
|
24
|
+
- Raw SQL strings, `WHERE` clauses, hand-built query AST — the only query surface is `db.collection(...).where({ field: value }).all()` or `.where(q => q.gte("count", 1))`. See the Predicates section of API.md.
|
|
25
|
+
- `.useIndex("name")` / `.hint(...)` — no such methods. Declared indexes do not change how a read runs. See the `defineConfig` section of API.md.
|
|
40
26
|
|
|
41
27
|
<!-- stop:end -->
|
|
28
|
+
|
|
42
29
|
## What this is
|
|
43
30
|
|
|
44
|
-
`react-cloudflare` is a baerly-storage app scaffolded with
|
|
45
|
-
`create-baerly-storage`. The Worker-side server lives in `src/server/`;
|
|
46
|
-
the React client lives in `src/web/`. Configuration lives in
|
|
47
|
-
`baerly.config.ts`.
|
|
31
|
+
`react-cloudflare` is a baerly-storage app scaffolded with `create-baerly-storage`. The Worker-side server lives in `src/server/`; the React client lives in `src/web/`. Configuration lives in `baerly.config.ts`.
|
|
48
32
|
|
|
49
|
-
Single package, single `vite` process: `@cloudflare/vite-plugin` runs
|
|
50
|
-
the Worker inside `workerd` alongside the SPA dev server, and
|
|
51
|
-
`wrangler.jsonc:assets` ships the built `dist/client/` bundle next to
|
|
52
|
-
the Worker on deploy. Same origin in dev and prod, one deploy.
|
|
33
|
+
Single package, single `vite` process: `@cloudflare/vite-plugin` runs the Worker inside `workerd` alongside the SPA dev server, and `wrangler.jsonc:assets` ships the built `dist/client/` bundle next to the Worker on deploy. Same origin in dev and prod, one deploy.
|
|
53
34
|
|
|
54
|
-
This starter is a generic notes app you extend with your own fields —
|
|
55
|
-
a Cloudflare Worker wired to R2 plus a working React+Vite frontend in
|
|
56
|
-
`src/web/` (served by the Worker via Workers Assets) with the `Note`
|
|
57
|
-
shape declared in `baerly.config.ts`. The bare server-only version is
|
|
58
|
-
`pnpm create @gusto/baerly-storage <app> --target=cloudflare`; this one is
|
|
59
|
-
`--target=cloudflare --starter=react`.
|
|
35
|
+
This starter is a generic notes app you extend with your own fields — a Cloudflare Worker wired to R2 plus a working React+Vite frontend in `src/web/` (served by the Worker via Workers Assets) with the `Note` shape declared in `baerly.config.ts`. The bare server-only version is `pnpm create @gusto/baerly-storage <app> --target=cloudflare`; this one is `--target=cloudflare --starter=react`.
|
|
60
36
|
|
|
61
|
-
Public API docs: the JSDoc on `baerly-storage`'s `Db` and `Collection`
|
|
62
|
-
is the canonical reference; read it via your editor's TS LS, the
|
|
63
|
-
published types, or `node_modules/@gusto/baerly-storage/dist/API.md`.
|
|
37
|
+
Public API docs: the JSDoc on `baerly-storage`'s `Db` and `Collection` is the canonical reference; read it via your editor's TS LS, the published types, or `node_modules/@gusto/baerly-storage/dist/API.md`.
|
|
64
38
|
|
|
65
39
|
## Toolchain
|
|
66
40
|
|
|
67
|
-
- **Package manager:** pnpm. The emitted repo pins
|
|
68
|
-
`packageManager: pnpm@11.1.2`.
|
|
41
|
+
- **Package manager:** pnpm. The emitted repo pins `packageManager: pnpm@12.22.0`.
|
|
69
42
|
- **Test runner:** vitest.
|
|
70
|
-
- **Type checker:** TypeScript
|
|
71
|
-
|
|
72
|
-
`@typescript/native-preview`.)
|
|
73
|
-
- **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
|
|
74
|
-
code stays compatible with type-stripping runtimes (Node's
|
|
75
|
-
`--experimental-strip-types`, esbuild's strip path). The flag bans
|
|
76
|
-
TS constructs that can't be type-erased: write
|
|
77
|
-
`class { x: T; constructor(x: T) { this.x = x } }` explicitly
|
|
78
|
-
instead of parameter-property shorthand
|
|
79
|
-
(`constructor(private x: T) {}` fails with TS1294). The same goes
|
|
80
|
-
for `enum`, namespaces with non-type bindings, and `private` /
|
|
81
|
-
`protected` / `public` accessibility modifiers on constructor
|
|
82
|
-
parameters.
|
|
43
|
+
- **Type checker:** TypeScript 7, as pinned in `package.json`.
|
|
44
|
+
- **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the code stays compatible with type-stripping runtimes (Node's built-in type stripping, esbuild's strip path). The flag bans TS constructs that can't be type-erased: write `class { x: T; constructor(x: T) { this.x = x } }` explicitly instead of parameter-property shorthand (`constructor(private x: T) {}` fails with TS1294). The same goes for `enum`, namespaces with non-type bindings, and `private` / `protected` / `public` accessibility modifiers on constructor parameters.
|
|
83
45
|
|
|
84
46
|
## Verification
|
|
85
47
|
|
|
86
|
-
| Command
|
|
87
|
-
|
|
|
88
|
-
| `pnpm install`
|
|
89
|
-
| `pnpm verify`
|
|
90
|
-
| `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`)
|
|
91
|
-
| `pnpm test`
|
|
92
|
-
| `pnpm dev`
|
|
93
|
-
| `pnpm build`
|
|
94
|
-
| `pnpm deploy`
|
|
95
|
-
|
|
96
|
-
**`pnpm verify` exercises typecheck + tests only.** The dev-auth
|
|
97
|
-
middleware, the SPA bundle, and any custom `/api/*` route are NOT
|
|
98
|
-
under test — verify will exit green even when the dev plugin returns
|
|
99
|
-
401 on every browser request or the SPA throws on mount. For changes
|
|
100
|
-
that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
|
|
101
|
-
`pnpm dev` and exercise the change in a browser (or `curl
|
|
102
|
-
http://localhost:5173/<path>`) before declaring the task complete.
|
|
103
|
-
|
|
104
|
-
## Where the code is
|
|
105
|
-
|
|
106
|
-
| Path | What it is |
|
|
107
|
-
| -------------------------- | ---------------------------------------------------------------------------------------------------------------- |
|
|
108
|
-
| `src/server/index.ts` | Server entry — `/v1/*` routing + SPA fallback via `env.ASSETS` |
|
|
109
|
-
| `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, Assets binding, vars |
|
|
110
|
-
| `src/web/` | React+Vite frontend. Served by the Worker via Workers Assets in production. |
|
|
111
|
-
| `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.tsx`. |
|
|
112
|
-
| `vite.config.ts` | Vite + `@vitejs/plugin-react` + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
|
|
113
|
-
| `tsconfig.json` | Root project-references stub |
|
|
114
|
-
| `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib, `jsx: react-jsx`) |
|
|
115
|
-
| `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
|
|
116
|
-
| `baerly.config.ts` | App config — `app`, `tenant`, `target`, `collections` (schemas live here). Also exports the inferred `Note` row type used by the web client. |
|
|
117
|
-
|
|
118
|
-
> **`baerly.config.ts` is dual-included.** Both `tsconfig.app.json`
|
|
119
|
-
> and `tsconfig.worker.json` `include` this file, so it must only
|
|
120
|
-
> import from `baerly-storage`, `zod`, and other files reachable
|
|
121
|
-
> from **both** projects. Paths under `src/server/` are worker-only;
|
|
122
|
-
> importing them here triggers `TS6307: File … is not listed within
|
|
123
|
-
> the file list of project … tsconfig.app.json`. Put document
|
|
124
|
-
> interfaces here next to their schema (`export type Note =
|
|
125
|
-
> z.infer<typeof NoteSchema>`); re-export from a server-only file if
|
|
126
|
-
> downstream code wants a local name.
|
|
48
|
+
| Command | What it does | Runtime |
|
|
49
|
+
| --- | --- | --- |
|
|
50
|
+
| `pnpm install` | One-time bootstrap — the scaffold ships without `node_modules/`, so `pnpm verify` / `pnpm dev` fail with `Cannot find package '…'` until this runs once | seconds to a minute |
|
|
51
|
+
| `pnpm verify` | `pnpm run typecheck && pnpm run test` — the green-light gate; what an agent should run as the smoke check before claiming the change works | seconds |
|
|
52
|
+
| `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`) | seconds |
|
|
53
|
+
| `pnpm test` | `vitest run` — standalone `vitest.config.ts` (Node env, ignores `vite.config.ts` so the Cloudflare plugin doesn't load) | seconds |
|
|
54
|
+
| `pnpm dev` | Run `vite` — the Cloudflare plugin runs the Worker inside `workerd` next to the SPA dev server; same origin on :5173 | seconds to start |
|
|
55
|
+
| `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the Workers Assets binding | seconds |
|
|
56
|
+
| `pnpm deploy` | `wrangler deploy` — ships Worker + assets in one shipment (Wrangler auto-creates the declared R2 bucket on first run) | seconds |
|
|
127
57
|
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
- **Typed collections** — two ways to get a typed row, in DX order.
|
|
131
|
-
The generic on `client.collection<N>(name)` is the collection
|
|
132
|
-
**name** (constrained to `CollectionNames<typeof config>`), not the
|
|
133
|
-
row type — so don't pass a row type to it.
|
|
134
|
-
1. **Bind the config.** This template's `src/web/client.ts`
|
|
135
|
-
already passes `config` to `createBaerlyClient({ baseUrl,
|
|
136
|
-
config })`, so `client.collection("notes")` returns
|
|
137
|
-
`ClientCollection<Row>` with `Row` derived from the
|
|
138
|
-
`NoteSchema` declared in `baerly.config.ts`. No generic
|
|
139
|
-
needed. When you need to name that row type elsewhere, use
|
|
140
|
-
`RowOf<typeof config, "notes">` (re-exported from
|
|
141
|
-
`@gusto/baerly-storage`) — not a generic on `.collection()`.
|
|
142
|
-
2. **Cast the handle (undeclared collection).** This template's
|
|
143
|
-
`client` is bound to `config`, so its names narrow to the
|
|
144
|
-
declared collections. To reach a collection that isn't in
|
|
145
|
-
`config`, build an unbound client
|
|
146
|
-
(`createBaerlyClient({ baseUrl })` with no `config`) — its names
|
|
147
|
-
widen to `string` and its row defaults to `DocumentData`. Cast at
|
|
148
|
-
the construction site for a narrower shape that still satisfies
|
|
149
|
-
the kernel's `DocumentData` constraint
|
|
150
|
-
(`{ [k: string]: DocumentValue }`):
|
|
151
|
-
```ts
|
|
152
|
-
import { createBaerlyClient, type ClientCollection } from "@gusto/baerly-storage/client";
|
|
153
|
-
import type { DocumentData } from "@gusto/baerly-storage";
|
|
154
|
-
interface Bookmark extends DocumentData { _id: string; url: string }
|
|
155
|
-
const raw = createBaerlyClient({ baseUrl: "" });
|
|
156
|
-
const bookmarks = raw.collection("bookmarks") as ClientCollection<Bookmark>;
|
|
157
|
-
await bookmarks.all();
|
|
158
|
-
```
|
|
159
|
-
A plain `interface Bookmark { _id: string; url: string }`
|
|
160
|
-
(no index signature) will fail with TS2344 — the constraint
|
|
161
|
-
is intentional so the row stays JSON-compatible.
|
|
162
|
-
|
|
163
|
-
- **Writing tests** — the kernel exports `MemoryStorage`, an
|
|
164
|
-
in-memory `Storage` impl that's the canonical backend for unit
|
|
165
|
-
tests. Don't roll your own — `Db.create({ storage, app, tenant,
|
|
166
|
-
config })` is the same boilerplate prod uses; passing
|
|
167
|
-
`new MemoryStorage()` swaps R2 / S3 for an in-process map.
|
|
168
|
-
|
|
169
|
-
```ts
|
|
170
|
-
// src/notes.test.ts
|
|
171
|
-
import { test, expect } from "vitest";
|
|
172
|
-
import { Db, MemoryStorage } from "@gusto/baerly-storage";
|
|
173
|
-
import config from "../baerly.config.ts";
|
|
174
|
-
|
|
175
|
-
test("notes round-trip", async () => {
|
|
176
|
-
const db = Db.create({
|
|
177
|
-
storage: new MemoryStorage(),
|
|
178
|
-
app: "test",
|
|
179
|
-
tenant: "t",
|
|
180
|
-
config,
|
|
181
|
-
});
|
|
182
|
-
const { _id } = await db.collection("notes").insert({ body: "hello" });
|
|
183
|
-
const row = await db.collection("notes").get(_id);
|
|
184
|
-
expect(row?.body).toBe("hello");
|
|
185
|
-
});
|
|
186
|
-
```
|
|
58
|
+
**`pnpm verify` exercises typecheck + tests only.** The dev-auth middleware, the SPA bundle, and any custom `/api/*` route are NOT under test — verify will exit green even when the dev plugin returns 401 on every browser request or the SPA throws on mount. For changes that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run `pnpm dev` and exercise the change in a browser (or `curl http://localhost:5173/<path>`) before declaring the task complete.
|
|
187
59
|
|
|
188
|
-
|
|
189
|
-
across tests. For multi-writer scenarios (causal-consistency
|
|
190
|
-
tests, etc.), construct one `MemoryStorage` and pass the same
|
|
191
|
-
instance into multiple `Db.create` calls so they share the
|
|
192
|
-
underlying bucket.
|
|
193
|
-
|
|
194
|
-
- **Predicates** — `db.collection("notes").where({...}).all()`. Two
|
|
195
|
-
shapes:
|
|
196
|
-
|
|
197
|
-
- **Object literal** — equality only (top-level, dotted-path, or
|
|
198
|
-
nested literal sub-predicate). Multi-field is implicit AND.
|
|
199
|
-
- **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
|
|
200
|
-
for the operator vocabulary. The methods on `PredicateBuilder<T>`
|
|
201
|
-
ARE the supported surface — `q.or` / `q.regex` / `q.ne` /
|
|
202
|
-
`q.exists` are TS compile errors. Chained `.where(...).where(...)`
|
|
203
|
-
AND-merges across shapes.
|
|
204
|
-
|
|
205
|
-
```ts
|
|
206
|
-
// Top-level equality
|
|
207
|
-
await db.collection("notes").where({ body: "TODO" }).all();
|
|
208
|
-
|
|
209
|
-
// Dotted-path on a nested field
|
|
210
|
-
await db.collection("notes")
|
|
211
|
-
.where({ "meta.source": "import" })
|
|
212
|
-
.all();
|
|
213
|
-
|
|
214
|
-
// Operator on a single field — set membership (callback form)
|
|
215
|
-
await db.collection("notes")
|
|
216
|
-
.where(q => q.in("tag", ["todo", "wip"]))
|
|
217
|
-
.all();
|
|
218
|
-
|
|
219
|
-
// Range — also callback form
|
|
220
|
-
await db.collection("notes")
|
|
221
|
-
.where(q => q.gte("created_at", "2026-01-01"))
|
|
222
|
-
.all();
|
|
223
|
-
|
|
224
|
-
// AND-merge across two .where() calls (mix shapes freely)
|
|
225
|
-
await db.collection("notes")
|
|
226
|
-
.where({ body: "TODO" })
|
|
227
|
-
.where(q => q.gte("priority", 5))
|
|
228
|
-
.all();
|
|
229
|
-
```
|
|
230
|
-
|
|
231
|
-
The plain-equality value type is JSON-arrayless: string / number /
|
|
232
|
-
boolean / nested object. Use `q.in("tag", [...])` for set
|
|
233
|
-
membership when you'd otherwise want `{ tag: ["todo","wip"] }`.
|
|
60
|
+
## Where the code is
|
|
234
61
|
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
62
|
+
| Path | What it is |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `src/server/index.ts` | Server entry — `/v1/*` routing + SPA fallback via `env.ASSETS` |
|
|
65
|
+
| `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, Assets binding, vars |
|
|
66
|
+
| `src/web/` | React+Vite frontend. Served by the Worker via Workers Assets in production. |
|
|
67
|
+
| `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.tsx`. |
|
|
68
|
+
| `vite.config.ts` | Vite + `@vitejs/plugin-react` + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
|
|
69
|
+
| `tsconfig.json` | Root project-references stub |
|
|
70
|
+
| `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib, `jsx: react-jsx`) |
|
|
71
|
+
| `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
|
|
72
|
+
| `baerly.config.ts` | App config — `app`, `tenant`, `target`, `collections` (schemas live here). Also exports the inferred `Note` row type used by the web client. |
|
|
240
73
|
|
|
241
|
-
|
|
242
|
-
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
74
|
+
> **`baerly.config.ts` is dual-included.** Both `tsconfig.app.json` and `tsconfig.worker.json` `include` this file, so it must only import from `baerly-storage`, `zod`, and other files reachable from **both** projects. Paths under `src/server/` are worker-only; importing them here triggers `TS6307: File … is not listed within the file list of project … tsconfig.app.json`. Put document interfaces here next to their schema (`export type Note = z.infer<typeof NoteSchema>`); re-export from a server-only file if downstream code wants a local name.
|
|
243
75
|
|
|
244
|
-
|
|
245
|
-
collections: {
|
|
246
|
-
notes: {
|
|
247
|
-
indexes: [{ name: "by_body", on: "body" }],
|
|
248
|
-
},
|
|
249
|
-
},
|
|
250
|
-
});
|
|
251
|
-
```
|
|
76
|
+
## When editing X, read Y
|
|
252
77
|
|
|
253
|
-
|
|
254
|
-
walks `by_body` automatically. Composite indexes (`on: ["body",
|
|
255
|
-
"tag"]`) match any leftmost prefix. Mismatches (predicate
|
|
256
|
-
doesn't cover any index) fall back to a full table scan with a
|
|
257
|
-
metric bump; correctness is preserved because the reader re-checks
|
|
258
|
-
the predicate in memory regardless of how it got the row set.
|
|
78
|
+
<!-- library:start -->
|
|
259
79
|
|
|
260
|
-
- **
|
|
261
|
-
|
|
262
|
-
`
|
|
263
|
-
|
|
80
|
+
- **Library reference** — the shared API guidance is installed with the package, in `node_modules/@gusto/baerly-storage/dist/`. Read the matching section before editing storage code:
|
|
81
|
+
- **Typed rows** (binding `config`, `RowOf`, casting an undeclared collection): `API.md#documentdata--row-shape-constraint`. A hand-written row type failing `DocumentData`: `RECIPES.md#type-bookmark-does-not-satisfy-the-constraint-documentdata-ts2344`.
|
|
82
|
+
- **Writing tests**: `API.md`, section `Db.create`. `new MemoryStorage()` is a fresh bucket per test; share one instance across `Db.create` calls for multi-writer tests. `src/notes.test.ts` is the working example.
|
|
83
|
+
- **Predicates** (object literal vs callback DSL, operators, by-`_id` verbs): `API.md#predicates`. Set membership is `q.in`, never an array in the object form: `RECIPES.md#baerlyerror-codeinvalidconfig--predicate-value-at--is-an-array`.
|
|
84
|
+
- **Indexes**: don't declare them; a read always folds the whole collection. `API.md`, section `defineConfig`.
|
|
85
|
+
- **Schemas** (StandardSchema validators, `SchemaError`): `API.md`, section `defineConfig`.
|
|
86
|
+
- **HTTP wire format** (calling `/v1/*` directly): `API.md#http-wire-format`.
|
|
87
|
+
- **Verifier presets** (`sharedSecret`, `bearerJwt`, `cloudflareAccess`, `tenantPrefix`): `API.md#verifier-presets`. Refreshing a client token on 401, logging, tracing: `RECIPES.md#recipe--wrapping-the-client-fetch`. Serving `/v1/*` behind your own gate: `RECIPES.md#recipe--authoring-a-gated-adapter`.
|
|
88
|
+
- **Errors by message** (`RECIPES.md`, one entry per error string) and the shared anti-patterns: `RECIPES.md#anti-patterns-compile-clean-but-wrong`.
|
|
264
89
|
|
|
265
|
-
|
|
266
|
-
import { z } from "zod";
|
|
267
|
-
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
90
|
+
<!-- library:end -->
|
|
268
91
|
|
|
269
|
-
|
|
270
|
-
_id: z.string(),
|
|
271
|
-
body: z.string().min(1),
|
|
272
|
-
});
|
|
92
|
+
- **This template** — `src/web/client.ts` binds `config` into `createBaerlyReact` and `src/notes.test.ts` passes it to `Db.create`, so rows are already typed: no generic. For a hot filtered read, maintain a side-projection (see Anti-patterns).
|
|
273
93
|
|
|
274
|
-
|
|
275
|
-
collections: {
|
|
276
|
-
notes: { schema: Note },
|
|
277
|
-
},
|
|
278
|
-
});
|
|
279
|
-
```
|
|
280
|
-
|
|
281
|
-
On a validation failure the server throws
|
|
282
|
-
`BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
|
|
283
|
-
HTTP clients see a 400 with the same envelope. Validation runs
|
|
284
|
-
on the post-image so `update` and `replace` see the full doc, not
|
|
285
|
-
just the patch.
|
|
286
|
-
|
|
287
|
-
- **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
|
|
288
|
-
(`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
|
|
289
|
-
only when debugging the wire. Mutation bodies are wrapped:
|
|
290
|
-
|
|
291
|
-
| Route | Body | Response |
|
|
292
|
-
| --------------------------- | ------------------- | ----------------------------- |
|
|
293
|
-
| `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
|
|
294
|
-
| `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
|
|
295
|
-
| `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
|
|
296
|
-
| `DELETE /v1/c/:collection/:id` | — | `204` |
|
|
297
|
-
|
|
298
|
-
Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
|
|
299
|
-
`GET /v1/since?collection=…&cursor=…`) take no body and return
|
|
300
|
-
`{ data, _meta }` or a route-specific envelope. A flat `POST` body
|
|
301
|
-
(without the `doc` wrapper) returns
|
|
302
|
-
`400 SchemaError "Request body must be { doc: object }"` — the
|
|
303
|
-
wording is locked by `assertJsonBodyField` in the kernel. Canonical
|
|
304
|
-
reference: the JSDoc on `createRouter` in
|
|
305
|
-
`baerly-storage`.
|
|
306
|
-
|
|
307
|
-
- **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
|
|
308
|
-
every request resolves to `tenant: "react-demo"` and `Authorization`
|
|
309
|
-
is ignored. The adapter reads `config.auth` to pick its verifier;
|
|
310
|
-
a `verifier:` on the factory overrides it. The schema-bound
|
|
311
|
-
`notes` collection (`baerly.config.ts:NoteSchema`) runs server-side
|
|
312
|
-
regardless of the auth posture. `baerly doctor --target=cloudflare`
|
|
313
|
-
warns on `"none"` for deploy targets. See "Going to production"
|
|
314
|
-
below for the two production-fit recipes.
|
|
94
|
+
- **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`: every request resolves to `tenant: "react-demo"` and `Authorization` is ignored. The adapter reads `config.auth` to pick its verifier; a `verifier:` on the factory overrides it. The schema-bound `notes` collection (`baerly.config.ts:NoteSchema`) runs server-side regardless of the auth posture. `baerly doctor --target=cloudflare` warns on `"none"` for deploy targets. See "Going to production" below for the two production-fit recipes.
|
|
315
95
|
|
|
316
96
|
### Going to production
|
|
317
97
|
|
|
318
|
-
The scaffold ships `auth: "none"` so the day-1 happy path works with
|
|
319
|
-
zero env vars. The `NoteSchema` in `baerly.config.ts` continues to
|
|
320
|
-
validate writes server-side under every posture below — only the
|
|
321
|
-
header-check seam changes.
|
|
98
|
+
The scaffold ships `auth: "none"` so the day-1 happy path works with zero env vars. The `NoteSchema` in `baerly.config.ts` continues to validate writes server-side under every posture below — only the header-check seam changes.
|
|
322
99
|
|
|
323
100
|
<!-- pattern-a:start -->
|
|
324
|
-
|
|
325
|
-
artifact ships to dev and prod; the factory `verifier:` override
|
|
326
|
-
engages only when prod env vars are present. `baerlyWorker` resolves
|
|
327
|
-
the factory `verifier:` first, so the override silently supersedes
|
|
328
|
-
`config.auth: "none"` in prod.
|
|
101
|
+
|
|
102
|
+
**Pattern A — env-aware verifier (recommended for CF Access).** Same artifact ships to dev and prod; the factory `verifier:` override engages only when prod env vars are present. `baerlyWorker` resolves the factory `verifier:` first, so the override silently supersedes `config.auth: "none"` in prod.
|
|
329
103
|
|
|
330
104
|
```ts
|
|
331
105
|
// baerly.config.ts — unchanged
|
|
@@ -342,7 +116,7 @@ export default defineConfig({
|
|
|
342
116
|
app: "react-cloudflare",
|
|
343
117
|
tenant: "react-demo",
|
|
344
118
|
target: "cloudflare",
|
|
345
|
-
auth: "none",
|
|
119
|
+
auth: "none", // dev default
|
|
346
120
|
collections: {
|
|
347
121
|
notes: { schema: NoteSchema },
|
|
348
122
|
},
|
|
@@ -373,19 +147,12 @@ export default baerlyWorker<AppEnv>((env) => ({
|
|
|
373
147
|
}));
|
|
374
148
|
```
|
|
375
149
|
|
|
376
|
-
Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in
|
|
377
|
-
`wrangler.jsonc:vars` for prod (they're public identifiers, not
|
|
378
|
-
secrets). Dev `wrangler dev` sees them as `undefined`, the spread
|
|
379
|
-
short-circuits, and `config.auth: "none"` runs. Prod sees them set
|
|
380
|
-
and `cloudflareAccess` engages. Every verified token is pinned to
|
|
381
|
-
`config.tenant`; pass `tenantClaim` instead only when your Access JWT
|
|
382
|
-
actually carries a tenant claim.
|
|
150
|
+
Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in `wrangler.jsonc:vars` for prod (they're public identifiers, not secrets). Dev `wrangler dev` sees them as `undefined`, the spread short-circuits, and `config.auth: "none"` runs. Prod sees them set and `cloudflareAccess` engages. Every verified token is pinned to `config.tenant`; pass `tenantClaim` instead only when your Access JWT actually carries a tenant claim.
|
|
383
151
|
|
|
384
152
|
<!-- pattern-a:end -->
|
|
385
153
|
<!-- pattern-b:start -->
|
|
386
|
-
|
|
387
|
-
server-to-server callers (CI and internal services). No factory
|
|
388
|
-
code changes; only `baerly.config.ts` flips:
|
|
154
|
+
|
|
155
|
+
**Pattern B — `auth: "shared-secret"`.** Single-tenant server-to-server callers (CI and internal services). No factory code changes; only `baerly.config.ts` flips:
|
|
389
156
|
|
|
390
157
|
```ts
|
|
391
158
|
// baerly.config.ts
|
|
@@ -400,8 +167,7 @@ echo 'SHARED_SECRET=dev-shared-secret' > .dev.vars
|
|
|
400
167
|
wrangler secret put SHARED_SECRET
|
|
401
168
|
```
|
|
402
169
|
|
|
403
|
-
The Vite dev plugin needs the bearer injected for browser calls —
|
|
404
|
-
re-enable `baerlyDevAuth` in `vite.config.ts`:
|
|
170
|
+
The Vite dev plugin needs the bearer injected for browser calls — re-enable `baerlyDevAuth` in `vite.config.ts`:
|
|
405
171
|
|
|
406
172
|
```ts
|
|
407
173
|
import { cloudflare } from "@cloudflare/vite-plugin";
|
|
@@ -415,24 +181,16 @@ export default defineConfig({
|
|
|
415
181
|
plugins: [
|
|
416
182
|
react(),
|
|
417
183
|
cloudflare(),
|
|
418
|
-
...(SHARED_SECRET !== undefined
|
|
419
|
-
? [baerlyDevAuth({ secret: SHARED_SECRET })]
|
|
420
|
-
: []),
|
|
184
|
+
...(SHARED_SECRET !== undefined ? [baerlyDevAuth({ secret: SHARED_SECRET })] : []),
|
|
421
185
|
],
|
|
422
186
|
});
|
|
423
187
|
```
|
|
424
188
|
|
|
425
|
-
`baerly doctor --target=cloudflare` FAILs (`auth.shared-secret-missing`)
|
|
426
|
-
if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable
|
|
427
|
-
from the runtime env.
|
|
189
|
+
`baerly doctor --target=cloudflare` FAILs (`auth.shared-secret-missing`) if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable from the runtime env.
|
|
428
190
|
|
|
429
191
|
<!-- pattern-b:end -->
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
client can't run on its own (the canonical case: an endpoint that
|
|
433
|
-
fans a write across several documents server-side, since
|
|
434
|
-
`createBaerlyClient` is reads + by-id mutations only), wrap the
|
|
435
|
-
worker `fetch`:
|
|
192
|
+
|
|
193
|
+
- **Extending the Worker with a custom route** — `baerlyWorker(...)` owns `/v1/*`, including `/v1/healthz`. For server-side endpoints the SPA client can't run on its own (the canonical case: an endpoint that fans a write across several documents server-side, since `createBaerlyClient` is reads + by-id mutations only), wrap the worker `fetch`:
|
|
436
194
|
|
|
437
195
|
```ts
|
|
438
196
|
// src/server/index.ts
|
|
@@ -474,124 +232,48 @@ from the runtime env.
|
|
|
474
232
|
} satisfies ExportedHandler<BaerlyEnv>;
|
|
475
233
|
```
|
|
476
234
|
|
|
477
|
-
Under `auth: "none"` the dev plugin no longer injects an
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
verify `Authorization` explicitly; `baerlyWorker` only does the
|
|
483
|
-
header check for routes it owns (`/v1/*`).
|
|
484
|
-
|
|
485
|
-
- **Secrets vs. vars** — `wrangler.jsonc:vars` carries non-secret
|
|
486
|
-
config (`APP`, `TENANT`, and CF Access identifiers
|
|
487
|
-
`CF_ACCESS_TEAM_DOMAIN` / `CF_ACCESS_AUDIENCE_TAG` — both are
|
|
488
|
-
public identifiers, not secrets). Secrets like
|
|
489
|
-
`SHARED_SECRET` (only required if you flip `auth` to
|
|
490
|
-
`"shared-secret"`) live in `.dev.vars` for local `wrangler dev`
|
|
491
|
-
and behind `wrangler secret put` in production. `baerly doctor
|
|
492
|
-
--target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars`
|
|
493
|
-
only, so setting them via `wrangler secret put` would silently
|
|
494
|
-
defeat the doctor check.
|
|
495
|
-
|
|
496
|
-
- **Deploy** — `baerly deploy --target=cloudflare` runs
|
|
497
|
-
`wrangler deploy --x-provision --x-auto-create` (Wrangler 4.10+)
|
|
498
|
-
to auto-create the declared R2 buckets and ship the Worker. When
|
|
499
|
-
the experimental flag is unavailable it falls back to
|
|
500
|
-
`wrangler r2 bucket create` + `wrangler deploy`. The fallback is
|
|
501
|
-
also what `baerly doctor --target=cloudflare --fix` exercises.
|
|
235
|
+
Under `auth: "none"` the dev plugin no longer injects an `Authorization` header — `/api/*` and `/v1/*` reach the Worker unauthenticated and the adapter pins both to `config.tenant`. When you flip to `auth: "shared-secret"` (or a custom verifier) per the "Going to production" recipe, your `/api/*` handler must read and verify `Authorization` explicitly; `baerlyWorker` only does the header check for routes it owns (`/v1/*`).
|
|
236
|
+
|
|
237
|
+
- **Secrets vs. vars** — `wrangler.jsonc:vars` carries non-secret config (`APP`, `TENANT`, and CF Access identifiers `CF_ACCESS_TEAM_DOMAIN` / `CF_ACCESS_AUDIENCE_TAG` — both are public identifiers, not secrets). Secrets like `SHARED_SECRET` (only required if you flip `auth` to `"shared-secret"`) live in `.dev.vars` for local `wrangler dev` and behind `wrangler secret put` in production. `baerly doctor --target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars` only, so setting them via `wrangler secret put` would silently defeat the doctor check.
|
|
238
|
+
|
|
239
|
+
- **Deploy** — `baerly deploy --target=cloudflare` creates any missing declared R2 buckets with `wrangler r2 bucket create`, then runs `wrangler deploy` to ship the Worker. The bucket step is also what `baerly doctor --target=cloudflare --fix` exercises.
|
|
502
240
|
|
|
503
241
|
## Anti-patterns
|
|
504
242
|
|
|
505
|
-
-
|
|
506
|
-
|
|
507
|
-
- Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
|
|
508
|
-
consume the published exports.
|
|
509
|
-
- Mutating `VerifierResult.tenantPrefix` between the verifier
|
|
510
|
-
and `Db.create`. The dispatcher pins the tenant from the
|
|
511
|
-
verifier's return value.
|
|
512
|
-
- Calling `db.collection(...).all()` (or any unbounded read) inside a
|
|
513
|
-
per-request handler. The call scans the entire collection on every
|
|
514
|
-
request — fine for a fixture-sized table, catastrophic at any real
|
|
515
|
-
size, and `pnpm verify` doesn't surface the cost. Push the filter
|
|
516
|
-
into the predicate so the index planner can prune
|
|
517
|
-
(`db.collection("notes").where({ ... }).all()`), or maintain a
|
|
518
|
-
side-projection (D1/KV/search index) populated incrementally from
|
|
519
|
-
the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from
|
|
520
|
-
a write hook — never re-scan per
|
|
521
|
-
request.
|
|
243
|
+
- The shared anti-patterns (branded types, the verifier's tenant, secrets in the SPA bundle) are in `RECIPES.md#anti-patterns-compile-clean-but-wrong`.
|
|
244
|
+
- Calling `db.collection(...).all()` (or any unbounded read) inside a per-request handler. The call scans the entire collection on every request — fine for a fixture-sized table, catastrophic at any real size, and `pnpm verify` doesn't surface the cost. A predicate (`db.collection("notes").where({ ... }).all()`) trims the response but still folds the whole collection, so instead maintain a side-projection (D1/KV/search index) populated incrementally from the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from a write hook — never re-scan per request.
|
|
522
245
|
|
|
523
246
|
## Maintenance
|
|
524
247
|
|
|
525
248
|
<!-- pattern-d:start -->
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
whose default is safe on every tier. A size-ratio threshold means idle buckets pay
|
|
530
|
-
nothing. Concurrent folds are safe without coordination: the commit is a
|
|
531
|
-
compare-and-swap, so a fold that loses to a concurrent write is simply discarded and
|
|
532
|
-
its leftover swept by GC. On Cloudflare the fold is deferred past the response via
|
|
533
|
-
ctx.waitUntil; everywhere else it runs inline. **Reads are pure** — they never run
|
|
534
|
-
maintenance, so the published idle-reader cost bound holds.
|
|
535
|
-
|
|
536
|
-
A bucket maintains itself as long as it takes writes. A bucket served read-only does
|
|
537
|
-
not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
|
|
538
|
-
graduate once a collection is large. See docs/about/graduation.md for the per-tier
|
|
539
|
-
envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
|
|
540
|
-
|
|
541
|
-
Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
|
|
542
|
-
your own schedule. Not required for steady-state operation.
|
|
249
|
+
|
|
250
|
+
Maintenance is automatic and write-triggered: nothing to install or schedule, identically on every host, and reads never run it. A scheduled `runScheduledMaintenance` pass is an optional extra for a collection served mostly read-only. The behavior, the call, its per-tier limits and the Workers Free / Paid differences are in `node_modules/@gusto/baerly-storage/dist/RECIPES.md#recipe--scheduled-maintenance`.
|
|
251
|
+
|
|
543
252
|
<!-- pattern-d:end -->
|
|
544
253
|
|
|
545
254
|
## When to graduate
|
|
546
255
|
|
|
547
|
-
baerly-storage is designed for the small-to-medium operating point.
|
|
548
|
-
The cost model puts the soft ceiling at:
|
|
256
|
+
baerly-storage is designed for the small-to-medium operating point. The soft ceiling has three lines, none enforced by the protocol: writes per collection (a throughput estimate), collections per tenant (a soft fan-out guideline), and the R2 free-tier storage line (a cost signal). The figures live in one place: docs/spec/scale-ceilings.md § "The published envelope" in the baerly-storage repo.
|
|
549
257
|
|
|
550
|
-
-
|
|
551
|
-
- **>10 GB / tenant stored** (R2 free-tier storage line — a cost signal, not a protocol ceiling)
|
|
552
|
-
- **~100 collections / tenant** (soft fan-out guideline — bench-grounded linear cost)
|
|
258
|
+
At the M-size operating point, the projected cost is ~$12/mo on Cloudflare, including Workers Paid, and ~$19/mo on Node, excluding Node hosting. Past those, per-class op pricing and fan-out scan cost start to dominate; you've outgrown the workload envelope — move to a database service (D1 / Postgres) suited to higher scale. Pick your graduation target:
|
|
553
259
|
|
|
554
|
-
At M-size (~30 writes/min) the projected cost is ~$18/mo on R2. Past
|
|
555
|
-
those, per-class op pricing and fan-out scan cost start to dominate;
|
|
556
|
-
you've outgrown the workload envelope — move to a database service (D1 / Postgres) suited to higher scale.
|
|
557
|
-
Pick your graduation target:
|
|
558
260
|
- **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
|
|
559
261
|
- **Off-Workers or portability matters:** managed Postgres.
|
|
560
262
|
- **Single-instance Node:** SQLite via Litestream.
|
|
561
263
|
|
|
562
|
-
Either way, the export below is mechanical because log entries are
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
**
|
|
567
|
-
`baerly admin usage --target=node --bucket=<bucket-uri> --app=<app>
|
|
568
|
-
--tenant=<tenant>` lists recent log entries per collection and computes
|
|
569
|
-
writes/min. On Cloudflare, use canonical logs for trend history and
|
|
570
|
-
`baerly cost --bucket=<bucket-uri> --collection=<collection>` for the
|
|
571
|
-
current operation-cost projection until the usage scanner is wired to
|
|
572
|
-
R2 bindings.
|
|
573
|
-
|
|
574
|
-
**Export when ready:** `baerly export --target=sqlite|postgres|d1
|
|
575
|
-
--bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
|
|
576
|
-
canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
|
|
577
|
-
inferred `ExportPlan`) that you load into your graduation target.
|
|
578
|
-
The export is point-in-time and honours the active schema. Flags:
|
|
579
|
-
`--where=<json-predicate>`, `--where-comment`, `--output`,
|
|
580
|
-
`--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
|
|
581
|
-
2 Storage/Network, 3 Protocol invariant.
|
|
264
|
+
Either way, the export below is mechanical because log entries are Debezium-style CDC change events — graduation is a baerly-storage win, not a churn event.
|
|
265
|
+
|
|
266
|
+
**Estimate your current rate:** for Node/self-hosted buckets, `baerly admin usage --target=node --bucket=<bucket-uri> --app=<app> --tenant=<tenant>` lists recent log entries per collection and computes writes/min. On Cloudflare, use canonical logs for trend history and `baerly cost --bucket=<bucket-uri> --collection=<collection>` for the current operation-cost projection until the usage scanner is wired to R2 bindings.
|
|
267
|
+
|
|
268
|
+
**Export when ready:** `baerly export --target=sqlite|postgres|d1 --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a canonical SQL dump (and a `<output>.plan.json` sidecar carrying the inferred `ExportPlan`) that you load into your graduation target. The export is point-in-time and honours the active schema. Flags: `--where=<json-predicate>`, `--where-comment`, `--output`, `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig, 2 Storage/Network, 3 Protocol invariant.
|
|
582
269
|
|
|
583
270
|
## Worked extensions
|
|
584
271
|
|
|
585
|
-
Three recipes that come up routinely when you extend the
|
|
586
|
-
scaffolded `notes` shape. Each one is target-agnostic — the same
|
|
587
|
-
code works in `react-cloudflare` and `react-node`.
|
|
272
|
+
Three recipes that come up routinely when you extend the scaffolded `notes` shape. Each one is target-agnostic — the same code works in `react-cloudflare` and `react-node`.
|
|
588
273
|
|
|
589
274
|
### Adding an enum field (e.g. `status`)
|
|
590
275
|
|
|
591
|
-
A row often needs a constrained set of string values. Declare the
|
|
592
|
-
enum inside the Zod schema and export the option tuple next to it
|
|
593
|
-
in `baerly.config.ts`; the predicate API picks the field up
|
|
594
|
-
automatically.
|
|
276
|
+
A row often needs a constrained set of string values. Declare the enum inside the Zod schema and export the option tuple next to it in `baerly.config.ts`; the predicate API picks the field up automatically.
|
|
595
277
|
|
|
596
278
|
```typescript
|
|
597
279
|
// baerly.config.ts
|
|
@@ -607,7 +289,7 @@ export const NoteSchema = z.object({
|
|
|
607
289
|
export type Note = z.infer<typeof NoteSchema>;
|
|
608
290
|
export const STATUSES = NoteSchema.shape.status.options;
|
|
609
291
|
|
|
610
|
-
export default defineConfig({
|
|
292
|
+
export default defineConfig({/* ... */});
|
|
611
293
|
```
|
|
612
294
|
|
|
613
295
|
```tsx
|
|
@@ -616,21 +298,18 @@ import { STATUSES } from "../../baerly.config.ts";
|
|
|
616
298
|
|
|
617
299
|
<select name="status" defaultValue="open">
|
|
618
300
|
{STATUSES.map((s) => (
|
|
619
|
-
<option key={s} value={s}>
|
|
301
|
+
<option key={s} value={s}>
|
|
302
|
+
{s}
|
|
303
|
+
</option>
|
|
620
304
|
))}
|
|
621
|
-
</select
|
|
305
|
+
</select>;
|
|
622
306
|
```
|
|
623
307
|
|
|
624
|
-
The schema enum is the single source of truth — adding a value
|
|
625
|
-
there expands the `<select>` immediately. Adding more enum fields
|
|
626
|
-
(`priority`, `severity`) follows the same shape.
|
|
308
|
+
The schema enum is the single source of truth — adding a value there expands the `<select>` immediately. Adding more enum fields (`priority`, `severity`) follows the same shape.
|
|
627
309
|
|
|
628
310
|
### Filtering a reactive query by predicate
|
|
629
311
|
|
|
630
|
-
`useQuery((c) => c.collection(...).where(...).all(), [deps])` accepts the
|
|
631
|
-
same predicate shapes as the bare client. To narrow by an enum field,
|
|
632
|
-
drive it off `useState` and lift the filter into the `deps` array so
|
|
633
|
-
the cache key changes when the filter does:
|
|
312
|
+
`useQuery((c) => c.collection(...).where(...).all(), [deps])` accepts the same predicate shapes as the bare client. To narrow by an enum field, drive it off `useState` and lift the filter into the `deps` array so the cache key changes when the filter does:
|
|
634
313
|
|
|
635
314
|
```tsx
|
|
636
315
|
import { useState } from "react";
|
|
@@ -651,30 +330,19 @@ const result = useQuery(
|
|
|
651
330
|
);
|
|
652
331
|
```
|
|
653
332
|
|
|
654
|
-
`useQuery` re-runs the callback
|
|
655
|
-
`/v1/since?collection=<name>&cursor=<opaque>` long-poll batches a
|
|
656
|
-
non-empty change for any subscribed
|
|
657
|
-
collection. Idle long-poll cycles (empty batches) drop at the
|
|
658
|
-
`subscription-pool` layer, so a steady-state collection costs zero list
|
|
659
|
-
reads. Add a `<select>` bound to `setFilter` and the list narrows live.
|
|
333
|
+
`useQuery` is live by default: it re-runs on dependency changes and non-empty `/v1/since` batches for any collection the callback reads. Pass `{ live: false }` for mount/dependency reads without `/v1/since`. Every result state has a stable `refetch()`; successful data stays available while refreshing and on error. A non-retriable subscription error stops automatic polling, while explicit `refetch()` retries the read and restarts the terminal live subscription. Idle long-poll cycles do not re-run the query.
|
|
660
334
|
|
|
661
|
-
For conditional / deferred reads, return the `useQuery.skip` sentinel
|
|
662
|
-
from the callback — the hook short-circuits to
|
|
663
|
-
`status: "skipped"` with no subscription:
|
|
335
|
+
For conditional / deferred reads, return the `useQuery.skip` sentinel from the callback — the hook short-circuits to `status: "skipped"` with no subscription:
|
|
664
336
|
|
|
665
337
|
```tsx
|
|
666
338
|
const filtered = useQuery(
|
|
667
|
-
(c) =>
|
|
668
|
-
filter === "all"
|
|
669
|
-
? useQuery.skip
|
|
670
|
-
: c.collection("notes").where({ status: filter }).all(),
|
|
339
|
+
(c) => (filter === "all" ? useQuery.skip : c.collection("notes").where({ status: filter }).all()),
|
|
671
340
|
[filter],
|
|
672
341
|
);
|
|
673
342
|
if (filtered.status === "skipped") return <FullList />;
|
|
674
343
|
```
|
|
675
344
|
|
|
676
|
-
For dependent reads, compose two `useQuery` calls — the second one
|
|
677
|
-
returns `useQuery.skip` until the first resolves to `"ok"`:
|
|
345
|
+
For dependent reads, compose two `useQuery` calls — the second one returns `useQuery.skip` until the first resolves to `"ok"`:
|
|
678
346
|
|
|
679
347
|
```tsx
|
|
680
348
|
// `comments` must be declared in baerly.config.ts — the bound hooks
|
|
@@ -689,8 +357,7 @@ const replies = useQuery(
|
|
|
689
357
|
);
|
|
690
358
|
```
|
|
691
359
|
|
|
692
|
-
Mutations are inline: `useMutation()` returns a `[mutate, { isPending,
|
|
693
|
-
error }]` tuple. `mutate(cb)` runs `cb` against the real client:
|
|
360
|
+
Mutations are inline: `useMutation()` returns a `[mutate, { isPending, error }]` tuple. `mutate(cb)` runs `cb` against the real client:
|
|
694
361
|
|
|
695
362
|
```tsx
|
|
696
363
|
const [mutate, { isPending, error }] = useMutation();
|
|
@@ -699,32 +366,22 @@ const [mutate, { isPending, error }] = useMutation();
|
|
|
699
366
|
onClick={() => mutate((c) => c.collection("notes").update(id, { body }))}
|
|
700
367
|
>
|
|
701
368
|
{isPending ? "Saving…" : "Save"}
|
|
702
|
-
</button
|
|
369
|
+
</button>;
|
|
703
370
|
```
|
|
704
371
|
|
|
705
372
|
### Optional fields
|
|
706
373
|
|
|
707
|
-
Some fields aren't always present (`tags` may be missing entirely
|
|
708
|
-
on some rows). Zod's `.optional()` models this:
|
|
374
|
+
Some fields aren't always present (`tags` may be missing entirely on some rows). Zod's `.optional()` models this:
|
|
709
375
|
|
|
710
376
|
```typescript
|
|
711
377
|
export const NoteSchema = z.object({
|
|
712
378
|
_id: z.string(),
|
|
713
379
|
body: z.string().min(1),
|
|
714
|
-
tags: z.array(z.string()).optional(),
|
|
380
|
+
tags: z.array(z.string()).optional(), // tags?: string[]
|
|
715
381
|
});
|
|
716
382
|
```
|
|
717
383
|
|
|
718
|
-
The Zod-inferred `Note` type reflects the shape (`tags?: string[]`)
|
|
719
|
-
and call sites pick it up through `import type { Note }`.
|
|
720
|
-
JSON-merge-patch (RFC 7386) semantics apply on `update()`:
|
|
721
|
-
omitting `tags` from an update preserves the existing value;
|
|
722
|
-
passing `tags: null` deletes the field; passing `tags: []` sets
|
|
723
|
-
it to an empty array. Note that `null` is the deletion sentinel,
|
|
724
|
-
not a storable value — `DocumentValue` doesn't include `null`, so
|
|
725
|
-
subsequent `get()` / query results expose deleted optional fields as
|
|
726
|
-
`undefined`, not `null`.
|
|
727
|
-
That's why this recipe uses `.optional()` and not `.nullable()`.
|
|
384
|
+
The Zod-inferred `Note` type reflects the shape (`tags?: string[]`) and call sites pick it up through `import type { Note }`. JSON-merge-patch (RFC 7386) semantics apply on `update()`: omitting `tags` from an update preserves the existing value; passing `tags: null` deletes the field; passing `tags: []` sets it to an empty array. Note that `null` is the deletion sentinel, not a storable value — `DocumentValue` doesn't include `null`, so subsequent `get()` / query results expose deleted optional fields as `undefined`, not `null`. That's why this recipe uses `.optional()` and not `.nullable()`.
|
|
728
385
|
|
|
729
386
|
## Pointers
|
|
730
387
|
|