@gusto/create-baerly-storage 0.1.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 (88) hide show
  1. package/dist/index.js +2737 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/templates/addons/docker/.dockerignore +13 -0
  4. package/dist/templates/addons/docker/Dockerfile +65 -0
  5. package/dist/templates/addons/docker/healthcheck.js +15 -0
  6. package/dist/templates/minimal-cloudflare/.baerly/scaffold.json +10 -0
  7. package/dist/templates/minimal-cloudflare/AGENTS.md +556 -0
  8. package/dist/templates/minimal-cloudflare/README.md +169 -0
  9. package/dist/templates/minimal-cloudflare/_gitignore +6 -0
  10. package/dist/templates/minimal-cloudflare/baerly.config.ts +20 -0
  11. package/dist/templates/minimal-cloudflare/index.html +12 -0
  12. package/dist/templates/minimal-cloudflare/package.json +28 -0
  13. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +15 -0
  14. package/dist/templates/minimal-cloudflare/src/notes.test.ts +19 -0
  15. package/dist/templates/minimal-cloudflare/src/server/index.ts +11 -0
  16. package/dist/templates/minimal-cloudflare/src/web/main.ts +27 -0
  17. package/dist/templates/minimal-cloudflare/tsconfig.app.json +28 -0
  18. package/dist/templates/minimal-cloudflare/tsconfig.json +9 -0
  19. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +28 -0
  20. package/dist/templates/minimal-cloudflare/types.ts +23 -0
  21. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +16 -0
  22. package/dist/templates/minimal-cloudflare/vite.config.ts +6 -0
  23. package/dist/templates/minimal-cloudflare/vitest.config.ts +11 -0
  24. package/dist/templates/minimal-cloudflare/wrangler.jsonc +27 -0
  25. package/dist/templates/minimal-node/.baerly/scaffold.json +13 -0
  26. package/dist/templates/minimal-node/.env.example +14 -0
  27. package/dist/templates/minimal-node/AGENTS.md +488 -0
  28. package/dist/templates/minimal-node/README.md +180 -0
  29. package/dist/templates/minimal-node/_gitignore +7 -0
  30. package/dist/templates/minimal-node/baerly.config.ts +20 -0
  31. package/dist/templates/minimal-node/index.html +12 -0
  32. package/dist/templates/minimal-node/package.json +26 -0
  33. package/dist/templates/minimal-node/pnpm-workspace.yaml +9 -0
  34. package/dist/templates/minimal-node/src/notes.test.ts +19 -0
  35. package/dist/templates/minimal-node/src/server/index.ts +46 -0
  36. package/dist/templates/minimal-node/src/web/main.ts +27 -0
  37. package/dist/templates/minimal-node/tsconfig.app.json +28 -0
  38. package/dist/templates/minimal-node/tsconfig.json +9 -0
  39. package/dist/templates/minimal-node/tsconfig.server.json +28 -0
  40. package/dist/templates/minimal-node/types.ts +23 -0
  41. package/dist/templates/minimal-node/uint8array-base64.d.ts +16 -0
  42. package/dist/templates/minimal-node/vite.config.ts +15 -0
  43. package/dist/templates/minimal-node/vitest.config.ts +12 -0
  44. package/dist/templates/react-cloudflare/.baerly/scaffold.json +10 -0
  45. package/dist/templates/react-cloudflare/AGENTS.md +715 -0
  46. package/dist/templates/react-cloudflare/README.md +115 -0
  47. package/dist/templates/react-cloudflare/_gitignore +6 -0
  48. package/dist/templates/react-cloudflare/baerly.config.ts +37 -0
  49. package/dist/templates/react-cloudflare/index.html +12 -0
  50. package/dist/templates/react-cloudflare/package.json +34 -0
  51. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +15 -0
  52. package/dist/templates/react-cloudflare/src/notes.test.ts +19 -0
  53. package/dist/templates/react-cloudflare/src/server/index.ts +12 -0
  54. package/dist/templates/react-cloudflare/src/web/App.tsx +38 -0
  55. package/dist/templates/react-cloudflare/src/web/NoteList.tsx +93 -0
  56. package/dist/templates/react-cloudflare/src/web/client.ts +13 -0
  57. package/dist/templates/react-cloudflare/src/web/main.tsx +14 -0
  58. package/dist/templates/react-cloudflare/src/web/styles.css +57 -0
  59. package/dist/templates/react-cloudflare/tsconfig.app.json +29 -0
  60. package/dist/templates/react-cloudflare/tsconfig.json +9 -0
  61. package/dist/templates/react-cloudflare/tsconfig.worker.json +28 -0
  62. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +16 -0
  63. package/dist/templates/react-cloudflare/vite.config.ts +7 -0
  64. package/dist/templates/react-cloudflare/vitest.config.ts +11 -0
  65. package/dist/templates/react-cloudflare/wrangler.jsonc +27 -0
  66. package/dist/templates/react-node/.baerly/scaffold.json +13 -0
  67. package/dist/templates/react-node/.env.example +14 -0
  68. package/dist/templates/react-node/AGENTS.md +662 -0
  69. package/dist/templates/react-node/README.md +187 -0
  70. package/dist/templates/react-node/_gitignore +7 -0
  71. package/dist/templates/react-node/baerly.config.ts +37 -0
  72. package/dist/templates/react-node/index.html +12 -0
  73. package/dist/templates/react-node/package.json +32 -0
  74. package/dist/templates/react-node/pnpm-workspace.yaml +9 -0
  75. package/dist/templates/react-node/src/notes.test.ts +19 -0
  76. package/dist/templates/react-node/src/server/index.ts +48 -0
  77. package/dist/templates/react-node/src/web/App.tsx +38 -0
  78. package/dist/templates/react-node/src/web/NoteList.tsx +93 -0
  79. package/dist/templates/react-node/src/web/client.ts +13 -0
  80. package/dist/templates/react-node/src/web/main.tsx +14 -0
  81. package/dist/templates/react-node/src/web/styles.css +57 -0
  82. package/dist/templates/react-node/tsconfig.app.json +29 -0
  83. package/dist/templates/react-node/tsconfig.json +9 -0
  84. package/dist/templates/react-node/tsconfig.server.json +28 -0
  85. package/dist/templates/react-node/uint8array-base64.d.ts +16 -0
  86. package/dist/templates/react-node/vite.config.ts +17 -0
  87. package/dist/templates/react-node/vitest.config.ts +12 -0
  88. package/package.json +41 -0
@@ -0,0 +1,662 @@
1
+ ---
2
+ title: AGENTS.md — agent guidance for react-node
3
+ audience: agent
4
+ summary: How to develop and deploy react-node, a baerly app.
5
+ tags: [agent-entry, baerly]
6
+ ---
7
+
8
+ # AGENTS.md
9
+
10
+ ## STOP — read this before writing any storage code
11
+
12
+ Your training data is dense with Postgres + Prisma/Drizzle, Mongo,
13
+ and Firebase patterns. **None of them apply here.** This is a baerly
14
+ app — a small, LLM-legible document database with a narrow API on top
15
+ of S3-compatible storage. Before writing or modifying storage code,
16
+ read:
17
+
18
+ - **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored
19
+ public-API quickref. Read first. Lists every method, every error
20
+ code, every example. If a pattern you want to use isn't here, it
21
+ doesn't exist in baerly.
22
+ - **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type
23
+ signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are
24
+ the whole API surface.
25
+
26
+ Common anti-patterns that compile but are wrong:
27
+
28
+ - `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use
29
+ `db.collection(name).insert(row)` and `.where({ ... }).all()`.
30
+ - `z.string().nullable()` in a schema — `DocumentValue` excludes
31
+ `null`. Use `.optional()`; `null` in an update patch is the RFC
32
+ 7396 deletion sentinel, not a storable value.
33
+ - Raw SQL strings, `WHERE` clauses, hand-built query AST — the only
34
+ query surface is `db.collection(...).where({ field: value }).all()` or
35
+ `.where(q => q.gte("count", 1))`. See **Predicates** below.
36
+ - `.useIndex("name")` / `.hint(...)` — no such methods. The planner
37
+ picks the index automatically from `IndexDefinition`s in
38
+ `baerly.config.ts`. See **Indexes** below.
39
+
40
+ ## What this is
41
+
42
+ `react-node` is a baerly app scaffolded with `create-baerly-storage` for the
43
+ Node target — any host that runs `node server.js` (Railway, Render,
44
+ Fly without Docker, Heroku, a VM, a container scheduler). The
45
+ Node-side server lives in `src/server/`; the React client lives in
46
+ `src/web/`. Configuration lives in `baerly.config.ts`.
47
+
48
+ Single package, single `vite` process: `baerlyDev()` from
49
+ `@gusto/baerly-storage/dev/vite` mounts the Node HTTP listener as Connect
50
+ middleware on `:5173` alongside the SPA dev server, so the SPA and
51
+ `/v1/*` share an origin (`http://localhost:5173`). In production the
52
+ same listener serves the built SPA from `dist/client/` via the
53
+ `baerlyNode({ webRoot })` option — same-origin in dev, same-origin
54
+ in prod, one process, one port.
55
+
56
+ This starter is a generic notes app you extend with your own fields —
57
+ a Node HTTP listener wired to an S3-compatible bucket plus a working
58
+ React+Vite frontend in `src/web/` (served by `baerlyNode({ webRoot })`
59
+ in production) with the `Note` shape declared in `baerly.config.ts`.
60
+ The bare server-only version is `pnpm create @gusto/baerly-storage <app> --target=node`;
61
+ this one is `--target=node --starter=react`.
62
+
63
+ If this scaffold was created with `--with=docker`, you'll also have a
64
+ multi-stage distroless `Dockerfile`, a `.dockerignore`, and a
65
+ `healthcheck.js` at the project root — wired to the same
66
+ `pnpm install && pnpm build && pnpm start` flow.
67
+
68
+ Public API docs: https://docs.baerly.dev/ (the JSDoc on
69
+ `baerly-storage`'s `Db` and `Collection` is the canonical reference;
70
+ read it via your editor's TS LS or via the published types).
71
+
72
+ ## Toolchain
73
+
74
+ - **Package manager:** pnpm. The emitted repo pins
75
+ `packageManager: pnpm@11.1.2`.
76
+ - **Test runner:** vitest.
77
+ - **Type checker:** TypeScript 5.6+. (The baerly-storage monorepo
78
+ itself uses TypeScript 7 via `@typescript/native-preview`; this
79
+ template tracks the broadly-compatible TS major so scaffolded
80
+ apps work with the wider ecosystem.)
81
+ - **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
82
+ code stays compatible with type-stripping runtimes (Node's
83
+ `--experimental-strip-types`, esbuild's strip path). The flag bans
84
+ TS constructs that can't be type-erased: write
85
+ `class { x: T; constructor(x: T) { this.x = x } }` explicitly
86
+ instead of parameter-property shorthand
87
+ (`constructor(private x: T) {}` fails with TS1294). The same goes
88
+ for `enum`, namespaces with non-type bindings, and `private` /
89
+ `protected` / `public` accessibility modifiers on constructor
90
+ parameters.
91
+
92
+ ## Verification
93
+
94
+ | Command | What it does | Runtime |
95
+ | ---------------- | --------------------------------------------------------------------------------------- | ---------------- |
96
+ | `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 |
97
+ | `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 |
98
+ | `pnpm typecheck` | TS typecheck across the `app` + `server` project references (`tsc -b --noEmit`) | seconds |
99
+ | `pnpm test` | `vitest run --passWithNoTests` — standalone `vitest.config.ts` (Node env) | seconds |
100
+ | `pnpm dev` | Run `vite` — `baerlyDev()` mounts the Node HTTP listener as Connect middleware next to the SPA dev server; same origin on :5173 | seconds to start |
101
+ | `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the `baerlyNode({ webRoot })` static-serve branch | seconds |
102
+ | `pnpm start` | `node --experimental-strip-types src/server/index.ts` — production entry; serves the SPA from `dist/client/` via `webRoot` | seconds to start |
103
+
104
+ **`pnpm verify` exercises typecheck + tests only.** The dev-auth
105
+ middleware, the SPA bundle, and any custom `/api/*` route are NOT
106
+ under test — verify will exit green even when the dev plugin returns
107
+ 401 on every browser request or the SPA throws on mount. For changes
108
+ that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
109
+ `pnpm dev` and exercise the change in a browser (or `curl
110
+ http://localhost:5173/<path>`) before declaring the task complete.
111
+
112
+ ## Where the code is
113
+
114
+ | Path | What it is |
115
+ | -------------------------- | ---------------------------------------------------------------------------------------------------------------- |
116
+ | `src/server/index.ts` | Server entry — composes `s3Storage` / `r2Storage` + a verifier and calls `baerlyNode({ ... }).listen(PORT)` |
117
+ | `src/web/` | React+Vite frontend. Served by the Node listener via `baerlyNode({ webRoot })` in production. |
118
+ | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.tsx`. |
119
+ | `vite.config.ts` | Vite + `@vitejs/plugin-react` + `baerlyDev()` — mounts the Node HTTP listener as middleware so SPA + `/v1/*` share `:5173` in dev |
120
+ | `tsconfig.json` | Root project-references stub |
121
+ | `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib, `jsx: react-jsx`) |
122
+ | `tsconfig.server.json` | Node server TS project (`src/server/`, Node lib) |
123
+ | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `collections` (schemas live here). Also exports the inferred `Note` row type used by the web client. |
124
+ | `.env.example` | Source of truth for env vars the Node entry reads (`BUCKET`, `AWS_*`, `MAINTENANCE_COLLECTIONS`, etc.; `SHARED_SECRET` / `JWKS_URL` only needed if you adopt the "Going to production" auth recipes) |
125
+
126
+ > **`baerly.config.ts` is dual-included.** Both `tsconfig.app.json`
127
+ > and `tsconfig.server.json` `include` this file, so it must only
128
+ > import from `baerly-storage`, `zod`, and other files reachable
129
+ > from **both** projects. Paths under `src/server/` are server-only;
130
+ > importing them here triggers `TS6307: File … is not listed within
131
+ > the file list of project … tsconfig.app.json`. Put document
132
+ > interfaces here next to their schema (`export type Note =
133
+ > z.infer<typeof NoteSchema>`); re-export from a server-only file if
134
+ > downstream code wants a local name.
135
+
136
+ ## When editing X, read Y
137
+
138
+ - **Typed collections** — three ways to get a typed row, in DX order:
139
+ 1. **Bind the config.** This template's `src/web/client.ts`
140
+ already passes `config` to `createBaerlyClient({ baseUrl,
141
+ config })`, so `client.collection("notes")` returns
142
+ `ClientCollection<Row>` with `Row` derived from the
143
+ `NoteSchema` declared in `baerly.config.ts`. No generic
144
+ needed. Use `client.collection<Note>("notes")` (with `Note`
145
+ exported from `baerly.config.ts` next to the schema)
146
+ only when you need the row type by name elsewhere.
147
+ 2. **Explicit generic, kernel constraint.** Without a declared
148
+ collection, the second overload requires the row to satisfy
149
+ the kernel's `DocumentData` shape (`{ [k: string]: DocumentValue }`):
150
+ ```ts
151
+ import type { DocumentData } from "@gusto/baerly-storage";
152
+ interface Bookmark extends DocumentData { _id: string; url: string }
153
+ await client.collection<Bookmark>("bookmarks").all();
154
+ ```
155
+ A plain `interface Bookmark { _id: string; url: string }`
156
+ (no index signature) will fail with TS2344 — the constraint
157
+ is intentional so the row stays JSON-compatible.
158
+
159
+ - **Writing tests** — the kernel exports `MemoryStorage`, an
160
+ in-memory `Storage` impl that's the canonical backend for unit
161
+ tests. Don't roll your own — `Db.create({ storage, app, tenant,
162
+ config })` is the same boilerplate prod uses; passing
163
+ `new MemoryStorage()` swaps S3 for an in-process map.
164
+
165
+ ```ts
166
+ // src/notes.test.ts
167
+ import { test, expect } from "vitest";
168
+ import { Db, MemoryStorage } from "@gusto/baerly-storage";
169
+ import config from "../baerly.config.ts";
170
+
171
+ test("notes round-trip", async () => {
172
+ const db = Db.create({
173
+ storage: new MemoryStorage(),
174
+ app: "test",
175
+ tenant: "t",
176
+ config,
177
+ });
178
+ const { _id } = await db.collection("notes").insert({ body: "hello" });
179
+ const row = await db.collection("notes").get(_id);
180
+ expect(row?.body).toBe("hello");
181
+ });
182
+ ```
183
+
184
+ Each `new MemoryStorage()` is a fresh bucket — no shared state
185
+ across tests. For multi-writer scenarios (causal-consistency
186
+ tests, etc.), construct one `MemoryStorage` and pass the same
187
+ instance into multiple `Db.create` calls so they share the
188
+ underlying bucket.
189
+
190
+ - **Predicates** — `db.collection("notes").where({...}).all()`. Two
191
+ shapes:
192
+
193
+ - **Object literal** — equality only (top-level, dotted-path, or
194
+ nested literal sub-predicate). Multi-field is implicit AND.
195
+ - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
196
+ for the operator vocabulary. The methods on `PredicateBuilder<T>`
197
+ ARE the supported surface — `q.or` / `q.regex` / `q.ne` /
198
+ `q.exists` are TS compile errors. Chained `.where(...).where(...)`
199
+ AND-merges across shapes.
200
+
201
+ ```ts
202
+ // Top-level equality
203
+ await db.collection("notes").where({ body: "TODO" }).all();
204
+
205
+ // Dotted-path on a nested field
206
+ await db.collection("notes")
207
+ .where({ "meta.source": "import" })
208
+ .all();
209
+
210
+ // Operator on a single field — set membership (callback form)
211
+ await db.collection("notes")
212
+ .where(q => q.in("tag", ["todo", "wip"]))
213
+ .all();
214
+
215
+ // Range — also callback form
216
+ await db.collection("notes")
217
+ .where(q => q.gte("created_at", "2026-01-01"))
218
+ .all();
219
+
220
+ // AND-merge across two .where() calls (mix shapes freely)
221
+ await db.collection("notes")
222
+ .where({ body: "TODO" })
223
+ .where(q => q.gte("priority", 5))
224
+ .all();
225
+ ```
226
+
227
+ The plain-equality value type is JSON-arrayless: string / number /
228
+ boolean / nested object. Use `q.in("tag", [...])` for set
229
+ membership when you'd otherwise want `{ tag: ["todo","wip"] }`.
230
+
231
+ - **Indexes** — declare them in `baerly.config.ts`; the read-path
232
+ planner picks one automatically when the predicate's equality
233
+ fields (and at most one range / `in` clause on the next indexed
234
+ field) cover the index's `on` tuple. No call-site hint is needed
235
+ — `Query<T>` has no `.useIndex()` method.
236
+
237
+ ```ts
238
+ import { defineConfig } from "@gusto/baerly-storage/config";
239
+
240
+ export default defineConfig({
241
+ collections: {
242
+ notes: {
243
+ indexes: [{ name: "by_body", on: "body" }],
244
+ },
245
+ },
246
+ });
247
+ ```
248
+
249
+ The adapter threads `collections` into `Db.create({ ... })` for
250
+ you. Predicates the planner can't route fall back to the full
251
+ scan with a metric bump — correctness is preserved.
252
+
253
+ - **Schemas (live feature)** — schemas are validated on the server
254
+ for every `insert` / `update` / `replace` when bound. Declare via
255
+ `defineConfig` using any StandardSchema v1 validator (Zod 3.24+,
256
+ Valibot 0.36+, ArkType 2.0+, or anything implementing the spec):
257
+
258
+ ```ts
259
+ import { z } from "zod";
260
+ import { defineConfig } from "@gusto/baerly-storage/config";
261
+
262
+ const Note = z.object({
263
+ _id: z.string(),
264
+ body: z.string().min(1),
265
+ });
266
+
267
+ export default defineConfig({
268
+ collections: {
269
+ notes: { schema: Note },
270
+ },
271
+ });
272
+ ```
273
+
274
+ On a validation failure the server throws
275
+ `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
276
+ HTTP clients see a 422 with the same envelope. Validation runs
277
+ on the post-image so `update` and `replace` see the full doc, not
278
+ just the patch.
279
+
280
+ - **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
281
+ (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
282
+ only when debugging the wire. Mutation bodies are wrapped:
283
+
284
+ | Route | Body | Response |
285
+ | --------------------------- | ------------------- | ----------------------------- |
286
+ | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
287
+ | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
288
+ | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
289
+ | `DELETE /v1/c/:collection/:id` | — | `204` |
290
+
291
+ Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
292
+ `GET /v1/since?collection=…&cursor=…`) take no body and return
293
+ `{ data, _meta }` or a route-specific envelope. A flat `POST` body
294
+ (without the `doc` wrapper) returns
295
+ `400 SchemaError "Request body must be { doc: object }"` — the
296
+ wording is locked by `assertJsonBodyField` in the kernel. Canonical
297
+ reference: the `Routes` type and the JSDoc on `createRouter` in
298
+ `baerly-storage`.
299
+
300
+ - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
301
+ every request resolves to `tenant: "react-demo"` and `Authorization`
302
+ is ignored. The adapter reads `config.auth` to pick its verifier;
303
+ a `verifier:` on `baerlyNode({ ... })` overrides it. The schema-
304
+ bound `notes` collection (`baerly.config.ts:NoteSchema`) runs
305
+ server-side regardless of the auth posture. `baerly doctor
306
+ --target=node` warns on `"none"` for deploy targets. See "Going to
307
+ production" below for the two production-fit recipes.
308
+
309
+ ### Going to production
310
+
311
+ The scaffold ships `auth: "none"` so the day-1 happy path works with
312
+ zero env vars. The `NoteSchema` in `baerly.config.ts` continues to
313
+ validate writes server-side under every posture below — only the
314
+ header-check seam changes.
315
+
316
+ <!-- pattern-b:start -->
317
+ **Pattern B — `auth: "shared-secret"`** (single-tenant
318
+ server-to-server). No factory code changes; `baerly.config.ts` flips:
319
+
320
+ ```ts
321
+ // baerly.config.ts
322
+ auth: "shared-secret", // ← flip from "none"
323
+ ```
324
+
325
+ Dev: put `SHARED_SECRET=dev-shared-secret` in `.env`. Prod: set
326
+ `SHARED_SECRET` in the process environment (your PaaS / secret
327
+ manager). `baerly doctor --target=node` FAILs if
328
+ `auth: "shared-secret"` is set without `SHARED_SECRET` reachable from
329
+ `process.env`.
330
+
331
+ <!-- pattern-b:end -->
332
+ <!-- pattern-c:start -->
333
+ **Pattern C — JWKS-backed JWT** (multi-tenant; OIDC IdP). The factory
334
+ `verifier:` overrides `config.auth`, so dev keeps `"none"` and prod
335
+ gets `bearerJwt`:
336
+
337
+ ```ts
338
+ // baerly.config.ts — unchanged
339
+ auth: "none", // dev default
340
+ ```
341
+
342
+ ```ts
343
+ // src/server/index.ts
344
+ import { baerlyNode, s3Storage } from "@gusto/baerly-storage/node";
345
+ import { bearerJwt } from "@gusto/baerly-storage/auth";
346
+ import config from "../../baerly.config.ts";
347
+
348
+ await baerlyNode({
349
+ config,
350
+ storage: s3Storage({
351
+ region: process.env["AWS_REGION"] ?? "us-east-1",
352
+ bucket: process.env["BUCKET"]!,
353
+ credentials: {
354
+ accessKeyId: process.env["AWS_ACCESS_KEY_ID"]!,
355
+ secretAccessKey: process.env["AWS_SECRET_ACCESS_KEY"]!,
356
+ },
357
+ }),
358
+ ...(process.env["JWKS_URL"] !== undefined && {
359
+ verifier: bearerJwt({
360
+ jwks: process.env["JWKS_URL"],
361
+ issuer: process.env["JWT_ISSUER"]!,
362
+ audience: process.env["JWT_AUDIENCE"]!,
363
+ }),
364
+ }),
365
+ }).listen(Number(process.env["PORT"] ?? 8080));
366
+ ```
367
+
368
+ Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
369
+ `config.auth: "none"` runs. Prod sets `JWKS_URL` + `JWT_ISSUER` +
370
+ `JWT_AUDIENCE` and `bearerJwt` engages.
371
+
372
+ <!-- pattern-c:end -->
373
+ - **Storage backend** — `src/server/index.ts` picks between
374
+ `s3Storage` (AWS) and `r2Storage` (Cloudflare R2 via S3-compat)
375
+ based on whether `R2_ACCOUNT_ID` is set. To use **Minio**
376
+ (self-hosted dev S3) or **GCS** (HMAC keys), swap the import to
377
+ `minioStorage` / `gcsStorage` from `@gusto/baerly-storage/node`. All
378
+ four factories take the same shape — a single bucket-name +
379
+ credentials object — and hide `aws4fetch` / `@xmldom/xmldom`
380
+ behind the package boundary. JSDoc `@example` blocks for each
381
+ factory are visible in your editor's TS hover. The bucket name
382
+ comes from the `BUCKET` env var; AWS credentials are read from
383
+ `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and optional
384
+ `AWS_REGION`).
385
+
386
+ - **Switching from static creds to EKS Pod Identity** — in
387
+ `src/server/index.ts`, swap `credentials: { accessKeyId,
388
+ secretAccessKey }` for `credentials: fromEksPodIdentity()` and add
389
+ `fromEksPodIdentity` to your import:
390
+ `import { s3Storage, fromEksPodIdentity } from "@gusto/baerly-storage/node"`.
391
+ The agent reads `AWS_CONTAINER_CREDENTIALS_FULL_URI` +
392
+ `AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE` (EKS injects both). For
393
+ IRSA / ECS / EC2 / other AWS contexts, see
394
+ `packages/adapter-node/AGENTS.md` — pass any
395
+ `() => Promise<Credentials>` or an `@aws-sdk/credential-providers`
396
+ factory through the seam.
397
+
398
+ - **Maintenance loop (Node)** — `src/server/index.ts` passes a
399
+ `maintenance: { collections, tenants }` option to `baerlyNode`.
400
+ Each tick (hourly by default; override via
401
+ `maintenance.intervalMs`) runs one compact+GC pass per
402
+ `(tenant, collection)` pair against the engine's default
403
+ unbounded maintenance profile (folds the entire live tail; sweeps
404
+ every aged-out candidate the GC marks).
405
+
406
+ Opt-in via the `MAINTENANCE_COLLECTIONS` env var — a comma-
407
+ separated list of collection slugs:
408
+
409
+ ```sh
410
+ MAINTENANCE_COLLECTIONS=notes
411
+ ```
412
+
413
+ When unset, the entry passes `maintenance: undefined` to
414
+ `baerlyNode` and no in-process loop runs. Operators who prefer
415
+ external scheduling can wire a separate cron trigger (PaaS cron,
416
+ k8s CronJob, systemd timer) per collection that invokes
417
+ `runMaintenanceTick` directly — that function stays exported
418
+ from `@gusto/baerly-storage/node`.
419
+
420
+ The template is single-tenant by default (`tenants: [TENANT]`).
421
+ Multi-tenant deployments override the `tenants` array in
422
+ `src/server/index.ts`; the cross-product `tenants × collections`
423
+ defines the work per tick. A separate `runMaintenanceTick` call
424
+ fires per pair, and a failure on one pair logs to stderr without
425
+ crashing the process or blocking the others.
426
+
427
+ Maintenance emits one canonical info line per `(tenant,
428
+ collection)` run on stdout. Filter your log stream on
429
+ `"unit_of_work": "maintenance"` and read these fields:
430
+
431
+ - `compact_written` — log entries folded into the new snapshot
432
+ this tick (`0` when the live tail was below
433
+ `minEntriesToCompact`).
434
+ - `gc_swept` — keys deleted this tick (`0` when no candidates
435
+ aged out).
436
+ - The kernel also emits the recorder-bag fields alongside:
437
+ `db.compact.entries_folded_p50` / `_p99` / `_count` / `_sum`,
438
+ `db.manifest.lag_window_depth`, `db.orphan.candidate_count`,
439
+ `db.gc.entries_swept_per_second`, `db.gc.swept_total`.
440
+ Useful for dashboards; the four explicit fields above are
441
+ the at-a-glance summary.
442
+
443
+ - **Deploy** — runs anywhere `node server.js` runs. The
444
+ `package.json`'s `start` script is
445
+ `node --experimental-strip-types src/server/index.ts`. Arrange the
446
+ host to run `pnpm install && pnpm build` (populates
447
+ `dist/client/` for the `webRoot` static-serve branch) before
448
+ `pnpm start`. Set env vars from `.env.example` in the host's
449
+ config — at minimum `BUCKET`, `AWS_ACCESS_KEY_ID`,
450
+ `AWS_SECRET_ACCESS_KEY`. The default scaffold's `auth: "none"`
451
+ needs no auth env vars; if you adopt Pattern B / C from "Going to
452
+ production" above, also set `SHARED_SECRET` (Pattern B) or
453
+ `JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE` (Pattern C).
454
+
455
+ Shapes: **managed PaaS** (Railway, Render, DO App Platform, Fly
456
+ without Docker, Heroku) auto-detects Node and runs the root
457
+ scripts directly. **VM / bare-metal** uses your process manager
458
+ of choice (systemd, pm2). **Container** (Docker, k8s, ECS, Fly
459
+ Machines with a Dockerfile) — scaffold with `--with=docker` to
460
+ add a production Dockerfile alongside this shape, or write your
461
+ own.
462
+
463
+ ## Anti-patterns
464
+
465
+ - Widening branded types from `baerly-storage` (`UUID`,
466
+ `ContentVersionId`). The types prevent confusion bugs.
467
+ - Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
468
+ consume the published exports.
469
+ - Mutating `VerifierResult.tenantPrefix` between the verifier
470
+ and `Db.create`. The dispatcher pins the tenant from the
471
+ verifier's return value.
472
+ - Calling `db.collection(...).all()` (or any unbounded read) inside a
473
+ per-request handler. The call scans the entire collection on every
474
+ request — fine for a fixture-sized table, catastrophic at any real
475
+ size, and `pnpm verify` doesn't surface the cost. Push the filter
476
+ into the predicate so the index planner can prune
477
+ (`db.collection("notes").where({ ... }).all()`), or maintain a
478
+ side-projection (Postgres/SQLite/search index) populated
479
+ incrementally from the `/v1/since` log feed or from a write hook —
480
+ never re-scan per request.
481
+
482
+ ## When to graduate
483
+
484
+ baerly is designed for the small-to-medium operating point. The cost
485
+ model puts the soft ceiling at:
486
+
487
+ - **~30 writes / minute / collection**
488
+ - **~10 GB / tenant**
489
+ - **~100 collections / tenant**
490
+
491
+ Past those, S3 list-prefix latency, manifest fold cost, and per-class
492
+ op pricing start to dominate; you're better off on a real database.
493
+ Pick your graduation target:
494
+ - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
495
+ - **Off-Workers or portability matters:** managed Postgres.
496
+ - **Single-instance Node:** SQLite via Litestream.
497
+
498
+ Either way, the export below is mechanical because log entries are
499
+ Postgres-logical-replication-shaped — graduation is a Baerly win,
500
+ not a churn event.
501
+
502
+ **Estimate your current rate:** `baerly admin usage --target=...`
503
+ lists recent log entries per collection and computes
504
+ writes/min. Warning at 50% of the ceiling; export suggestion at
505
+ 100%.
506
+
507
+ **Export when ready:** `baerly export --target=sqlite|postgres|d1
508
+ --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
509
+ canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
510
+ inferred `ExportPlan`) that you load into your graduation target.
511
+ The export is point-in-time and honours the active schema. Flags:
512
+ `--where=<json-predicate>`, `--where-comment`, `--output`,
513
+ `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
514
+ 2 Storage/Network, 3 Protocol invariant.
515
+
516
+ ## Worked extensions
517
+
518
+ Three recipes that come up routinely when you extend the
519
+ scaffolded `notes` shape. Each one is target-agnostic — the same
520
+ code works in `react-cloudflare` and `react-node`.
521
+
522
+ ### Adding an enum field (e.g. `status`)
523
+
524
+ A row often needs a constrained set of string values. Declare the
525
+ enum inside the Zod schema and export the option tuple next to it
526
+ in `baerly.config.ts`; the predicate API picks the field up
527
+ automatically.
528
+
529
+ ```typescript
530
+ // baerly.config.ts
531
+ import { z } from "zod";
532
+ import { defineConfig } from "@gusto/baerly-storage/config";
533
+
534
+ export const NoteSchema = z.object({
535
+ _id: z.string(),
536
+ body: z.string().min(1),
537
+ status: z.enum(["open", "in_progress", "closed"]),
538
+ });
539
+
540
+ export type Note = z.infer<typeof NoteSchema>;
541
+ export const STATUSES = NoteSchema.shape.status.options;
542
+
543
+ export default defineConfig({ /* ... */ });
544
+ ```
545
+
546
+ ```tsx
547
+ // In a form component:
548
+ import { STATUSES } from "../../baerly.config.ts";
549
+
550
+ <select name="status" defaultValue="open">
551
+ {STATUSES.map((s) => (
552
+ <option key={s} value={s}>{s}</option>
553
+ ))}
554
+ </select>
555
+ ```
556
+
557
+ The schema enum is the single source of truth — adding a value
558
+ there expands the `<select>` immediately. Adding more enum fields
559
+ (`priority`, `severity`) follows the same shape.
560
+
561
+ ### Filtering a reactive query by predicate
562
+
563
+ `useQuery((c) => c.collection(...).where(...).all(), [deps])` accepts the
564
+ same predicate shapes as the bare client. To narrow by an enum field,
565
+ drive it off `useState` and lift the filter into the `deps` array so
566
+ the cache key changes when the filter does:
567
+
568
+ ```tsx
569
+ import { useState } from "react";
570
+ import { useQuery } from "@gusto/baerly-storage/client/react";
571
+ import { STATUSES, type Note } from "../../baerly.config.ts";
572
+
573
+ type Filter = "all" | Note["status"];
574
+
575
+ const [filter, setFilter] = useState<Filter>("all");
576
+ const result = useQuery(
577
+ (c) =>
578
+ filter === "all"
579
+ ? c.collection<Note>("notes").all()
580
+ : c.collection<Note>("notes").where({ status: filter }).all(),
581
+ [filter],
582
+ );
583
+ ```
584
+
585
+ `useQuery` re-runs the callback when `deps` changes OR when the
586
+ `/v1/since` long-poll batches a non-empty change for any subscribed
587
+ collection. Idle long-poll cycles (empty batches) drop at the
588
+ `subscription-pool` layer, so a steady-state collection costs zero list
589
+ reads. Add a `<select>` bound to `setFilter` and the list narrows live.
590
+
591
+ For conditional / deferred reads, return the `useQuery.skip` sentinel
592
+ from the callback — the hook short-circuits to
593
+ `status: "skipped"` with no subscription:
594
+
595
+ ```tsx
596
+ const filtered = useQuery(
597
+ (c) =>
598
+ filter === "all"
599
+ ? useQuery.skip
600
+ : c.collection<Note>("notes").where({ status: filter }).all(),
601
+ [filter],
602
+ );
603
+ if (filtered.status === "skipped") return <FullList />;
604
+ ```
605
+
606
+ For dependent reads, compose two `useQuery` calls — the second one
607
+ returns `useQuery.skip` until the first resolves to `"ok"`:
608
+
609
+ ```tsx
610
+ const parent = useQuery((c) => c.collection<Note>("notes").get(id), [id]);
611
+ const replies = useQuery(
612
+ (c) =>
613
+ parent.status === "ok"
614
+ ? c.collection("comments").where({ noteId: parent.data?._id }).all()
615
+ : useQuery.skip,
616
+ [parent.status === "ok" ? parent.data?._id : undefined],
617
+ );
618
+ ```
619
+
620
+ Mutations are inline: `useMutation()` returns a `[mutate, { isPending,
621
+ error }]` tuple. `mutate(cb)` runs `cb` against the real client:
622
+
623
+ ```tsx
624
+ const [mutate, { isPending, error }] = useMutation();
625
+ <button
626
+ disabled={isPending}
627
+ onClick={() => mutate((c) => c.collection("notes").update(id, { body }))}
628
+ >
629
+ {isPending ? "Saving…" : "Save"}
630
+ </button>
631
+ ```
632
+
633
+ ### Optional fields
634
+
635
+ Some fields aren't always present (`tags` may be missing entirely
636
+ on some rows). Zod's `.optional()` models this:
637
+
638
+ ```typescript
639
+ export const NoteSchema = z.object({
640
+ _id: z.string(),
641
+ body: z.string().min(1),
642
+ tags: z.array(z.string()).optional(), // tags?: string[]
643
+ });
644
+ ```
645
+
646
+ The Zod-inferred `Note` type reflects the shape (`tags?: string[]`)
647
+ and call sites pick it up through `import type { Note }`.
648
+ JSON-merge-patch (RFC 7396) semantics apply on `update()`:
649
+ omitting `tags` from an update preserves the existing value;
650
+ passing `tags: null` deletes the field; passing `tags: []` sets
651
+ it to an empty array. Note that `null` is the deletion sentinel,
652
+ not a storable value — `DocumentValue` doesn't include `null`,
653
+ so `find()` returns deleted fields as `undefined`, not `null`.
654
+ That's why this recipe uses `.optional()` and not `.nullable()`.
655
+
656
+ ## Pointers
657
+
658
+ - `baerly.config.ts` — app config + `NoteSchema` + inferred `Note` type.
659
+ - `src/server/index.ts` — `node:http` listener entry (`baerlyNode`).
660
+ - `vite.config.ts` — Vite + `@vitejs/plugin-react` + `baerlyDev()`.
661
+ - `.env.example` — env vars the Node entry reads at startup.
662
+ - `package.json` — root scripts + dependencies.