`; renders `
` when not connected; "vercel" / "Vercel" in the wordmark, heading, lede and footer → "cloudflare" / "Cloudflare" | Read per request, not frozen at build; the deploy smoke's marker; the host it runs on |
+| 8 | `components/catalogue.tsx` (new) and `listProducts()` in `lib/products.ts`: while search is not connected, the products from Postgres (only the fields the connector indexes) in the hit cards' markup, each linking its product page; a missing table says the migrations have not run | A product goes live before its owner has an Algolia application, and still shows its data |
+| 9 | `app/layout.tsx`: Geist from the `geist` package (next/font/local) instead of `next/font/google`; `metadataBase` from `NEXT_PUBLIC_SITE_URL`; `title` from `SITE_NAME` (`lib/site.ts`, "Algolia x Supabase starter"; upstream "Algolia × Supabase × Vercel starter"); the description says Cloudflare | Google's font download fails on GitHub's runners; one rename seam (the card's name pattern has no `×`); the origin per environment |
+| 10 | `app/globals.css`: `@import "tailwindcss" source(none)` with `@source` for `app/` and `components/` | Tailwind 4 reads .gitignore only inside a git checkout, so a CI job tree would scan the build output |
+| 11 | `demo/seed.sql` → `packages/db/src/migrations/010_products` (its CREATE TABLE) and `030_demo_products` (its twenty upserts, byte for byte — tests/db rebuilds upstream's file from the two and checks its sha256); `020_row_level_security` enables RLS with no policy, behind a guard; `demo/transform.js` kept as is | Applied before the Worker serves; the Data API's roles see nothing (risk AL-E) |
+| 12 | `scripts/migrate.mjs`, `scripts/app-migrations.mjs` (new): `pnpm db:migrate` applies packages/db's app migrations to a local database in transactions, its ledger (with sha256s) in schema `local_migrations` | Local databases get the same files as the deployed ones |
+| 13 | `app/api/health/route.ts` (new): 200 only when the table exists with RLS on; reports `search: connected | not connected` | The deploy's smoke and the bootstrap's probes read it |
+| 14 | `wrangler.template.jsonc` → committed `wrangler.jsonc`, `wiring.fixture.json`, `cloudflare-env.d.ts`, `open-next.config.ts`, `component.yaml` (the Algolia secrets as `optionalSecretEnv`, unset for the build and pushed by `tooling/wire/worker-secrets.mjs`) | The Worker's config and deploy contract replace Vercel's |
+| 15 | `eslint.config.mjs`: also ignores `.open-next/**`, `.wrangler/**` and `cloudflare-env.d.ts`; upstream's two `no-unused-vars` warnings on `demo/transform.js` (a function pasted into Algolia's dashboard, never called here) are kept | The Workers build and its local state; the file stays byte for byte |
+| 16 | Tests: `tests/web` (the per-request client, the Algolia config, `/api/health`, the catalogue, the page's two states, the product queries, InstantSearch rendered in jsdom against an in-process Algolia stand-in — query, facets, the stock toggle — and the wrangler render) and `tests/db` (the manifest, the local migrator, the table's columns, the demo rows held to upstream's seed, the connector's transformation, row-level security, on PGlite) | The template ships none |
+| 17 | `tooling/rebrand/rebrand.mjs`: the leftover sweep allows exactly `ALGOLIA_SEARCH_API_KEY` and `NEXT_PUBLIC_ALGOLIA_SEARCH_API_KEY` | Algolia's names, which share this baseline's env-var prefix (risk AL-F) |
+
+## Verified
+
+- Locally: every contract tier, the component docs, the blueprint's `--status`, the leak gate and placement; the landing checks (typecheck, lint, test, build); the built Worker under `wrangler dev` over a migrated PGlite (the catalogue, the product pages, the 404s, `/api/health`), and with the Algolia secrets as vars, a headless Chrome rendering 20 hits, the facets and the stock toggle from an Algolia stand-in. Worker: 1147 KiB gzipped (Workers Free).
+- On the PR's Baseline CI `product` job: the e2e tier on real Postgres (this machine has no `psql`).
diff --git a/specs/epics/algolia-search/README.md b/specs/epics/algolia-search/README.md
index 74dba65..cbfdc25 100644
--- a/specs/epics/algolia-search/README.md
+++ b/specs/epics/algolia-search/README.md
@@ -8,7 +8,7 @@ The port keeps the page, the InstantSearch UI and its facets, the hit cards, the
| Field | Value |
|-------|-------|
-| Status | In progress — AL0 on main |
+| Status | In progress — AL1 on main: the site runs on Workers |
| Cluster | **AL** (AL0–AL2) |
| Owner(s) | `apps/web` (the pages, the search UI, `lib/db.ts`, `lib/algolia.ts`, `components/catalogue.tsx`, `scripts/migrate.mjs`) · `packages/db` (the migrations and their runner) · `tests/web`, `tests/db` · `infra/terraform/{supabase,cloudflare-hyperdrive}`, `infra/db-migrate` |
| Builds on | `postgres-kysely` (its scaffolding, Supabase and Hyperdrive roots, migrations, health check and baseline machinery), `prisma-nextjs-blog` (the Worker-secrets push), and through them `postgres-drizzle-starter` and `lumen` |
diff --git a/tests/db/component.yaml b/tests/db/component.yaml
new file mode 100644
index 0000000..b0b5032
--- /dev/null
+++ b/tests/db/component.yaml
@@ -0,0 +1,31 @@
+apiVersion: sourceplane.io/v1
+kind: Component
+metadata:
+ name: db-tests
+ description: The migrations' tests (the manifest and its checksums, the local migrator and its list, the products table and its demo rows held to upstream's seed, the connector's transformation, and row-level security on every table in public after every migration, on an in-process Postgres)
+spec:
+ type: turbo-package
+ lifecycle: production
+ owner: platform
+ # Its pages, attached to it in the workspace's catalog: what the Docs
+ # library shows for it, and what the catalog's docs and runbook checks read.
+ # Generated from what this manifest and its sources declare.
+ docs:
+ overview: docs/overview.md
+ pages:
+ - { path: docs/architecture.md, role: architecture, title: Architecture }
+ - { path: docs/runbook.md, role: runbook, title: Runbook }
+ domain: tests
+ subscribe:
+ environments:
+ - name: dev
+ profile: quick-check
+ parameters:
+ nodeVersion: "22"
+ pnpmVersion: "10.12.1"
+ buildCommand: pnpm exec turbo run build --filter=./
+ typecheckCommand: pnpm exec turbo run typecheck --filter=./
+ preBuildCommand: pnpm exec turbo run test --filter=./
+ labels:
+ team: platform
+ layer: test
diff --git a/tests/db/docs/architecture.md b/tests/db/docs/architecture.md
new file mode 100644
index 0000000..285e916
--- /dev/null
+++ b/tests/db/docs/architecture.md
@@ -0,0 +1,10 @@
+# db-tests — architecture
+
+A test package at `tests/db`. Its lane runs the suite before it builds.
+
+## Suites (4)
+
+- `local-migrate.test.ts`
+- `migrations.test.ts`
+- `products.test.ts`
+- `row-level-security.test.ts`
diff --git a/tests/db/docs/overview.md b/tests/db/docs/overview.md
new file mode 100644
index 0000000..011db63
--- /dev/null
+++ b/tests/db/docs/overview.md
@@ -0,0 +1,20 @@
+# db-tests
+
+The migrations' tests (the manifest and its checksums, the local migrator and its list, the products table and its demo rows held to upstream's seed, the connector's transformation, and row-level security on every table in public after every migration, on an in-process Postgres)
+
+The test suite for **db**. It deploys nothing: its lane installs, builds and runs the tests.
+
+| | |
+| ------------ | -------------------- |
+| Type | `turbo-package` |
+| Source | `tests/db` |
+| Package | `@app/db-tests` |
+| Environments | `dev`: `quick-check` |
+
+## Depends on
+
+- (none)
+
+## Depended on by
+
+- (none)
diff --git a/tests/db/docs/runbook.md b/tests/db/docs/runbook.md
new file mode 100644
index 0000000..aa64499
--- /dev/null
+++ b/tests/db/docs/runbook.md
@@ -0,0 +1,26 @@
+# db-tests — runbook
+
+## How it runs
+
+Its lane runs on every pull request that changes it; it has no deployed surface.
+CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;
+the plan orders a component after everything it depends on.
+
+## Local commands
+
+```bash
+pnpm --filter @app/db-tests build
+pnpm --filter @app/db-tests test
+pnpm --filter @app/db-tests typecheck
+pnpm --filter @app/db-tests lint
+```
+
+## Rollback
+
+Revert the commit on `main`. The next convergence applies the previous desired
+state; nothing was changed out of band, so there is nothing else to undo.
+
+## Common failures
+
+- **A dependent fails to build after a change here**: run `pnpm typecheck`
+ across the workspace before merging.
diff --git a/tests/db/eslint.config.js b/tests/db/eslint.config.js
new file mode 100644
index 0000000..2e905dc
--- /dev/null
+++ b/tests/db/eslint.config.js
@@ -0,0 +1,2 @@
+import config from "../../tooling/eslint/index.js";
+export default config;
diff --git a/tests/db/package.json b/tests/db/package.json
new file mode 100644
index 0000000..ad6e1e3
--- /dev/null
+++ b/tests/db/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@app/db-tests",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "tsc --noEmit",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run",
+ "lint": "eslint src"
+ },
+ "devDependencies": {
+ "@app/eslint-config": "workspace:*",
+ "@app/tsconfig": "workspace:*",
+ "@electric-sql/pglite": "0.5.8",
+ "@saas/db": "workspace:*",
+ "@types/node": "^22.9.0",
+ "typescript": "^5.8.3",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/tests/db/src/local-migrate.test.ts b/tests/db/src/local-migrate.test.ts
new file mode 100644
index 0000000..9edc67e
--- /dev/null
+++ b/tests/db/src/local-migrate.test.ts
@@ -0,0 +1,73 @@
+import { describe, expect, it } from "vitest";
+import { PGlite } from "@electric-sql/pglite";
+// `pnpm --filter @app/web db:migrate`: the schema and the demo products into a
+// LOCAL database, from the very files db-migrate applies to stage and prod.
+import { connection, migrate } from "../../../apps/web/scripts/migrate.mjs";
+
+// pg's `query`, over PGlite: a statement with parameters runs on the extended
+// protocol, one without on the simple protocol (a file runs whole), as pg does.
+function client(db: PGlite, failOn?: RegExp) {
+ return {
+ async query(text: string, params?: unknown[]) {
+ if (failOn?.test(text)) throw new Error("boom");
+ if (params) return db.query
>(text, params);
+ const results = await db.exec(text);
+ return { rows: (results.at(-1)?.rows ?? []) as Record[] };
+ },
+ };
+}
+const count = async (db: PGlite, sql: string) => (await db.query<{ n: number }>(sql)).rows[0]!.n;
+
+describe("pnpm db:migrate (apps/web/scripts/migrate.mjs)", () => {
+ it("applies the app migrations in order, keeping its ledger out of public", async () => {
+ const db = new PGlite();
+ const lines: string[] = [];
+ expect(await migrate(client(db), (l) => lines.push(l))).toBe(3);
+ expect(lines).toEqual(["applied: 010_products", "applied: 020_row_level_security", "applied: 030_demo_products"]);
+ expect(await count(db, "select count(*)::int as n from products")).toBe(20);
+ expect(await count(db, "select count(*)::int as n from local_migrations.applied")).toBe(3);
+ const publicTables = await db.query<{ relname: string }>(
+ `select c.relname from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = 'public' and c.relkind in ('r', 'p') order by 1`,
+ );
+ expect(publicTables.rows.map((r) => r.relname)).toEqual(["products"]);
+ }, 60_000);
+
+ it("is up to date the second time, and writes nothing", async () => {
+ const db = new PGlite();
+ await migrate(client(db), () => {});
+ await db.exec("delete from products where id = 20");
+ const lines: string[] = [];
+ expect(await migrate(client(db), (l) => lines.push(l))).toBe(0);
+ expect(lines).toEqual(["up to date"]);
+ expect(await count(db, "select count(*)::int as n from products")).toBe(19);
+ }, 60_000);
+
+ it("stops on a file changed after it was applied", async () => {
+ const db = new PGlite();
+ await migrate(client(db), () => {});
+ await db.exec("update local_migrations.applied set checksum = 'x' where id = '020_row_level_security'");
+ await expect(migrate(client(db), () => {})).rejects.toThrow(/020_row_level_security changed after it was applied/);
+ }, 60_000);
+
+ it("rolls a failed migration back with its ledger row, and applies it on the next run", async () => {
+ const db = new PGlite();
+ await expect(migrate(client(db, /insert into products/), () => {})).rejects.toThrow("boom");
+ expect(await count(db, "select count(*)::int as n from local_migrations.applied")).toBe(2);
+ expect(await count(db, "select count(*)::int as n from products")).toBe(0);
+ const lines: string[] = [];
+ expect(await migrate(client(db), (l) => lines.push(l))).toBe(1);
+ expect(lines).toEqual(["applied: 030_demo_products"]);
+ expect(await count(db, "select count(*)::int as n from products")).toBe(20);
+ }, 60_000);
+
+ it("talks TLS to a remote database, as the app's pool does, and plain to a local one", () => {
+ expect(connection("postgres://postgres:postgres@localhost:54322/postgres")).toEqual({
+ connectionString: "postgres://postgres:postgres@localhost:54322/postgres",
+ });
+ expect(connection("postgres://u:p@db.abc.supabase.co:5432/postgres?sslmode=require")).toEqual({
+ connectionString: "postgres://u:p@db.abc.supabase.co:5432/postgres",
+ ssl: { rejectUnauthorized: false },
+ });
+ });
+});
diff --git a/tests/db/src/migrations.test.ts b/tests/db/src/migrations.test.ts
new file mode 100644
index 0000000..ae59f40
--- /dev/null
+++ b/tests/db/src/migrations.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import * as path from "node:path";
+import { manifest } from "@saas/db/manifest";
+import { buildPlan, runMigrations } from "@saas/db/runner";
+
+const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations");
+// db-migrate applies these files to stage and prod; `pnpm --filter @app/web
+// db:migrate` applies the very same files to a local database
+// (apps/web/scripts/migrate.mjs). There is one copy of the schema and of the
+// demo dataset; what can drift is the LIST the local migrator reads.
+import { appMigrations } from "../../../apps/web/scripts/app-migrations.mjs";
+
+describe("the migration manifest (packages/db)", () => {
+ it("starts with the control migration and names every file with its checksum", () => {
+ expect(manifest.migrations[0]?.id).toBe("000_control_baseline");
+ for (const entry of manifest.migrations) {
+ const file = readFileSync(path.join(migrationsDir, entry.path));
+ expect(createHash("sha256").update(file).digest("hex"), entry.id).toBe(entry.checksum);
+ }
+ });
+
+ it("plans every migration as pending offline", async () => {
+ const result = await runMigrations(manifest, { mode: "plan", migrationsDir, adapter: null });
+ expect(result.failed).toBeNull();
+ expect(result.applied).toEqual(manifest.migrations.map((m) => m.id));
+ });
+
+ it("gives the local migrator exactly the app migrations, in the manifest's order", () => {
+ const app = manifest.migrations.filter((m) => m.context === "app");
+ expect(appMigrations()).toEqual(app.map((m) => ({ id: m.id, path: m.path })));
+ // the control migration is the runner's own ledger, never a local one
+ expect(appMigrations().map((m) => m.id)).not.toContain("000_control_baseline");
+ });
+
+ it("creates the table idempotently — a database someone seeded by hand keeps its table", () => {
+ const sql = readFileSync(path.join(migrationsDir, "010_products/up.sql"), "utf8");
+ expect(sql).toMatch(/create table if not exists products \(/);
+ // the demo rows' ON CONFLICT (id) needs the primary key upstream's seed declared
+ expect(sql).toMatch(/id integer primary key/);
+ });
+
+ it("orders the table, its row-level security, then its rows", () => {
+ expect(manifest.migrations.map((m) => m.id)).toEqual([
+ "000_control_baseline",
+ "010_products",
+ "020_row_level_security",
+ "030_demo_products",
+ ]);
+ });
+
+ it("skips what the database already recorded", () => {
+ const applied = new Map([[manifest.migrations[0]!.id, manifest.migrations[0]!.checksum]]);
+ const plan = buildPlan(manifest, applied, migrationsDir);
+ expect(plan.alreadyApplied).toEqual([manifest.migrations[0]!.id]);
+ expect(plan.pending.map((m) => m.id)).toEqual(manifest.migrations.slice(1).map((m) => m.id));
+ expect(plan.checksumMismatches).toEqual([]);
+ });
+});
diff --git a/tests/db/src/products.test.ts b/tests/db/src/products.test.ts
new file mode 100644
index 0000000..6b445bf
--- /dev/null
+++ b/tests/db/src/products.test.ts
@@ -0,0 +1,115 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { PGlite } from "@electric-sql/pglite";
+import { createHash } from "node:crypto";
+import { readFileSync } from "node:fs";
+import * as path from "node:path";
+import { manifest } from "@saas/db/manifest";
+
+// The products table and its demo rows as the migrations leave them, on a real
+// Postgres in process (PGlite). Upstream had one file, demo/seed.sql, pasted
+// into the Supabase SQL Editor: its CREATE TABLE is migration 010 and its
+// twenty upserts are 030. These hold the two to that file byte for byte, and
+// the connector's transformation (apps/web/demo/transform.js) to what the
+// product page says never reaches the index.
+const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations");
+const sqlOf = (rel: string) => readFileSync(path.join(migrationsDir, rel), "utf8");
+const transformJs = path.resolve(__dirname, "../../../apps/web/demo/transform.js");
+
+// algolia/algolia-supabase-vercel-starter @ da3f27b, demo/seed.sql: its sha256,
+// and the three comment lines it opens with (written for the SQL Editor).
+const UPSTREAM_SEED_SHA256 = "7012a7606fd0b0ba90ca0d7ab3c2f45a5588da6a497b15b387d937bb93305d5b";
+const UPSTREAM_SEED_HEADER =
+ "-- Seed data for the Algolia × Supabase starter.\n" +
+ "-- Paste this whole file into the Supabase SQL Editor and run it.\n" +
+ "-- Idempotent: re-running upserts the same 20 products, never duplicates.\n\n";
+
+async function migrated(): Promise {
+ const db = new PGlite();
+ for (const entry of manifest.migrations) await db.exec(sqlOf(entry.path));
+ return db;
+}
+
+type Transform = (record: Record, helper: unknown) => Promise>;
+function transform(): Transform {
+ // The file is pasted into Algolia's dashboard as is: a bare function, no export.
+ return new Function(`${readFileSync(transformJs, "utf8")}\nreturn transform;`)() as Transform;
+}
+
+describe("migrations 010 and 030 against upstream's demo/seed.sql", () => {
+ it("are its CREATE TABLE and its twenty upserts, byte for byte", () => {
+ const m10 = sqlOf("010_products/up.sql");
+ const m30 = sqlOf("030_demo_products/up.sql");
+ const create = m10.slice(m10.indexOf("create table if not exists products ("));
+ const inserts = m30.slice(m30.indexOf("insert into products"));
+ const rebuilt = UPSTREAM_SEED_HEADER + create + "\n" + inserts;
+ expect(createHash("sha256").update(rebuilt).digest("hex")).toBe(UPSTREAM_SEED_SHA256);
+ });
+});
+
+describe("the products table (after every migration)", () => {
+ let db: PGlite;
+ beforeAll(async () => {
+ db = await migrated();
+ }, 60_000);
+
+ it("has upstream's columns", async () => {
+ const { rows } = await db.query<{ column_name: string; data_type: string; is_nullable: string }>(
+ `select column_name, data_type, is_nullable from information_schema.columns
+ where table_schema = 'public' and table_name = 'products' order by ordinal_position`,
+ );
+ expect(rows.map((r) => `${r.column_name} ${r.data_type} ${r.is_nullable}`)).toEqual([
+ "id integer NO",
+ "name text NO",
+ "description text NO",
+ "category text NO",
+ "price numeric NO",
+ "image_url text YES",
+ "rating numeric YES",
+ "cost_price numeric YES",
+ "supplier_id text YES",
+ "internal_notes text YES",
+ "stock_location text YES",
+ "quantity integer NO",
+ "updated_at timestamp with time zone NO",
+ ]);
+ });
+
+ it("holds the twenty demo products, ids 1 to 20", async () => {
+ const { rows } = await db.query<{ n: number; lo: number; hi: number }>(
+ "select count(*)::int as n, min(id) as lo, max(id) as hi from products",
+ );
+ expect(rows[0]).toEqual({ n: 20, lo: 1, hi: 20 });
+ });
+
+ it("keeps exactly those twenty however often 030 is applied", async () => {
+ await db.exec(sqlOf("030_demo_products/up.sql"));
+ await db.exec(sqlOf("030_demo_products/up.sql"));
+ const { rows } = await db.query<{ n: number }>("select count(*)::int as n from products");
+ expect(rows[0]!.n).toBe(20);
+ });
+
+ it("applies the table migration again without harm", async () => {
+ await db.exec(sqlOf("010_products/up.sql"));
+ const { rows } = await db.query<{ n: number }>("select count(*)::int as n from products");
+ expect(rows[0]!.n).toBe(20);
+ });
+
+ it("gives the connector's transformation every row, and it drops the database-only fields", async () => {
+ const fn = transform();
+ const { rows } = await db.query>("select * from products order by id");
+ for (const row of rows) {
+ const record = await fn(row, {});
+ expect(Object.keys(record).sort()).toEqual(
+ ["category", "description", "image_url", "in_stock", "name", "objectID", "price", "quantity", "rating"].sort(),
+ );
+ expect(record.objectID).toBe(String(row.id));
+ expect(record.in_stock).toBe(Number(row.quantity) > 0);
+ for (const internal of ["cost_price", "supplier_id", "internal_notes", "stock_location"]) {
+ expect(record).not.toHaveProperty(internal);
+ }
+ }
+ // Not vacuous: the dataset has both sides of the stock toggle.
+ const stock = await Promise.all(rows.map((r) => fn(r, {})));
+ expect(new Set(stock.map((r) => r.in_stock))).toEqual(new Set([true, false]));
+ });
+});
diff --git a/tests/db/src/row-level-security.test.ts b/tests/db/src/row-level-security.test.ts
new file mode 100644
index 0000000..56c1883
--- /dev/null
+++ b/tests/db/src/row-level-security.test.ts
@@ -0,0 +1,125 @@
+import { beforeAll, describe, expect, it } from "vitest";
+import { PGlite } from "@electric-sql/pglite";
+import { readFileSync } from "node:fs";
+import * as path from "node:path";
+import { manifest } from "@saas/db/manifest";
+
+// Supabase's Data API (PostgREST) serves the `public` schema to anyone holding
+// the project's anon key. Migration 020 enables row-level security, with no
+// policy, on every table there: `anon` and `authenticated` get nothing, and the
+// app — which owns the table — keeps everything. These run every migration
+// db-migrate applies, in the manifest's order, on a real Postgres in process
+// (PGlite: Postgres compiled to WASM), and read the catalog it leaves.
+const migrationsDir = path.resolve(__dirname, "../../../packages/db/src/migrations");
+const sqlOf = (rel: string) => readFileSync(path.join(migrationsDir, rel), "utf8");
+
+async function migrated(): Promise {
+ const db = new PGlite();
+ for (const entry of manifest.migrations) {
+ await db.exec(sqlOf(entry.path));
+ }
+ return db;
+}
+
+type Rel = { relname: string; relrowsecurity: boolean; relforcerowsecurity: boolean };
+const PUBLIC_TABLES = `
+ select c.relname, c.relrowsecurity, c.relforcerowsecurity
+ from pg_class c join pg_namespace n on n.oid = c.relnamespace
+ where n.nspname = 'public' and c.relkind in ('r', 'p')
+ order by c.relname`;
+
+const SEED_ROW = `insert into products (id, name, description, category, price, quantity)
+ values (1001, 'Owner Row', 'Written by the table''s owner.', 'Test', 1, 1)`;
+
+describe("row-level security on public (after every migration)", () => {
+ let db: PGlite;
+ beforeAll(async () => {
+ db = await migrated();
+ }, 60_000);
+
+ it("leaves no table in public without row-level security", async () => {
+ const { rows } = await db.query(PUBLIC_TABLES);
+ // Not vacuous: the template's table is there.
+ expect(rows.map((r) => r.relname)).toEqual(expect.arrayContaining(["products"]));
+ expect(rows.filter((r) => !r.relrowsecurity).map((r) => r.relname)).toEqual([]);
+ });
+
+ it("adds no policy and forces none — the owner is never subject to it", async () => {
+ const { rows } = await db.query(PUBLIC_TABLES);
+ expect(rows.filter((r) => r.relforcerowsecurity).map((r) => r.relname)).toEqual([]);
+ const policies = await db.query<{ n: number }>(
+ "select count(*)::int as n from pg_policies where schemaname = 'public'",
+ );
+ expect(policies.rows[0]!.n).toBe(0);
+ });
+
+ it("gives a role with the Data API's grants nothing, and the owner everything", async () => {
+ await db.exec(SEED_ROW);
+ // What Supabase grants `anon` on public by default — so a refusal below is
+ // row-level security's, not a missing grant's.
+ await db.exec(`
+ create role anon nologin;
+ grant usage on schema public to anon;
+ grant select, insert, update, delete on all tables in schema public to anon;
+ grant usage on all sequences in schema public to anon;`);
+ await db.exec("set role anon");
+ try {
+ const seen = await db.query<{ n: number }>("select count(*)::int as n from products");
+ expect(seen.rows[0]!.n).toBe(0);
+ // the internal-only fields above all
+ const internal = await db.query<{ n: number }>(
+ "select count(*)::int as n from products where cost_price is not null or internal_notes is not null",
+ );
+ expect(internal.rows[0]!.n).toBe(0);
+ await expect(
+ db.exec("insert into products (id, name, description, category, price) values (2001, 'Anon', 'x', 'x', 1)"),
+ ).rejects.toThrow(/row-level security/);
+ } finally {
+ await db.exec("reset role");
+ }
+ // the owner keeps everything: the twenty demo products and its own row
+ const owner = await db.query<{ n: number }>("select count(*)::int as n from products");
+ expect(owner.rows[0]!.n).toBe(21);
+ });
+
+ it("applies twice without error — every migration is idempotent", async () => {
+ for (const entry of manifest.migrations) {
+ await db.exec(sqlOf(entry.path));
+ }
+ const { rows } = await db.query(PUBLIC_TABLES);
+ expect(rows.every((r) => r.relrowsecurity)).toBe(true);
+ });
+});
+
+describe("migration 020's guard", () => {
+ // The guard names `postgres`, the role Hyperdrive connects as, which PGlite
+ // cannot take SUPERUSER from. Pointed instead at a role that neither owns the
+ // tables nor bypasses RLS, it must refuse — and enable nothing.
+ const migration = sqlOf("020_row_level_security/up.sql");
+ const aimedAt = (role: string) =>
+ migration.replaceAll("rolname = 'postgres'", `rolname = '${role}'`).replaceAll("<> 'postgres'", `<> '${role}'`);
+
+ async function beforeRls(): Promise {
+ const db = new PGlite();
+ for (const entry of manifest.migrations.filter((m) => m.id < "020")) {
+ await db.exec(sqlOf(entry.path));
+ }
+ return db;
+ }
+
+ it("refuses when the app's role would be locked out, enabling nothing", async () => {
+ const db = await beforeRls();
+ await db.exec("create role app_without_bypass nologin");
+ await expect(db.exec(aimedAt("app_without_bypass"))).rejects.toThrow(/would lock the app out/);
+ const { rows } = await db.query(PUBLIC_TABLES);
+ expect(rows.filter((r) => r.relrowsecurity)).toEqual([]);
+ }, 60_000);
+
+ it("passes for a role with BYPASSRLS", async () => {
+ const db = await beforeRls();
+ await db.exec("create role app_with_bypass nologin bypassrls");
+ await db.exec(aimedAt("app_with_bypass"));
+ const { rows } = await db.query(PUBLIC_TABLES);
+ expect(rows.every((r) => r.relrowsecurity)).toBe(true);
+ }, 60_000);
+});
diff --git a/tests/db/tsconfig.json b/tests/db/tsconfig.json
new file mode 100644
index 0000000..47d9ecc
--- /dev/null
+++ b/tests/db/tsconfig.json
@@ -0,0 +1,11 @@
+{
+ "extends": "../../tooling/tsconfig/base.json",
+ "compilerOptions": {
+ "composite": false,
+ "declaration": false,
+ "declarationMap": false,
+ "noEmit": true,
+ "types": ["node"]
+ },
+ "include": ["src/**/*.ts"]
+}
diff --git a/tests/db/vitest.config.ts b/tests/db/vitest.config.ts
new file mode 100644
index 0000000..ce36a74
--- /dev/null
+++ b/tests/db/vitest.config.ts
@@ -0,0 +1,8 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ test: {
+ include: ["src/**/*.test.ts"],
+ environment: "node",
+ },
+});
diff --git a/tests/web/component.yaml b/tests/web/component.yaml
new file mode 100644
index 0000000..a6d09a3
--- /dev/null
+++ b/tests/web/component.yaml
@@ -0,0 +1,31 @@
+apiVersion: sourceplane.io/v1
+kind: Component
+metadata:
+ name: web-tests
+ description: The app's tests (the per-request Postgres client, Hyperdrive first; the Algolia config read from the Worker; InstantSearch against an in-process Algolia stand-in; the catalogue and the page's two states; the /api/health database check; the committed wrangler config)
+spec:
+ type: turbo-package
+ lifecycle: production
+ owner: platform
+ # Its pages, attached to it in the workspace's catalog: what the Docs
+ # library shows for it, and what the catalog's docs and runbook checks read.
+ # Generated from what this manifest and its sources declare.
+ docs:
+ overview: docs/overview.md
+ pages:
+ - { path: docs/architecture.md, role: architecture, title: Architecture }
+ - { path: docs/runbook.md, role: runbook, title: Runbook }
+ domain: tests
+ subscribe:
+ environments:
+ - name: dev
+ profile: quick-check
+ parameters:
+ nodeVersion: "22"
+ pnpmVersion: "10.12.1"
+ buildCommand: pnpm exec turbo run build --filter=./
+ typecheckCommand: pnpm exec turbo run typecheck --filter=./
+ preBuildCommand: pnpm exec turbo run test --filter=./
+ labels:
+ team: platform
+ layer: test
diff --git a/tests/web/docs/architecture.md b/tests/web/docs/architecture.md
new file mode 100644
index 0000000..9e5a070
--- /dev/null
+++ b/tests/web/docs/architecture.md
@@ -0,0 +1,14 @@
+# web-tests — architecture
+
+A test package at `tests/web`. Its lane runs the suite before it builds.
+
+## Suites (8)
+
+- `algolia.test.ts`
+- `catalogue.test.tsx`
+- `db.test.ts`
+- `health.test.ts`
+- `page.test.tsx`
+- `products.test.ts`
+- `search.test.tsx`
+- `wrangler-config.test.ts`
diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md
new file mode 100644
index 0000000..c5d6122
--- /dev/null
+++ b/tests/web/docs/overview.md
@@ -0,0 +1,20 @@
+# web-tests
+
+The app's tests (the per-request Postgres client, Hyperdrive first; the Algolia config read from the Worker; InstantSearch against an in-process Algolia stand-in; the catalogue and the page's two states; the /api/health database check; the committed wrangler config)
+
+The test suite for **web**. It deploys nothing: its lane installs, builds and runs the tests.
+
+| | |
+| ------------ | -------------------- |
+| Type | `turbo-package` |
+| Source | `tests/web` |
+| Package | `@app/web-tests` |
+| Environments | `dev`: `quick-check` |
+
+## Depends on
+
+- (none)
+
+## Depended on by
+
+- (none)
diff --git a/tests/web/docs/runbook.md b/tests/web/docs/runbook.md
new file mode 100644
index 0000000..c687de2
--- /dev/null
+++ b/tests/web/docs/runbook.md
@@ -0,0 +1,26 @@
+# web-tests — runbook
+
+## How it runs
+
+Its lane runs on every pull request that changes it; it has no deployed surface.
+CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;
+the plan orders a component after everything it depends on.
+
+## Local commands
+
+```bash
+pnpm --filter @app/web-tests build
+pnpm --filter @app/web-tests test
+pnpm --filter @app/web-tests typecheck
+pnpm --filter @app/web-tests lint
+```
+
+## Rollback
+
+Revert the commit on `main`. The next convergence applies the previous desired
+state; nothing was changed out of band, so there is nothing else to undo.
+
+## Common failures
+
+- **A dependent fails to build after a change here**: run `pnpm typecheck`
+ across the workspace before merging.
diff --git a/tests/web/eslint.config.js b/tests/web/eslint.config.js
new file mode 100644
index 0000000..2e905dc
--- /dev/null
+++ b/tests/web/eslint.config.js
@@ -0,0 +1,2 @@
+import config from "../../tooling/eslint/index.js";
+export default config;
diff --git a/tests/web/package.json b/tests/web/package.json
new file mode 100644
index 0000000..6c3b45e
--- /dev/null
+++ b/tests/web/package.json
@@ -0,0 +1,34 @@
+{
+ "name": "@app/web-tests",
+ "version": "0.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "tsc --noEmit",
+ "typecheck": "tsc --noEmit",
+ "test": "vitest run",
+ "lint": "eslint src"
+ },
+ "devDependencies": {
+ "@app/eslint-config": "workspace:*",
+ "@app/tsconfig": "workspace:*",
+ "@cloudflare/workers-types": "^4.20250508.0",
+ "@opennextjs/cloudflare": "^1.20.11",
+ "@testing-library/dom": "^10.4.0",
+ "@testing-library/react": "^16.3.0",
+ "@types/node": "^22.9.0",
+ "@types/pg": "^8.20.0",
+ "@types/react": "^19",
+ "@types/react-dom": "^19",
+ "algoliasearch": "^5.56.0",
+ "instantsearch.js": "^4.122.0",
+ "jsdom": "^26.1.0",
+ "next": "16.3.8",
+ "pg": "^8.22.0",
+ "react": "19.2.4",
+ "react-dom": "19.2.4",
+ "react-instantsearch": "^7.39.1",
+ "typescript": "^5.8.3",
+ "vitest": "^3.2.4"
+ }
+}
diff --git a/tests/web/src/algolia.test.ts b/tests/web/src/algolia.test.ts
new file mode 100644
index 0000000..fe39094
--- /dev/null
+++ b/tests/web/src/algolia.test.ts
@@ -0,0 +1,70 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// lib/algolia.ts: the browser's InstantSearch config, read from the Worker per
+// request — the template inlined NEXT_PUBLIC_ variables at build time.
+let cf: { env: Record } | null = null;
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => {
+ if (!cf) throw new Error("no Cloudflare context");
+ return cf;
+ },
+}));
+
+beforeEach(() => {
+ cf = null;
+ for (const k of ["ALGOLIA_APP_ID", "ALGOLIA_SEARCH_API_KEY", "ALGOLIA_HOST"]) delete process.env[k];
+ vi.resetModules();
+});
+
+async function config() {
+ const { searchConfig } = await import("@/lib/algolia");
+ return searchConfig();
+}
+
+describe("searchConfig (lib/algolia.ts)", () => {
+ it("is the Worker's application id and search-only key", async () => {
+ cf = { env: { ALGOLIA_APP_ID: " APP1 ", ALGOLIA_SEARCH_API_KEY: "search-key" } };
+ expect(await config()).toEqual({ appId: "APP1", searchApiKey: "search-key" });
+ });
+
+ it("is null — search not connected — until both are set", async () => {
+ cf = { env: {} };
+ expect(await config()).toBeNull();
+ cf = { env: { ALGOLIA_APP_ID: "APP1" } };
+ expect(await config()).toBeNull();
+ cf = { env: { ALGOLIA_SEARCH_API_KEY: "search-key" } };
+ expect(await config()).toBeNull();
+ cf = { env: { ALGOLIA_APP_ID: " ", ALGOLIA_SEARCH_API_KEY: "search-key" } };
+ expect(await config()).toBeNull();
+ });
+
+ it("carries another search host only when ALGOLIA_HOST is set", async () => {
+ cf = { env: { ALGOLIA_APP_ID: "APP1", ALGOLIA_SEARCH_API_KEY: "k", ALGOLIA_HOST: "http://127.0.0.1:9" } };
+ expect(await config()).toEqual({ appId: "APP1", searchApiKey: "k", host: "http://127.0.0.1:9" });
+ });
+
+ it("never hands out any other key, the write/admin key above all", async () => {
+ cf = {
+ env: { ALGOLIA_APP_ID: "APP1", ALGOLIA_SEARCH_API_KEY: "k", ALGOLIA_WRITE_API_KEY: "admin", ALGOLIA_ADMIN_API_KEY: "admin" },
+ };
+ const c = await config();
+ expect(JSON.stringify(c)).not.toContain("admin");
+ expect(Object.keys(c ?? {}).sort()).toEqual(["appId", "searchApiKey"]);
+ });
+
+ it("reads the process environment without a Cloudflare context", async () => {
+ process.env.ALGOLIA_APP_ID = "APP2";
+ process.env.ALGOLIA_SEARCH_API_KEY = "k2";
+ expect(await config()).toEqual({ appId: "APP2", searchApiKey: "k2" });
+ });
+
+ it("is never read at build time: no NEXT_PUBLIC_ name, and next.config inlines nothing", async () => {
+ const { readFileSync } = await import("node:fs");
+ const path = await import("node:path");
+ const web = path.resolve(__dirname, "../../../apps/web");
+ expect(readFileSync(path.join(web, "lib/algolia.ts"), "utf8")).not.toMatch(/process\.env\.NEXT_PUBLIC_ALGOLIA/);
+ const component = readFileSync(path.join(web, "components/search/search-experience.tsx"), "utf8");
+ expect(component).not.toMatch(/process\.env/);
+ expect(readFileSync(path.join(web, "next.config.ts"), "utf8")).not.toMatch(/^\s*env\s*:/m);
+ });
+});
diff --git a/tests/web/src/catalogue.test.tsx b/tests/web/src/catalogue.test.tsx
new file mode 100644
index 0000000..1c87624
--- /dev/null
+++ b/tests/web/src/catalogue.test.tsx
@@ -0,0 +1,54 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+
+// components/catalogue.tsx: the home page's list while search is not
+// connected — the catalogue read from Postgres, in the hits' own cards.
+const rows = [
+ { id: 1, name: "Aurora Wireless Headphones", description: "Over-ear", category: "Audio", price: "199.00", image_url: "https://images.example/a.jpg", rating: "3.7", quantity: 120 },
+ { id: 2, name: "Pulse Earbuds", description: "In-ear", category: "Audio", price: "129.99", image_url: null, rating: null, quantity: 0 },
+];
+
+async function render(result: unknown[] | Error) {
+ vi.resetModules();
+ vi.doMock("@/lib/products", () => ({
+ listProducts: async () => {
+ if (result instanceof Error) throw result;
+ return result;
+ },
+ }));
+ const { Catalogue } = await import("@/components/catalogue");
+ return renderToStaticMarkup(await Catalogue()).replaceAll("", "");
+}
+
+describe("Catalogue (components/catalogue.tsx)", () => {
+ it("lists every product as a card that opens its product page", async () => {
+ const html = await render(rows);
+ expect(html).toContain("2 products · read from");
+ expect(html).toContain('href="/products/1"');
+ expect(html).toContain('href="/products/2"');
+ expect(html).toContain("Aurora Wireless Headphones");
+ expect(html).toContain("$199.00");
+ expect(html).toContain("$129.99");
+ expect(html).toContain("3.7");
+ });
+
+ it("marks a product with no stock, as a hit does", async () => {
+ const html = await render(rows);
+ expect(html.match(/Out of stock/g)).toHaveLength(1);
+ });
+
+ it("says one product, not one products", async () => {
+ expect(await render([rows[0]])).toContain("1 product · read from");
+ });
+
+ it("says the migrations have not run instead of failing when the table is missing", async () => {
+ const html = await render(new Error('relation "products" does not exist'));
+ expect(html).toContain('data-schema="missing"');
+ expect(html).toContain("db:migrate");
+ expect(html).not.toContain("/products/");
+ });
+
+ it("lets any other database error through", async () => {
+ await expect(render(new Error("connection refused"))).rejects.toThrow("connection refused");
+ });
+});
diff --git a/tests/web/src/db.test.ts b/tests/web/src/db.test.ts
new file mode 100644
index 0000000..2ec918a
--- /dev/null
+++ b/tests/web/src/db.test.ts
@@ -0,0 +1,114 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// lib/db.ts: upstream's `query(text, params)`, unchanged at every call site.
+// On the Worker the connection string is the HYPERDRIVE binding's and each
+// request's ExecutionContext keeps one connected pg Client; without a
+// Cloudflare context it is upstream's own pool over POSTGRES_URL.
+type Ctx = { env: { HYPERDRIVE?: { connectionString: string } }; ctx: object };
+let cf: Ctx | null = null;
+vi.mock("@opennextjs/cloudflare", () => ({
+ getCloudflareContext: () => {
+ if (!cf) throw new Error("no Cloudflare context");
+ return cf;
+ },
+}));
+
+const made: { kind: "client" | "pool"; config: Record; queries: unknown[][]; connects: number }[] = [];
+let failConnect = 0;
+vi.mock("pg", () => {
+ class Client {
+ record: (typeof made)[number];
+ constructor(config: Record) {
+ this.record = { kind: "client", config, queries: [], connects: 0 };
+ made.push(this.record);
+ }
+ async connect() {
+ this.record.connects += 1;
+ if (failConnect > 0) {
+ failConnect -= 1;
+ throw new Error("connection refused");
+ }
+ }
+ async query(text: string, params: unknown[]) {
+ this.record.queries.push([text, params]);
+ return { rows: [{ text }] };
+ }
+ }
+ class Pool {
+ record: (typeof made)[number];
+ constructor(config: Record) {
+ this.record = { kind: "pool", config, queries: [], connects: 0 };
+ made.push(this.record);
+ }
+ async query(text: string, params: unknown[]) {
+ this.record.queries.push([text, params]);
+ return { rows: [{ text }] };
+ }
+ }
+ return { Client, Pool };
+});
+
+beforeEach(() => {
+ made.length = 0;
+ failConnect = 0;
+ cf = null;
+ delete process.env.POSTGRES_URL;
+ vi.resetModules();
+});
+
+const hyperdrive = { HYPERDRIVE: { connectionString: "postgres://user:pw@hyperdrive.local:5432/db" } };
+
+describe("query (lib/db.ts)", () => {
+ it("connects a pg Client through the Hyperdrive binding, with no ssl override", async () => {
+ cf = { env: hyperdrive, ctx: {} };
+ const { query } = await import("@/lib/db");
+ expect(await query("select 1", [7])).toEqual([{ text: "select 1" }]);
+ expect(made).toHaveLength(1);
+ expect(made[0]).toMatchObject({ kind: "client", config: { connectionString: hyperdrive.HYPERDRIVE.connectionString } });
+ expect(made[0]!.config).not.toHaveProperty("ssl");
+ expect(made[0]!.queries).toEqual([["select 1", [7]]]);
+ });
+
+ it("keeps one client per request, connected once, and a new one for the next", async () => {
+ const first = {};
+ cf = { env: hyperdrive, ctx: first };
+ const { query } = await import("@/lib/db");
+ await Promise.all([query("a"), query("b")]);
+ expect(made).toHaveLength(1);
+ expect(made[0]!.connects).toBe(1);
+ expect(made[0]!.queries.map((q) => q[0])).toEqual(["a", "b"]);
+ cf = { env: hyperdrive, ctx: {} };
+ await query("c");
+ expect(made).toHaveLength(2);
+ cf = { env: hyperdrive, ctx: first };
+ await query("d");
+ expect(made).toHaveLength(2);
+ expect(made[0]!.queries.map((q) => q[0])).toEqual(["a", "b", "d"]);
+ });
+
+ it("does not keep a client whose connect failed: the request's next query connects again", async () => {
+ cf = { env: hyperdrive, ctx: {} };
+ failConnect = 1;
+ const { query } = await import("@/lib/db");
+ await expect(query("a")).rejects.toThrow("connection refused");
+ await new Promise((r) => setTimeout(r, 0));
+ expect(await query("b")).toEqual([{ text: "b" }]);
+ expect(made).toHaveLength(2);
+ });
+
+ it("falls back to upstream's pool over POSTGRES_URL without a Cloudflare context", async () => {
+ process.env.POSTGRES_URL = "postgres://u:p@db.supabase.co:6543/postgres?sslmode=require";
+ const { query } = await import("@/lib/db");
+ await query("select 2");
+ await query("select 3");
+ expect(made).toHaveLength(1);
+ expect(made[0]).toMatchObject({
+ kind: "pool",
+ config: {
+ connectionString: "postgres://u:p@db.supabase.co:6543/postgres",
+ ssl: { rejectUnauthorized: false },
+ max: 5,
+ },
+ });
+ });
+});
diff --git a/tests/web/src/health.test.ts b/tests/web/src/health.test.ts
new file mode 100644
index 0000000..cfddf34
--- /dev/null
+++ b/tests/web/src/health.test.ts
@@ -0,0 +1,69 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+// /api/health is what the deploy's smoke and the bootstrap's probes read: 200
+// only when the database answers through the binding and the migrations have
+// run — the products table exists, with row-level security on. `search` says
+// whether the Algolia secrets reached the Worker; a product goes live without
+// them, so it is not part of `ok`.
+let answer: () => Promise;
+let connected = false;
+vi.mock("@/lib/db", () => ({ query: async () => answer() }));
+vi.mock("@/lib/algolia", () => ({
+ searchConfig: () => (connected ? { appId: "APP", searchApiKey: "secret-search-key" } : null),
+}));
+
+beforeEach(() => {
+ connected = false;
+ vi.spyOn(console, "error").mockImplementation(() => {});
+});
+
+async function health() {
+ const { GET } = await import("@/app/api/health/route");
+ const res = await GET();
+ const text = await res.text();
+ return { status: res.status, body: JSON.parse(text) as Record, text, cache: res.headers.get("cache-control") };
+}
+
+describe("GET /api/health (app/api/health/route.ts)", () => {
+ it("is ok when the table exists with row-level security, search not connected yet", async () => {
+ answer = async () => [{ products: "products", rls: true }];
+ const r = await health();
+ expect({ status: r.status, body: r.body, cache: r.cache }).toEqual({
+ status: 200,
+ body: { ok: true, database: "reachable", schema: "migrated", search: "not connected" },
+ cache: "no-store",
+ });
+ });
+
+ it("says search is connected, never with the key", async () => {
+ connected = true;
+ answer = async () => [{ products: "products", rls: true }];
+ const r = await health();
+ expect(r.body.search).toBe("connected");
+ expect(r.text).not.toContain("secret-search-key");
+ expect(r.text).not.toContain("APP");
+ });
+
+ it("is 503 when the migrations have not run", async () => {
+ answer = async () => [{ products: null, rls: false }];
+ const r = await health();
+ expect(r.status).toBe(503);
+ expect(r.body).toEqual({ ok: false, database: "reachable", schema: "missing", search: "not connected" });
+ });
+
+ it("is 503 when the table is there without row-level security", async () => {
+ answer = async () => [{ products: "products", rls: false }];
+ const r = await health();
+ expect(r.status).toBe(503);
+ expect(r.body.schema).toBe("missing");
+ });
+
+ it("is 503 when the database is unreachable", async () => {
+ answer = async () => {
+ throw new Error("connection refused");
+ };
+ const r = await health();
+ expect(r.status).toBe(503);
+ expect(r.body).toEqual({ ok: false, database: "unreachable", search: "not connected" });
+ });
+});
diff --git a/tests/web/src/page.test.tsx b/tests/web/src/page.test.tsx
new file mode 100644
index 0000000..bb1887c
--- /dev/null
+++ b/tests/web/src/page.test.tsx
@@ -0,0 +1,53 @@
+import { describe, expect, it, vi } from "vitest";
+import { renderToStaticMarkup } from "react-dom/server";
+
+// app/page.tsx: the template's page, with the search config read per request
+// and the catalogue listed while search is not connected.
+type Config = { appId: string; searchApiKey: string } | null;
+
+async function render(config: Config) {
+ vi.resetModules();
+ const props: unknown[] = [];
+ vi.doMock("@/lib/algolia", () => ({ searchConfig: () => config }));
+ vi.doMock("@/components/search/search-experience", () => ({
+ SearchExperience: (p: { config: Config }) => {
+ props.push(p.config);
+ return {p.config ? "instantsearch" : "notice"}
;
+ },
+ }));
+ vi.doMock("@/components/catalogue", () => ({ Catalogue: () => }));
+ const { default: Home, dynamic } = await import("@/app/page");
+ return { html: renderToStaticMarkup().replaceAll("", ""), props, dynamic };
+}
+
+describe("Home (app/page.tsx)", () => {
+ it("renders per request: the Algolia secrets are read at render, never frozen in at build", async () => {
+ expect((await render(null)).dynamic).toBe("force-dynamic");
+ });
+
+ it("without Algolia: the notice and the catalogue, marked not-connected", async () => {
+ const { html, props } = await render(null);
+ expect(html).toContain('data-search="not-connected"');
+ expect(html).toContain("notice");
+ expect(html).toContain('data-testid="catalogue"');
+ expect(props).toEqual([null]);
+ });
+
+ it("with Algolia: InstantSearch handed the Worker's config, and no catalogue", async () => {
+ const config = { appId: "APP", searchApiKey: "search-key" };
+ const { html, props } = await render(config);
+ expect(html).toContain('data-search="connected"');
+ expect(html).toContain("instantsearch");
+ expect(html).not.toContain('data-testid="catalogue"');
+ expect(props).toEqual([config]);
+ });
+
+ it("keeps the template's words, with Cloudflare where Vercel was", async () => {
+ const { html } = await render(null);
+ expect(html).toContain("finds it.");
+ expect(html).toContain("Cloudflare wires them.");
+ expect(html).toContain("deployed on Cloudflare.");
+ expect(html).toContain("Open-source search starter");
+ expect(html.toLowerCase()).not.toContain("vercel");
+ });
+});
diff --git a/tests/web/src/products.test.ts b/tests/web/src/products.test.ts
new file mode 100644
index 0000000..79a71f3
--- /dev/null
+++ b/tests/web/src/products.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, it, vi } from "vitest";
+
+// lib/products.ts: the product page's one query is upstream's; the catalogue's
+// is new, and reads only what the connector's transformation would index.
+const sent: [string, unknown[] | undefined][] = [];
+vi.mock("@/lib/db", () => ({
+ query: async (text: string, params?: unknown[]) => {
+ sent.push([text, params]);
+ return text.includes("where id") ? [{ id: params?.[0], name: "x" }] : [];
+ },
+}));
+vi.mock("server-only", () => ({}));
+
+describe("lib/products.ts", () => {
+ it("reads one product by id, as upstream did", async () => {
+ const { getProduct } = await import("@/lib/products");
+ expect(await getProduct(3)).toEqual({ id: 3, name: "x" });
+ expect(sent.at(-1)).toEqual(["select * from products where id = $1", [3]]);
+ });
+
+ it("lists the catalogue in id order without a single database-only field", async () => {
+ const { listProducts } = await import("@/lib/products");
+ await listProducts();
+ const [text] = sent.at(-1)!;
+ expect(text).toMatch(/from products order by id$/);
+ for (const internal of ["cost_price", "supplier_id", "internal_notes", "stock_location", "*"]) {
+ expect(text).not.toContain(internal);
+ }
+ for (const field of ["id", "name", "description", "category", "price", "image_url", "rating", "quantity"]) {
+ expect(text).toContain(field);
+ }
+ });
+});
diff --git a/tests/web/src/search.test.tsx b/tests/web/src/search.test.tsx
new file mode 100644
index 0000000..4506200
--- /dev/null
+++ b/tests/web/src/search.test.tsx
@@ -0,0 +1,85 @@
+// @vitest-environment jsdom
+import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { SearchExperience } from "@/components/search/search-experience";
+import { fakeAlgolia, type Indexed } from "./support/fake-algolia";
+
+// components/search/search-experience.tsx, the template's InstantSearch UI,
+// rendered for real against a local stand-in for Algolia's search API. The
+// application id, the search-only key and the host arrive as props (the page
+// reads them from the Worker per request); the component builds its lite
+// client from them and nothing else.
+const records: Indexed[] = [
+ { objectID: "1", name: "Aurora Wireless Headphones", description: "Over-ear noise-cancelling headphones.", category: "Audio", price: 199, image_url: null, rating: 3.7, quantity: 120, in_stock: true },
+ { objectID: "2", name: "Pulse True Wireless Earbuds", description: "Compact in-ear earbuds.", category: "Audio", price: 129.99, image_url: null, rating: 1.2, quantity: 0, in_stock: false },
+ { objectID: "3", name: "Summit Trail Backpack", description: "A 28-litre daypack.", category: "Outdoor", price: 89, image_url: null, rating: 4.4, quantity: 40, in_stock: true },
+ { objectID: "4", name: "Ember Pour-Over Kettle", description: "A gooseneck kettle.", category: "Kitchen", price: 59.5, image_url: null, rating: 4.8, quantity: 12, in_stock: true },
+];
+let stand: Awaited>;
+
+beforeAll(async () => {
+ stand = await fakeAlgolia(records);
+});
+afterAll(async () => {
+ await stand.close();
+});
+afterEach(() => {
+ cleanup();
+ stand.seen.length = 0;
+});
+
+function connected() {
+ return render();
+}
+const links = () => Array.from(document.querySelectorAll('a[href^="/products/"]')).map((a) => a.getAttribute("href"));
+
+describe("SearchExperience, connected", () => {
+ it("searches the products index with the application id and search-only key it was handed", async () => {
+ connected();
+ expect(await screen.findByText(/^4 results · \d+ms$/, undefined, { timeout: 5000 })).toBeTruthy();
+ expect(links().sort()).toEqual(["/products/1", "/products/2", "/products/3", "/products/4"]);
+ const first = stand.seen[0]!;
+ expect(first.path).toBe("/1/indexes/*/queries");
+ expect(first.app).toBe("TESTAPP");
+ expect(first.key).toBe("search-only-key");
+ expect(first.body.requests?.[0]).toMatchObject({ indexName: "products" });
+ });
+
+ it("narrows the hits as a visitor types", async () => {
+ connected();
+ await screen.findByText(/^4 results/, undefined, { timeout: 5000 });
+ fireEvent.input(screen.getByPlaceholderText("Try “headphones”…"), { target: { value: "headphones" } });
+ expect(await screen.findByText(/^1 result · \d+ms$/, undefined, { timeout: 5000 })).toBeTruthy();
+ await waitFor(() => expect(links()).toEqual(["/products/1"]));
+ });
+
+ it("hides what is out of stock when asked", async () => {
+ connected();
+ await screen.findByText(/^4 results/, undefined, { timeout: 5000 });
+ expect(screen.getAllByText("Out of stock")).toHaveLength(1);
+ fireEvent.click(screen.getByLabelText("Hide out of stock"));
+ expect(await screen.findByText(/^3 results/, undefined, { timeout: 5000 })).toBeTruthy();
+ expect(links()).not.toContain("/products/2");
+ const filters = stand.seen.at(-1)!.body.requests?.[0]?.facetFilters;
+ expect(JSON.stringify(filters)).toContain("in_stock:true");
+ });
+
+ it("lists the categories as facets, with their counts", async () => {
+ connected();
+ const facet = () =>
+ Array.from(document.querySelectorAll(".ais-RefinementList-item")).map((li) => li.textContent?.replace(/\s+/g, " ").trim());
+ await waitFor(() => expect(facet()).toEqual(["Audio2", "Kitchen1", "Outdoor1"]), { timeout: 5000 });
+ });
+});
+
+describe("SearchExperience, not connected", () => {
+ it("says which secrets to set, and calls nobody", async () => {
+ render();
+ const notice = screen.getByText(/Search activates once the/).textContent ?? "";
+ expect(notice).toContain("ALGOLIA_APP_ID");
+ expect(notice).toContain("ALGOLIA_SEARCH_API_KEY");
+ expect(notice).toContain("redeploy");
+ await new Promise((r) => setTimeout(r, 300));
+ expect(stand.seen).toHaveLength(0);
+ });
+});
diff --git a/tests/web/src/support/fake-algolia.ts b/tests/web/src/support/fake-algolia.ts
new file mode 100644
index 0000000..66dc1b1
--- /dev/null
+++ b/tests/web/src/support/fake-algolia.ts
@@ -0,0 +1,146 @@
+import { createServer, type IncomingMessage, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+
+// An in-process stand-in for Algolia's search API: the multi-query endpoint
+// the lite client calls (POST /1/indexes/*/queries), answering with hits,
+// nbHits, facets and highlights over the records it is given, and honouring
+// `query`, `facetFilters` and `numericFilters`. Every request is recorded
+// with the application id and key it carried (headers or query string).
+export type Indexed = {
+ objectID: string;
+ name: string;
+ description: string;
+ category: string;
+ price: number;
+ image_url: string | null;
+ rating: number | null;
+ quantity: number;
+ in_stock: boolean;
+};
+export type Seen = { path: string; app: string | null; key: string | null; body: { requests?: Record[] } };
+
+function params(req: Record): Record {
+ const p = req.params;
+ if (typeof p === "string") {
+ const out: Record = { ...req };
+ for (const [k, v] of new URLSearchParams(p)) {
+ try {
+ out[k] = JSON.parse(v);
+ } catch {
+ out[k] = v;
+ }
+ }
+ return out;
+ }
+ return { ...req, ...(p as object | undefined) };
+}
+
+function alts(f: unknown): string[] {
+ return Array.isArray(f) ? (f as string[]) : [String(f)];
+}
+
+function search(records: Indexed[], req: Record) {
+ const r = params(req);
+ const q = String(r.query ?? "").toLowerCase();
+ const words = q.split(/\s+/).filter(Boolean);
+ const pre = String(r.highlightPreTag ?? "");
+ const post = String(r.highlightPostTag ?? "");
+ const hits = records.filter((rec) => {
+ const hay = `${rec.name} ${rec.description} ${rec.category}`.toLowerCase();
+ if (!words.every((w) => hay.includes(w))) return false;
+ for (const f of (r.facetFilters as unknown[]) ?? []) {
+ const ok = alts(f).some((a) => {
+ const [k, v] = a.split(":");
+ return String(rec[k as keyof Indexed]).toLowerCase() === String(v).toLowerCase();
+ });
+ if (!ok) return false;
+ }
+ for (const f of (r.numericFilters as unknown[]) ?? []) {
+ const ok = alts(f).some((a) => {
+ const m = /^\s*([a-z_]+)\s*(<=|>=|<|>|=)\s*(-?[\d.]+)\s*$/.exec(a);
+ if (!m) return false;
+ const v = rec[m[1] as keyof Indexed] as number | null;
+ const n = Number(m[3]);
+ if (v == null) return false;
+ return { "<=": v <= n, ">=": v >= n, "<": v < n, ">": v > n, "=": v === n }[m[2] as "<="];
+ });
+ if (!ok) return false;
+ }
+ return true;
+ });
+ // `facets` is a list, or one name (a toggle's own facet request sends one).
+ const asked = r.facets == null ? [] : Array.isArray(r.facets) ? (r.facets as string[]) : [String(r.facets)];
+ const facetNames = asked.includes("*") ? ["category", "price", "rating", "in_stock"] : asked.filter((f) => ["category", "price", "rating", "in_stock"].includes(f));
+ const facets: Record> = {};
+ for (const f of facetNames) {
+ facets[f] = {};
+ for (const h of hits) {
+ const v = h[f as keyof Indexed];
+ if (v == null) continue;
+ facets[f][String(v)] = (facets[f][String(v)] ?? 0) + 1;
+ }
+ }
+ const mark = (s: string) =>
+ words.reduce((acc, w) => acc.replace(new RegExp(w.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "gi"), (m) => `${pre}${m}${post}`), s);
+ return {
+ hits: hits.map((h) => ({
+ ...h,
+ _highlightResult: Object.fromEntries(
+ (["name", "description", "category"] as const).map((k) => [k, { value: mark(h[k]), matchLevel: words.length ? "full" : "none", matchedWords: words }]),
+ ),
+ })),
+ nbHits: hits.length,
+ page: 0,
+ nbPages: 1,
+ hitsPerPage: 20,
+ processingTimeMS: 1,
+ exhaustiveNbHits: true,
+ query: q,
+ params: "",
+ index: String(r.indexName ?? "products"),
+ facets,
+ };
+}
+
+async function read(req: IncomingMessage): Promise {
+ const chunks: Buffer[] = [];
+ for await (const c of req) chunks.push(c as Buffer);
+ return Buffer.concat(chunks).toString("utf8");
+}
+
+export async function fakeAlgolia(records: Indexed[]): Promise<{ url: string; seen: Seen[]; close: () => Promise }> {
+ const seen: Seen[] = [];
+ const server: Server = createServer(async (req, res) => {
+ const cors = {
+ "access-control-allow-origin": "*",
+ "access-control-allow-headers": "*",
+ "access-control-allow-methods": "GET, POST, OPTIONS",
+ };
+ if (req.method === "OPTIONS") {
+ res.writeHead(204, cors).end();
+ return;
+ }
+ const u = new URL(req.url ?? "/", "http://stand-in");
+ const text = await read(req);
+ const body = text ? JSON.parse(text) : {};
+ seen.push({
+ path: u.pathname,
+ app: (req.headers["x-algolia-application-id"] as string) ?? u.searchParams.get("x-algolia-application-id"),
+ key: (req.headers["x-algolia-api-key"] as string) ?? u.searchParams.get("x-algolia-api-key"),
+ body,
+ });
+ if (req.method !== "POST" || !/^\/1\/indexes\/[^/]+\/queries$/.test(u.pathname)) {
+ res.writeHead(404, { ...cors, "content-type": "application/json" }).end('{"message":"not found"}');
+ return;
+ }
+ const out = JSON.stringify({ results: (body.requests ?? []).map((r: Record) => search(records, r)) });
+ res.writeHead(200, { ...cors, "content-type": "application/json; charset=utf-8" }).end(out);
+ });
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
+ const { port } = server.address() as AddressInfo;
+ return {
+ url: `http://127.0.0.1:${port}`,
+ seen,
+ close: () => new Promise((resolve) => server.close(() => resolve())),
+ };
+}
diff --git a/tests/web/src/wrangler-config.test.ts b/tests/web/src/wrangler-config.test.ts
new file mode 100644
index 0000000..250802a
--- /dev/null
+++ b/tests/web/src/wrangler-config.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import * as path from 'node:path';
+
+// apps/web's wrangler.jsonc is COMMITTED: the composition checks that it
+// exists before the build, in a fresh checkout, so it cannot be a file a build
+// generates. It is the render of wrangler.template.jsonc from
+// wiring.fixture.json, and the stage and prod deploy lanes re-render it from
+// their live wiring document (apps/web/component.yaml's buildCommand). These
+// hold the committed file to the template, and the live render to the
+// document it is given.
+const app = path.resolve(__dirname, '../../../apps/web');
+const wire = path.resolve(__dirname, '../../../tooling/wire');
+
+function renderFixture(env: string): string {
+ const dir = mkdtempSync(path.join(tmpdir(), 'wire-'));
+ try {
+ const out = path.join(dir, 'wrangler.jsonc');
+ execFileSync(process.execPath, [
+ path.join(wire, 'render.mjs'),
+ '--template', path.join(app, 'wrangler.template.jsonc'),
+ '--out', out,
+ '--map', path.join(app, 'wiring.fixture.json'),
+ '--env', env
+ ]);
+ return readFileSync(out, 'utf8');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+}
+
+describe('apps/web wrangler config', () => {
+ it('is committed as the fixture render of the template (pnpm run wire:fixture)', () => {
+ expect(readFileSync(path.join(app, 'wrangler.jsonc'), 'utf8')).toBe(renderFixture('stage'));
+ });
+
+ it('keeps every resource id in the template a wiring token', () => {
+ const template = readFileSync(path.join(app, 'wrangler.template.jsonc'), 'utf8');
+ expect(template).not.toMatch(/"id":\s*"[0-9a-f]{32}"/);
+ expect(template).toMatch(/@@wiring\(cloudflare-hyperdrive\/__ENV__:hyperdrive_id\)@@/);
+ });
+
+ it('renders a deploy lane its own environment from the live wiring document', () => {
+ const dir = mkdtempSync(path.join(tmpdir(), 'wire-'));
+ try {
+ const out = path.join(dir, 'wrangler.jsonc');
+ execFileSync(
+ process.execPath,
+ [
+ path.join(wire, 'live.mjs'),
+ '--template', path.join(app, 'wrangler.template.jsonc'),
+ '--out', out,
+ '--components', 'cloudflare-hyperdrive',
+ '--env', 'prod'
+ ],
+ {
+ env: {
+ ...process.env,
+ WIRING_CLOUDFLARE_HYPERDRIVE_PROD: JSON.stringify({
+ hyperdrive_id: 'f'.repeat(32),
+ hyperdrive_name: 'prod-x-prod'
+ })
+ }
+ }
+ );
+ const rendered = readFileSync(out, 'utf8');
+ expect(rendered).toContain(`"id": "${'f'.repeat(32)}"`);
+ expect(rendered).toMatch(/"name": "[a-z0-9-]+-web"/);
+ expect(rendered).not.toContain('__ENV__');
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+
+ it('refuses a deploy render with no wiring document', () => {
+ const env = { ...process.env };
+ delete env.WIRING_CLOUDFLARE_HYPERDRIVE_STAGE;
+ expect(() =>
+ execFileSync(
+ process.execPath,
+ [
+ path.join(wire, 'live.mjs'),
+ '--template', path.join(app, 'wrangler.template.jsonc'),
+ '--out', path.join(tmpdir(), 'never-written.jsonc'),
+ '--components', 'cloudflare-hyperdrive',
+ '--env', 'stage'
+ ],
+ { env, stdio: 'pipe' }
+ )
+ ).toThrow();
+ });
+});
diff --git a/tests/web/tsconfig.json b/tests/web/tsconfig.json
new file mode 100644
index 0000000..d8d1c79
--- /dev/null
+++ b/tests/web/tsconfig.json
@@ -0,0 +1,25 @@
+{
+ "extends": "../../tooling/tsconfig/web.json",
+ "compilerOptions": {
+ "composite": false,
+ "declaration": false,
+ "declarationMap": false,
+ "noEmit": true,
+ "jsx": "react-jsx",
+ "types": [
+ "node",
+ "@cloudflare/workers-types"
+ ],
+ "paths": {
+ "@/*": [
+ "../../apps/web/*"
+ ]
+ },
+ "noUncheckedIndexedAccess": false
+ },
+ "include": [
+ "src/**/*.ts",
+ "src/**/*.tsx",
+ "../../apps/web/cloudflare-env.d.ts"
+ ]
+}
diff --git a/tests/web/vitest.config.ts b/tests/web/vitest.config.ts
new file mode 100644
index 0000000..9d8b62a
--- /dev/null
+++ b/tests/web/vitest.config.ts
@@ -0,0 +1,14 @@
+import { defineConfig } from "vitest/config";
+import * as path from "node:path";
+
+export default defineConfig({
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "../../apps/web/"),
+ },
+ },
+ test: {
+ include: ["src/**/*.test.ts", "src/**/*.test.tsx"],
+ environment: "node",
+ },
+});
diff --git a/tooling/catalog/gen-component-docs.py b/tooling/catalog/gen-component-docs.py
new file mode 100644
index 0000000..743782b
--- /dev/null
+++ b/tooling/catalog/gen-component-docs.py
@@ -0,0 +1,550 @@
+#!/usr/bin/env python3
+"""Generate each component's docs (overview / architecture / runbook).
+
+ python3 tooling/catalog/gen-component-docs.py # write
+ python3 tooling/catalog/gen-component-docs.py --check # fail on drift (CI)
+
+Every `component.yaml` attaches its `docs/` folder in `spec.docs` (overview,
+architecture, runbook), which is what the Orun workspace's Docs library shows
+and what the catalog's docs and runbook checks read; a folder nothing declares
+is never attached (testing/coverage.test.sh holds the rule). These pages are
+generated, not hand-written, because almost
+everything in them is already declared somewhere CI validates: the component's
+manifest (type, description, dependencies, environments, the secrets a lane
+resolves, the smoke), its Worker config (bindings, triggers, the wiring the
+deploy fills in), its Terraform (resources and outputs), its migrations and its
+package scripts. A hand-written copy of those facts drifts the first time one
+changes; a generated one cannot, because `--check` fails the pull request that
+changes the fact without the page.
+
+What is NOT derivable (why a component exists, what a failure means for this
+product in particular) belongs in the component's `description` and in the
+product's own docs, not here.
+
+The pages ship with the component into every product built from this tree, so
+they say nothing about where they came from: no factory paths, no generator
+path, no provenance. Zero dependencies beyond PyYAML.
+"""
+
+from __future__ import annotations
+
+import json
+import pathlib
+import re
+import sys
+
+try:
+ import yaml
+except ImportError: # pragma: no cover - the contract job installs it
+ sys.exit("gen-component-docs needs PyYAML (pip install pyyaml)")
+
+ROOT = pathlib.Path(__file__).resolve().parents[2]
+ROOTS = ("apps", "packages", "infra", "tests")
+SKIP_DIRS = {"node_modules", "dist", ".turbo", "docs", ".next", ".open-next",
+ ".wrangler", ".svelte-kit", ".nuxt", ".output", ".astro", "coverage"}
+
+# Paths a shipped page must never name: products are not placed with them.
+FACTORY = re.compile(
+ r"repo-blueprint|BOOTSTRAP\.md|(? str:
+ """JSONC → JSON: drop comments outside strings, then trailing commas."""
+ out, i, n, in_str = [], 0, len(text), False
+ while i < n:
+ c = text[i]
+ if in_str:
+ out.append(c)
+ if c == "\\" and i + 1 < n:
+ out.append(text[i + 1])
+ i += 2
+ continue
+ if c == '"':
+ in_str = False
+ i += 1
+ continue
+ if c == '"':
+ in_str = True
+ out.append(c)
+ i += 1
+ elif text.startswith("//", i):
+ j = text.find("\n", i)
+ i = n if j < 0 else j
+ elif text.startswith("/*", i):
+ j = text.find("*/", i + 2)
+ i = n if j < 0 else j + 2
+ else:
+ out.append(c)
+ i += 1
+ return re.sub(r",(\s*[}\]])", r"\1", "".join(out))
+
+
+def read_json(path: pathlib.Path) -> dict | None:
+ try:
+ return json.loads(strip_jsonc(path.read_text(encoding="utf-8")))
+ except (OSError, ValueError):
+ return None
+
+
+def rel(p: pathlib.Path) -> str:
+ return p.relative_to(ROOT).as_posix()
+
+
+def discover() -> list[dict]:
+ found = []
+ for root in ROOTS:
+ base = ROOT / root
+ if not base.is_dir():
+ continue
+ stack = [base]
+ while stack:
+ d = stack.pop()
+ for entry in sorted(d.iterdir()):
+ if entry.is_dir():
+ if entry.name in SKIP_DIRS or entry.name.startswith("."):
+ continue
+ if (entry / "main.tf").exists() and not (entry / "component.yaml").exists():
+ continue
+ if len(entry.relative_to(base).parts) <= 3:
+ stack.append(entry)
+ elif entry.name == "component.yaml":
+ found.append(read_component(entry))
+ comps = [c for c in found if c["name"] and c["type"]]
+ return sorted(comps, key=lambda c: c["name"])
+
+
+def read_component(file: pathlib.Path) -> dict:
+ doc = yaml.safe_load(file.read_text(encoding="utf-8")) or {}
+ meta, spec = doc.get("metadata") or {}, doc.get("spec") or {}
+ params = spec.get("parameters") or {}
+ deps = [d.get("component") for d in (spec.get("dependsOn") or []) if isinstance(d, dict)]
+ envs = []
+ # Secrets may be declared for the whole component or per environment
+ # (`subscribe.environments[].secretEnv`); a page lists both.
+ req_env = set((spec.get("secretEnv") or {}).keys())
+ opt_env = set((spec.get("optionalSecretEnv") or {}).keys())
+ for e in ((spec.get("subscribe") or {}).get("environments") or []):
+ req_env |= set((e.get("secretEnv") or {}).keys())
+ opt_env |= set((e.get("optionalSecretEnv") or {}).keys())
+ rules = [(r.get("profile"), ((r.get("when") or {}).get("triggerRef")))
+ for r in (e.get("profileRules") or [])]
+ envs.append({"name": e.get("name"), "profile": e.get("profile"), "rules": rules})
+ return {
+ "dir": file.parent,
+ "path": rel(file.parent),
+ "name": meta.get("name"),
+ "description": (meta.get("description") or "").strip(),
+ "type": spec.get("type"),
+ "deps": [d for d in deps if d],
+ "secret_env": sorted(req_env),
+ "optional_env": sorted(opt_env - req_env),
+ "envs": envs,
+ "params": params,
+ "migrations_path": spec.get("path") if spec.get("type") == "db-migrate" else None,
+ }
+
+
+def package_of(c: dict) -> dict | None:
+ return read_json(c["dir"] / "package.json")
+
+
+def worker_config(c: dict) -> tuple[str | None, dict | None]:
+ """The config a deploy uses: the template when wiring renders one."""
+ names = ["wrangler.template.jsonc", c["params"].get("wranglerConfig") or "",
+ "wrangler.jsonc", "wrangler.json"]
+ for name in names:
+ if name and (c["dir"] / name).is_file():
+ return name, read_json(c["dir"] / name)
+ return None, None
+
+
+WIRING = re.compile(r"@@wiring\(([^/)]+)/__ENV__:([^)]+)\)@@")
+
+
+def wired(value) -> str | None:
+ m = WIRING.search(str(value)) if value is not None else None
+ return f"`{m.group(2)}` from `{m.group(1)}`" if m else None
+
+
+def bindings(cfg: dict) -> list[tuple[str, str, str]]:
+ rows = []
+ for kv in cfg.get("kv_namespaces") or []:
+ rows.append((kv.get("binding"), "Workers KV namespace", wired(kv.get("id")) or "declared in the config"))
+ for b in cfg.get("r2_buckets") or []:
+ rows.append((b.get("binding"), "R2 bucket", wired(b.get("bucket_name")) or f"`{b.get('bucket_name')}`"))
+ for d in cfg.get("d1_databases") or []:
+ rows.append((d.get("binding"), "D1 database", wired(d.get("database_id")) or "declared in the config"))
+ for h in cfg.get("hyperdrive") or []:
+ rows.append((h.get("binding"), "Hyperdrive (pooled Postgres)", wired(h.get("id")) or "declared in the config"))
+ if isinstance(cfg.get("ai"), dict) and cfg["ai"].get("binding"):
+ rows.append((cfg["ai"]["binding"], "Workers AI", "account-level; no resource to provision"))
+ for d in ((cfg.get("durable_objects") or {}).get("bindings") or []):
+ rows.append((d.get("name"), "Durable Object", f"class `{d.get('class_name')}`"))
+ for s in cfg.get("services") or []:
+ rows.append((s.get("binding"), "Service binding", f"Worker `{s.get('service')}`"))
+ for q in ((cfg.get("queues") or {}).get("producers") or []):
+ rows.append((q.get("binding"), "Queue producer", f"queue `{q.get('queue')}`"))
+ for r in cfg.get("ratelimits") or []:
+ simple = r.get("simple") or {}
+ rows.append((r.get("name"), "Rate limiter",
+ f"{simple.get('limit')} requests / {simple.get('period')}s per location"))
+ assets = cfg.get("assets") or {}
+ if assets.get("binding"):
+ rows.append((assets["binding"], "Static assets", f"`{assets.get('directory')}`"))
+ return [r for r in rows if r[0]]
+
+
+def tf_facts(c: dict) -> dict:
+ tf_dir = c["dir"] / (c["params"].get("terraformDir") or "terraform")
+ resources, outputs, variables, backend = [], [], [], None
+ for f in sorted(tf_dir.glob("*.tf")) if tf_dir.is_dir() else []:
+ text = f.read_text(encoding="utf-8")
+ resources += [f"{t}.{n}" for t, n in re.findall(r'^resource\s+"([^"]+)"\s+"([^"]+)"', text, re.M)]
+ outputs += re.findall(r'^output\s+"([^"]+)"', text, re.M)
+ variables += re.findall(r'^variable\s+"([^"]+)"', text, re.M)
+ m = re.search(r'backend\s+"([^"]+)"', text)
+ backend = backend or (m.group(1) if m else None)
+ imports = (tf_dir / "adopt.tf").is_file() if tf_dir.is_dir() else False
+ return {"dir": rel(tf_dir) if tf_dir.is_dir() else None, "resources": resources,
+ "outputs": outputs, "variables": variables, "backend": backend, "adopt": imports}
+
+
+def published(c: dict) -> list[tuple[str, str]]:
+ spec = c["params"].get("secretOutputs") or ""
+ pairs = []
+ for part in str(spec).split(","):
+ if "=" in part:
+ k, v = part.split("=", 1)
+ pairs.append((k.strip(), v.strip()))
+ return pairs
+
+
+def test_files(c: dict) -> list[str]:
+ out = []
+ for p in sorted(c["dir"].rglob("*")):
+ if any(part in SKIP_DIRS for part in p.relative_to(c["dir"]).parts):
+ continue
+ if p.is_file() and re.search(r"\.(test|spec)\.(ts|tsx|js|mjs|cjs)$", p.name):
+ out.append(p.name)
+ return out
+
+
+def migrations(c: dict) -> list[str]:
+ path = c["migrations_path"]
+ if not path:
+ return []
+ d = ROOT / path
+ if not d.is_dir():
+ return []
+ return sorted(p.name for p in d.iterdir() if p.is_dir() or p.suffix == ".sql")
+
+
+# ── markdown ─────────────────────────────────────────────────────────────
+
+def md_table(header: list[str], rows: list[list[str]]) -> list[str]:
+ """A table laid out the way prettier lays it out, so a repo whose lint is
+ `prettier --check` accepts the page as written."""
+ cols = len(header)
+ width = [max(3, len(header[i]), *(len(r[i]) for r in rows)) for i in range(cols)]
+ def line(cells):
+ return "| " + " | ".join(c.ljust(width[i]) for i, c in enumerate(cells)) + " |"
+ return [line(header), "| " + " | ".join("-" * w for w in width) + " |", *(line(r) for r in rows)]
+
+
+# ── phrasing ─────────────────────────────────────────────────────────────
+
+KIND = {
+ "cloudflare-worker-turbo": "A Cloudflare Worker, deployed per environment by its CI lane.",
+ "cloudflare-workers-assets-turbo": "A Cloudflare Worker with Static Assets (server rendering plus "
+ "static files), deployed per environment by its CI lane.",
+ "terraform": "Terraform-managed infrastructure, planned and applied per environment by its CI lane.",
+ "db-migrate": "Applies this repository's ordered database migrations per environment: "
+ "plan on pull requests, apply on merge to `main`.",
+ "turbo-package": "A workspace package built by the turbo pipeline. It deploys nothing itself: "
+ "its lane type-checks, lints, tests and builds it.",
+}
+
+TRIGGER = {"github-push-main": "a push to `main`", "github-pull-request": "a pull request"}
+
+
+def env_line(e: dict) -> str:
+ s = f"`{e['name']}`: `{e['profile']}`"
+ for profile, ref in e["rules"]:
+ s += f", `{profile}` on {TRIGGER.get(ref, f'`{ref}`')}"
+ return s
+
+
+def is_tests(c: dict) -> bool:
+ return c["name"].endswith("-tests") or c["path"].startswith("tests/")
+
+
+def subject_of(c: dict, by_name: dict) -> str | None:
+ if c["name"].endswith("-tests"):
+ s = c["name"][: -len("-tests")]
+ return s if s in by_name else None
+ return None
+
+
+def names_list(c: dict, keep) -> list[str]:
+ """Secret names a lane resolves, required first; an optional one (from
+ `optionalSecretEnv`) is resolved when it exists and skipped when not."""
+ req = [f"- `{k}`" for k in c["secret_env"] if keep(k)]
+ opt = [f"- `{k}` (optional)" for k in c["optional_env"] if keep(k)]
+ return req + opt
+
+
+def bullet_list(names: list[str], by_name: dict) -> list[str]:
+ if not names:
+ return ["- (none)"]
+ out = []
+ for n in names:
+ d = by_name.get(n)
+ out.append(f"- **{n}** — {d['description']}" if d and d["description"] else f"- **{n}**")
+ return out
+
+
+# ── pages ────────────────────────────────────────────────────────────────
+
+def overview(c: dict, by_name: dict, dependents: list[str]) -> str:
+ pkg = package_of(c)
+ kind = KIND.get(c["type"], f"A `{c['type']}` component.")
+ subject = subject_of(c, by_name)
+ if is_tests(c):
+ kind = (f"The test suite for **{subject}**. " if subject else "A test suite. ") + \
+ "It deploys nothing: its lane installs, builds and runs the tests."
+ lines = [f"# {c['name']}", ""]
+ if c["description"]:
+ lines += [c["description"], ""]
+ facts = [["Type", f"`{c['type']}`"], ["Source", f"`{c['path']}`"]]
+ if pkg and pkg.get("name"):
+ facts.append(["Package", f"`{pkg['name']}`"])
+ if c["envs"]:
+ facts.append(["Environments", " · ".join(env_line(e) for e in c["envs"])])
+ lines += [kind, "", *md_table(["", ""], facts)]
+ lines += ["", "## Depends on", "", *bullet_list(c["deps"], by_name),
+ "", "## Depended on by", "", *bullet_list(dependents, by_name), ""]
+ return "\n".join(lines)
+
+
+def architecture(c: dict, by_name: dict) -> str:
+ lines = [f"# {c['name']} — architecture", ""]
+ t = c["type"]
+
+ if t == "terraform":
+ f = tf_facts(c)
+ lines += [f"A `terraform` root at `{f['dir'] or c['path']}`.", ""]
+ if f["backend"] == "http":
+ lines += ["- **State** lives in the Orun Cloud HTTP state backend — no local state and",
+ " no state bucket to manage."]
+ lines += ["- **Credentials are brokered per run** from the workspace's provider",
+ " connections and resolved by name; none is stored in this repository."]
+ if f["adopt"]:
+ lines += ["- **Adoption** (`adopt.tf`): when state is empty but the resource already",
+ " exists, plan-time import adopts it instead of failing."]
+ lines.append("")
+ if f["resources"]:
+ lines += ["## Resources", "", *[f"- `{r}`" for r in f["resources"]], ""]
+ pub = published(c)
+ if pub:
+ lines += ["## Published outputs", "",
+ "Written as job-output secrets on each environment after an apply; deploy",
+ "lanes downstream resolve them by name.", "",
+ *md_table(["Secret", "Terraform output"], [[f"`{k}`", f"`{v}`"] for k, v in pub]), ""]
+ elif f["outputs"]:
+ lines += ["## Outputs", "", *[f"- `{o}`" for o in f["outputs"]], ""]
+ if c["secret_env"] or c["optional_env"]:
+ lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""]
+ return "\n".join(lines)
+
+ if t == "db-migrate":
+ migs = migrations(c)
+ lines += [f"Applies the migrations under `{c['migrations_path']}` in order, recording each one",
+ "it applies so a run only ever applies what is new. An already-applied migration",
+ "is never edited: a change is a new, later migration.", ""]
+ if migs:
+ lines += ["## Migrations", "", *[f"- `{m}`" for m in migs], ""]
+ if c["secret_env"] or c["optional_env"]:
+ lines += ["## Resolved at run time (names only)", "", *names_list(c, lambda k: True), ""]
+ return "\n".join(lines)
+
+ pkg = package_of(c)
+ if t.startswith("cloudflare-"):
+ cfg_name, cfg = worker_config(c)
+ lines += [f"Built by the turbo pipeline from `{c['path']}` and deployed with wrangler.", ""]
+ if cfg:
+ facts = [["Worker config", f"`{c['path']}/{cfg_name}`"]]
+ if cfg.get("main"):
+ facts.append(["Entry", f"`{cfg['main']}`"])
+ if cfg.get("compatibility_date"):
+ facts.append(["Compatibility date", f"`{cfg['compatibility_date']}`"])
+ if cfg.get("compatibility_flags"):
+ facts.append(["Compatibility flags", ", ".join(f"`{x}`" for x in cfg["compatibility_flags"])])
+ lines += [*md_table(["", ""], facts), ""]
+ rows = bindings(cfg)
+ lines += ["## Bindings", ""]
+ if rows:
+ lines += [*md_table(["Binding", "Kind", "Source"], [[f"`{b}`", k, s] for b, k, s in rows]), ""]
+ if any("from `" in s for _, _, s in rows):
+ lines += ["Identifiers marked _from_ a component are filled in at deploy time from",
+ "that component's published outputs for the environment being deployed.", ""]
+ else:
+ lines += ["None: the Worker binds no storage or service.", ""]
+ crons = (cfg.get("triggers") or {}).get("crons") or []
+ if crons:
+ lines += ["## Scheduled triggers", "", *[f"- `{x}`" for x in crons], ""]
+ env_names = sorted((cfg.get("env") or {}).keys())
+ var_names = sorted((cfg.get("vars") or {}).keys())
+ if var_names:
+ lines += ["## Variables", "", ", ".join(f"`{v}`" for v in var_names)
+ + (f" — overridden per environment ({', '.join(f'`{e}`' for e in env_names)})."
+ if env_names else "."), ""]
+ wiring = names_list(c, lambda k: k.startswith("WIRING_"))
+ others = names_list(c, lambda k: not k.startswith("WIRING_"))
+ if wiring:
+ lines += ["## Wiring", "",
+ "Resolved at deploy time from secrets the infrastructure lanes publish (names only):",
+ "", *wiring, ""]
+ if others:
+ lines += ["## Secrets resolved by the lane (names only)", "", *others, ""]
+ return "\n".join(lines)
+
+ # turbo-package
+ if is_tests(c):
+ files = test_files(c)
+ lines += [f"A test package at `{c['path']}`. Its lane runs the suite before it builds.", ""]
+ if files:
+ lines += [f"## Suites ({len(files)})", "", *[f"- `{f}`" for f in files], ""]
+ return "\n".join(lines)
+ lines += [f"A workspace package at `{c['path']}`, consumed by the components that depend",
+ "on it. It has no deployed surface of its own.", ""]
+ if pkg and pkg.get("exports"):
+ ex = pkg["exports"]
+ keys = sorted(ex.keys()) if isinstance(ex, dict) else ["."]
+ lines += ["## Exports", "", *[f"- `{k}`" for k in keys], ""]
+ return "\n".join(lines)
+
+
+def runbook(c: dict, by_name: dict) -> str:
+ t = c["type"]
+ pkg = package_of(c)
+ lines = [f"# {c['name']} — runbook", "", "## How it runs", ""]
+ deploys = [e["name"] for e in c["envs"]
+ if any(ref == "github-push-main" for _, ref in e["rules"])]
+ if deploys and t in ("terraform", "db-migrate"):
+ lines += [f"Pull requests plan it; a merge to `main` applies it to "
+ f"{', '.join(f'`{e}`' for e in deploys)}."]
+ elif deploys:
+ lines += [f"Pull requests verify it; a merge to `main` deploys it to "
+ f"{', '.join(f'`{e}`' for e in deploys)}."]
+ else:
+ lines += ["Its lane runs on every pull request that changes it; it has no deployed surface."]
+ lines += ["CI plans what changed (`orun plan --changed`) and runs each lane with `orun run`;",
+ "the plan orders a component after everything it depends on.", ""]
+
+ if pkg and pkg.get("scripts"):
+ name = pkg.get("name")
+ wanted = [s for s in ("dev", "build", "test", "typecheck", "lint", "preview") if s in pkg["scripts"]]
+ if name and wanted:
+ lines += ["## Local commands", "", "```bash",
+ *[f"pnpm --filter {name} {s}" for s in wanted], "```", ""]
+
+ smoke = c["params"].get("smokeCommand")
+ if smoke and "No smoke" not in str(smoke):
+ lines += ["## Verify", "", "After a deploy the lane runs this smoke against the environment it",
+ "deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL:", "",
+ "```bash", str(smoke).strip(), "```", ""]
+
+ lines += ["## Rollback", "",
+ "Revert the commit on `main`. The next convergence applies the previous desired",
+ "state; nothing was changed out of band, so there is nothing else to undo.", "",
+ "## Common failures", ""]
+ if t == "terraform":
+ lines += ["- **Provider authentication fails**: the workspace's provider connection is",
+ " missing or revoked. Reconnect it in the console; credentials are brokered",
+ " from it per run.",
+ "- **\"Already exists\" on a first apply**: state is empty but the resource is",
+ " not." + (" `adopt.tf` imports it at plan time; if it still fails, the resource"
+ " was renamed outside Terraform." if tf_facts(c)["adopt"] else
+ " Import it, or delete the stray resource, then re-run."), ""]
+ elif t == "db-migrate":
+ lines += ["- **An applied migration's file changed**: the run stops rather than guess.",
+ " Restore the file and write the change as a new migration.",
+ "- **The database is unreachable**: the infrastructure lane it depends on has",
+ " not applied for this environment; that lane runs first in a convergence.", ""]
+ elif t.startswith("cloudflare-"):
+ _, cfg = worker_config(c)
+ takes_wiring = any(k.startswith("WIRING_") for k in c["secret_env"] + c["optional_env"]) or \
+ bool(cfg and WIRING.search(json.dumps(cfg)))
+ if takes_wiring:
+ lines += ["- **A `WIRING_*` secret is missing at deploy**: an infrastructure lane upstream",
+ " has not applied for this environment yet. Within one convergence the plan",
+ " runs it first; on its own, re-run that lane."]
+ lines += ["- **The smoke fails right after a first deploy**: a new workers.dev route can",
+ " answer 4xx for a few seconds and the lane retries. A failure that persists",
+ " is a regression in the deployed code.", ""]
+ else:
+ lines += ["- **A dependent fails to build after a change here**: run `pnpm typecheck`",
+ " across the workspace before merging.", ""]
+ return "\n".join(lines)
+
+
+# ── main ─────────────────────────────────────────────────────────────────
+
+def main() -> int:
+ check = "--check" in sys.argv[1:]
+ comps = discover()
+ if not comps:
+ print("no component.yaml found", file=sys.stderr)
+ return 1
+ by_name = {c["name"]: c for c in comps}
+ dependents: dict[str, list[str]] = {c["name"]: [] for c in comps}
+ for c in comps:
+ for d in c["deps"]:
+ dependents.setdefault(d, []).append(c["name"])
+
+ drifted, written, leaks = [], 0, []
+ for c in comps:
+ pages = {
+ "overview.md": overview(c, by_name, sorted(dependents.get(c["name"], []))),
+ "architecture.md": architecture(c, by_name),
+ "runbook.md": runbook(c, by_name),
+ }
+ for fname, body in pages.items():
+ target = c["dir"] / "docs" / fname
+ for n, line in enumerate(body.splitlines(), 1):
+ m = FACTORY.search(line)
+ if m:
+ leaks.append(f"{rel(target)}:{n} would name {m.group(0)!r}")
+ current = target.read_text(encoding="utf-8") if target.exists() else None
+ if current == body:
+ continue
+ if check:
+ drifted.append(rel(target))
+ continue
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(body, encoding="utf-8")
+ written += 1
+
+ if leaks:
+ print("✗ a generated page would name a path products do not have:", file=sys.stderr)
+ for l in leaks:
+ print(f" {l}", file=sys.stderr)
+ return 1
+ if check:
+ if drifted:
+ print(f"✗ {len(drifted)} component doc(s) differ from what the manifests say:", file=sys.stderr)
+ for f in drifted:
+ print(f" {f}", file=sys.stderr)
+ print("\nRun: python3 tooling/catalog/gen-component-docs.py", file=sys.stderr)
+ return 1
+ print(f"✓ component docs match {len(comps)} component.yaml file(s)")
+ return 0
+ print(f"✓ wrote {written} page(s) for {len(comps)} component(s)")
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())