@gusto/create-baerly-storage 0.5.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/THIRD-PARTY-LICENSES.txt +204 -0
- package/dist/index.js +1537 -145
- package/dist/index.js.map +1 -1
- package/dist/templates/addons/docker/Dockerfile +13 -11
- package/dist/templates/minimal-cloudflare/AGENTS.md +77 -399
- package/dist/templates/minimal-cloudflare/README.md +33 -97
- package/dist/templates/minimal-cloudflare/package.json +12 -9
- package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +13 -7
- package/dist/templates/minimal-cloudflare/tsconfig.app.json +2 -3
- package/dist/templates/minimal-cloudflare/tsconfig.worker.json +2 -3
- package/dist/templates/minimal-cloudflare/vitest.config.ts +1 -1
- package/dist/templates/minimal-cloudflare/wrangler.jsonc +4 -2
- package/dist/templates/minimal-node/AGENTS.md +80 -380
- package/dist/templates/minimal-node/README.md +37 -135
- package/dist/templates/minimal-node/package.json +11 -9
- package/dist/templates/minimal-node/pnpm-workspace.yaml +14 -9
- package/dist/templates/minimal-node/tsconfig.app.json +2 -3
- package/dist/templates/minimal-node/tsconfig.server.json +2 -3
- package/dist/templates/react-cloudflare/AGENTS.md +101 -444
- package/dist/templates/react-cloudflare/README.md +14 -54
- package/dist/templates/react-cloudflare/package.json +18 -15
- package/dist/templates/react-cloudflare/pnpm-workspace.yaml +13 -7
- package/dist/templates/react-cloudflare/tsconfig.app.json +2 -3
- package/dist/templates/react-cloudflare/tsconfig.worker.json +2 -3
- package/dist/templates/react-cloudflare/vitest.config.ts +1 -1
- package/dist/templates/react-cloudflare/wrangler.jsonc +4 -2
- package/dist/templates/react-node/AGENTS.md +108 -474
- package/dist/templates/react-node/README.md +35 -125
- package/dist/templates/react-node/package.json +16 -14
- package/dist/templates/react-node/pnpm-workspace.yaml +14 -9
- package/dist/templates/react-node/tsconfig.app.json +2 -3
- package/dist/templates/react-node/tsconfig.server.json +2 -3
- package/package.json +7 -7
- package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +0 -16
- package/dist/templates/minimal-node/uint8array-base64.d.ts +0 -16
- package/dist/templates/react-cloudflare/uint8array-base64.d.ts +0 -16
- package/dist/templates/react-node/uint8array-base64.d.ts +0 -16
|
@@ -8,348 +8,112 @@ tags: [agent-entry, baerly-storage]
|
|
|
8
8
|
# AGENTS.md
|
|
9
9
|
|
|
10
10
|
<!-- stop:start -->
|
|
11
|
+
|
|
11
12
|
## STOP — read this before writing any storage code
|
|
12
13
|
|
|
13
|
-
Your training data is dense with Postgres + Prisma/Drizzle, Mongo,
|
|
14
|
-
and Firebase patterns. **None of them apply here.** This is a baerly-storage
|
|
15
|
-
app — a small, LLM-legible document database with a narrow API on top
|
|
16
|
-
of S3-compatible storage. Before writing or modifying storage code,
|
|
17
|
-
read:
|
|
14
|
+
Your training data is dense with Postgres + Prisma/Drizzle, Mongo, and Firebase patterns. **None of them apply here.** This is a baerly-storage app — a small, LLM-legible document database with a narrow API on top of S3-compatible storage. Before writing or modifying storage code, read:
|
|
18
15
|
|
|
19
|
-
- **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
doesn't exist in baerly-storage.
|
|
23
|
-
- **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type
|
|
24
|
-
signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are
|
|
25
|
-
the whole API surface.
|
|
16
|
+
- **`node_modules/@gusto/baerly-storage/dist/API.md`** — hand-authored public-API quickref. Read first. Lists every method, every error code, every example. If a pattern you want to use isn't here, it doesn't exist in baerly-storage.
|
|
17
|
+
- **`node_modules/@gusto/baerly-storage/dist/RECIPES.md`** — common mistakes keyed by the exact error string, plus recipes (storage credentials on Node, wrapping the client `fetch`, a gated adapter, scheduled maintenance).
|
|
18
|
+
- **`node_modules/@gusto/baerly-storage/dist/*.d.ts`** — authoritative type signatures. `Db`, `Collection<T>`, `Query<T>`, and `Predicate<T>` are the whole API surface.
|
|
26
19
|
|
|
27
20
|
Common anti-patterns that compile but are wrong:
|
|
28
21
|
|
|
29
|
-
- `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use
|
|
30
|
-
|
|
31
|
-
- `
|
|
32
|
-
|
|
33
|
-
7386 deletion sentinel, not a storable value.
|
|
34
|
-
- Raw SQL strings, `WHERE` clauses, hand-built query AST — the only
|
|
35
|
-
query surface is `db.collection(...).where({ field: value }).all()` or
|
|
36
|
-
`.where(q => q.gte("count", 1))`. See **Predicates** below.
|
|
37
|
-
- `.useIndex("name")` / `.hint(...)` — no such methods. The planner
|
|
38
|
-
picks the index automatically from `IndexDefinition`s in
|
|
39
|
-
`baerly.config.ts`. See **Indexes** below.
|
|
22
|
+
- `db.collection(name).insertOne(...)` / `.find({...})` (Mongo) — use `db.collection(name).insert(row)` and `.where({ ... }).all()`.
|
|
23
|
+
- `z.string().nullable()` in a schema — `DocumentValue` excludes `null`. Use `.optional()`; `null` in an update patch is the RFC 7386 deletion sentinel, not a storable value.
|
|
24
|
+
- Raw SQL strings, `WHERE` clauses, hand-built query AST — the only query surface is `db.collection(...).where({ field: value }).all()` or `.where(q => q.gte("count", 1))`. See the Predicates section of API.md.
|
|
25
|
+
- `.useIndex("name")` / `.hint(...)` — no such methods. Declared indexes do not change how a read runs. See the `defineConfig` section of API.md.
|
|
40
26
|
|
|
41
27
|
<!-- stop:end -->
|
|
28
|
+
|
|
42
29
|
## What this is
|
|
43
30
|
|
|
44
|
-
`react-node` is a baerly-storage app scaffolded with
|
|
45
|
-
|
|
46
|
-
`
|
|
47
|
-
|
|
48
|
-
React
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
middleware on `:5173` alongside the SPA dev server, so the SPA and
|
|
54
|
-
`/v1/*` share an origin (`http://localhost:5173`). In production the
|
|
55
|
-
same listener serves the built SPA from `dist/client/` via the
|
|
56
|
-
`baerlyNode({ webRoot })` option — same-origin in dev, same-origin
|
|
57
|
-
in prod, one process, one port.
|
|
58
|
-
|
|
59
|
-
This starter is a generic notes app you extend with your own fields —
|
|
60
|
-
a Node HTTP listener wired to an S3-compatible bucket plus a working
|
|
61
|
-
React+Vite frontend in `src/web/` (served by `baerlyNode({ webRoot })`
|
|
62
|
-
in production) with the `Note` shape declared in `baerly.config.ts`.
|
|
63
|
-
The bare server-only version is `pnpm create @gusto/baerly-storage <app> --target=node`;
|
|
64
|
-
this one is `--target=node --starter=react`.
|
|
65
|
-
|
|
66
|
-
If this scaffold was created with `--with=docker`, you'll also have a
|
|
67
|
-
multi-stage distroless `Dockerfile`, a `.dockerignore`, and a
|
|
68
|
-
`healthcheck.js` at the project root — wired to the same
|
|
69
|
-
`pnpm install && pnpm build && pnpm start` flow.
|
|
70
|
-
|
|
71
|
-
Public API docs: the JSDoc on `baerly-storage`'s `Db` and `Collection`
|
|
72
|
-
is the canonical reference; read it via your editor's TS LS, the
|
|
73
|
-
published types, or `node_modules/@gusto/baerly-storage/dist/API.md`.
|
|
31
|
+
`react-node` is a baerly-storage app scaffolded with `create-baerly-storage` for the Node target: any host that runs `node server.js` (Railway, Render, Fly without Docker, Heroku, a VM, a container scheduler). The Node-side server lives in `src/server/`; the React client lives in `src/web/`. Configuration lives in `baerly.config.ts`.
|
|
32
|
+
|
|
33
|
+
Single package, single `vite` process: `baerlyDev()` from `@gusto/baerly-storage/dev/vite` mounts the Node HTTP listener as Connect middleware on `:5173` alongside the SPA dev server, so the SPA and `/v1/*` share an origin (`http://localhost:5173`). In production the same listener serves the built SPA from `dist/client/` via the `baerlyNode({ webRoot })` option — same-origin in dev, same-origin in prod, one process, one port.
|
|
34
|
+
|
|
35
|
+
This starter is a generic notes app you extend with your own fields — a Node HTTP listener wired to an S3-compatible bucket plus a working React+Vite frontend in `src/web/` (served by `baerlyNode({ webRoot })` in production) with the `Note` shape declared in `baerly.config.ts`. The bare server-only version is `pnpm create @gusto/baerly-storage <app> --target=node`; this one is `--target=node --starter=react`.
|
|
36
|
+
|
|
37
|
+
If this scaffold was created with `--with=docker`, you'll also have a multi-stage distroless `Dockerfile`, a `.dockerignore`, and a `healthcheck.js` at the project root — wired to the same `pnpm install && pnpm build && pnpm start` flow.
|
|
38
|
+
|
|
39
|
+
Public API docs: the JSDoc on `baerly-storage`'s `Db` and `Collection` is the canonical reference; read it via your editor's TS LS, the published types, or `node_modules/@gusto/baerly-storage/dist/API.md`.
|
|
74
40
|
|
|
75
41
|
## Toolchain
|
|
76
42
|
|
|
77
|
-
- **Package manager:** pnpm. The emitted repo pins
|
|
78
|
-
`packageManager: pnpm@11.1.2`.
|
|
43
|
+
- **Package manager:** pnpm. The emitted repo pins `packageManager: pnpm@12.22.0`.
|
|
79
44
|
- **Test runner:** vitest.
|
|
80
|
-
- **Type checker:** TypeScript
|
|
81
|
-
|
|
82
|
-
`@typescript/native-preview`.)
|
|
83
|
-
- **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the
|
|
84
|
-
code stays compatible with type-stripping runtimes (Node's
|
|
85
|
-
`--experimental-strip-types`, esbuild's strip path). The flag bans
|
|
86
|
-
TS constructs that can't be type-erased: write
|
|
87
|
-
`class { x: T; constructor(x: T) { this.x = x } }` explicitly
|
|
88
|
-
instead of parameter-property shorthand
|
|
89
|
-
(`constructor(private x: T) {}` fails with TS1294). The same goes
|
|
90
|
-
for `enum`, namespaces with non-type bindings, and `private` /
|
|
91
|
-
`protected` / `public` accessibility modifiers on constructor
|
|
92
|
-
parameters.
|
|
45
|
+
- **Type checker:** TypeScript 7, as pinned in `package.json`.
|
|
46
|
+
- **`erasableSyntaxOnly`** is enabled in every `tsconfig*.json` so the code stays compatible with type-stripping runtimes (Node's built-in type stripping, esbuild's strip path). The flag bans TS constructs that can't be type-erased: write `class { x: T; constructor(x: T) { this.x = x } }` explicitly instead of parameter-property shorthand (`constructor(private x: T) {}` fails with TS1294). The same goes for `enum`, namespaces with non-type bindings, and `private` / `protected` / `public` accessibility modifiers on constructor parameters.
|
|
93
47
|
|
|
94
48
|
## Verification
|
|
95
49
|
|
|
96
|
-
| Command
|
|
97
|
-
|
|
|
98
|
-
| `pnpm install`
|
|
99
|
-
| `pnpm verify`
|
|
100
|
-
| `pnpm typecheck` | TS typecheck across the `app` + `server` project references (`tsc -b --noEmit`)
|
|
101
|
-
| `pnpm test`
|
|
102
|
-
| `pnpm dev`
|
|
103
|
-
| `pnpm build`
|
|
104
|
-
| `pnpm start`
|
|
105
|
-
|
|
106
|
-
**`pnpm verify` exercises typecheck + tests only.** The dev-auth
|
|
107
|
-
middleware, the SPA bundle, and any custom `/api/*` route are NOT
|
|
108
|
-
under test — verify will exit green even when the dev plugin returns
|
|
109
|
-
401 on every browser request or the SPA throws on mount. For changes
|
|
110
|
-
that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run
|
|
111
|
-
`pnpm dev` and exercise the change in a browser (or `curl
|
|
112
|
-
http://localhost:5173/<path>`) before declaring the task complete.
|
|
50
|
+
| Command | What it does | Runtime |
|
|
51
|
+
| --- | --- | --- |
|
|
52
|
+
| `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 |
|
|
53
|
+
| `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 |
|
|
54
|
+
| `pnpm typecheck` | TS typecheck across the `app` + `server` project references (`tsc -b --noEmit`) | seconds |
|
|
55
|
+
| `pnpm test` | `vitest run` — standalone `vitest.config.ts` (Node env) | seconds |
|
|
56
|
+
| `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 |
|
|
57
|
+
| `pnpm build` | `tsc -b && vite build` — emits `dist/client/` for the `baerlyNode({ webRoot })` static-serve branch | seconds |
|
|
58
|
+
| `pnpm start` | `node src/server/index.ts` — production entry; serves the SPA from `dist/client/` via `webRoot` | seconds to start |
|
|
59
|
+
|
|
60
|
+
**`pnpm verify` exercises typecheck + tests only.** The dev-auth middleware, the SPA bundle, and any custom `/api/*` route are NOT under test — verify will exit green even when the dev plugin returns 401 on every browser request or the SPA throws on mount. For changes that touch `vite.config.ts`, `src/server/index.ts`, or SPA logic, run `pnpm dev` and exercise the change in a browser (or `curl http://localhost:5173/<path>`) before declaring the task complete.
|
|
113
61
|
|
|
114
62
|
## Where the code is
|
|
115
63
|
|
|
116
|
-
| Path
|
|
117
|
-
|
|
|
118
|
-
| `src/server/index.ts`
|
|
119
|
-
| `src/web/`
|
|
120
|
-
| `index.html`
|
|
121
|
-
| `vite.config.ts`
|
|
122
|
-
| `tsconfig.json`
|
|
123
|
-
| `tsconfig.app.json`
|
|
124
|
-
| `tsconfig.server.json`
|
|
125
|
-
| `baerly.config.ts`
|
|
126
|
-
| `.env.example`
|
|
127
|
-
|
|
128
|
-
> **`baerly.config.ts` is dual-included.** Both `tsconfig.app.json`
|
|
129
|
-
> and `tsconfig.server.json` `include` this file, so it must only
|
|
130
|
-
> import from `baerly-storage`, `zod`, and other files reachable
|
|
131
|
-
> from **both** projects. Paths under `src/server/` are server-only;
|
|
132
|
-
> importing them here triggers `TS6307: File … is not listed within
|
|
133
|
-
> the file list of project … tsconfig.app.json`. Put document
|
|
134
|
-
> interfaces here next to their schema (`export type Note =
|
|
135
|
-
> z.infer<typeof NoteSchema>`); re-export from a server-only file if
|
|
136
|
-
> downstream code wants a local name.
|
|
64
|
+
| Path | What it is |
|
|
65
|
+
| --- | --- |
|
|
66
|
+
| `src/server/index.ts` | Server entry — defaults to zero-config `localFsStorage()` (persists to `./.baerly-data`); promotes to `s3Storage` (AWS) when `BUCKET` is set or `r2Storage` (Cloudflare R2) when `R2_ACCOUNT_ID` is set; composes a verifier and calls `baerlyNode({ ... }).listen(PORT)` |
|
|
67
|
+
| `src/web/` | React+Vite frontend. Served by the Node listener via `baerlyNode({ webRoot })` in production. |
|
|
68
|
+
| `index.html` | SPA shell — Vite's entry point at the project root; references `/src/web/main.tsx`. |
|
|
69
|
+
| `vite.config.ts` | Vite + `@vitejs/plugin-react` + `baerlyDev()` — mounts the Node HTTP listener as middleware so SPA + `/v1/*` share `:5173` in dev |
|
|
70
|
+
| `tsconfig.json` | Root project-references stub |
|
|
71
|
+
| `tsconfig.app.json` | Client TS project (`src/web/`, DOM lib, `jsx: react-jsx`) |
|
|
72
|
+
| `tsconfig.server.json` | Node server TS project (`src/server/`, Node lib) |
|
|
73
|
+
| `baerly.config.ts` | App config — `app`, `tenant`, `target`, `collections` (schemas live here). Also exports the inferred `Note` row type used by the web client. |
|
|
74
|
+
| `.env.example` | Source of truth for env vars the default Node entry reads (`BUCKET`, `AWS_*`, optional `R2_ACCOUNT_ID`, optional `PORT`) |
|
|
75
|
+
|
|
76
|
+
> **`baerly.config.ts` is dual-included.** Both `tsconfig.app.json` and `tsconfig.server.json` `include` this file, so it must only import from `baerly-storage`, `zod`, and other files reachable from **both** projects. Paths under `src/server/` are server-only; importing them here triggers `TS6307: File … is not listed within the file list of project … tsconfig.app.json`. Put document interfaces here next to their schema (`export type Note = z.infer<typeof NoteSchema>`); re-export from a server-only file if downstream code wants a local name.
|
|
137
77
|
|
|
138
78
|
## When editing X, read Y
|
|
139
79
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
widen to `string` and its row defaults to `DocumentData`. Cast at
|
|
158
|
-
the construction site for a narrower shape that still satisfies
|
|
159
|
-
the kernel's `DocumentData` constraint
|
|
160
|
-
(`{ [k: string]: DocumentValue }`):
|
|
161
|
-
```ts
|
|
162
|
-
import { createBaerlyClient, type ClientCollection } from "@gusto/baerly-storage/client";
|
|
163
|
-
import type { DocumentData } from "@gusto/baerly-storage";
|
|
164
|
-
interface Bookmark extends DocumentData { _id: string; url: string }
|
|
165
|
-
const raw = createBaerlyClient({ baseUrl: "" });
|
|
166
|
-
const bookmarks = raw.collection("bookmarks") as ClientCollection<Bookmark>;
|
|
167
|
-
await bookmarks.all();
|
|
168
|
-
```
|
|
169
|
-
A plain `interface Bookmark { _id: string; url: string }`
|
|
170
|
-
(no index signature) will fail with TS2344 — the constraint
|
|
171
|
-
is intentional so the row stays JSON-compatible.
|
|
172
|
-
|
|
173
|
-
- **Writing tests** — the kernel exports `MemoryStorage`, an
|
|
174
|
-
in-memory `Storage` impl that's the canonical backend for unit
|
|
175
|
-
tests. Don't roll your own — `Db.create({ storage, app, tenant,
|
|
176
|
-
config })` is the same boilerplate prod uses; passing
|
|
177
|
-
`new MemoryStorage()` swaps S3 for an in-process map.
|
|
178
|
-
|
|
179
|
-
```ts
|
|
180
|
-
// src/notes.test.ts
|
|
181
|
-
import { test, expect } from "vitest";
|
|
182
|
-
import { Db, MemoryStorage } from "@gusto/baerly-storage";
|
|
183
|
-
import config from "../baerly.config.ts";
|
|
184
|
-
|
|
185
|
-
test("notes round-trip", async () => {
|
|
186
|
-
const db = Db.create({
|
|
187
|
-
storage: new MemoryStorage(),
|
|
188
|
-
app: "test",
|
|
189
|
-
tenant: "t",
|
|
190
|
-
config,
|
|
191
|
-
});
|
|
192
|
-
const { _id } = await db.collection("notes").insert({ body: "hello" });
|
|
193
|
-
const row = await db.collection("notes").get(_id);
|
|
194
|
-
expect(row?.body).toBe("hello");
|
|
195
|
-
});
|
|
196
|
-
```
|
|
197
|
-
|
|
198
|
-
Each `new MemoryStorage()` is a fresh bucket — no shared state
|
|
199
|
-
across tests. For multi-writer scenarios (causal-consistency
|
|
200
|
-
tests, etc.), construct one `MemoryStorage` and pass the same
|
|
201
|
-
instance into multiple `Db.create` calls so they share the
|
|
202
|
-
underlying bucket.
|
|
203
|
-
|
|
204
|
-
- **Predicates** — `db.collection("notes").where({...}).all()`. Two
|
|
205
|
-
shapes:
|
|
206
|
-
|
|
207
|
-
- **Object literal** — equality only (top-level, dotted-path, or
|
|
208
|
-
nested literal sub-predicate). Multi-field is implicit AND.
|
|
209
|
-
- **Callback DSL** — `q => q.eq(...).gt(...).gte(...).lt(...).lte(...).in(...)`
|
|
210
|
-
for the operator vocabulary. The methods on `PredicateBuilder<T>`
|
|
211
|
-
ARE the supported surface — `q.or` / `q.regex` / `q.ne` /
|
|
212
|
-
`q.exists` are TS compile errors. Chained `.where(...).where(...)`
|
|
213
|
-
AND-merges across shapes.
|
|
214
|
-
|
|
215
|
-
```ts
|
|
216
|
-
// Top-level equality
|
|
217
|
-
await db.collection("notes").where({ body: "TODO" }).all();
|
|
218
|
-
|
|
219
|
-
// Dotted-path on a nested field
|
|
220
|
-
await db.collection("notes")
|
|
221
|
-
.where({ "meta.source": "import" })
|
|
222
|
-
.all();
|
|
223
|
-
|
|
224
|
-
// Operator on a single field — set membership (callback form)
|
|
225
|
-
await db.collection("notes")
|
|
226
|
-
.where(q => q.in("tag", ["todo", "wip"]))
|
|
227
|
-
.all();
|
|
228
|
-
|
|
229
|
-
// Range — also callback form
|
|
230
|
-
await db.collection("notes")
|
|
231
|
-
.where(q => q.gte("created_at", "2026-01-01"))
|
|
232
|
-
.all();
|
|
233
|
-
|
|
234
|
-
// AND-merge across two .where() calls (mix shapes freely)
|
|
235
|
-
await db.collection("notes")
|
|
236
|
-
.where({ body: "TODO" })
|
|
237
|
-
.where(q => q.gte("priority", 5))
|
|
238
|
-
.all();
|
|
239
|
-
```
|
|
240
|
-
|
|
241
|
-
The plain-equality value type is JSON-arrayless: string / number /
|
|
242
|
-
boolean / nested object. Use `q.in("tag", [...])` for set
|
|
243
|
-
membership when you'd otherwise want `{ tag: ["todo","wip"] }`.
|
|
244
|
-
|
|
245
|
-
- **Indexes** — declare them in `baerly.config.ts`; the read-path
|
|
246
|
-
planner picks one automatically when the predicate's equality
|
|
247
|
-
fields (and at most one range / `in` clause on the next indexed
|
|
248
|
-
field) cover the index's `on` tuple. No call-site hint is needed
|
|
249
|
-
— `Query<T>` has no `.useIndex()` method.
|
|
250
|
-
|
|
251
|
-
```ts
|
|
252
|
-
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
253
|
-
|
|
254
|
-
export default defineConfig({
|
|
255
|
-
collections: {
|
|
256
|
-
notes: {
|
|
257
|
-
indexes: [{ name: "by_body", on: "body" }],
|
|
258
|
-
},
|
|
259
|
-
},
|
|
260
|
-
});
|
|
261
|
-
```
|
|
262
|
-
|
|
263
|
-
The adapter passes your `config` into
|
|
264
|
-
`Db.create({ storage, app, tenant, config })` for you. Predicates the
|
|
265
|
-
planner can't route fall back to the full scan with a metric bump —
|
|
266
|
-
correctness is preserved.
|
|
267
|
-
|
|
268
|
-
- **Schemas (live feature)** — schemas are validated on the server
|
|
269
|
-
for every `insert` / `update` / `replace` when bound. Declare via
|
|
270
|
-
`defineConfig` using any StandardSchema v1 validator (Zod 3.24+,
|
|
271
|
-
Valibot 0.36+, ArkType 2.0+, or anything implementing the spec):
|
|
272
|
-
|
|
273
|
-
```ts
|
|
274
|
-
import { z } from "zod";
|
|
275
|
-
import { defineConfig } from "@gusto/baerly-storage/config";
|
|
276
|
-
|
|
277
|
-
const Note = z.object({
|
|
278
|
-
_id: z.string(),
|
|
279
|
-
body: z.string().min(1),
|
|
280
|
-
});
|
|
281
|
-
|
|
282
|
-
export default defineConfig({
|
|
283
|
-
collections: {
|
|
284
|
-
notes: { schema: Note },
|
|
285
|
-
},
|
|
286
|
-
});
|
|
287
|
-
```
|
|
288
|
-
|
|
289
|
-
On a validation failure the server throws
|
|
290
|
-
`BaerlyError{ code: "SchemaError", issues: [{ path, message }] }`;
|
|
291
|
-
HTTP clients see a 400 with the same envelope. Validation runs
|
|
292
|
-
on the post-image so `update` and `replace` see the full doc, not
|
|
293
|
-
just the patch.
|
|
294
|
-
|
|
295
|
-
- **HTTP wire format (calling `/v1/*` directly)** — the JS SDK
|
|
296
|
-
(`db.collection(name).insert(...)`) is the canonical path; reach for `curl`
|
|
297
|
-
only when debugging the wire. Mutation bodies are wrapped:
|
|
298
|
-
|
|
299
|
-
| Route | Body | Response |
|
|
300
|
-
| --------------------------- | ------------------- | ----------------------------- |
|
|
301
|
-
| `POST /v1/c/:collection` | `{"doc":{...}}` | `201 {_id}` |
|
|
302
|
-
| `PATCH /v1/c/:collection/:id` | `{"patch":{...}}` | `200 {modified}` |
|
|
303
|
-
| `PUT /v1/c/:collection/:id` | `{"doc":{...}}` | `200 {modified}` |
|
|
304
|
-
| `DELETE /v1/c/:collection/:id` | — | `204` |
|
|
305
|
-
|
|
306
|
-
Reads (`GET /v1/c/:collection[/:id]`, `GET /v1/count?collection=…`,
|
|
307
|
-
`GET /v1/since?collection=…&cursor=…`) take no body and return
|
|
308
|
-
`{ data, _meta }` or a route-specific envelope. A flat `POST` body
|
|
309
|
-
(without the `doc` wrapper) returns
|
|
310
|
-
`400 SchemaError "Request body must be { doc: object }"` — the
|
|
311
|
-
wording is locked by `assertJsonBodyField` in the kernel. Canonical
|
|
312
|
-
reference: the JSDoc on `createRouter` in
|
|
313
|
-
`baerly-storage`.
|
|
314
|
-
|
|
315
|
-
- **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`:
|
|
316
|
-
every request resolves to `tenant: "react-demo"` and `Authorization`
|
|
317
|
-
is ignored. The adapter reads `config.auth` to pick its verifier;
|
|
318
|
-
a `verifier:` on `baerlyNode({ ... })` overrides it. The schema-
|
|
319
|
-
bound `notes` collection (`baerly.config.ts:NoteSchema`) runs
|
|
320
|
-
server-side regardless of the auth posture. There is no `baerly
|
|
321
|
-
doctor --target=node` backend today; verify bucket CAS with
|
|
322
|
-
`baerly doctor --bucket=<s3-uri>` and probe `/v1/healthz` after
|
|
323
|
-
deploy. See "Going to production" below for the two production-fit
|
|
324
|
-
recipes.
|
|
80
|
+
<!-- library:start -->
|
|
81
|
+
|
|
82
|
+
- **Library reference** — the shared API guidance is installed with the package, in `node_modules/@gusto/baerly-storage/dist/`. Read the matching section before editing storage code:
|
|
83
|
+
- **Typed rows** (binding `config`, `RowOf`, casting an undeclared collection): `API.md#documentdata--row-shape-constraint`. A hand-written row type failing `DocumentData`: `RECIPES.md#type-bookmark-does-not-satisfy-the-constraint-documentdata-ts2344`.
|
|
84
|
+
- **Writing tests**: `API.md`, section `Db.create`. `new MemoryStorage()` is a fresh bucket per test; share one instance across `Db.create` calls for multi-writer tests. `src/notes.test.ts` is the working example.
|
|
85
|
+
- **Predicates** (object literal vs callback DSL, operators, by-`_id` verbs): `API.md#predicates`. Set membership is `q.in`, never an array in the object form: `RECIPES.md#baerlyerror-codeinvalidconfig--predicate-value-at--is-an-array`.
|
|
86
|
+
- **Indexes**: don't declare them; a read always folds the whole collection. `API.md`, section `defineConfig`.
|
|
87
|
+
- **Schemas** (StandardSchema validators, `SchemaError`): `API.md`, section `defineConfig`.
|
|
88
|
+
- **HTTP wire format** (calling `/v1/*` directly): `API.md#http-wire-format`.
|
|
89
|
+
- **Verifier presets** (`sharedSecret`, `bearerJwt`, `cloudflareAccess`, `tenantPrefix`): `API.md#verifier-presets`. Refreshing a client token on 401, logging, tracing: `RECIPES.md#recipe--wrapping-the-client-fetch`. Serving `/v1/*` behind your own gate: `RECIPES.md#recipe--authoring-a-gated-adapter`.
|
|
90
|
+
- **Errors by message** (`RECIPES.md`, one entry per error string) and the shared anti-patterns: `RECIPES.md#anti-patterns-compile-clean-but-wrong`.
|
|
91
|
+
|
|
92
|
+
<!-- library:end -->
|
|
93
|
+
|
|
94
|
+
- **This template** — `src/web/client.ts` binds `config` into `createBaerlyReact` and `src/notes.test.ts` passes it to `Db.create`, so rows are already typed: no generic. For a hot filtered read, maintain a side-projection (see Anti-patterns).
|
|
95
|
+
|
|
96
|
+
- **Auth** — your scaffold ships `auth: "none"` in `baerly.config.ts`: every request resolves to `tenant: "react-demo"` and `Authorization` is ignored. The adapter reads `config.auth` to pick its verifier; a `verifier:` on `baerlyNode({ ... })` overrides it. The schema- bound `notes` collection (`baerly.config.ts:NoteSchema`) runs server-side regardless of the auth posture. There is no `baerly doctor --target=node` backend today; verify bucket CAS with `baerly doctor --bucket=<s3-uri>` and probe `/v1/healthz` after deploy. See "Going to production" below for the two production-fit recipes.
|
|
325
97
|
|
|
326
98
|
### Going to production
|
|
327
99
|
|
|
328
|
-
The scaffold ships `auth: "none"` so the day-1 happy path works with
|
|
329
|
-
zero env vars. The `NoteSchema` in `baerly.config.ts` continues to
|
|
330
|
-
validate writes server-side under every posture below — only the
|
|
331
|
-
header-check seam changes.
|
|
100
|
+
The scaffold ships `auth: "none"` so the day-1 happy path works with zero env vars. The `NoteSchema` in `baerly.config.ts` continues to validate writes server-side under every posture below — only the header-check seam changes.
|
|
332
101
|
|
|
333
102
|
<!-- pattern-b:start -->
|
|
334
|
-
|
|
335
|
-
server-to-server). No factory code changes; `baerly.config.ts` flips:
|
|
103
|
+
|
|
104
|
+
**Pattern B — `auth: "shared-secret"`** (single-tenant server-to-server). No factory code changes; `baerly.config.ts` flips:
|
|
336
105
|
|
|
337
106
|
```ts
|
|
338
107
|
// baerly.config.ts
|
|
339
108
|
auth: "shared-secret", // ← flip from "none"
|
|
340
109
|
```
|
|
341
110
|
|
|
342
|
-
Dev: put `SHARED_SECRET=dev-shared-secret` in `.env`. Prod: set
|
|
343
|
-
`SHARED_SECRET` in the process environment (your PaaS / secret
|
|
344
|
-
manager). The Node process fails closed if `auth: "shared-secret"`
|
|
345
|
-
is set without `SHARED_SECRET` reachable from `process.env`; verify
|
|
346
|
-
the live bucket separately with `baerly doctor --bucket=<s3-uri>`.
|
|
111
|
+
Dev: put `SHARED_SECRET=dev-shared-secret` in `.env`. Prod: set `SHARED_SECRET` in the process environment (your PaaS / secret manager). The Node process fails closed if `auth: "shared-secret"` is set without `SHARED_SECRET` reachable from `process.env`; verify the live bucket separately with `baerly doctor --bucket=<s3-uri>`.
|
|
347
112
|
|
|
348
113
|
<!-- pattern-b:end -->
|
|
349
114
|
<!-- pattern-c:start -->
|
|
350
|
-
|
|
351
|
-
`verifier:` overrides `config.auth`, so dev keeps `"none"` and prod
|
|
352
|
-
gets `bearerJwt`:
|
|
115
|
+
|
|
116
|
+
**Pattern C — JWKS-backed JWT** (multi-tenant; OIDC IdP). The factory `verifier:` overrides `config.auth`, so dev keeps `"none"` and prod gets `bearerJwt`:
|
|
353
117
|
|
|
354
118
|
```ts
|
|
355
119
|
// baerly.config.ts — unchanged
|
|
@@ -383,159 +147,54 @@ await baerlyNode({
|
|
|
383
147
|
}).listen(Number(process.env["PORT"] ?? 8080));
|
|
384
148
|
```
|
|
385
149
|
|
|
386
|
-
Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and
|
|
387
|
-
`config.auth: "none"` runs. Prod sets `JWKS_URL` + `JWT_ISSUER` +
|
|
388
|
-
`JWT_AUDIENCE` and `bearerJwt` engages. Use `tenantClaim` when your
|
|
389
|
-
IdP issues one tenant per token; use `tenantPrefix` for single-tenant
|
|
390
|
-
apps or tenancy enforced outside baerly-storage.
|
|
150
|
+
Dev sees `JWKS_URL` as `undefined`, spread short-circuits, and `config.auth: "none"` runs. Prod sets `JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE` and `bearerJwt` engages. Use `tenantClaim` when your IdP issues one tenant per token; use `tenantPrefix` for single-tenant apps or tenancy enforced outside baerly-storage.
|
|
391
151
|
|
|
392
152
|
<!-- pattern-c:end -->
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
self-hosting without a cloud bucket, run **MinIO** on the box (also the
|
|
402
|
-
local/dev conformance target) or graduate to SQLite + Litestream. Other S3-compatible endpoints need a
|
|
403
|
-
green `baerly doctor --bucket` plus owner validation; GCS S3-interop
|
|
404
|
-
is not supported for database use today. The bucket name comes from
|
|
405
|
-
the `BUCKET` env var; AWS credentials are read from
|
|
406
|
-
`AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and optional
|
|
407
|
-
`AWS_REGION`).
|
|
408
|
-
|
|
409
|
-
- **Switching from static creds to EKS** — in
|
|
410
|
-
`src/server/index.ts`, swap `credentials: { accessKeyId,
|
|
411
|
-
secretAccessKey }` for `credentials: fromEks()` and add `fromEks`
|
|
412
|
-
to your import:
|
|
413
|
-
`import { s3Storage, fromEks } from "@gusto/baerly-storage/node"`.
|
|
414
|
-
`fromEks()` auto-detects the cluster's mechanism — EKS Pod Identity
|
|
415
|
-
(`AWS_CONTAINER_CREDENTIALS_FULL_URI` +
|
|
416
|
-
`AWS_CONTAINER_AUTHORIZATION_TOKEN_FILE`) or IRSA (`AWS_ROLE_ARN` +
|
|
417
|
-
`AWS_WEB_IDENTITY_TOKEN_FILE`), both EKS-injected; to pin one, use
|
|
418
|
-
`fromEksPodIdentity()` or `fromWebIdentity()`. For ECS / EC2 / other
|
|
419
|
-
AWS contexts, see `packages/adapter-node/AGENTS.md` — pass any
|
|
420
|
-
`() => Promise<Credentials>` or an `@aws-sdk/credential-providers`
|
|
421
|
-
factory through the seam.
|
|
422
|
-
|
|
423
|
-
- **Deploy** — runs anywhere `node server.js` runs. The
|
|
424
|
-
`package.json`'s `start` script is
|
|
425
|
-
`node --experimental-strip-types src/server/index.ts`. Arrange the
|
|
426
|
-
host to run `pnpm install && pnpm build` (populates
|
|
427
|
-
`dist/client/` for the `webRoot` static-serve branch) before
|
|
428
|
-
`pnpm start`. A deployment **must** configure a durable bucket:
|
|
429
|
-
`BUCKET` + `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (S3) or
|
|
430
|
-
`R2_ACCOUNT_ID` + those creds (R2). With none set, the server fails
|
|
431
|
-
loud in a detected deployment (`NODE_ENV=production` or a known PaaS)
|
|
432
|
-
rather than running on local-fs, which is local-dev only. Self-hosting
|
|
433
|
-
without a cloud bucket, run MinIO on the box or use SQLite + Litestream.
|
|
434
|
-
The default scaffold's `auth: "none"` needs no
|
|
435
|
-
auth env vars; if you adopt Pattern B / C from "Going to production" above,
|
|
436
|
-
also set `SHARED_SECRET` (Pattern B) or `JWKS_URL` + `JWT_ISSUER` +
|
|
437
|
-
`JWT_AUDIENCE` (Pattern C).
|
|
438
|
-
|
|
439
|
-
Shapes: **managed PaaS** (Railway, Render, DO App Platform, Fly
|
|
440
|
-
without Docker, Heroku) auto-detects Node and runs the root
|
|
441
|
-
scripts directly. **VM / bare-metal** uses your process manager
|
|
442
|
-
of choice (systemd, pm2). **Container** (Docker, k8s, ECS, Fly
|
|
443
|
-
Machines with a Dockerfile) — scaffold with `--with=docker` to
|
|
444
|
-
add a production Dockerfile alongside this shape, or write your
|
|
445
|
-
own.
|
|
153
|
+
|
|
154
|
+
- **Storage backend** — `src/server/resolve-storage.ts` resolves storage by env: `R2_ACCOUNT_ID` → Cloudflare R2, else `BUCKET` → AWS S3, else zero-config `localFsStorage()` (persists to `./.baerly-data`, no credentials, local dev only). **In a detected deployment (`NODE_ENV=production` or a known PaaS) the server fails loud and requires a bucket** — local-fs is single-process with no cross-process CAS or crash durability, so it is never a production store (there is no opt-in). AWS S3 and Cloudflare R2 are the production-supported stores; self-hosting without a cloud bucket, run **MinIO** on the box (also the local/dev conformance target) or graduate to SQLite + Litestream. Other S3-compatible endpoints need a green `baerly doctor --bucket` plus owner validation; GCS S3-interop is not supported for database use today. The bucket name comes from the `BUCKET` env var; AWS credentials are read from `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and optional `AWS_REGION`).
|
|
155
|
+
|
|
156
|
+
- **Storage credentials** — the default `resolveStorage()` (`src/server/resolve-storage.ts`) reads static keys from `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY`. For EKS (`fromEks()`), expiring or vault-issued credentials, or an `@aws-sdk/credential-providers` provider, replace that re-export with your own `s3Storage({ ..., credentials })` call, following `node_modules/@gusto/baerly-storage/dist/RECIPES.md#recipe--storage-credentials-on-node`.
|
|
157
|
+
|
|
158
|
+
- **Deploy** — runs anywhere `node server.js` runs. The `package.json`'s `start` script is `node src/server/index.ts`. Arrange the host to run `pnpm install && pnpm build` (populates `dist/client/` for the `webRoot` static-serve branch) before `pnpm start`. A deployment **must** configure a durable bucket: `BUCKET` + `AWS_ACCESS_KEY_ID` + `AWS_SECRET_ACCESS_KEY` (S3) or `R2_ACCOUNT_ID` + those creds (R2). With none set, the server fails loud in a detected deployment (`NODE_ENV=production` or a known PaaS) rather than running on local-fs, which is local-dev only. Self-hosting without a cloud bucket, run MinIO on the box or use SQLite + Litestream. The default scaffold's `auth: "none"` needs no auth env vars; if you adopt Pattern B / C from "Going to production" above, also set `SHARED_SECRET` (Pattern B) or `JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE` (Pattern C).
|
|
159
|
+
|
|
160
|
+
Shapes: **managed PaaS** (Railway, Render, DO App Platform, Fly without Docker, Heroku) auto-detects Node and runs the root scripts directly. **VM / bare-metal** uses your process manager of choice (systemd, pm2). **Container** (Docker, k8s, ECS, Fly Machines with a Dockerfile) — scaffold with `--with=docker` to add a production Dockerfile alongside this shape, or write your own.
|
|
446
161
|
|
|
447
162
|
## Anti-patterns
|
|
448
163
|
|
|
449
|
-
-
|
|
450
|
-
|
|
451
|
-
- Reaching into `node_modules/@gusto/baerly-storage/dist/` directly —
|
|
452
|
-
consume the published exports.
|
|
453
|
-
- Mutating `VerifierResult.tenantPrefix` between the verifier
|
|
454
|
-
and `Db.create`. The dispatcher pins the tenant from the
|
|
455
|
-
verifier's return value.
|
|
456
|
-
- Calling `db.collection(...).all()` (or any unbounded read) inside a
|
|
457
|
-
per-request handler. The call scans the entire collection on every
|
|
458
|
-
request — fine for a fixture-sized table, catastrophic at any real
|
|
459
|
-
size, and `pnpm verify` doesn't surface the cost. Push the filter
|
|
460
|
-
into the predicate so the index planner can prune
|
|
461
|
-
(`db.collection("notes").where({ ... }).all()`), or maintain a
|
|
462
|
-
side-projection (Postgres/SQLite/search index) populated
|
|
463
|
-
incrementally from the `/v1/since?collection=<name>&cursor=<opaque>`
|
|
464
|
-
log feed or from a write hook —
|
|
465
|
-
never re-scan per request.
|
|
164
|
+
- The shared anti-patterns (branded types, the verifier's tenant, secrets in the SPA bundle) are in `RECIPES.md#anti-patterns-compile-clean-but-wrong`.
|
|
165
|
+
- Calling `db.collection(...).all()` (or any unbounded read) inside a per-request handler. The call scans the entire collection on every request — fine for a fixture-sized table, catastrophic at any real size, and `pnpm verify` doesn't surface the cost. A predicate (`db.collection("notes").where({ ... }).all()`) trims the response but still folds the whole collection, so instead maintain a side-projection (Postgres/SQLite/search index) populated incrementally from the `/v1/since?collection=<name>&cursor=<opaque>` log feed or from a write hook — never re-scan per request.
|
|
466
166
|
|
|
467
167
|
## Maintenance
|
|
468
168
|
|
|
469
169
|
<!-- pattern-d:start -->
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
whose default is safe on every tier. A size-ratio threshold means idle buckets pay
|
|
474
|
-
nothing. Concurrent folds are safe without coordination: the commit is a
|
|
475
|
-
compare-and-swap, so a fold that loses to a concurrent write is simply discarded and
|
|
476
|
-
its leftover swept by GC. On Cloudflare the fold is deferred past the response via
|
|
477
|
-
ctx.waitUntil; everywhere else it runs inline. **Reads are pure** — they never run
|
|
478
|
-
maintenance, so the published idle-reader cost bound holds.
|
|
479
|
-
|
|
480
|
-
A bucket maintains itself as long as it takes writes. A bucket served read-only does
|
|
481
|
-
not auto-compact and pays a small, bounded replay — fine at small scale, a signal to
|
|
482
|
-
graduate once a collection is large. See docs/about/graduation.md for the per-tier
|
|
483
|
-
envelope and the `BAERLY_MAINTENANCE_*` operator env vars (you almost never need them).
|
|
484
|
-
|
|
485
|
-
Operator opt-in: call runScheduledMaintenance from @gusto/baerly-storage/maintenance on
|
|
486
|
-
your own schedule. Not required for steady-state operation.
|
|
170
|
+
|
|
171
|
+
Maintenance is automatic and write-triggered: nothing to install or schedule, identically on every host, and reads never run it. A scheduled `runScheduledMaintenance` pass is an optional extra for a collection served mostly read-only. The behavior, the call, its per-tier limits and the Workers Free / Paid differences are in `node_modules/@gusto/baerly-storage/dist/RECIPES.md#recipe--scheduled-maintenance`.
|
|
172
|
+
|
|
487
173
|
<!-- pattern-d:end -->
|
|
488
174
|
|
|
489
175
|
## When to graduate
|
|
490
176
|
|
|
491
|
-
baerly-storage is designed for the small-to-medium operating point.
|
|
492
|
-
The cost model puts the soft ceiling at:
|
|
177
|
+
baerly-storage is designed for the small-to-medium operating point. The soft ceiling has three lines, none enforced by the protocol: writes per collection (a throughput estimate), collections per tenant (a soft fan-out guideline), and the R2 free-tier storage line (a cost signal). The figures live in one place: docs/spec/scale-ceilings.md § "The published envelope" in the baerly-storage repo.
|
|
493
178
|
|
|
494
|
-
-
|
|
495
|
-
- **>10 GB / tenant stored** (R2 free-tier storage line — a cost signal, not a protocol ceiling)
|
|
496
|
-
- **~100 collections / tenant** (soft fan-out guideline — bench-grounded linear cost)
|
|
179
|
+
At the M-size operating point, the projected cost is ~$12/mo on Cloudflare, including Workers Paid, and ~$19/mo on Node, excluding Node hosting. Past those, per-class op pricing and fan-out scan cost start to dominate; you've outgrown the workload envelope — move to a database service (D1 / Postgres) suited to higher scale. Pick your graduation target:
|
|
497
180
|
|
|
498
|
-
At M-size (~30 writes/min) the projected cost is ~$26/mo on S3 (~$18/mo on R2). Past
|
|
499
|
-
those, per-class op pricing and fan-out scan cost start to dominate;
|
|
500
|
-
you've outgrown the workload envelope — move to a database service (D1 / Postgres) suited to higher scale.
|
|
501
|
-
Pick your graduation target:
|
|
502
181
|
- **Cloudflare Workers + lock-in OK:** [D1](https://developers.cloudflare.com/d1/) — cheaper per-write at M-size.
|
|
503
182
|
- **Off-Workers or portability matters:** managed Postgres.
|
|
504
183
|
- **Single-instance Node:** SQLite via Litestream.
|
|
505
184
|
|
|
506
|
-
Either way, the export below is mechanical because log entries are
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
**
|
|
511
|
-
`baerly admin usage --target=node --bucket=<bucket-uri> --app=<app>
|
|
512
|
-
--tenant=<tenant>` lists recent log entries per collection and computes
|
|
513
|
-
writes/min. On Cloudflare, use canonical logs for trend history and
|
|
514
|
-
`baerly cost --bucket=<bucket-uri> --collection=<collection>` for the
|
|
515
|
-
current operation-cost projection until the usage scanner is wired to
|
|
516
|
-
R2 bindings.
|
|
517
|
-
|
|
518
|
-
**Export when ready:** `baerly export --target=sqlite|postgres|d1
|
|
519
|
-
--bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a
|
|
520
|
-
canonical SQL dump (and a `<output>.plan.json` sidecar carrying the
|
|
521
|
-
inferred `ExportPlan`) that you load into your graduation target.
|
|
522
|
-
The export is point-in-time and honours the active schema. Flags:
|
|
523
|
-
`--where=<json-predicate>`, `--where-comment`, `--output`,
|
|
524
|
-
`--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig,
|
|
525
|
-
2 Storage/Network, 3 Protocol invariant.
|
|
185
|
+
Either way, the export below is mechanical because log entries are Debezium-style CDC change events — graduation is a baerly-storage win, not a churn event.
|
|
186
|
+
|
|
187
|
+
**Estimate your current rate:** for Node/self-hosted buckets, `baerly admin usage --target=node --bucket=<bucket-uri> --app=<app> --tenant=<tenant>` lists recent log entries per collection and computes writes/min. On Cloudflare, use canonical logs for trend history and `baerly cost --bucket=<bucket-uri> --collection=<collection>` for the current operation-cost projection until the usage scanner is wired to R2 bindings.
|
|
188
|
+
|
|
189
|
+
**Export when ready:** `baerly export --target=sqlite|postgres|d1 --bucket=<...> --app=<...> --tenant=<...> --collection=<...>` writes a canonical SQL dump (and a `<output>.plan.json` sidecar carrying the inferred `ExportPlan`) that you load into your graduation target. The export is point-in-time and honours the active schema. Flags: `--where=<json-predicate>`, `--where-comment`, `--output`, `--no-sidecar`, `--json`. Exit codes: 0 success, 1 InvalidConfig, 2 Storage/Network, 3 Protocol invariant.
|
|
526
190
|
|
|
527
191
|
## Worked extensions
|
|
528
192
|
|
|
529
|
-
Three recipes that come up routinely when you extend the
|
|
530
|
-
scaffolded `notes` shape. Each one is target-agnostic — the same
|
|
531
|
-
code works in `react-cloudflare` and `react-node`.
|
|
193
|
+
Three recipes that come up routinely when you extend the scaffolded `notes` shape. Each one is target-agnostic — the same code works in `react-cloudflare` and `react-node`.
|
|
532
194
|
|
|
533
195
|
### Adding an enum field (e.g. `status`)
|
|
534
196
|
|
|
535
|
-
A row often needs a constrained set of string values. Declare the
|
|
536
|
-
enum inside the Zod schema and export the option tuple next to it
|
|
537
|
-
in `baerly.config.ts`; the predicate API picks the field up
|
|
538
|
-
automatically.
|
|
197
|
+
A row often needs a constrained set of string values. Declare the enum inside the Zod schema and export the option tuple next to it in `baerly.config.ts`; the predicate API picks the field up automatically.
|
|
539
198
|
|
|
540
199
|
```typescript
|
|
541
200
|
// baerly.config.ts
|
|
@@ -551,7 +210,7 @@ export const NoteSchema = z.object({
|
|
|
551
210
|
export type Note = z.infer<typeof NoteSchema>;
|
|
552
211
|
export const STATUSES = NoteSchema.shape.status.options;
|
|
553
212
|
|
|
554
|
-
export default defineConfig({
|
|
213
|
+
export default defineConfig({/* ... */});
|
|
555
214
|
```
|
|
556
215
|
|
|
557
216
|
```tsx
|
|
@@ -560,21 +219,18 @@ import { STATUSES } from "../../baerly.config.ts";
|
|
|
560
219
|
|
|
561
220
|
<select name="status" defaultValue="open">
|
|
562
221
|
{STATUSES.map((s) => (
|
|
563
|
-
<option key={s} value={s}>
|
|
222
|
+
<option key={s} value={s}>
|
|
223
|
+
{s}
|
|
224
|
+
</option>
|
|
564
225
|
))}
|
|
565
|
-
</select
|
|
226
|
+
</select>;
|
|
566
227
|
```
|
|
567
228
|
|
|
568
|
-
The schema enum is the single source of truth — adding a value
|
|
569
|
-
there expands the `<select>` immediately. Adding more enum fields
|
|
570
|
-
(`priority`, `severity`) follows the same shape.
|
|
229
|
+
The schema enum is the single source of truth — adding a value there expands the `<select>` immediately. Adding more enum fields (`priority`, `severity`) follows the same shape.
|
|
571
230
|
|
|
572
231
|
### Filtering a reactive query by predicate
|
|
573
232
|
|
|
574
|
-
`useQuery((c) => c.collection(...).where(...).all(), [deps])` accepts the
|
|
575
|
-
same predicate shapes as the bare client. To narrow by an enum field,
|
|
576
|
-
drive it off `useState` and lift the filter into the `deps` array so
|
|
577
|
-
the cache key changes when the filter does:
|
|
233
|
+
`useQuery((c) => c.collection(...).where(...).all(), [deps])` accepts the same predicate shapes as the bare client. To narrow by an enum field, drive it off `useState` and lift the filter into the `deps` array so the cache key changes when the filter does:
|
|
578
234
|
|
|
579
235
|
```tsx
|
|
580
236
|
import { useState } from "react";
|
|
@@ -595,30 +251,19 @@ const result = useQuery(
|
|
|
595
251
|
);
|
|
596
252
|
```
|
|
597
253
|
|
|
598
|
-
`useQuery` re-runs the callback
|
|
599
|
-
`/v1/since?collection=<name>&cursor=<opaque>` long-poll batches a
|
|
600
|
-
non-empty change for any subscribed
|
|
601
|
-
collection. Idle long-poll cycles (empty batches) drop at the
|
|
602
|
-
`subscription-pool` layer, so a steady-state collection costs zero list
|
|
603
|
-
reads. Add a `<select>` bound to `setFilter` and the list narrows live.
|
|
254
|
+
`useQuery` is live by default: it re-runs on dependency changes and non-empty `/v1/since` batches for any collection the callback reads. Pass `{ live: false }` for mount/dependency reads without `/v1/since`. Every result state has a stable `refetch()`; successful data stays available while refreshing and on error. A non-retriable subscription error stops automatic polling, while explicit `refetch()` retries the read and restarts the terminal live subscription. Idle long-poll cycles do not re-run the query.
|
|
604
255
|
|
|
605
|
-
For conditional / deferred reads, return the `useQuery.skip` sentinel
|
|
606
|
-
from the callback — the hook short-circuits to
|
|
607
|
-
`status: "skipped"` with no subscription:
|
|
256
|
+
For conditional / deferred reads, return the `useQuery.skip` sentinel from the callback — the hook short-circuits to `status: "skipped"` with no subscription:
|
|
608
257
|
|
|
609
258
|
```tsx
|
|
610
259
|
const filtered = useQuery(
|
|
611
|
-
(c) =>
|
|
612
|
-
filter === "all"
|
|
613
|
-
? useQuery.skip
|
|
614
|
-
: c.collection("notes").where({ status: filter }).all(),
|
|
260
|
+
(c) => (filter === "all" ? useQuery.skip : c.collection("notes").where({ status: filter }).all()),
|
|
615
261
|
[filter],
|
|
616
262
|
);
|
|
617
263
|
if (filtered.status === "skipped") return <FullList />;
|
|
618
264
|
```
|
|
619
265
|
|
|
620
|
-
For dependent reads, compose two `useQuery` calls — the second one
|
|
621
|
-
returns `useQuery.skip` until the first resolves to `"ok"`:
|
|
266
|
+
For dependent reads, compose two `useQuery` calls — the second one returns `useQuery.skip` until the first resolves to `"ok"`:
|
|
622
267
|
|
|
623
268
|
```tsx
|
|
624
269
|
// `comments` must be declared in baerly.config.ts — the bound hooks
|
|
@@ -633,8 +278,7 @@ const replies = useQuery(
|
|
|
633
278
|
);
|
|
634
279
|
```
|
|
635
280
|
|
|
636
|
-
Mutations are inline: `useMutation()` returns a `[mutate, { isPending,
|
|
637
|
-
error }]` tuple. `mutate(cb)` runs `cb` against the real client:
|
|
281
|
+
Mutations are inline: `useMutation()` returns a `[mutate, { isPending, error }]` tuple. `mutate(cb)` runs `cb` against the real client:
|
|
638
282
|
|
|
639
283
|
```tsx
|
|
640
284
|
const [mutate, { isPending, error }] = useMutation();
|
|
@@ -643,32 +287,22 @@ const [mutate, { isPending, error }] = useMutation();
|
|
|
643
287
|
onClick={() => mutate((c) => c.collection("notes").update(id, { body }))}
|
|
644
288
|
>
|
|
645
289
|
{isPending ? "Saving…" : "Save"}
|
|
646
|
-
</button
|
|
290
|
+
</button>;
|
|
647
291
|
```
|
|
648
292
|
|
|
649
293
|
### Optional fields
|
|
650
294
|
|
|
651
|
-
Some fields aren't always present (`tags` may be missing entirely
|
|
652
|
-
on some rows). Zod's `.optional()` models this:
|
|
295
|
+
Some fields aren't always present (`tags` may be missing entirely on some rows). Zod's `.optional()` models this:
|
|
653
296
|
|
|
654
297
|
```typescript
|
|
655
298
|
export const NoteSchema = z.object({
|
|
656
299
|
_id: z.string(),
|
|
657
300
|
body: z.string().min(1),
|
|
658
|
-
tags: z.array(z.string()).optional(),
|
|
301
|
+
tags: z.array(z.string()).optional(), // tags?: string[]
|
|
659
302
|
});
|
|
660
303
|
```
|
|
661
304
|
|
|
662
|
-
The Zod-inferred `Note` type reflects the shape (`tags?: string[]`)
|
|
663
|
-
and call sites pick it up through `import type { Note }`.
|
|
664
|
-
JSON-merge-patch (RFC 7386) semantics apply on `update()`:
|
|
665
|
-
omitting `tags` from an update preserves the existing value;
|
|
666
|
-
passing `tags: null` deletes the field; passing `tags: []` sets
|
|
667
|
-
it to an empty array. Note that `null` is the deletion sentinel,
|
|
668
|
-
not a storable value — `DocumentValue` doesn't include `null`, so
|
|
669
|
-
subsequent `get()` / query results expose deleted optional fields as
|
|
670
|
-
`undefined`, not `null`.
|
|
671
|
-
That's why this recipe uses `.optional()` and not `.nullable()`.
|
|
305
|
+
The Zod-inferred `Note` type reflects the shape (`tags?: string[]`) and call sites pick it up through `import type { Note }`. JSON-merge-patch (RFC 7386) semantics apply on `update()`: omitting `tags` from an update preserves the existing value; passing `tags: null` deletes the field; passing `tags: []` sets it to an empty array. Note that `null` is the deletion sentinel, not a storable value — `DocumentValue` doesn't include `null`, so subsequent `get()` / query results expose deleted optional fields as `undefined`, not `null`. That's why this recipe uses `.optional()` and not `.nullable()`.
|
|
672
306
|
|
|
673
307
|
## Pointers
|
|
674
308
|
|