@gusto/create-baerly-storage 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/dist/index.js +2737 -0
  2. package/dist/index.js.map +1 -0
  3. package/dist/templates/addons/docker/.dockerignore +13 -0
  4. package/dist/templates/addons/docker/Dockerfile +65 -0
  5. package/dist/templates/addons/docker/healthcheck.js +15 -0
  6. package/dist/templates/minimal-cloudflare/.baerly/scaffold.json +10 -0
  7. package/dist/templates/minimal-cloudflare/AGENTS.md +556 -0
  8. package/dist/templates/minimal-cloudflare/README.md +169 -0
  9. package/dist/templates/minimal-cloudflare/_gitignore +6 -0
  10. package/dist/templates/minimal-cloudflare/baerly.config.ts +20 -0
  11. package/dist/templates/minimal-cloudflare/index.html +12 -0
  12. package/dist/templates/minimal-cloudflare/package.json +28 -0
  13. package/dist/templates/minimal-cloudflare/pnpm-workspace.yaml +15 -0
  14. package/dist/templates/minimal-cloudflare/src/notes.test.ts +19 -0
  15. package/dist/templates/minimal-cloudflare/src/server/index.ts +11 -0
  16. package/dist/templates/minimal-cloudflare/src/web/main.ts +27 -0
  17. package/dist/templates/minimal-cloudflare/tsconfig.app.json +28 -0
  18. package/dist/templates/minimal-cloudflare/tsconfig.json +9 -0
  19. package/dist/templates/minimal-cloudflare/tsconfig.worker.json +28 -0
  20. package/dist/templates/minimal-cloudflare/types.ts +23 -0
  21. package/dist/templates/minimal-cloudflare/uint8array-base64.d.ts +16 -0
  22. package/dist/templates/minimal-cloudflare/vite.config.ts +6 -0
  23. package/dist/templates/minimal-cloudflare/vitest.config.ts +11 -0
  24. package/dist/templates/minimal-cloudflare/wrangler.jsonc +27 -0
  25. package/dist/templates/minimal-node/.baerly/scaffold.json +13 -0
  26. package/dist/templates/minimal-node/.env.example +14 -0
  27. package/dist/templates/minimal-node/AGENTS.md +488 -0
  28. package/dist/templates/minimal-node/README.md +180 -0
  29. package/dist/templates/minimal-node/_gitignore +7 -0
  30. package/dist/templates/minimal-node/baerly.config.ts +20 -0
  31. package/dist/templates/minimal-node/index.html +12 -0
  32. package/dist/templates/minimal-node/package.json +26 -0
  33. package/dist/templates/minimal-node/pnpm-workspace.yaml +9 -0
  34. package/dist/templates/minimal-node/src/notes.test.ts +19 -0
  35. package/dist/templates/minimal-node/src/server/index.ts +46 -0
  36. package/dist/templates/minimal-node/src/web/main.ts +27 -0
  37. package/dist/templates/minimal-node/tsconfig.app.json +28 -0
  38. package/dist/templates/minimal-node/tsconfig.json +9 -0
  39. package/dist/templates/minimal-node/tsconfig.server.json +28 -0
  40. package/dist/templates/minimal-node/types.ts +23 -0
  41. package/dist/templates/minimal-node/uint8array-base64.d.ts +16 -0
  42. package/dist/templates/minimal-node/vite.config.ts +15 -0
  43. package/dist/templates/minimal-node/vitest.config.ts +12 -0
  44. package/dist/templates/react-cloudflare/.baerly/scaffold.json +10 -0
  45. package/dist/templates/react-cloudflare/AGENTS.md +715 -0
  46. package/dist/templates/react-cloudflare/README.md +115 -0
  47. package/dist/templates/react-cloudflare/_gitignore +6 -0
  48. package/dist/templates/react-cloudflare/baerly.config.ts +37 -0
  49. package/dist/templates/react-cloudflare/index.html +12 -0
  50. package/dist/templates/react-cloudflare/package.json +34 -0
  51. package/dist/templates/react-cloudflare/pnpm-workspace.yaml +15 -0
  52. package/dist/templates/react-cloudflare/src/notes.test.ts +19 -0
  53. package/dist/templates/react-cloudflare/src/server/index.ts +12 -0
  54. package/dist/templates/react-cloudflare/src/web/App.tsx +38 -0
  55. package/dist/templates/react-cloudflare/src/web/NoteList.tsx +93 -0
  56. package/dist/templates/react-cloudflare/src/web/client.ts +13 -0
  57. package/dist/templates/react-cloudflare/src/web/main.tsx +14 -0
  58. package/dist/templates/react-cloudflare/src/web/styles.css +57 -0
  59. package/dist/templates/react-cloudflare/tsconfig.app.json +29 -0
  60. package/dist/templates/react-cloudflare/tsconfig.json +9 -0
  61. package/dist/templates/react-cloudflare/tsconfig.worker.json +28 -0
  62. package/dist/templates/react-cloudflare/uint8array-base64.d.ts +16 -0
  63. package/dist/templates/react-cloudflare/vite.config.ts +7 -0
  64. package/dist/templates/react-cloudflare/vitest.config.ts +11 -0
  65. package/dist/templates/react-cloudflare/wrangler.jsonc +27 -0
  66. package/dist/templates/react-node/.baerly/scaffold.json +13 -0
  67. package/dist/templates/react-node/.env.example +14 -0
  68. package/dist/templates/react-node/AGENTS.md +662 -0
  69. package/dist/templates/react-node/README.md +187 -0
  70. package/dist/templates/react-node/_gitignore +7 -0
  71. package/dist/templates/react-node/baerly.config.ts +37 -0
  72. package/dist/templates/react-node/index.html +12 -0
  73. package/dist/templates/react-node/package.json +32 -0
  74. package/dist/templates/react-node/pnpm-workspace.yaml +9 -0
  75. package/dist/templates/react-node/src/notes.test.ts +19 -0
  76. package/dist/templates/react-node/src/server/index.ts +48 -0
  77. package/dist/templates/react-node/src/web/App.tsx +38 -0
  78. package/dist/templates/react-node/src/web/NoteList.tsx +93 -0
  79. package/dist/templates/react-node/src/web/client.ts +13 -0
  80. package/dist/templates/react-node/src/web/main.tsx +14 -0
  81. package/dist/templates/react-node/src/web/styles.css +57 -0
  82. package/dist/templates/react-node/tsconfig.app.json +29 -0
  83. package/dist/templates/react-node/tsconfig.json +9 -0
  84. package/dist/templates/react-node/tsconfig.server.json +28 -0
  85. package/dist/templates/react-node/uint8array-base64.d.ts +16 -0
  86. package/dist/templates/react-node/vite.config.ts +17 -0
  87. package/dist/templates/react-node/vitest.config.ts +12 -0
  88. package/package.json +41 -0
@@ -0,0 +1,187 @@
1
+ # react-node
2
+
3
+ A baerly app scaffolded with `@gusto/create-baerly-storage` for the **Node** target —
4
+ any host that runs `node server.js` (Railway, Render, Fly without
5
+ Docker, Heroku, a VM, a container scheduler, your laptop). Uses
6
+ `@gusto/baerly-storage/node` against an S3-compatible bucket (AWS S3, R2 via
7
+ S3-compat, Minio, etc.). Ships `auth: "none"` so the day-1 happy
8
+ path works with zero env vars, plus a React + Vite SPA and a
9
+ one-collection `notes` schema you extend; flip to a shared secret
10
+ or wire `bearerJwt` against your OIDC IdP before deploy — see
11
+ "Production auth" below.
12
+
13
+ To ship a production Dockerfile alongside, scaffold with
14
+ `--with=docker` — the add-on writes a multi-stage distroless Dockerfile,
15
+ `.dockerignore`, and `healthcheck.js` into this same shape.
16
+
17
+ ## What you got
18
+
19
+ ```
20
+ react-node/
21
+ ├── package.json # one package, all deps
22
+ ├── tsconfig.json # project-references stub
23
+ ├── tsconfig.app.json # client TS project (src/web)
24
+ ├── tsconfig.server.json # Node server TS project (src/server)
25
+ ├── vite.config.ts # Vite + @vitejs/plugin-react + baerlyDev()
26
+ ├── index.html # SPA shell — Vite's entry point
27
+ ├── .env.example # storage creds, verifier, observability
28
+ ├── baerly.config.ts # app, tenant, target, NoteSchema, `Note` type
29
+ ├── AGENTS.md # deeper guide: hooks, schema, auth, deploy
30
+ ├── CLAUDE.md # same content (Claude Code reads this)
31
+ ├── src/
32
+ │ ├── server/
33
+ │ │ └── index.ts # baerlyNode({ app, storage, verifier, webRoot, maintenance? }).listen(PORT)
34
+ │ └── web/
35
+ │ ├── main.tsx # React entry
36
+ │ ├── App.tsx # Provider + new-note form (useMutation)
37
+ │ ├── client.ts # BaerlyClient bound to this config
38
+ │ └── NoteList.tsx # useQuery + per-row useMutation
39
+ └── README.md
40
+ ```
41
+
42
+ ## Run locally
43
+
44
+ ```sh
45
+ pnpm install
46
+ pnpm dev
47
+ ```
48
+
49
+
50
+ `pnpm dev` runs `vite`. `baerlyDev()` from `@gusto/baerly-storage/dev/vite`
51
+ mounts the Node HTTP listener as Connect middleware on the same Vite
52
+ process that serves the SPA, so `GET /` hits the SPA on
53
+ `http://localhost:5173/` and anything baerly handles (e.g.
54
+ `GET /v1/healthz`, `POST /v1/notes`) is served on the same origin —
55
+ one process, one port, SPA + HMR + `/v1/*` in one command. Storage is
56
+ `LocalFsStorage` rooted at `.baerly-data/`, so first-touch needs no
57
+ S3 creds, no JWKS, and no second process.
58
+
59
+ Open <http://localhost:5173>. Type a note, hit "Add note." Open a
60
+ second tab — inserts, edits, and deletes in one tab appear in the
61
+ other over the `/v1/since` long-poll.
62
+
63
+ For production-shaped local runs (S3 and the bundled SPA served
64
+ from `dist/client/`):
65
+
66
+ ```sh
67
+ pnpm build
68
+ BUCKET=... AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... pnpm start
69
+ ```
70
+
71
+ The server reads `BUCKET`, `AWS_ACCESS_KEY_ID`,
72
+ `AWS_SECRET_ACCESS_KEY` at startup. The default `auth: "none"`
73
+ posture needs no auth env vars; if you adopt Pattern B / C from
74
+ "Production auth" below, also set `SHARED_SECRET` (Pattern B) or
75
+ `JWKS_URL` + `JWT_ISSUER` + `JWT_AUDIENCE` (Pattern C). Optional:
76
+ `R2_ACCOUNT_ID` (switches the storage factory from `s3Storage` to
77
+ `r2Storage`), `AWS_REGION`, `PORT`, `TENANT`, `WEB_ROOT`,
78
+ `MAINTENANCE_COLLECTIONS` (comma-separated collection slugs — when
79
+ set, `baerlyNode` runs one compact+GC pass per `(tenant, collection)`
80
+ pair on its hourly tick; leave unset to skip the in-process loop
81
+ and schedule maintenance externally — a PaaS cron, k8s CronJob,
82
+ systemd timer).
83
+
84
+ After `pnpm build`, `http://localhost:8080/` serves the built SPA
85
+ out of `dist/client/` and `http://localhost:8080/v1/*` is the
86
+ baerly HTTP surface — single origin, no CORS.
87
+
88
+ `pnpm typecheck` runs `tsc -b --noEmit` across both project
89
+ references.
90
+
91
+ ## Deploy
92
+
93
+ This scaffold runs anywhere `node server.js` runs. The `package.json`
94
+ exposes `build` (Vite SPA + TS check) and `start`
95
+ (`node --experimental-strip-types src/server/index.ts`); arrange your
96
+ host to run `pnpm install && pnpm build`, then `pnpm start`.
97
+
98
+ Concrete shapes:
99
+
100
+ - **Managed PaaS** (Railway, Render, DO App Platform, Fly Machines
101
+ without a Dockerfile, Heroku): push the repo to a connected GitHub
102
+ repo, set env vars from `.env.example` in the dashboard, deploy.
103
+ The platform's buildpack detects Node and runs the root scripts.
104
+ - **VM / bare-metal**: clone, install Node 24+, copy `.env.example`
105
+ to `.env`, run `pnpm install && pnpm build && pnpm start` under
106
+ your process manager of choice (systemd, pm2, etc.).
107
+ - **Container** (Docker, k8s, ECS, Fly Machines with a Dockerfile):
108
+ scaffold with `pnpm create @gusto/baerly-storage@latest --target=node --with=docker` to add
109
+ a production Dockerfile, `.dockerignore`, and `healthcheck.js`
110
+ alongside this shape, then `docker build .`.
111
+
112
+ Verify: `curl https://<your-service>/v1/healthz`.
113
+
114
+ ## Extend the schema
115
+
116
+ Edit `baerly.config.ts`. The `Note` row type is inferred from
117
+ `NoteSchema` in the same file — adding a field to the schema
118
+ propagates to the UI through `import type { Note }`.
119
+
120
+ ```typescript
121
+ export const NoteSchema = z.object({
122
+ _id: z.string(),
123
+ body: z.string().min(1),
124
+ // Add fields here:
125
+ tags: z.array(z.string()).optional(),
126
+ });
127
+ ```
128
+
129
+ ## Production auth
130
+
131
+ The scaffold ships `auth: "none"` so the day-1 happy path works
132
+ with zero env vars; every request resolves to `config.tenant` and
133
+ the `NoteSchema` still validates writes server-side. Before deploy,
134
+ follow `AGENTS.md` → "Going to production":
135
+
136
+ - **Pattern B — `auth: "shared-secret"`.** Single-tenant
137
+ server-to-server callers (CI, cron, internal services). Flip
138
+ `auth` in `baerly.config.ts` and put `SHARED_SECRET` in
139
+ `process.env` (your PaaS / secret manager).
140
+ - **Pattern C — JWKS-backed JWT (recommended for multi-tenant).**
141
+ Same artifact in dev and prod; the factory `verifier:` override
142
+ engages when `JWKS_URL` is set. `bearerJwt()` (re-exported from
143
+ `@gusto/baerly-storage/auth`) validates against your IdP's JWKS endpoint
144
+ (`https://<issuer>/.well-known/jwks.json`) with `JWT_ISSUER` +
145
+ `JWT_AUDIENCE` and pins the tenant from a claim.
146
+
147
+ ## When to graduate
148
+
149
+ baerly is designed for the small-to-medium operating point. Past these
150
+ thresholds, S3 list-prefix latency and per-class operation pricing
151
+ start to dominate, and you're better off on a real database:
152
+
153
+ - **~30 writes / minute / collection**
154
+ - **~10 GB / tenant**
155
+ - **~100 collections / tenant**
156
+
157
+ When you cross the soft ceiling, graduation is mechanical:
158
+ `baerly export --target=postgres` walks your log entries (already
159
+ Postgres-logical-replication-shaped) into a real DB. If your
160
+ deploy target is Cloudflare Workers and you'll accept Cloudflare
161
+ lock-in, [D1](https://developers.cloudflare.com/d1/) is cheaper
162
+ per-write at M-size and is a natural next step. If you're on
163
+ AWS, on-prem, or want your data portable, managed Postgres is
164
+ the typical destination. Either way — graduation is a Baerly win,
165
+ not a churn event.
166
+
167
+ **Export to a real database** (swap `--target=` for `sqlite`,
168
+ `postgres`, or `d1`):
169
+
170
+ ```sh
171
+ baerly export --target=postgres \
172
+ --bucket=react-node --app=react-node --tenant=<your-tenant> \
173
+ --collection=<collection-name> --output=./out.sql
174
+ ```
175
+
176
+ The export is a **point-in-time** snapshot and honors any active
177
+ schema on the collection. Your data was already in your bucket and
178
+ your code is a portable HTTP server, so the graduation doesn't
179
+ require vendor cooperation.
180
+
181
+ ## Pointers
182
+
183
+ - `baerly.config.ts` — app config + Zod schema.
184
+ - `src/server/index.ts` — `node:http` listener entry (`baerlyNode`).
185
+ - `src/web/NoteList.tsx` — `useQuery` reactive read.
186
+ - `vite.config.ts` — Vite + React + `baerlyDev()` dev middleware.
187
+ - `AGENTS.md` / `CLAUDE.md` — agent-facing guide (byte-identical).
@@ -0,0 +1,7 @@
1
+ node_modules/
2
+ dist/
3
+ .baerly-data/
4
+ .env
5
+ .env.local
6
+ .DS_Store
7
+ *.tsbuildinfo
@@ -0,0 +1,37 @@
1
+ import { z } from "zod";
2
+ import { defineConfig } from "@gusto/baerly-storage/config";
3
+
4
+ /**
5
+ * Zod schema for one note. Source of truth for both the runtime
6
+ * `SchemaValidator` consumed by `baerly-storage`'s writer and the
7
+ * compile-time `Note` row type imported by the UI.
8
+ */
9
+ export const NoteSchema = z.object({
10
+ // Auto-stamped by the kernel on insert (UUIDv7) — never provide it from the
11
+ // client. Declared here so `z.infer<typeof NoteSchema>` produces a row type
12
+ // that includes `_id`, which the UI reads via `n._id`. UUIDv7 sorts
13
+ // by server mint time, so the list orders newest-first via `_id` —
14
+ // no separate `created_at` column needed.
15
+ _id: z.string(),
16
+ body: z.string().min(1),
17
+ });
18
+
19
+ /**
20
+ * Compile-time row type derived from {@link NoteSchema}. Single
21
+ * source of truth — adding a field to the schema adds it here.
22
+ *
23
+ * **Replacing the demo?** `src/web/{App,NoteList}.tsx` import
24
+ * `Note` from this file; rename `NoteSchema` first and the
25
+ * inferred type follows.
26
+ */
27
+ export type Note = z.infer<typeof NoteSchema>;
28
+
29
+ export default defineConfig({
30
+ app: "react-node",
31
+ tenant: "react-demo",
32
+ target: "node",
33
+ auth: "none",
34
+ collections: {
35
+ notes: { schema: NoteSchema },
36
+ },
37
+ });
@@ -0,0 +1,12 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
+ <title>Notes</title>
7
+ </head>
8
+ <body>
9
+ <div id="root"></div>
10
+ <script type="module" src="/src/web/main.tsx"></script>
11
+ </body>
12
+ </html>
@@ -0,0 +1,32 @@
1
+ {
2
+ "name": "react-node",
3
+ "version": "0.0.0",
4
+ "private": true,
5
+ "type": "module",
6
+ "scripts": {
7
+ "dev": "vite",
8
+ "build": "tsc -b && vite build",
9
+ "start": "node --experimental-strip-types src/server/index.ts",
10
+ "test": "vitest run",
11
+ "typecheck": "tsc -b --noEmit",
12
+ "verify": "pnpm run typecheck && pnpm run test"
13
+ },
14
+ "dependencies": {
15
+ "@gusto/baerly-storage": "workspace:*",
16
+ "aws4fetch": "^1.0.20",
17
+ "react": "^19.0.0",
18
+ "react-dom": "^19.0.0",
19
+ "zod": "^4.4.3"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^24.0.0",
23
+ "@types/react": "^19.2.15",
24
+ "@types/react-dom": "^19.0.0",
25
+ "@vitejs/plugin-react": "^6.0.2",
26
+ "happy-dom": "^20.9.0",
27
+ "typescript": "^6.0.3",
28
+ "vite": "^8.0.14",
29
+ "vitest": "^4.1.7"
30
+ },
31
+ "packageManager": "pnpm@11.1.2"
32
+ }
@@ -0,0 +1,9 @@
1
+ # pnpm 11 reads the postinstall-script allowlist only from this
2
+ # file: `package.json#pnpm.*` is no longer honoured. Without this
3
+ # map, `pnpm install` exits with `ERR_PNPM_IGNORED_BUILDS` for the
4
+ # bundler chain below.
5
+ #
6
+ # `esbuild` ships a working install script we want to run (it
7
+ # arrives via vite).
8
+ allowBuilds:
9
+ esbuild: true
@@ -0,0 +1,19 @@
1
+ // Example test for the shipped `notes` collection. Replace or
2
+ // delete when you change the schema in `baerly.config.ts` — the
3
+ // import on line below will stop typechecking once `notes` is
4
+ // gone.
5
+ import { test, expect } from "vitest";
6
+ import { Db, MemoryStorage } from "@gusto/baerly-storage";
7
+ import config from "../baerly.config.ts";
8
+
9
+ test("notes round-trip", async () => {
10
+ const db = Db.create({
11
+ storage: new MemoryStorage(),
12
+ app: "test",
13
+ tenant: "t",
14
+ config,
15
+ });
16
+ const { _id } = await db.collection("notes").insert({ body: "hello" });
17
+ const row = await db.collection("notes").get(_id);
18
+ expect(row?.body).toBe("hello");
19
+ });
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Server entry for react-node. `baerlyNode(opts)` reads
3
+ * `opts.config.auth` to choose its verifier — the scaffold ships
4
+ * `auth: "none"`, so every request resolves to `config.tenant`
5
+ * with no header check. The schema declared in
6
+ * `baerly.config.ts:collections.notes.schema` runs server-side on
7
+ * every write. See AGENTS.md "Going to production" for the recipe
8
+ * to flip `auth` or wire a custom verifier.
9
+ *
10
+ * Storage: AWS S3 by default; set `R2_ACCOUNT_ID` to switch to
11
+ * Cloudflare R2 via the S3-compat endpoint.
12
+ */
13
+ import { baerlyNode, r2Storage, s3Storage } from "@gusto/baerly-storage/node";
14
+ import type { Storage } from "@gusto/baerly-storage";
15
+ import config from "../../baerly.config.ts";
16
+
17
+ const reqEnv = (name: string): string => {
18
+ const v = process.env[name];
19
+ if (v === undefined || v === "") {
20
+ throw new Error(`Missing required env var: ${name}`);
21
+ }
22
+ return v;
23
+ };
24
+
25
+ const storage: Storage =
26
+ process.env["R2_ACCOUNT_ID"] !== undefined
27
+ ? r2Storage({
28
+ accountId: reqEnv("R2_ACCOUNT_ID"),
29
+ bucket: reqEnv("BUCKET"),
30
+ credentials: {
31
+ accessKeyId: reqEnv("AWS_ACCESS_KEY_ID"),
32
+ secretAccessKey: reqEnv("AWS_SECRET_ACCESS_KEY"),
33
+ },
34
+ })
35
+ : s3Storage({
36
+ region: process.env["AWS_REGION"] ?? "us-east-1",
37
+ bucket: reqEnv("BUCKET"),
38
+ credentials: {
39
+ accessKeyId: reqEnv("AWS_ACCESS_KEY_ID"),
40
+ secretAccessKey: reqEnv("AWS_SECRET_ACCESS_KEY"),
41
+ },
42
+ });
43
+
44
+ const PORT = Number(process.env["PORT"] ?? 8080);
45
+
46
+ await baerlyNode({ config, storage }).listen(PORT);
47
+
48
+ console.log(`react-node listening on :${PORT}`);
@@ -0,0 +1,38 @@
1
+ import { BaerlyProvider, useMutation } from "@gusto/baerly-storage/client/react";
2
+ import { client } from "./client.ts";
3
+ import { NoteList } from "./NoteList.tsx";
4
+
5
+ const NewNoteForm = () => {
6
+ const [mutate, { isPending, error }] = useMutation();
7
+ return (
8
+ <form
9
+ className="new-note"
10
+ onSubmit={async (e) => {
11
+ e.preventDefault();
12
+ const form = e.currentTarget;
13
+ const body = String(new FormData(form).get("body")).trim();
14
+ if (body.length === 0) {
15
+ return;
16
+ }
17
+ await mutate((c) => c.collection("notes").insert({ body }));
18
+ form.reset();
19
+ }}
20
+ >
21
+ <textarea name="body" placeholder="Write a note…" rows={2} required />
22
+ <button type="submit" disabled={isPending}>
23
+ {isPending ? "Saving…" : "Add note"}
24
+ </button>
25
+ {error && <p className="error">Save failed: {error.message}</p>}
26
+ </form>
27
+ );
28
+ };
29
+
30
+ export const App = () => (
31
+ <BaerlyProvider client={client}>
32
+ <div className="app">
33
+ <h1>Notes</h1>
34
+ <NewNoteForm />
35
+ <NoteList />
36
+ </div>
37
+ </BaerlyProvider>
38
+ );
@@ -0,0 +1,93 @@
1
+ import { useState } from "react";
2
+ import { useMutation, useQuery } from "@gusto/baerly-storage/client/react";
3
+ import type { Note } from "../../baerly.config.ts";
4
+
5
+ const NoteRow = ({ note }: { note: Note }) => {
6
+ const [isEditing, setIsEditing] = useState(false);
7
+ const [body, setBody] = useState(note.body);
8
+ const [save, { isPending: isSaving, error: saveError }] = useMutation();
9
+ const [del, { isPending: isDeleting, error: deleteError }] = useMutation();
10
+ const error = saveError ?? deleteError;
11
+ return (
12
+ <li className="note-row">
13
+ {isEditing ? (
14
+ <textarea value={body} onChange={(e) => setBody(e.target.value)} rows={2} />
15
+ ) : (
16
+ <p className="note-body">{note.body}</p>
17
+ )}
18
+ <div className="actions">
19
+ {isEditing ? (
20
+ <>
21
+ <button
22
+ disabled={isSaving}
23
+ onClick={async () => {
24
+ await save((c) => c.collection("notes").update(note._id, { body }));
25
+ setIsEditing(false);
26
+ }}
27
+ >
28
+ {isSaving ? "Saving…" : "Save"}
29
+ </button>
30
+ <button
31
+ disabled={isSaving}
32
+ onClick={() => {
33
+ setBody(note.body);
34
+ setIsEditing(false);
35
+ }}
36
+ >
37
+ Cancel
38
+ </button>
39
+ </>
40
+ ) : (
41
+ <>
42
+ <button
43
+ onClick={() => {
44
+ setBody(note.body);
45
+ setIsEditing(true);
46
+ }}
47
+ >
48
+ Edit
49
+ </button>
50
+ <button
51
+ className="danger"
52
+ disabled={isDeleting}
53
+ onClick={async () => {
54
+ if (!window.confirm("Delete this note?")) {
55
+ return;
56
+ }
57
+ await del((c) => c.collection("notes").delete(note._id));
58
+ }}
59
+ >
60
+ {isDeleting ? "Deleting…" : "Delete"}
61
+ </button>
62
+ </>
63
+ )}
64
+ </div>
65
+ {error && <p className="error">{error.message}</p>}
66
+ </li>
67
+ );
68
+ };
69
+
70
+ export const NoteList = () => {
71
+ const result = useQuery((c) => c.collection("notes").all() as Promise<Note[]>, []);
72
+ if (result.status === "error") {
73
+ return <p className="error">Error: {result.error.message}</p>;
74
+ }
75
+ if (result.status === "loading") {
76
+ return <p>Loading…</p>;
77
+ }
78
+ // `result.status` is now "ok" or "refreshing" — `data` is `Note[]`.
79
+ // ("skipped" is unreachable: this useQuery never returns the skip sentinel.)
80
+ const rows = result.data ?? [];
81
+ if (rows.length === 0) {
82
+ return <p>No notes yet. Add one above.</p>;
83
+ }
84
+ // Newest first — UUIDv7 `_id`s sort by server mint time descending.
85
+ const sorted = rows.toSorted((a, b) => b._id.localeCompare(a._id));
86
+ return (
87
+ <ul className="note-list">
88
+ {sorted.map((n) => (
89
+ <NoteRow key={n._id} note={n} />
90
+ ))}
91
+ </ul>
92
+ );
93
+ };
@@ -0,0 +1,13 @@
1
+ import { createBaerlyClient } from "@gusto/baerly-storage/client";
2
+ import config from "../../baerly.config.ts";
3
+
4
+ // Same-origin baseUrl works in both dev and production. With
5
+ // `auth: "none"` in baerly.config.ts (the scaffold default), this
6
+ // file never sends an `Authorization` header and the adapter pins
7
+ // every request to `config.tenant`. When you flip `auth` for
8
+ // production, the AGENTS.md "Going to production" recipe shows
9
+ // where the token / cookie comes from.
10
+ export const client = createBaerlyClient({
11
+ baseUrl: "",
12
+ config,
13
+ });
@@ -0,0 +1,14 @@
1
+ import { StrictMode } from "react";
2
+ import { createRoot } from "react-dom/client";
3
+ import { App } from "./App.tsx";
4
+ import "./styles.css";
5
+
6
+ const root = document.getElementById("root");
7
+ if (root === null) {
8
+ throw new Error("No #root element");
9
+ }
10
+ createRoot(root).render(
11
+ <StrictMode>
12
+ <App />
13
+ </StrictMode>,
14
+ );
@@ -0,0 +1,57 @@
1
+ body {
2
+ font-family: system-ui, sans-serif;
3
+ margin: 0;
4
+ }
5
+
6
+ .app {
7
+ padding: 24px;
8
+ max-width: 720px;
9
+ margin: 0 auto;
10
+ }
11
+
12
+ .app h1 {
13
+ margin: 0 0 24px;
14
+ }
15
+
16
+ .new-note {
17
+ margin-bottom: 24px;
18
+ }
19
+
20
+ .new-note textarea,
21
+ .note-row textarea {
22
+ display: block;
23
+ width: 100%;
24
+ resize: vertical;
25
+ }
26
+
27
+ .new-note button {
28
+ margin-top: 8px;
29
+ }
30
+
31
+ .note-list {
32
+ list-style: none;
33
+ padding: 0;
34
+ }
35
+
36
+ .note-row {
37
+ padding: 12px 0;
38
+ border-bottom: 1px solid #eee;
39
+ }
40
+
41
+ .note-body {
42
+ margin: 0;
43
+ white-space: pre-wrap;
44
+ }
45
+
46
+ .actions {
47
+ margin-top: 8px;
48
+ }
49
+
50
+ .actions button + button {
51
+ margin-left: 8px;
52
+ }
53
+
54
+ .error,
55
+ .danger {
56
+ color: crimson;
57
+ }
@@ -0,0 +1,29 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "allowImportingTsExtensions": true,
8
+ "noEmit": true,
9
+
10
+ "strict": true,
11
+ "noUncheckedIndexedAccess": true,
12
+ "noImplicitOverride": true,
13
+ "noImplicitReturns": true,
14
+ "noPropertyAccessFromIndexSignature": true,
15
+ "noFallthroughCasesInSwitch": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": true,
18
+ "verbatimModuleSyntax": true,
19
+ "isolatedModules": true,
20
+ "erasableSyntaxOnly": true,
21
+
22
+ "esModuleInterop": true,
23
+ "skipLibCheck": true,
24
+ "jsx": "react-jsx",
25
+ "types": ["vite/client"],
26
+ "composite": true
27
+ },
28
+ "include": ["src/web/**/*", "uint8array-base64.d.ts", "baerly.config.ts"]
29
+ }
@@ -0,0 +1,9 @@
1
+ // Stub — TS picks up the referenced projects below.
2
+ // `tsconfig.app.json` covers the SPA (DOM); `tsconfig.server.json`
3
+ // covers the Node entry (`server.ts`). Tests at the repo root match
4
+ // `vitest.config.ts:test.include` (e.g. `*.test.ts`); they don't
5
+ // belong to any tsconfig — vitest type-checks them via its own pipe.
6
+ {
7
+ "files": [],
8
+ "references": [{ "path": "./tsconfig.app.json" }, { "path": "./tsconfig.server.json" }]
9
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2024",
4
+ "lib": ["ES2024", "DOM", "DOM.Iterable"],
5
+ "module": "ESNext",
6
+ "moduleResolution": "bundler",
7
+ "allowImportingTsExtensions": true,
8
+ "noEmit": true,
9
+
10
+ "strict": true,
11
+ "noUncheckedIndexedAccess": true,
12
+ "noImplicitOverride": true,
13
+ "noImplicitReturns": true,
14
+ "noPropertyAccessFromIndexSignature": true,
15
+ "noFallthroughCasesInSwitch": true,
16
+ "noUnusedLocals": true,
17
+ "noUnusedParameters": true,
18
+ "verbatimModuleSyntax": true,
19
+ "isolatedModules": true,
20
+ "erasableSyntaxOnly": true,
21
+
22
+ "esModuleInterop": true,
23
+ "skipLibCheck": true,
24
+ "types": ["node"],
25
+ "composite": true
26
+ },
27
+ "include": ["src/server/**/*", "uint8array-base64.d.ts", "baerly.config.ts"]
28
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * TC39 Stage-4 base64 codec methods — Node 22+, Bun, Workerd. Delete
3
+ * when TypeScript accepts `esnext.typedarrays` in `--lib`.
4
+ */
5
+ interface Uint8Array<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> {
6
+ toBase64(options?: { alphabet?: "base64" | "base64url"; omitPadding?: boolean }): string;
7
+ }
8
+ interface Uint8ArrayConstructor {
9
+ fromBase64(
10
+ input: string,
11
+ options?: {
12
+ alphabet?: "base64" | "base64url";
13
+ lastChunkHandling?: "loose" | "strict" | "stop-before-partial";
14
+ },
15
+ ): Uint8Array;
16
+ }