@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.
Files changed (37) hide show
  1. package/dist/THIRD-PARTY-LICENSES.txt +204 -0
  2. package/dist/index.js +1537 -145
  3. package/dist/index.js.map +1 -1
  4. package/dist/templates/addons/docker/Dockerfile +13 -11
  5. package/dist/templates/minimal-cloudflare/AGENTS.md +77 -399
  6. package/dist/templates/minimal-cloudflare/README.md +33 -97
  7. package/dist/templates/minimal-cloudflare/package.json +12 -9
  8. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +13 -7
  9. package/dist/templates/minimal-cloudflare/tsconfig.app.json +2 -3
  10. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +2 -3
  11. package/dist/templates/minimal-cloudflare/vitest.config.ts +1 -1
  12. package/dist/templates/minimal-cloudflare/wrangler.jsonc +4 -2
  13. package/dist/templates/minimal-node/AGENTS.md +80 -380
  14. package/dist/templates/minimal-node/README.md +37 -135
  15. package/dist/templates/minimal-node/package.json +11 -9
  16. package/dist/templates/minimal-node/pnpm-workspace.yaml +14 -9
  17. package/dist/templates/minimal-node/tsconfig.app.json +2 -3
  18. package/dist/templates/minimal-node/tsconfig.server.json +2 -3
  19. package/dist/templates/react-cloudflare/AGENTS.md +101 -444
  20. package/dist/templates/react-cloudflare/README.md +14 -54
  21. package/dist/templates/react-cloudflare/package.json +18 -15
  22. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +13 -7
  23. package/dist/templates/react-cloudflare/tsconfig.app.json +2 -3
  24. package/dist/templates/react-cloudflare/tsconfig.worker.json +2 -3
  25. package/dist/templates/react-cloudflare/vitest.config.ts +1 -1
  26. package/dist/templates/react-cloudflare/wrangler.jsonc +4 -2
  27. package/dist/templates/react-node/AGENTS.md +108 -474
  28. package/dist/templates/react-node/README.md +35 -125
  29. package/dist/templates/react-node/package.json +16 -14
  30. package/dist/templates/react-node/pnpm-workspace.yaml +14 -9
  31. package/dist/templates/react-node/tsconfig.app.json +2 -3
  32. package/dist/templates/react-node/tsconfig.server.json +2 -3
  33. package/package.json +7 -7
  34. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +0 -16
  35. package/dist/templates/minimal-node/uint8array-base64.d.ts +0 -16
  36. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +0 -16
  37. package/dist/templates/react-node/uint8array-base64.d.ts +0 -16
@@ -8,327 +8,97 @@ 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
- public-API quickref. Read first. Lists every method, every error
21
- code, every example. If a pattern you want to use isn't here, it
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
- `db.collection(name).insert(row)` and `.where({ ... }).all()`.
31
- - `z.string().nullable()` in a schema — `DocumentValue` excludes
32
- `null`. Use `.optional()`; `null` in an update patch is the RFC
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
- `minimal-cloudflare` is a baerly-storage app scaffolded with
45
- `create-baerly-storage`. The Worker-side server lives in `src/server/`;
46
- the optional client lives in `src/web/`. Configuration lives in
47
- `baerly.config.ts`.
31
+ `minimal-cloudflare` is a baerly-storage app scaffolded with `create-baerly-storage`. The Worker-side server lives in `src/server/`; the optional 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
- Public API docs: the JSDoc on `baerly-storage`'s `Db` and `Collection`
55
- is the canonical reference; read it via your editor's TS LS, the
56
- published types, or `node_modules/@gusto/baerly-storage/dist/API.md`.
35
+ 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`.
57
36
 
58
37
  ## Toolchain
59
38
 
60
- - **Package manager:** pnpm. The emitted repo pins
61
- `packageManager: pnpm@11.1.2`.
39
+ - **Package manager:** pnpm. The emitted repo pins `packageManager: pnpm@12.22.0`.
62
40
  - **Test runner:** vitest.
63
- - **Type checker:** TypeScript 6.x, as pinned in `package.json`.
64
- (The baerly-storage monorepo itself uses TypeScript 7 via
65
- `@typescript/native-preview`.)
66
- - **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
67
- code stays compatible with type-stripping runtimes (Node's
68
- `--experimental-strip-types`, esbuild's strip path). The flag bans
69
- TS constructs that can't be type-erased: write
70
- `class { x: T; constructor(x: T) { this.x = x } }` explicitly
71
- instead of parameter-property shorthand
72
- (`constructor(private x: T) {}` fails with TS1294). The same goes
73
- for `enum`, namespaces with non-type bindings, and `private` /
74
- `protected` / `public` accessibility modifiers on constructor
75
- parameters.
41
+ - **Type checker:** TypeScript 7, as pinned in `package.json`.
42
+ - **`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.
76
43
 
77
44
  ## Verification
78
45
 
79
- | Command | What it does | Runtime |
80
- | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
81
- | `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 |
82
- | `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 |
83
- | `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`) | seconds |
84
- | `pnpm test` | `vitest run` — standalone `vitest.config.ts` (Node env, ignores `vite.config.ts` so the Cloudflare plugin doesn't load). The template ships `src/notes.test.ts` by default. | seconds |
85
- | `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 |
86
- | `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the Workers Assets binding | seconds |
87
- | `pnpm deploy` | `wrangler deploy` — ships Worker + assets in one shipment (auto-creates R2 on first run via `--x-provision`) | seconds |
88
-
89
- **`pnpm verify` exercises typecheck + tests only.** The dev-auth
90
- middleware, the SPA bundle, and any custom `/api/*` route are NOT
91
- under test — verify will exit green even when the dev plugin returns
92
- 401 on every browser request or the SPA throws on mount. For changes
93
- that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
94
- `pnpm dev` and exercise the change in a browser (or `curl
95
- http://localhost:5173/<path>`) before declaring the task complete.
46
+ | Command | What it does | Runtime |
47
+ | --- | --- | --- |
48
+ | `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 |
49
+ | `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 |
50
+ | `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`) | seconds |
51
+ | `pnpm test` | `vitest run` — standalone `vitest.config.ts` (Node env, ignores `vite.config.ts` so the Cloudflare plugin doesn't load). The template ships `src/notes.test.ts` by default. | seconds |
52
+ | `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 |
53
+ | `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the Workers Assets binding | seconds |
54
+ | `pnpm deploy` | `wrangler deploy` — ships Worker + assets in one shipment (Wrangler auto-creates the declared R2 bucket on first run) | seconds |
55
+
56
+ **`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.
96
57
 
97
58
  ## Where the code is
98
59
 
99
- | Path | What it is |
100
- | ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
101
- | `src/server/index.ts` | Worker entry — `baerlyWorker((env) => ({ verifier }))` |
102
- | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, assets, vars |
103
- | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.ts`. |
104
- | `src/web/main.ts` | SPA client entry — a ~17-line hello-world: reads `client.collection("notes").all()` to render a `${n} note(s)` count and an `[Add note]` button that inserts a timestamped row and re-fetches. Demonstrates both read and write paths on first load. Extend or replace; the `config`-bound `client.collection("notes")` is the typed surface (the generic on `.collection()` is the collection **name**, not the row type). Workers Assets serves the built bundle from `dist/client/`. |
105
- | `vite.config.ts` | Vite + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
106
- | `tsconfig.json` | Root project-references stub |
107
- | `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib) |
108
- | `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
109
- | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
110
- | `types.ts` | Shared types between the Worker (`src/server/`) and the SPA (`src/web/`). Both project tsconfigs include this file; put any row type or interface that crosses the boundary here. |
111
-
112
- > **`baerly.config.ts` and `types.ts` are dual-included** by both
113
- > `tsconfig.app.json` and `tsconfig.worker.json`. Both can only
114
- > import from `baerly-storage`, `zod`, and other dual-included root
115
- > files. Paths under `src/server/` are worker-only; importing them
116
- > here triggers a `TS6307` "not listed within the file list of
117
- > project … tsconfig.app.json" error. Cross-boundary interfaces
118
- > belong in `types.ts`; re-export from a server-only file if
119
- > downstream code wants a local name.
60
+ | Path | What it is |
61
+ | --- | --- |
62
+ | `src/server/index.ts` | Worker entry — `baerlyWorker((env) => ({ verifier }))` |
63
+ | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, assets, vars |
64
+ | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.ts`. |
65
+ | `src/web/main.ts` | SPA client entry — a ~17-line hello-world: reads `client.collection("notes").all()` to render a `${n} note(s)` count and an `[Add note]` button that inserts a timestamped row and re-fetches. Demonstrates both read and write paths on first load. Extend or replace; the `config`-bound `client.collection("notes")` is the typed surface (the generic on `.collection()` is the collection **name**, not the row type). Workers Assets serves the built bundle from `dist/client/`. |
66
+ | `vite.config.ts` | Vite + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
67
+ | `tsconfig.json` | Root project-references stub |
68
+ | `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib) |
69
+ | `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
70
+ | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
71
+ | `types.ts` | Shared types between the Worker (`src/server/`) and the SPA (`src/web/`). Both project tsconfigs include this file; put any row type or interface that crosses the boundary here. |
72
+
73
+ > **`baerly.config.ts` and `types.ts` are dual-included** by both `tsconfig.app.json` and `tsconfig.worker.json`. Both can only import from `baerly-storage`, `zod`, and other dual-included root files. Paths under `src/server/` are worker-only; importing them here triggers a `TS6307` "not listed within the file list of project … tsconfig.app.json" error. Cross-boundary interfaces belong in `types.ts`; re-export from a server-only file if downstream code wants a local name.
120
74
 
121
75
  ## When editing X, read Y
122
76
 
123
- - **Typed collections** — two ways to get a typed row, in DX order.
124
- The generic on `client.collection<N>(name)` is the collection
125
- **name** (constrained to `CollectionNames<typeof config>`), not the
126
- row type — so don't pass a row type to it.
127
- 1. **Bind the config.** This template's `src/web/main.ts` already
128
- passes `config` to `createBaerlyClient({ baseUrl, config })` (and
129
- `src/notes.test.ts` passes `config` to `Db.create`), so
130
- `client.collection("notes")` returns `ClientCollection<Row>` with
131
- `Row` derived from the schema declared in `baerly.config.ts`. No
132
- generic needed. When you need to name that row type elsewhere, use
133
- `RowOf<typeof config, "notes">` (re-exported from
134
- `@gusto/baerly-storage`) — not a generic on `.collection()`.
135
- 2. **Cast the handle (undeclared collection).** This template's
136
- `client` is bound to `config`, so its names narrow to the
137
- declared collections. To reach a collection that isn't in
138
- `config`, build an unbound client
139
- (`createBaerlyClient({ baseUrl })` with no `config`) — its names
140
- widen to `string` and its row defaults to `DocumentData`. Cast at
141
- the construction site for a narrower shape that still satisfies
142
- the kernel's `DocumentData` constraint
143
- (`{ [k: string]: DocumentValue }`):
144
- ```ts
145
- import {
146
- createBaerlyClient,
147
- type ClientCollection,
148
- type DocumentData,
149
- } from "@gusto/baerly-storage/client";
150
- interface Bookmark extends DocumentData {
151
- _id: string;
152
- url: string;
153
- }
154
- const raw = createBaerlyClient({ baseUrl: "" });
155
- const bookmarks = raw.collection("bookmarks") as ClientCollection<Bookmark>;
156
- await bookmarks.all();
157
- ```
158
- A plain `interface Bookmark { _id: string; url: string }`
159
- (no index signature) will fail with TS2344 — the constraint
160
- is intentional so the row stays JSON-compatible.
161
-
162
- - **Writing tests** — the kernel exports `MemoryStorage`, an
163
- in-memory `Storage` impl that's the canonical backend for unit
164
- tests. Don't roll your own: the same
165
- `Db.create({ storage, app, tenant, config })` boilerplate prod uses
166
- also accepts a `new MemoryStorage()` that swaps R2 for an
167
- 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
- ```
187
-
188
- Each `new MemoryStorage()` is a fresh bucket — no shared state
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("tickets").where({...}).all()`. Two
195
- shapes:
196
- - **Object literal** — equality only (top-level, dotted-path, or
197
- nested literal sub-predicate). Multi-field is implicit AND.
198
- - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
199
- for the operator vocabulary. The methods on `PredicateBuilder<T>`
200
- ARE the supported surface — invoking `q.or` / `q.regex` /
201
- `q.ne` / `q.exists` is a TS compile error, not a runtime
202
- `InvalidConfig`. Chained `.where(...).where(...)` AND-merges
203
- across calls and across shapes.
77
+ <!-- library:start -->
204
78
 
205
- ```ts
206
- // Top-level equality (Db inside the Worker, client in the SPA)
207
- await db.collection("tickets").where({ status: "open" }).all();
208
-
209
- // Dotted-path on a nested field
210
- await db.collection("tickets").where({ "assignee.team": "platform" }).all();
211
-
212
- // Operator on a single field — set membership (callback form)
213
- await db
214
- .collection("tickets")
215
- .where((q) => q.in("status", ["open", "pending"]))
216
- .all();
217
-
218
- // Range — also callback form
219
- await db
220
- .collection("tickets")
221
- .where((q) => q.gte("priority", 5).lt("priority", 10))
222
- .all();
223
-
224
- // AND-merge across two .where() calls (mix shapes freely)
225
- await db
226
- .collection("tickets")
227
- .where({ status: "open" })
228
- .where((q) => q.gte("priority", 5))
229
- .all();
230
- ```
79
+ - **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:
80
+ - **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`.
81
+ - **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.
82
+ - **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`.
83
+ - **Indexes**: don't declare them; a read always folds the whole collection. `API.md`, section `defineConfig`.
84
+ - **Schemas** (StandardSchema validators, `SchemaError`): `API.md`, section `defineConfig`.
85
+ - **HTTP wire format** (calling `/v1/*` directly): `API.md#http-wire-format`.
86
+ - **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`.
87
+ - **Errors by message** (`RECIPES.md`, one entry per error string) and the shared anti-patterns: `RECIPES.md#anti-patterns-compile-clean-but-wrong`.
231
88
 
232
- The plain-equality value type is JSON-arrayless: string / number /
233
- boolean / nested object. Use `q.in("status", [...])` for
234
- set membership when you'd otherwise want
235
- `{ status: ["open","pending"] }`.
89
+ <!-- library:end -->
236
90
 
237
- - **Indexes** — declare them in `baerly.config.ts`; the read-path
238
- planner picks one automatically when the predicate's equality
239
- fields cover an index's keys. No call-site hint is needed (the
240
- earlier `.useIndex(name)` chain was removed when the planner
241
- shipped — `Query<T>` has no such method).
242
-
243
- ```ts
244
- import { defineConfig } from "@gusto/baerly-storage/config";
245
-
246
- export default defineConfig({
247
- collections: {
248
- tickets: {
249
- indexes: [{ name: "by_status", on: "status" }],
250
- },
251
- },
252
- });
253
- ```
91
+ - **This template** — `src/web/main.ts` passes `config` to `createBaerlyClient` 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).
254
92
 
255
- With that declared, a query like
256
- `db.collection("tickets").where({ status: "open" }).all()` walks
257
- `by_status` automatically. Composite indexes
258
- (`on: ["status", "priority"]`) match any leftmost prefix.
259
- Mismatches (predicate doesn't cover any index) fall back to a full
260
- table scan with a metric bump; correctness is preserved because the
261
- reader re-checks the predicate in memory regardless of how it got
262
- the row set.
263
-
264
- - **Schemas (live feature)** — schemas are validated on the server
265
- for every `insert` / `update` / `replace` when bound. Declare via
266
- `defineConfig` using any StandardSchema v1 validator (Zod 3.24+,
267
- Valibot 0.36+, ArkType 2.0+, or anything implementing the spec):
268
-
269
- ```ts
270
- import { z } from "zod";
271
- import { defineConfig } from "@gusto/baerly-storage/config";
272
-
273
- const Ticket = z.object({
274
- _id: z.string(),
275
- status: z.enum(["open", "closed"]),
276
- title: z.string().min(1),
277
- });
278
-
279
- export default defineConfig({
280
- collections: {
281
- tickets: { schema: Ticket },
282
- },
283
- });
284
- ```
285
-
286
- On a validation failure the server throws
287
- `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
288
- HTTP clients see a 400 with the same envelope. Validation runs
289
- on the post-image so `update` and `replace` see the full doc, not
290
- just the patch.
291
-
292
- - **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
293
- (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
294
- only when debugging the wire. Mutation bodies are wrapped:
295
-
296
- | Route | Body | Response |
297
- | ------------------------------ | ----------------- | ---------------- |
298
- | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
299
- | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
300
- | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
301
- | `DELETE /v1/c/:collection/:id` | — | `204` |
302
-
303
- Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
304
- `GET /v1/since?collection=…&cursor=…`) take no body and return
305
- `{ data, _meta }` or a route-specific envelope. A flat `POST` body
306
- (without the `doc` wrapper) returns
307
- `400 SchemaError "Request body must be { doc: object }"` — the
308
- wording is locked by `assertJsonBodyField` in the kernel. Canonical
309
- reference: the JSDoc on `createRouter` in
310
- `baerly-storage`.
311
-
312
- - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
313
- every request resolves to `tenant: "minimal-demo"` and `Authorization`
314
- is ignored. The adapter reads `config.auth` to pick its verifier;
315
- a `verifier:` on the factory overrides it. `baerly doctor
316
- --target=cloudflare` warns on `"none"` for deploy targets. See
317
- "Going to production" below for the two production-fit recipes.
93
+ - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`: every request resolves to `tenant: "minimal-demo"` and `Authorization` is ignored. The adapter reads `config.auth` to pick its verifier; a `verifier:` on the factory overrides it. `baerly doctor --target=cloudflare` warns on `"none"` for deploy targets. See "Going to production" below for the two production-fit recipes.
318
94
 
319
95
  ### Going to production
320
96
 
321
- The scaffold ships `auth: "none"` so the day-1 happy path works with
322
- zero env vars. Two patterns flip to a production-fit posture; pick the
323
- one matching your gate.
97
+ The scaffold ships `auth: "none"` so the day-1 happy path works with zero env vars. Two patterns flip to a production-fit posture; pick the one matching your gate.
324
98
 
325
99
  <!-- pattern-a:start -->
326
100
 
327
- **Pattern A — env-aware verifier (recommended for CF Access).** Same
328
- artifact ships to dev and prod; the factory `verifier:` override
329
- engages only when prod env vars are present. `baerlyWorker` resolves
330
- the factory `verifier:` first, so the override silently supersedes
331
- `config.auth: "none"` in prod.
101
+ **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.
332
102
 
333
103
  ```ts
334
104
  // baerly.config.ts — unchanged
@@ -367,20 +137,12 @@ export default baerlyWorker<AppEnv>((env) => ({
367
137
  }));
368
138
  ```
369
139
 
370
- Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in
371
- `wrangler.jsonc:vars` for prod (they're public identifiers, not
372
- secrets). Dev `wrangler dev` sees them as `undefined`, the spread
373
- short-circuits, and `config.auth: "none"` runs. Prod sees them set
374
- and `cloudflareAccess` engages. Every verified token is pinned to
375
- `config.tenant`; pass `tenantClaim` instead only when your Access JWT
376
- actually carries a tenant claim.
140
+ 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.
377
141
 
378
142
  <!-- pattern-a:end -->
379
143
  <!-- pattern-b:start -->
380
144
 
381
- **Pattern B — `auth: "shared-secret"`.** Single-tenant
382
- server-to-server callers (CI and internal services). No factory
383
- code changes; only `baerly.config.ts` flips:
145
+ **Pattern B — `auth: "shared-secret"`.** Single-tenant server-to-server callers (CI and internal services). No factory code changes; only `baerly.config.ts` flips:
384
146
 
385
147
  ```ts
386
148
  // baerly.config.ts
@@ -395,8 +157,7 @@ echo 'SHARED_SECRET=dev-shared-secret' > .dev.vars
395
157
  wrangler secret put SHARED_SECRET
396
158
  ```
397
159
 
398
- The Vite dev plugin needs the bearer injected for browser calls —
399
- re-enable `baerlyDevAuth` in `vite.config.ts`:
160
+ The Vite dev plugin needs the bearer injected for browser calls — re-enable `baerlyDevAuth` in `vite.config.ts`:
400
161
 
401
162
  ```ts
402
163
  import { cloudflare } from "@cloudflare/vite-plugin";
@@ -408,25 +169,16 @@ const { SHARED_SECRET } = loadDevVars(".dev.vars", "SHARED_SECRET");
408
169
  export default defineConfig({
409
170
  plugins: [
410
171
  cloudflare(),
411
- ...(SHARED_SECRET !== undefined
412
- ? [baerlyDevAuth({ secret: SHARED_SECRET })]
413
- : []),
172
+ ...(SHARED_SECRET !== undefined ? [baerlyDevAuth({ secret: SHARED_SECRET })] : []),
414
173
  ],
415
174
  });
416
175
  ```
417
176
 
418
- `baerly doctor --target=cloudflare` FAILs (`auth.shared-secret-missing`)
419
- if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable
420
- from the runtime env.
177
+ `baerly doctor --target=cloudflare` FAILs (`auth.shared-secret-missing`) if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable from the runtime env.
421
178
 
422
179
  <!-- pattern-b:end -->
423
180
 
424
- - **Extending the Worker with a custom route** — `baerlyWorker(...)`
425
- owns `/v1/*`, including `/v1/healthz`. For server-side endpoints the SPA
426
- client can't run on its own (the canonical case: an endpoint that
427
- fans a write across several documents server-side, since
428
- `createBaerlyClient` is reads + by-id mutations only), wrap the
429
- worker `fetch`:
181
+ - **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`:
430
182
 
431
183
  ```ts
432
184
  // src/server/index.ts
@@ -468,114 +220,40 @@ from the runtime env.
468
220
  } satisfies ExportedHandler<BaerlyEnv>;
469
221
  ```
470
222
 
471
- Under `auth: "none"` the dev plugin no longer injects an
472
- `Authorization` header — `/api/*` and `/v1/*` reach the Worker
473
- unauthenticated and the adapter pins both to `config.tenant`. When
474
- you flip to `auth: "shared-secret"` (or a custom verifier) per the
475
- "Going to production" recipe, your `/api/*` handler must read and
476
- verify `Authorization` explicitly; `baerlyWorker` only does the
477
- header check for routes it owns (`/v1/*`).
478
-
479
- - **Secrets vs. vars** — `wrangler.jsonc:vars` carries non-secret
480
- config (`APP`, `TENANT`, and CF Access identifiers
481
- `CF_ACCESS_TEAM_DOMAIN` / `CF_ACCESS_AUDIENCE_TAG` — both are
482
- public identifiers, not secrets). Secrets like
483
- `SHARED_SECRET` (only required if you flip `auth` to
484
- `"shared-secret"`) live in `.dev.vars` for local `wrangler dev`
485
- and behind `wrangler secret put` in production. `baerly doctor
486
- --target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars`
487
- only, so setting them via `wrangler secret put` would silently
488
- defeat the doctor check.
489
-
490
- - **Deploy** — `baerly deploy --target=cloudflare` runs
491
- `wrangler deploy --x-provision --x-auto-create` (Wrangler 4.10+)
492
- to auto-create the declared R2 buckets and ship the Worker. When
493
- the experimental flag is unavailable it falls back to
494
- `wrangler r2 bucket create` + `wrangler deploy`. The fallback is
495
- also what `baerly doctor --target=cloudflare --fix` exercises.
223
+ 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/*`).
224
+
225
+ - **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.
226
+
227
+ - **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.
496
228
 
497
229
  ## Anti-patterns
498
230
 
499
- - Widening branded types from `baerly-storage` (`UUID`,
500
- `ContentVersionId`). The types prevent confusion bugs.
501
- - Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
502
- consume the published exports.
503
- - Mutating `VerifierResult.tenantPrefix` between the verifier
504
- and `Db.create`. The dispatcher pins the tenant from the
505
- verifier's return value.
506
- - Calling `db.collection(...).all()` (or any unbounded read) inside a
507
- per-request handler. The call scans the entire collection on every
508
- request — fine for a fixture-sized table, catastrophic at any real
509
- size, and `pnpm verify` doesn't surface the cost. Push the filter
510
- into the predicate so the index planner can prune
511
- (`db.collection("notes").where({ ... }).all()`), or maintain a
512
- side-projection (D1/KV/search index) populated incrementally from
513
- the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from
514
- a write hook — never re-scan per
515
- request.
231
+ - 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`.
232
+ - 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.
516
233
 
517
234
  ## Maintenance
518
235
 
519
236
  <!-- pattern-d:start -->
520
237
 
521
- Maintenance is automatic and write-triggered. No cron, no sidecar, no scheduler, no
522
- timer, no lock, no app-config knob — identical on every host. Every write runs a
523
- bounded GC slice inline plus a go/no-go compaction fold bounded by a fold-size ceiling
524
- whose default is safe on every tier. A size-ratio threshold means idle buckets pay
525
- nothing. Concurrent folds are safe without coordination: the commit is a
526
- compare-and-swap, so a fold that loses to a concurrent write is simply discarded and
527
- its leftover swept by GC. On Cloudflare the fold is deferred past the response via
528
- ctx.waitUntil; everywhere else it runs inline. **Reads are pure** — they never run
529
- maintenance, so the published idle-reader cost bound holds.
530
-
531
- A bucket maintains itself as long as it takes writes. A bucket served read-only does
532
- not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
533
- graduate once a collection is large. See docs/about/graduation.md for the per-tier
534
- envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
535
-
536
- Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
537
- your own schedule. Not required for steady-state operation.
238
+ 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`.
538
239
 
539
240
  <!-- pattern-d:end -->
540
241
 
541
242
  ## When to graduate
542
243
 
543
- baerly-storage is designed for the small-to-medium operating point.
544
- The cost model puts the soft ceiling at:
244
+ 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.
545
245
 
546
- - **~30 writes / minute / collection** (throughput ceiling — model/estimate)
547
- - **>10 GB / tenant stored** (R2 free-tier storage line — a cost signal, not a protocol ceiling)
548
- - **~100 collections / tenant** (soft fan-out guideline — bench-grounded linear cost)
549
-
550
- At M-size (~30 writes/min) the projected cost is ~$18/mo on R2. Past
551
- those, per-class op pricing and fan-out scan cost start to dominate;
552
- you've outgrown the workload envelope — move to a database service (D1 / Postgres) suited to higher scale.
553
- Pick your graduation target:
246
+ 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:
554
247
 
555
248
  - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
556
249
  - **Off-Workers or portability matters:** managed Postgres.
557
250
  - **Single-instance Node:** SQLite via Litestream.
558
251
 
559
- Either way, the export below is mechanical because log entries are
560
- Debezium-style CDC change events — graduation is a baerly-storage
561
- win, not a churn event.
562
-
563
- **Estimate your current rate:** for Node/self-hosted buckets,
564
- `baerly admin usage --target=node --bucket=<bucket-uri> --app=<app>
565
- --tenant=<tenant>` lists recent log entries per collection and computes
566
- writes/min. On Cloudflare, use canonical logs for trend history and
567
- `baerly cost --bucket=<bucket-uri> --collection=<collection>` for the
568
- current operation-cost projection until the usage scanner is wired to
569
- R2 bindings.
570
-
571
- **Export when ready:** `baerly export --target=sqlite|postgres|d1
572
- --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
573
- canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
574
- inferred `ExportPlan`) that you load into your graduation target.
575
- The export is point-in-time and honours the active schema. Flags:
576
- `--where=<json-predicate>`, `--where-comment`, `--output`,
577
- `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
578
- 2 Storage/Network, 3 Protocol invariant.
252
+ 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.
253
+
254
+ **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.
255
+
256
+ **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.
579
257
 
580
258
  ## Pointers
581
259