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