@gusto/create-baerly-storage 0.2.0 → 0.4.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 (29) hide show
  1. package/LICENSE +202 -0
  2. package/dist/index.js +54 -28
  3. package/dist/index.js.map +1 -1
  4. package/dist/templates/addons/docker/Dockerfile +8 -2
  5. package/dist/templates/minimal-cloudflare/AGENTS.md +140 -101
  6. package/dist/templates/minimal-cloudflare/README.md +43 -33
  7. package/dist/templates/minimal-cloudflare/package.json +7 -7
  8. package/dist/templates/minimal-cloudflare/wrangler.jsonc +1 -1
  9. package/dist/templates/minimal-node/.baerly/scaffold.json +1 -1
  10. package/dist/templates/minimal-node/.env.example +12 -5
  11. package/dist/templates/minimal-node/AGENTS.md +135 -107
  12. package/dist/templates/minimal-node/README.md +77 -44
  13. package/dist/templates/minimal-node/package.json +5 -5
  14. package/dist/templates/minimal-node/src/server/index.ts +22 -30
  15. package/dist/templates/minimal-node/src/server/resolve-storage.ts +18 -0
  16. package/dist/templates/minimal-node/vite.config.ts +0 -2
  17. package/dist/templates/react-cloudflare/AGENTS.md +77 -52
  18. package/dist/templates/react-cloudflare/README.md +25 -16
  19. package/dist/templates/react-cloudflare/index.html +1 -1
  20. package/dist/templates/react-cloudflare/package.json +12 -12
  21. package/dist/templates/react-cloudflare/wrangler.jsonc +1 -1
  22. package/dist/templates/react-node/.env.example +12 -5
  23. package/dist/templates/react-node/AGENTS.md +117 -81
  24. package/dist/templates/react-node/README.md +67 -37
  25. package/dist/templates/react-node/package.json +10 -10
  26. package/dist/templates/react-node/src/server/index.ts +18 -29
  27. package/dist/templates/react-node/src/server/resolve-storage.ts +18 -0
  28. package/dist/templates/react-node/vite.config.ts +0 -2
  29. package/package.json +16 -11
@@ -45,9 +45,15 @@ WORKDIR /app
45
45
  # Distroless's `nonroot` user is UID 65532. We run as that.
46
46
  USER nonroot:nonroot
47
47
 
48
- # Copy the TS source, the SPA build, the healthcheck, the manifest,
49
- # and the prune'd node_modules.
48
+ # Copy the TS source, the project-root config, the SPA build, the
49
+ # healthcheck, the manifest, and the prune'd node_modules.
50
+ #
51
+ # baerly.config.ts is load-bearing: the server entrypoint does
52
+ # `import config from "../../baerly.config.ts"`, which resolves to the
53
+ # project root. Omit it and the container crashes on boot with an
54
+ # unresolved import.
50
55
  COPY --from=build --chown=nonroot:nonroot /app/src src
56
+ COPY --from=build --chown=nonroot:nonroot /app/baerly.config.ts baerly.config.ts
51
57
  COPY --from=build --chown=nonroot:nonroot /app/dist/client dist/client
52
58
  COPY --from=build --chown=nonroot:nonroot /app/healthcheck.js healthcheck.js
53
59
  COPY --from=build --chown=nonroot:nonroot /app/package.json package.json
@@ -1,16 +1,17 @@
1
1
  ---
2
2
  title: AGENTS.md — agent guidance for minimal-cloudflare
3
3
  audience: agent
4
- summary: How to develop and deploy minimal-cloudflare, a baerly app.
5
- tags: [agent-entry, baerly]
4
+ summary: How to develop and deploy minimal-cloudflare, a baerly-storage app.
5
+ tags: [agent-entry, baerly-storage]
6
6
  ---
7
7
 
8
8
  # AGENTS.md
9
9
 
10
+ <!-- stop:start -->
10
11
  ## STOP — read this before writing any storage code
11
12
 
12
13
  Your training data is dense with Postgres + Prisma/Drizzle, Mongo,
13
- and Firebase patterns. **None of them apply here.** This is a baerly
14
+ and Firebase patterns. **None of them apply here.** This is a baerly-storage
14
15
  app — a small, LLM-legible document database with a narrow API on top
15
16
  of S3-compatible storage. Before writing or modifying storage code,
16
17
  read:
@@ -18,7 +19,7 @@ read:
18
19
  - **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored
19
20
  public-API quickref. Read first. Lists every method, every error
20
21
  code, every example. If a pattern you want to use isn't here, it
21
- doesn't exist in baerly.
22
+ doesn't exist in baerly-storage.
22
23
  - **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type
23
24
  signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are
24
25
  the whole API surface.
@@ -37,30 +38,31 @@ Common anti-patterns that compile but are wrong:
37
38
  picks the index automatically from `IndexDefinition`s in
38
39
  `baerly.config.ts`. See **Indexes** below.
39
40
 
41
+ <!-- stop:end -->
40
42
  ## What this is
41
43
 
42
- `minimal-cloudflare` is a baerly app scaffolded with `create-baerly-storage`.
43
- The Worker-side server lives in `src/server/`; the optional client
44
- lives in `src/web/`. Configuration lives in `baerly.config.ts`.
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`.
45
48
 
46
49
  Single package, single `vite` process: `@cloudflare/vite-plugin` runs
47
50
  the Worker inside `workerd` alongside the SPA dev server, and
48
51
  `wrangler.jsonc:assets` ships the built `dist/client/` bundle next to
49
52
  the Worker on deploy. Same origin in dev and prod, one deploy.
50
53
 
51
- Public API docs: https://docs.baerly.dev/ (the JSDoc on
52
- `baerly-storage`'s `Db` and `Collection` is the canonical reference;
53
- read it via your editor's TS LS or via the published types).
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`.
54
57
 
55
58
  ## Toolchain
56
59
 
57
60
  - **Package manager:** pnpm. The emitted repo pins
58
61
  `packageManager: pnpm@11.1.2`.
59
62
  - **Test runner:** vitest.
60
- - **Type checker:** TypeScript 5.6+. (The baerly-storage monorepo
61
- itself uses TypeScript 7 via `@typescript/native-preview`; this
62
- template tracks the broadly-compatible TS major so scaffolded
63
- apps work with the wider ecosystem.)
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`.)
64
66
  - **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
65
67
  code stays compatible with type-stripping runtimes (Node's
66
68
  `--experimental-strip-types`, esbuild's strip path). The flag bans
@@ -74,15 +76,15 @@ read it via your editor's TS LS or via the published types).
74
76
 
75
77
  ## Verification
76
78
 
77
- | Command | What it does | Runtime |
78
- | ---------------- | --------------------------------------------------------------------------------------- | ---------------- |
79
- | `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 |
80
- | `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 |
81
- | `pnpm typecheck` | TS typecheck across the worker + web project references (`tsc -b --noEmit`) | seconds |
82
- | `pnpm test` | `vitest run --passWithNoTests` — standalone `vitest.config.ts` (Node env, ignores `vite.config.ts` so the Cloudflare plugin doesn't load). The minimal template ships no SPA tests by default; `--passWithNoTests` keeps the gate green until you add one. | seconds |
83
- | `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 |
84
- | `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the Workers Assets binding | seconds |
85
- | `pnpm deploy` | `wrangler deploy` — ships Worker + assets in one shipment (auto-creates R2 on first run via `--x-provision`) | seconds |
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 |
86
88
 
87
89
  **`pnpm verify` exercises typecheck + tests only.** The dev-auth
88
90
  middleware, the SPA bundle, and any custom `/api/*` route are NOT
@@ -94,44 +96,64 @@ http://localhost:5173/<path>`) before declaring the task complete.
94
96
 
95
97
  ## Where the code is
96
98
 
97
- | Path | What it is |
98
- | -------------------------- | ------------------------------------------------------------------------------------ |
99
- | `src/server/index.ts` | Worker entry — `baerlyWorker((env) => ({ verifier }))` |
100
- | `wrangler.jsonc` | Cloudflare Worker manifest — name, R2 binding, assets, vars, triggers, limits, observability |
101
- | `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.ts`. |
102
- | `src/web/main.ts` | SPA client entry — a ~17-line hello-world: reads `client.collection<Note>("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; `client.collection<Row>(name)` is the typed surface. Workers Assets serves the built bundle from `dist/client/`. |
103
- | `vite.config.ts` | Vite + `@cloudflare/vite-plugin` — runs the Worker inside `workerd` in dev |
104
- | `tsconfig.json` | Root project-references stub |
105
- | `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib) |
106
- | `tsconfig.worker.json` | Worker TS project (`src/server/`, workerd lib) |
107
- | `baerly.config.ts` | App config — `app`, `tenant`, `target`, `domain`, `collections` (schemas live here). |
108
- | `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. |
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. |
109
111
 
110
112
  > **`baerly.config.ts` and `types.ts` are dual-included** by both
111
113
  > `tsconfig.app.json` and `tsconfig.worker.json`. Both can only
112
114
  > import from `baerly-storage`, `zod`, and other dual-included root
113
115
  > files. Paths under `src/server/` are worker-only; importing them
114
- > here triggers `TS6307: File … is not listed within the file list
115
- > of project … tsconfig.app.json`. Cross-boundary interfaces belong
116
- > in `types.ts`; re-export from a server-only file if downstream code
117
- > wants a local name.
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.
118
120
 
119
121
  ## When editing X, read Y
120
122
 
121
- - **Typed collections** — three ways to get a typed row, in DX order:
122
- 1. **Bind the config.** Declare the collection (with an optional
123
- schema) in `baerly.config.ts`, pass `config` to
124
- `createBaerlyClient({ baseUrl, config })` (or `Db.create({
125
- storage, config })`), and `client.collection("tickets")` returns
126
- `ClientCollection<Row>` with `Row` derived from the schema. No
127
- generic needed.
128
- 2. **Explicit generic, kernel constraint.** Without a declared
129
- collection, the second overload requires the row to satisfy
130
- the kernel's `DocumentData` shape (`{ [k: string]: DocumentValue }`):
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 }`):
131
144
  ```ts
132
- import type { DocumentData } from "@gusto/baerly-storage";
133
- interface Bookmark extends DocumentData { _id: string; url: string }
134
- await client.collection<Bookmark>("bookmarks").all();
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();
135
157
  ```
136
158
  A plain `interface Bookmark { _id: string; url: string }`
137
159
  (no index signature) will fail with TS2344 — the constraint
@@ -139,9 +161,10 @@ http://localhost:5173/<path>`) before declaring the task complete.
139
161
 
140
162
  - **Writing tests** — the kernel exports `MemoryStorage`, an
141
163
  in-memory `Storage` impl that's the canonical backend for unit
142
- tests. Don't roll your own — `Db.create({ storage, app, tenant,
143
- config })` is the same boilerplate prod uses; passing
144
- `new MemoryStorage()` swaps R2 for an in-process map.
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.
145
168
 
146
169
  ```ts
147
170
  // src/notes.test.ts
@@ -170,7 +193,6 @@ http://localhost:5173/<path>`) before declaring the task complete.
170
193
 
171
194
  - **Predicates** — `db.collection("tickets").where({...}).all()`. Two
172
195
  shapes:
173
-
174
196
  - **Object literal** — equality only (top-level, dotted-path, or
175
197
  nested literal sub-predicate). Multi-field is implicit AND.
176
198
  - **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
@@ -185,24 +207,25 @@ http://localhost:5173/<path>`) before declaring the task complete.
185
207
  await db.collection("tickets").where({ status: "open" }).all();
186
208
 
187
209
  // Dotted-path on a nested field
188
- await db.collection("tickets")
189
- .where({ "assignee.team": "platform" })
190
- .all();
210
+ await db.collection("tickets").where({ "assignee.team": "platform" }).all();
191
211
 
192
212
  // Operator on a single field — set membership (callback form)
193
- await db.collection("tickets")
194
- .where(q => q.in("status", ["open", "pending"]))
213
+ await db
214
+ .collection("tickets")
215
+ .where((q) => q.in("status", ["open", "pending"]))
195
216
  .all();
196
217
 
197
218
  // Range — also callback form
198
- await db.collection("tickets")
199
- .where(q => q.gte("priority", 5).lt("priority", 10))
219
+ await db
220
+ .collection("tickets")
221
+ .where((q) => q.gte("priority", 5).lt("priority", 10))
200
222
  .all();
201
223
 
202
224
  // AND-merge across two .where() calls (mix shapes freely)
203
- await db.collection("tickets")
225
+ await db
226
+ .collection("tickets")
204
227
  .where({ status: "open" })
205
- .where(q => q.gte("priority", 5))
228
+ .where((q) => q.gte("priority", 5))
206
229
  .all();
207
230
  ```
208
231
 
@@ -229,8 +252,9 @@ http://localhost:5173/<path>`) before declaring the task complete.
229
252
  });
230
253
  ```
231
254
 
232
- With that declared, `db.collection("tickets").where({ status: "open"
233
- }).all()` walks `by_status` automatically. Composite indexes
255
+ With that declared, a query like
256
+ `db.collection("tickets").where({ status: "open" }).all()` walks
257
+ `by_status` automatically. Composite indexes
234
258
  (`on: ["status", "priority"]`) match any leftmost prefix.
235
259
  Mismatches (predicate doesn't cover any index) fall back to a full
236
260
  table scan with a metric bump; correctness is preserved because the
@@ -261,7 +285,7 @@ http://localhost:5173/<path>`) before declaring the task complete.
261
285
 
262
286
  On a validation failure the server throws
263
287
  `BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
264
- HTTP clients see a 422 with the same envelope. Validation runs
288
+ HTTP clients see a 400 with the same envelope. Validation runs
265
289
  on the post-image so `update` and `replace` see the full doc, not
266
290
  just the patch.
267
291
 
@@ -269,12 +293,12 @@ http://localhost:5173/<path>`) before declaring the task complete.
269
293
  (`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
270
294
  only when debugging the wire. Mutation bodies are wrapped:
271
295
 
272
- | Route | Body | Response |
273
- | --------------------------- | ------------------- | ----------------------------- |
274
- | `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
275
- | `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
276
- | `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
277
- | `DELETE /v1/c/:collection/:id` | — | `204` |
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` |
278
302
 
279
303
  Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
280
304
  `GET /v1/since?collection=…&cursor=…`) take no body and return
@@ -282,14 +306,14 @@ http://localhost:5173/<path>`) before declaring the task complete.
282
306
  (without the `doc` wrapper) returns
283
307
  `400 SchemaError "Request body must be { doc: object }"` — the
284
308
  wording is locked by `assertJsonBodyField` in the kernel. Canonical
285
- reference: the `Routes` type and the JSDoc on `createRouter` in
309
+ reference: the JSDoc on `createRouter` in
286
310
  `baerly-storage`.
287
311
 
288
312
  - **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
289
313
  every request resolves to `tenant: "minimal-demo"` and `Authorization`
290
314
  is ignored. The adapter reads `config.auth` to pick its verifier;
291
315
  a `verifier:` on the factory overrides it. `baerly doctor
292
- --target=cloudflare` warns on `"none"` for deploy targets. See
316
+ --target=cloudflare` warns on `"none"` for deploy targets. See
293
317
  "Going to production" below for the two production-fit recipes.
294
318
 
295
319
  ### Going to production
@@ -299,6 +323,7 @@ zero env vars. Two patterns flip to a production-fit posture; pick the
299
323
  one matching your gate.
300
324
 
301
325
  <!-- pattern-a:start -->
326
+
302
327
  **Pattern A — env-aware verifier (recommended for CF Access).** Same
303
328
  artifact ships to dev and prod; the factory `verifier:` override
304
329
  engages only when prod env vars are present. `baerlyWorker` resolves
@@ -313,7 +338,7 @@ export default defineConfig({
313
338
  app: "minimal-cloudflare",
314
339
  tenant: "minimal-demo",
315
340
  target: "cloudflare",
316
- auth: "none", // dev default
341
+ auth: "none", // dev default
317
342
  collections: { notes: {} },
318
343
  });
319
344
  ```
@@ -336,6 +361,7 @@ export default baerlyWorker<AppEnv>((env) => ({
336
361
  verifier: cloudflareAccess({
337
362
  teamDomain: env.CF_ACCESS_TEAM_DOMAIN,
338
363
  audienceTag: env.CF_ACCESS_AUDIENCE_TAG,
364
+ tenantPrefix: config.tenant,
339
365
  }),
340
366
  }),
341
367
  }));
@@ -345,12 +371,15 @@ Set both `CF_ACCESS_TEAM_DOMAIN` and `CF_ACCESS_AUDIENCE_TAG` in
345
371
  `wrangler.jsonc:vars` for prod (they're public identifiers, not
346
372
  secrets). Dev `wrangler dev` sees them as `undefined`, the spread
347
373
  short-circuits, and `config.auth: "none"` runs. Prod sees them set
348
- and `cloudflareAccess` engages.
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.
349
377
 
350
378
  <!-- pattern-a:end -->
351
379
  <!-- pattern-b:start -->
380
+
352
381
  **Pattern B — `auth: "shared-secret"`.** Single-tenant
353
- server-to-server callers (CI, cron, internal services). No factory
382
+ server-to-server callers (CI and internal services). No factory
354
383
  code changes; only `baerly.config.ts` flips:
355
384
 
356
385
  ```ts
@@ -391,11 +420,13 @@ if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable
391
420
  from the runtime env.
392
421
 
393
422
  <!-- pattern-b:end -->
423
+
394
424
  - **Extending the Worker with a custom route** — `baerlyWorker(...)`
395
- owns `/v1/*` + `/healthz`. For server-side endpoints the SPA
425
+ owns `/v1/*`, including `/v1/healthz`. For server-side endpoints the SPA
396
426
  client can't run on its own (the canonical case: an endpoint that
397
- needs `db.transaction(...)`, since `createBaerlyClient` is
398
- reads + by-id mutations only), wrap the worker `fetch`:
427
+ fans a write across several documents server-side, since
428
+ `createBaerlyClient` is reads + by-id mutations only), wrap the
429
+ worker `fetch`:
399
430
 
400
431
  ```ts
401
432
  // src/server/index.ts
@@ -428,10 +459,10 @@ from the runtime env.
428
459
  tenant: config.tenant,
429
460
  config,
430
461
  });
431
- // …db.transaction(...), db.collection(...).get(id), etc.
462
+ // …db.collection(...).insert(doc), db.collection(...).get(id), etc.
432
463
  return new Response(null, { status: 204 });
433
464
  }
434
- // Fall through to the baerly cascade for /v1/* + /healthz.
465
+ // Fall through to the baerly cascade for /v1/*, including /v1/healthz.
435
466
  return baerly.fetch!(req, env, ctx);
436
467
  },
437
468
  } satisfies ExportedHandler<BaerlyEnv>;
@@ -452,7 +483,7 @@ from the runtime env.
452
483
  `SHARED_SECRET` (only required if you flip `auth` to
453
484
  `"shared-secret"`) live in `.dev.vars` for local `wrangler dev`
454
485
  and behind `wrangler secret put` in production. `baerly doctor
455
- --target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars`
486
+ --target=cloudflare` reads `CF_ACCESS_*` from `wrangler.jsonc:vars`
456
487
  only, so setting them via `wrangler secret put` would silently
457
488
  defeat the doctor check.
458
489
 
@@ -479,12 +510,14 @@ from the runtime env.
479
510
  into the predicate so the index planner can prune
480
511
  (`db.collection("notes").where({ ... }).all()`), or maintain a
481
512
  side-projection (D1/KV/search index) populated incrementally from
482
- the `/v1/since` log feed or from a write hook — never re-scan per
513
+ the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from
514
+ a write hook — never re-scan per
483
515
  request.
484
516
 
485
517
  ## Maintenance
486
518
 
487
519
  <!-- pattern-d:start -->
520
+
488
521
  Maintenance is automatic and write-triggered. No cron, no sidecar, no scheduler, no
489
522
  timer, no lock, no app-config knob — identical on every host. Every write runs a
490
523
  bounded GC slice inline plus a go/no-go compaction fold bounded by a fold-size ceiling
@@ -498,36 +531,42 @@ maintenance, so the published idle-reader cost bound holds.
498
531
  A bucket maintains itself as long as it takes writes. A bucket served read-only does
499
532
  not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
500
533
  graduate once a collection is large. See docs/about/graduation.md for the per-tier
501
- envelope and the BAERLY_MAINTENANCE_* operator env vars (you almost never need them).
534
+ envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
502
535
 
503
536
  Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
504
537
  your own schedule. Not required for steady-state operation.
538
+
505
539
  <!-- pattern-d:end -->
506
540
 
507
541
  ## When to graduate
508
542
 
509
- baerly is designed for the small-to-medium operating point. The cost
510
- model puts the soft ceiling at:
543
+ baerly-storage is designed for the small-to-medium operating point.
544
+ The cost model puts the soft ceiling at:
511
545
 
512
- - **~30 writes / minute / collection**
513
- - **~10 GB / tenant**
514
- - **~100 collections / tenant**
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)
515
549
 
516
- Past those, S3 list-prefix latency, manifest fold cost, and per-class
517
- op pricing start to dominate; you're better off on a real database.
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.
518
553
  Pick your graduation target:
554
+
519
555
  - **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
520
556
  - **Off-Workers or portability matters:** managed Postgres.
521
557
  - **Single-instance Node:** SQLite via Litestream.
522
558
 
523
559
  Either way, the export below is mechanical because log entries are
524
- Postgres-logical-replication-shaped — graduation is a Baerly win,
525
- not a churn event.
560
+ Debezium-style CDC change events — graduation is a baerly-storage
561
+ win, not a churn event.
526
562
 
527
- **Estimate your current rate:** `baerly admin usage --target=...`
528
- lists recent log entries per collection and computes
529
- writes/min. Warning at 50% of the ceiling; export suggestion at
530
- 100%.
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.
531
570
 
532
571
  **Export when ready:** `baerly export --target=sqlite|postgres|d1
533
572
  --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
@@ -542,6 +581,6 @@ The export is point-in-time and honours the active schema. Flags:
542
581
 
543
582
  - `baerly.config.ts` — app config.
544
583
  - `src/server/index.ts` — Worker entry.
545
- - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars, cron, observability).
584
+ - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars).
546
585
  - `vite.config.ts` — Vite + `@cloudflare/vite-plugin`.
547
586
  - `package.json` — root scripts + dependencies.
@@ -1,12 +1,17 @@
1
1
  # minimal-cloudflare
2
2
 
3
- A baerly app scaffolded with `@gusto/create-baerly-storage` for the **Cloudflare
4
- Workers** target. Single-bucket R2-backed deployment via the
5
- `@gusto/baerly-storage/cloudflare` adapter. Ships `auth: "none"` so the
6
- day-1 happy path works with zero env vars; flip to Cloudflare
7
- Access or a shared secret before deploy — see "Going to
3
+ A baerly-storage app scaffolded with `@gusto/create-baerly-storage` for
4
+ the **Cloudflare Workers** target. Single-bucket R2-backed deployment
5
+ via the `@gusto/baerly-storage/cloudflare` adapter. Ships
6
+ `auth: "none"` so the day-1 happy path works with zero env vars; flip
7
+ to Cloudflare Access or a shared secret before deploy — see "Going to
8
8
  production" below.
9
9
 
10
+ **The R2 bucket is the durable state.** The Worker is trusted app code
11
+ with an R2 binding; it applies the baerly-storage protocol, but it is
12
+ not a database server. No daemon, lock table, scheduler, or idle
13
+ database bill; maintenance is automatic and write-triggered.
14
+
10
15
  ## What you got
11
16
 
12
17
  ```
@@ -16,7 +21,7 @@ minimal-cloudflare/
16
21
  ├── tsconfig.app.json # client TS project (src/web)
17
22
  ├── tsconfig.worker.json # Worker TS project (src/server)
18
23
  ├── vite.config.ts # Vite + @cloudflare/vite-plugin
19
- ├── wrangler.jsonc # Worker manifest — R2 binding, assets, vars, triggers, limits, observability
24
+ ├── wrangler.jsonc # Worker manifest — R2 binding, assets, vars
20
25
  ├── index.html # SPA shell — Vite's entry point
21
26
  ├── baerly.config.ts # app, tenant, target, domain
22
27
  ├── AGENTS.md # deeper guide: predicates, schemas,
@@ -61,7 +66,7 @@ references.
61
66
  # `wrangler r2 bucket create` + `wrangler deploy`.
62
67
  baerly deploy
63
68
 
64
- # Verify the deployed config — bindings, secrets, cron triggers.
69
+ # Verify the deployed config — bindings, secrets, optional triggers.
65
70
  baerly doctor --target=cloudflare
66
71
  ```
67
72
 
@@ -84,44 +89,48 @@ needs no secrets. If you adopt a "Going to production" recipe:
84
89
  `CF_ACCESS_AUDIENCE_TAG` go in `wrangler.jsonc:vars` (they're
85
90
  public identifiers, not secrets).
86
91
  - **Pattern B (`auth: "shared-secret"`):** `SHARED_SECRET` is a
87
- secret — `.dev.vars` for `wrangler dev`, `wrangler secret put
88
- SHARED_SECRET` for production. Each secret is encrypted at rest
89
- and exposed on `env` at runtime.
92
+ secret — use `.dev.vars` for `wrangler dev` and
93
+ `wrangler secret put SHARED_SECRET` for production. Each secret is
94
+ encrypted at rest and exposed on `env` at runtime.
90
95
 
91
96
  ## Next steps
92
97
 
93
98
  1. **Read `AGENTS.md`** for the agent-facing guide — predicates,
94
- indexes, schemas, auth recipes, the maintenance cron, and the
99
+ indexes, schemas, auth recipes, write-triggered maintenance, and the
95
100
  graduation criteria. Codex CLI reads `AGENTS.md`; Claude Code
96
101
  reads `CLAUDE.md`; both files are byte-identical so either
97
102
  surface lands you the same context.
98
103
  2. **Declare your first collection schema** in `baerly.config.ts`
99
- via `defineConfig({ collections: { ... } })` and pass it to
100
- `Db.create({ ..., collections })`. Schema validation is live;
101
- bad inserts return 422.
104
+ via `defineConfig({ collections: { ... } })`. The Worker adapter
105
+ passes that config to `Db.create({ storage, app, tenant, config })`,
106
+ so schema validation is live and bad inserts return 400.
102
107
  3. **Set up production auth** — follow `AGENTS.md` → "Going to
103
108
  production". Pattern A wires CF Access via an env-aware factory
104
109
  `verifier:` override; Pattern B flips `auth: "shared-secret"`.
105
110
  `baerly doctor --target=cloudflare` reports any gaps.
106
- 4. **Check usage trends** — run `baerly doctor --target=cloudflare
107
- --usage` periodically. It estimates your current writes/minute
108
- per collection from recent log entries and warns when you're
109
- approaching the graduation ceiling described in the "When to
110
- graduate" section below.
111
+ 4. **Check usage trends** — run the current operation-cost
112
+ projection:
113
+
114
+ ```sh
115
+ baerly cost --bucket=<bucket-uri> --collection=<collection-name>
116
+ ```
117
+
118
+ Then pipe canonical logs to your observability system for 7-day /
119
+ 30-day write-rate trends. The graduation ceiling is described in
120
+ the "When to graduate" section below.
111
121
 
112
122
  ## When to graduate
113
123
 
114
- baerly is designed for the small-to-medium operating point. Past these
115
- thresholds, S3 list-prefix latency and per-class operation pricing
116
- start to dominate, and you're better off on a real database:
124
+ baerly-storage is designed for the small-to-medium operating point.
125
+ Past these thresholds, S3 list-prefix latency and per-class operation
126
+ pricing starts to dominate, and you've outgrown the workload envelope — move to a database service:
117
127
 
118
- - **~30 writes / minute / collection**
119
- - **~10 GB / tenant**
120
- - **~100 collections / tenant**
128
+ - **~30 writes / minute / collection** — per-collection throughput estimate (CAS-livelock model)
129
+ - **>10 GB / tenant** — R2 free-tier storage cost line (a billing signal, not a protocol ceiling)
130
+ - **~100 collections / tenant** — soft fan-out guideline (linear cost, bench-grounded; nothing enforces it)
121
131
 
122
- When you cross the soft ceiling, graduation is mechanical:
123
- `baerly export --target=postgres` walks your log entries (already
124
- Postgres-logical-replication-shaped) into a real DB. If your
132
+ When you cross these signals, graduation is mechanical:
133
+ `baerly export --target=postgres` walks your log entries (already Debezium-style CDC change events) into a database service. If your
125
134
  deploy target is Cloudflare Workers and you'll accept Cloudflare
126
135
  lock-in, [D1](https://developers.cloudflare.com/d1/) is cheaper
127
136
  per-write at M-size and is a natural next step. If you're on
@@ -129,12 +138,12 @@ AWS, on-prem, or want your data portable, managed Postgres is
129
138
  the typical destination. Either way — graduation is a Baerly win,
130
139
  not a churn event.
131
140
 
132
- **Export to a real database** (swap `--target=` for `sqlite`,
141
+ **Export to a database service** (swap `--target=` for `sqlite`,
133
142
  `postgres`, or `d1`):
134
143
 
135
144
  ```sh
136
145
  baerly export --target=postgres \
137
- --bucket=minimal-cloudflare --app=minimal-cloudflare --tenant=<your-tenant> \
146
+ --bucket=s3://minimal-cloudflare --app=minimal-cloudflare --tenant=<your-tenant> \
138
147
  --collection=<collection-name> --output=./out.sql
139
148
  ```
140
149
 
@@ -155,7 +164,8 @@ Before deploy, follow `AGENTS.md` → "Going to production":
155
164
  `wrangler.jsonc:vars`. The `cloudflareAccess()` preset
156
165
  (re-exported from `@gusto/baerly-storage/auth`) reads the JWT off
157
166
  `Cf-Access-Jwt-Assertion`, validates it against your team's JWKS,
158
- and derives `tenantPrefix` from the email claim.
167
+ and pins `tenantPrefix` to `config.tenant` unless you pass an
168
+ explicit tenant claim.
159
169
  - **Pattern B — `auth: "shared-secret"`.** Single-tenant
160
170
  server-to-server callers. Flip `auth` in `baerly.config.ts` and
161
171
  set `SHARED_SECRET` via `wrangler secret put`.
@@ -163,7 +173,7 @@ Before deploy, follow `AGENTS.md` → "Going to production":
163
173
  ## Pointers
164
174
 
165
175
  - `baerly.config.ts` — app config (`app`, `tenant`, `target`, `domain`).
166
- - `src/server/index.ts` — Worker fetch + scheduled handler.
167
- - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars, cron, observability).
176
+ - `src/server/index.ts` — Worker fetch entry.
177
+ - `wrangler.jsonc` — Cloudflare Worker manifest (R2 binding, `assets:`, vars).
168
178
  - `vite.config.ts` — Vite + `@cloudflare/vite-plugin`.
169
179
  - `AGENTS.md` / `CLAUDE.md` — agent-facing guide (byte-identical).