diff --git a/README.md b/README.md index ca0ee3e..467f01d 100644 --- a/README.md +++ b/README.md @@ -3,14 +3,123 @@ Vercel's [v0 clone](https://github.com/vercel/v0-sdk/tree/main/examples/v0-clone) — the v0 SDK's example app: a v0-style chat that builds apps through the [v0 Platform API](https://v0.app/docs/api/platform), with a live preview served -from an isolated origin, Design Mode, file, ZIP and GitHub imports and -one-click deploys — as **two Cloudflare Workers** built by -[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare): the host app and -its preview proxy, each on its own origin, deployed per environment through -[Orun](https://github.com/sourceplane/orun), and packaged, once it is built, as -an **Orun baseline**. +from an isolated origin, Design Mode, file, ZIP and GitHub imports, version +restore and one-click deploys — running as **two Cloudflare Workers** built by +[`@opennextjs/cloudflare`](https://opennext.js.org/cloudflare): the host app +and its preview proxy, each on its own origin, deployed per environment +through [Orun](https://github.com/sourceplane/orun). It keeps no store of its +own: chats, files and previews are the v0 API's. -Being built in reviewed steps; the plan and its status are in -[`specs/epics/v0-clone`](specs/epics/v0-clone/README.md). +The v0 SDK and its example are © Vercel, Inc., under the Apache License 2.0 +(`apps/web/LICENSE`, `apps/preview/LICENSE`). See +[`specs/epics/v0-clone`](specs/epics/v0-clone/README.md) for the design, the +milestones and the as-built status. -The v0 SDK and its example are © Vercel, Inc., under the Apache License 2.0. +> **Security warning — upstream's, read for Cloudflare.** The example has no +> user accounts. With `V0_API_KEY` stored, everyone who can reach the Workers +> shares that key's v0 workspace: they can read, create, change and delete +> chats, run generations at its expense and deploy with the Vercel token the +> key carries. Every server route passes through `authorizeProxyRequest` +> (`apps/web/lib/proxy.ts`, `apps/preview/lib/authorize.ts`), a same-origin +> check only — the seam where real session auth goes. Until it does, **leave +> `V0_API_KEY` unset** (each visitor then uses their own key, through the +> app's dialog) or put [Cloudflare Access](https://developers.cloudflare.com/cloudflare-one/applications/) +> in front of both Workers before you store one. + +## What is here + +| Surface | Where | +|---|---| +| The host app: the chat, the sidebar, the files, code and preview panes, the server routes over the v0 API | `apps/web` | +| The preview proxy: each chat's preview, fetched with the key and served into the host's iframe; the key route the host provisions | `apps/preview` | +| Where each app finds the other | `apps/web/lib/preview-proxy.ts`, `apps/preview/lib/origins.ts` | +| The v0 key (server, else the visitor's cookie) | `apps/web/lib/v0-client.ts`, `apps/preview/lib/v0-client.ts` | +| Workers build and deploy contract | each app's `next.config.mjs`, `open-next.config.ts`, `wrangler.jsonc`, `component.yaml` | +| Tests | `tests/web` (upstream's Design Mode tests, the host's routes), `tests/preview` (the key route, trusted hosts) | + +## Getting started + +```bash +pnpm install +pnpm typecheck +pnpm lint +pnpm test +pnpm build # next build + opennextjs-cloudflare build, for both apps +``` + +```bash +pnpm dev # both apps: the host on http://localhost:3000, the proxy on http://localhost:3001 +``` + +Open the host app and save a v0 API key through its dialog +([v0.app → Settings → API keys](https://v0.app/chat/settings/keys); it needs +write access and generation credits). The key is validated, kept in an +HTTP-only cookie on the host's origin, and handed by your browser straight to +the preview proxy, which keeps its own copy in its own cookie. To serve the +built Workers instead: `pnpm --filter @app/preview preview` and +`pnpm --filter @app/web preview` (wrangler dev; `.dev.vars.example` in each +app). + +## Connecting v0 + +Each app resolves its credential in this order: `V0_API_KEY`, then its own +cookie. Upstream's third, Vercel OIDC, has no Cloudflare equivalent. + +- **Bring your own key (the default).** Leave `V0_API_KEY` unset. Every + visitor saves their own key through the dialog and spends their own credits. +- **One shared key.** Store it per environment as the Orun secret + `V0_API_KEY` and redeploy: both Workers' deploys push it as a Worker secret + (it never reaches a bundle), and the dialog turns read-only. Read the + security warning above first. + +## How it maps to Vercel + +| Vercel-side | Here | +|---|---| +| `apps/web`, a Vercel project | `apps/web`, the Worker `-web-` (`.open-next/worker.js` + Static Assets) | +| `apps/preview-proxy`, a second project on another domain | `apps/preview`, the Worker `-preview-` — its own hostname per environment | +| Related Projects telling each app the other's URL | each build is told the other's origin: `V0_PREVIEW_PROXY_URL` / `V0_CLONE_ORIGIN` from the environment when set (custom domains), else the sibling Worker's workers.dev URL (`component.yaml`'s `buildCommand`) | +| Vercel OIDC as the fallback credential | left out; `V0_API_KEY` (optional Orun secret → Worker secret) or the visitor's own key | +| Deployment Protection on both projects | Cloudflare Access on both Workers, before a shared key is stored | +| Deploy on push | Orun deploys the preview proxy, then the host, to stage → prod on merge to `main`, each smoke-tested | +| `bun test` | `vitest` in `tests/web` and `tests/preview` | + +## Deploying + +A merge to `main` deploys, per environment, `-preview-` and then +`-web-` (the host waits for its proxy), each checked by its +`smokeCommand`: the proxy's `/api/health`, then the host's page, its +`/api/health` and the proxy origin it was built with. Neither needs a v0 key +to pass. + +**Deploy by hand:** Orunbase's Deploy button, or Actions → CI → Run workflow +on `main` with a component (`web`, `preview`, or empty for both) and an +environment, deploys exactly as a merge does. + +### Custom domains + +Attach a domain to each Worker in Cloudflare, then set the two origins under +the environment's `env:` in `intent.yaml` and redeploy both apps: + +```yaml +env: + V0_PREVIEW_PROXY_URL: https://acme-previews.net # the host's iframe points here + V0_CLONE_ORIGIN: https://app.acme.com # the only origin the proxy lets provision its key +``` + +Both Workers' workers.dev hostnames share one registrable domain +(`.workers.dev`), so the preview is cross-origin to the host but +same-site with it. For production, give the preview proxy a domain on a +**different registrable domain** from the host's, as upstream recommends. + +### Trusted preview hosts + +The preview proxy registers its own hostname in the v0 team's trusted preview +hosts (at most five) the first time it is provisioned with a key or serves a +preview. Stage and prod take two; remove stale ones in v0's settings. + +## CI + +| Workflow | What it runs | +|---|---| +| `ci.yml` | the Orun pipeline: `orun plan --changed`, then one job per lane. A pull request verifies (both apps built and dry-deployed per environment, both test suites run); a merge deploys the preview proxy, then the host, stage → prod. It plans nothing while `intent.yaml` names the placeholder workspace `ws_CHANGE_ME`, as this repository does. A manual run (Orunbase's Deploy button, or Run workflow on `main`) plans the environment and components it names under the push-to-main trigger | diff --git a/apps/preview/README.md b/apps/preview/README.md new file mode 100644 index 0000000..99790cb --- /dev/null +++ b/apps/preview/README.md @@ -0,0 +1,10 @@ +# apps/preview — the preview proxy + +The v0 clone's preview origin (upstream's `apps/preview-proxy`): it fetches a +chat's preview from the v0 API with the key and serves it, path for path, +into the host app's iframe; `proxy.ts` keeps root-relative preview requests on +the chat's proxy path; `/api/api-key` lets only the host app's origin +provision this proxy's own cookie. Generated code runs here, never on the +host's origin. One Cloudflare Worker per environment (`-preview-`). +Upstream: [vercel/v0-sdk `examples/v0-clone/apps/preview-proxy`](https://github.com/vercel/v0-sdk/tree/main/examples/v0-clone/apps/preview-proxy) +(Apache-2.0, `LICENSE`). diff --git a/apps/preview/component.yaml b/apps/preview/component.yaml new file mode 100644 index 0000000..1900168 --- /dev/null +++ b/apps/preview/component.yaml @@ -0,0 +1,82 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: preview + description: The v0 clone's preview proxy, on an origin of its own — it fetches each chat's preview with the v0 key and serves it into the host app's iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) +spec: + type: cloudflare-workers-assets-turbo + 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: app + path: apps/preview + # Its own lane per environment, as the host's: a Next.js build each. + lane: isolated + # The same optional v0 key the host reads (apps/web/component.yaml): unset, + # the host app provisions each visitor's key into this proxy's own + # partitioned cookie; set, both Workers use it. A Worker SECRET, never in + # a bundle (buildCommand below). + optionalSecretEnv: + V0_API_KEY: "secret://v0-clone/v0-clone/{{ .environment }}/V0_API_KEY" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/preview" + wranglerConfig: wrangler.jsonc + + workerEntrypoint: .open-next/worker.js + assetsDir: .open-next/assets + + # Per-env worker name: v0-clone-preview-{dev,stage,prod} — a hostname of + # its own, so the preview is cross-origin to the host app. + workerName: v0-clone-preview + environmentAwareWorkerName: true + + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # The host app's origin, inlined into the build + # (NEXT_PUBLIC_V0_CLONE_ORIGIN, lib/origins.ts) — the only origin allowed + # to provision this proxy's key: the environment's V0_CLONE_ORIGIN when + # intent.yaml sets one (a custom domain), else the host Worker's + # workers.dev URL for this environment. The v0 key never reaches the + # build, and goes to the Worker as a SECRET when the environment has one, + # as the host's does. + buildCommand: env -u V0_API_KEY NEXT_PUBLIC_V0_CLONE_ORIGIN="${V0_CLONE_ORIGIN:-https://v0-clone-web-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm exec turbo run build --filter=@app/preview && node ../../tooling/wire/worker-secrets.mjs --secret V0_API_KEY --worker "v0-clone-preview-${ORUN_ENVIRONMENT}" --config wrangler.jsonc + + # Smoke: /api/health answers as the preview proxy — which only this + # Worker can — naming the host app origin its build was given. Read-only, + # no v0 call; a preview itself needs a chat, which needs a key. + smokeCommand: "health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"app\":\"preview\"' && echo \"${health}\" | grep -q '\"ok\":true'" + labels: + team: platform + layer: delivery + surface: preview + runtime: cloudflare diff --git a/apps/preview/docs/architecture.md b/apps/preview/docs/architecture.md new file mode 100644 index 0000000..769955b --- /dev/null +++ b/apps/preview/docs/architecture.md @@ -0,0 +1,20 @@ +# preview — architecture + +Built by the turbo pipeline from `apps/preview` and deployed with wrangler. + +| | | +| ------------------- | ----------------------------------------------- | +| Worker config | `apps/preview/wrangler.jsonc` | +| Entry | `.open-next/worker.js` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | + +## Bindings + +| Binding | Kind | Source | +| -------- | ------------- | ------------------- | +| `ASSETS` | Static assets | `.open-next/assets` | + +## Secrets resolved by the lane (names only) + +- `V0_API_KEY` (optional) diff --git a/apps/preview/docs/overview.md b/apps/preview/docs/overview.md new file mode 100644 index 0000000..f52b114 --- /dev/null +++ b/apps/preview/docs/overview.md @@ -0,0 +1,20 @@ +# preview + +The v0 clone's preview proxy, on an origin of its own — it fetches each chat's preview with the v0 key and serves it into the host app's iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) + +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. + +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/preview` | +| Package | `@app/preview` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- (none) + +## Depended on by + +- **web** — The v0 clone's host app — the chat UI, its server routes over the v0 Platform API and the preview iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) diff --git a/apps/preview/docs/runbook.md b/apps/preview/docs/runbook.md new file mode 100644 index 0000000..4062792 --- /dev/null +++ b/apps/preview/docs/runbook.md @@ -0,0 +1,37 @@ +# preview — runbook + +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +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/preview dev +pnpm --filter @app/preview build +pnpm --filter @app/preview typecheck +pnpm --filter @app/preview lint +pnpm --filter @app/preview preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +health=$(curl -sf "${DEPLOYED_URL}/api/health") && echo "${health}" | grep -q '"app":"preview"' && echo "${health}" | grep -q '"ok":true' +``` + +## 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 + +- **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. diff --git a/apps/web/README.md b/apps/web/README.md new file mode 100644 index 0000000..6d69bd6 --- /dev/null +++ b/apps/web/README.md @@ -0,0 +1,9 @@ +# apps/web — the host app + +The v0 clone's host: the chat UI, its server routes over the v0 Platform API +(`app/api/**`, each behind `authorizeProxyRequest`) and the preview iframe, +which points at the preview proxy (`../preview`) on its own origin. One +Cloudflare Worker per environment, built by `@opennextjs/cloudflare` +(`-web-`). See the repository README for running, connecting v0 +and deploying. Upstream: [vercel/v0-sdk `examples/v0-clone/apps/web`](https://github.com/vercel/v0-sdk/tree/main/examples/v0-clone/apps/web) +(Apache-2.0, `LICENSE`). diff --git a/apps/web/component.yaml b/apps/web/component.yaml new file mode 100644 index 0000000..7e8c86b --- /dev/null +++ b/apps/web/component.yaml @@ -0,0 +1,114 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web + description: The v0 clone's host app — the chat UI, its server routes over the v0 Platform API and the preview iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) +spec: + type: cloudflare-workers-assets-turbo + 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 } + # `app`, not `web`: a domain and a component share one name space in the + # catalog, and a domain called `web` would hide this component from it. + domain: app + path: apps/web + # Its own lane per environment: the Next.js build is the longest job in the + # plan, and a shared lane would wait on it. + lane: isolated + # THE PREVIEW PROXY BEFORE THE HOST. The host's iframe points at the preview + # Worker, and this deploy's smoke checks that the origin it was built with + # answers as the preview proxy. So on a merge to main this deploy waits for + # its environment's preview deploy (enforced). A pull request deploys + # nothing, so nothing on one waits (advisory). + dependsOn: + - component: preview + mode: enforced + modeRules: + - mode: advisory + when: + triggerRef: github-pull-request + # The v0 API key, stored per environment as the product's secret + # V0_API_KEY (README → Connecting v0). OPTIONAL, as upstream makes it: a key + # nobody has stored is skipped when the job resolves its secrets (no env + # var, no failure), and the app then asks each visitor for their own key. + # Set, every visitor shares it — the README says to put Cloudflare Access in + # front of both Workers first. The Worker reads it at request time, so the + # build hands it to the Worker as a Worker SECRET and no bundle contains it + # (buildCommand below). The preview proxy reads the same key. + optionalSecretEnv: + V0_API_KEY: "secret://v0-clone/v0-clone/{{ .environment }}/V0_API_KEY" + subscribe: + environments: + - name: dev + profile: verify + - name: stage + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + - name: prod + profile: verify + profileRules: + - profile: deploy + when: + triggerRef: github-push-main + parameters: + nodeVersion: "22" + pnpmVersion: "10.12.1" + + workspaceDir: ../.. + appDir: . + + turboFilter: "@app/web" + wranglerConfig: wrangler.jsonc + + # @opennextjs/cloudflare emits a Worker entrypoint plus a static-assets + # directory bound via ASSETS — both deploy in one `wrangler deploy`. + workerEntrypoint: .open-next/worker.js + assetsDir: .open-next/assets + + # Per-env worker name: v0-clone-web-{dev,stage,prod}. + workerName: v0-clone-web + environmentAwareWorkerName: true + + # The account's workers.dev subdomain; exported to the smoke step as + # ${WORKERS_DEV_SUBDOMAIN} and used to build ${DEPLOYED_URL}. + workersDevSubdomain: your-workers-subdomain + + installCommand: pnpm install --frozen-lockfile + # The preview proxy's origin, inlined into the build + # (NEXT_PUBLIC_V0_PREVIEW_PROXY_URL, lib/preview-proxy.ts): the + # environment's V0_PREVIEW_PROXY_URL when intent.yaml sets one (a custom + # domain), else the preview Worker's workers.dev URL for this environment. + # The subdomain is written out rather than read from + # ${WORKERS_DEV_SUBDOMAIN}: the composition exports that to the smoke step + # only. ${ORUN_ENVIRONMENT} the runner sets for every step. The v0 key + # never reaches the build (`env -u`): the Worker reads it at request time. + # Then the key, when the environment has one, goes to the Worker as a + # SECRET (tooling/wire/worker-secrets.mjs: `wrangler secret bulk`, the + # value over stdin) before the composition deploys it. Only the deploy + # lane holds a Cloudflare credential, so a verify lane builds the same and + # pushes nothing. + buildCommand: env -u V0_API_KEY NEXT_PUBLIC_V0_PREVIEW_PROXY_URL="${V0_PREVIEW_PROXY_URL:-https://v0-clone-preview-${ORUN_ENVIRONMENT}.your-workers-subdomain.workers.dev}" pnpm exec turbo run build --filter=@app/web && node ../../tooling/wire/worker-secrets.mjs --secret V0_API_KEY --worker "v0-clone-web-${ORUN_ENVIRONMENT}" --config wrangler.jsonc + + # Smoke: the home page renders to its end (`` — a render that + # throws partway through a streamed page still sent a 200) with no v0 + # key involved, /api/health answers ok — which only the Worker can — and + # the preview proxy origin it names, the one this build inlined, answers + # as the preview proxy: the iframe points somewhere real. Read-only, no v0 + # call. Each response is buffered before grep so an early match cannot + # SIGPIPE curl. + smokeCommand: "html=$(curl -sfL \"${DEPLOYED_URL}/\") && echo \"${html}\" | grep -q '' && health=$(curl -sf \"${DEPLOYED_URL}/api/health\") && echo \"${health}\" | grep -q '\"ok\":true' && proxy=$(printf '%s' \"${health}\" | grep -Eo '\"previewProxy\":\"[^\"]+\"' | cut -d'\"' -f4) && pv=$(curl -sf \"${proxy}/api/health\") && echo \"${pv}\" | grep -q '\"app\":\"preview\"'" + labels: + team: platform + layer: delivery + surface: web + runtime: cloudflare diff --git a/apps/web/docs/architecture.md b/apps/web/docs/architecture.md new file mode 100644 index 0000000..35850f2 --- /dev/null +++ b/apps/web/docs/architecture.md @@ -0,0 +1,20 @@ +# web — architecture + +Built by the turbo pipeline from `apps/web` and deployed with wrangler. + +| | | +| ------------------- | ----------------------------------------------- | +| Worker config | `apps/web/wrangler.jsonc` | +| Entry | `.open-next/worker.js` | +| Compatibility date | `2026-10-01` | +| Compatibility flags | `nodejs_compat`, `global_fetch_strictly_public` | + +## Bindings + +| Binding | Kind | Source | +| -------- | ------------- | ------------------- | +| `ASSETS` | Static assets | `.open-next/assets` | + +## Secrets resolved by the lane (names only) + +- `V0_API_KEY` (optional) diff --git a/apps/web/docs/overview.md b/apps/web/docs/overview.md new file mode 100644 index 0000000..20c9b49 --- /dev/null +++ b/apps/web/docs/overview.md @@ -0,0 +1,20 @@ +# web + +The v0 clone's host app — the chat UI, its server routes over the v0 Platform API and the preview iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) + +A Cloudflare Worker with Static Assets (server rendering plus static files), deployed per environment by its CI lane. + +| | | +| ------------ | ------------------------------------------------------------------------------------------------------------------ | +| Type | `cloudflare-workers-assets-turbo` | +| Source | `apps/web` | +| Package | `@app/web` | +| Environments | `dev`: `verify` · `stage`: `verify`, `deploy` on a push to `main` · `prod`: `verify`, `deploy` on a push to `main` | + +## Depends on + +- **preview** — The v0 clone's preview proxy, on an origin of its own — it fetches each chat's preview with the v0 key and serves it into the host app's iframe (Next.js on Cloudflare Workers + Static Assets via @opennextjs/cloudflare, per environment) + +## Depended on by + +- (none) diff --git a/apps/web/docs/runbook.md b/apps/web/docs/runbook.md new file mode 100644 index 0000000..47bf30d --- /dev/null +++ b/apps/web/docs/runbook.md @@ -0,0 +1,37 @@ +# web — runbook + +## How it runs + +Pull requests verify it; a merge to `main` deploys it to `stage`, `prod`. +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 dev +pnpm --filter @app/web build +pnpm --filter @app/web typecheck +pnpm --filter @app/web lint +pnpm --filter @app/web preview +``` + +## Verify + +After a deploy the lane runs this smoke against the environment it +deployed (`ORUN_ENVIRONMENT`); `DEPLOYED_URL` overrides the URL: + +```bash +html=$(curl -sfL "${DEPLOYED_URL}/") && echo "${html}" | grep -q '' && health=$(curl -sf "${DEPLOYED_URL}/api/health") && echo "${health}" | grep -q '"ok":true' && proxy=$(printf '%s' "${health}" | grep -Eo '"previewProxy":"[^"]+"' | cut -d'"' -f4) && pv=$(curl -sf "${proxy}/api/health") && echo "${pv}" | grep -q '"app":"preview"' +``` + +## 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 + +- **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. diff --git a/specs/epics/v0-clone/IMPLEMENTATION-STATUS.md b/specs/epics/v0-clone/IMPLEMENTATION-STATUS.md index 47569ba..77bdbe5 100644 --- a/specs/epics/v0-clone/IMPLEMENTATION-STATUS.md +++ b/specs/epics/v0-clone/IMPLEMENTATION-STATUS.md @@ -2,7 +2,25 @@ | Milestone | Status | Shipped as | |---|---|---| -| VC0 — the spec | In progress | — | -| VC1 — the apps on Workers | Not started | — | -| VC2 — ready to instantiate | Not started | — | +| VC0 — the spec | ✅ Shipped | [#1](https://github.com/sourceplane/v0-clone/pull/1) | +| VC1 — the apps on Workers | ✅ Shipped | [#2](https://github.com/sourceplane/v0-clone/pull/2) | +| VC2 — ready to instantiate | In progress | — | | VC3 — a baseline | Not started | — | + +## Departures from upstream (vercel/v0-sdk `examples/v0-clone` at `024bcaf`) + +1. **Two Cloudflare Workers** instead of two Vercel projects: `apps/web` (the host) and `apps/preview` (upstream's `apps/preview-proxy`, renamed for the component), each built by `@opennextjs/cloudflare` and deployed per environment as `-web-` and `-preview-`. +2. **Related Projects → build-time origins.** `lib/preview-proxy.ts` and `lib/origins.ts` read `NEXT_PUBLIC_V0_PREVIEW_PROXY_URL` / `NEXT_PUBLIC_V0_CLONE_ORIGIN`, inlined by each component's `buildCommand` from the environment's `V0_PREVIEW_PROXY_URL` / `V0_CLONE_ORIGIN`, else the sibling Worker's workers.dev URL. The validation is upstream's, except that plain HTTP is allowed on loopback (a local `wrangler dev`) rather than everywhere off Vercel. `@vercel/related-projects` is gone. +3. **Vercel OIDC left out.** Both `lib/v0-client.ts` resolve `V0_API_KEY`, then the app's cookie; with neither the call is unauthenticated and refused, and the host opens its key dialog. +4. **`V0_API_BASE_URL`** (`lib/v0-fetch.ts`, unset in a product): the v0 calls go to another origin with the same paths — the stand-in v0 API of the end-to-end test. +5. **A health route per app** (`/api/health`) for the deploy's smoke: no v0 call, the other app's origin, whether a server key is set (never its value). +6. **The web Worker waits for the preview Worker** on a merge (`dependsOn`, enforced on push to main), so the host's smoke can check that the proxy origin it was built with answers. +7. **The cookie and storage keys** no longer carry the example's name (`v0-api-key`, `__Host-v0-preview-api-key`, `v0-settings`), so a product renamed from this baseline keeps upstream's keys' meaning without the baseline's slug in them. +8. **bun → pnpm 10 + Node 22**, the reference's ESLint (eslint-config-next 16; the React Compiler and TypeScript rules that flag upstream's code as written are off by name, in the two files they flag), Next 16.2.4 → 16.3.8 (the reference's OpenNext-tested version), React 19.2.5 → 19.2.7, TypeScript 6 → 5.8 (the reference's). `v0` and `@v0-sdk/react` from npm at 3.0.12 (upstream used the monorepo's workspace copies of the same release). +9. **Tests:** upstream's three bun test files run under vitest in `tests/web` (`mock.module` → `vi.doMock` + a dynamic import, the same un-hoisted semantics), unchanged otherwise; new tests in `tests/web` and `tests/preview` cover the departures above. +10. **Upstream's security model is unchanged** — no accounts, a same-origin seam — and the README re-reads its warning for Cloudflare: leave `V0_API_KEY` unset, or put Cloudflare Access in front of both Workers. + +## Measured + +- Worker sizes (`wrangler deploy --dry-run`, gzipped): web 2,173 KiB, preview 1,600 KiB — both under Workers Free's 3 MiB. +- Under `wrangler dev`, against a stand-in v0 API: both serve with no key; the dialog validates a key (401 for a wrong one); the proxy accepts a key only from the host's origin (403 otherwise) and keeps it in its own cookie; a chat's preview is served through the proxy with v0's preview token. diff --git a/specs/epics/v0-clone/README.md b/specs/epics/v0-clone/README.md index 7855ca5..3eb3245 100644 --- a/specs/epics/v0-clone/README.md +++ b/specs/epics/v0-clone/README.md @@ -8,7 +8,7 @@ The port keeps the chat, the sidebar of favourite and recent chats, file, ZIP an | Field | Value | |-------|-------| -| Status | VC0 in progress | +| Status | VC0–VC1 shipped (#1, #2); VC2 in progress | | Cluster | **VC** (VC0–VC3) | | Owner(s) | `apps/web` (the host: chat UI, server routes, the preview iframe) · `apps/preview` (the preview proxy) · `tests/web` | | Builds on | `ai-chatbot` (the OpenNext shape, the CI and tooling), `portfolio-starter-kit` (a baseline with no data plane), `next-forge` (several Workers in one product), `ai-emoji-generator` (optional Orun secrets pushed as Worker secrets) | diff --git a/tests/preview/component.yaml b/tests/preview/component.yaml new file mode 100644 index 0000000..2b65521 --- /dev/null +++ b/tests/preview/component.yaml @@ -0,0 +1,31 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: preview-tests + description: The preview proxy's vitest suite (the host app origin, the health route, the key route's CORS and cookie, trusted preview hosts, the same-origin seam and the v0 fetch override), run on every pull request +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/preview/docs/architecture.md b/tests/preview/docs/architecture.md new file mode 100644 index 0000000..e5abd8e --- /dev/null +++ b/tests/preview/docs/architecture.md @@ -0,0 +1,11 @@ +# preview-tests — architecture + +A test package at `tests/preview`. Its lane runs the suite before it builds. + +## Suites (5) + +- `api-key.test.ts` +- `health.test.ts` +- `origins.test.ts` +- `trusted-host.test.ts` +- `v0-fetch.test.ts` diff --git a/tests/preview/docs/overview.md b/tests/preview/docs/overview.md new file mode 100644 index 0000000..51f6bda --- /dev/null +++ b/tests/preview/docs/overview.md @@ -0,0 +1,20 @@ +# preview-tests + +The preview proxy's vitest suite (the host app origin, the health route, the key route's CORS and cookie, trusted preview hosts, the same-origin seam and the v0 fetch override), run on every pull request + +The test suite for **preview**. It deploys nothing: its lane installs, builds and runs the tests. + +| | | +| ------------ | -------------------- | +| Type | `turbo-package` | +| Source | `tests/preview` | +| Package | `@app/preview-tests` | +| Environments | `dev`: `quick-check` | + +## Depends on + +- (none) + +## Depended on by + +- (none) diff --git a/tests/preview/docs/runbook.md b/tests/preview/docs/runbook.md new file mode 100644 index 0000000..ecb23fc --- /dev/null +++ b/tests/preview/docs/runbook.md @@ -0,0 +1,26 @@ +# preview-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/preview-tests build +pnpm --filter @app/preview-tests test +pnpm --filter @app/preview-tests typecheck +pnpm --filter @app/preview-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/component.yaml b/tests/web/component.yaml new file mode 100644 index 0000000..35f57b9 --- /dev/null +++ b/tests/web/component.yaml @@ -0,0 +1,31 @@ +apiVersion: sourceplane.io/v1 +kind: Component +metadata: + name: web-tests + description: The host app's vitest suite (upstream's Design Mode tests, the preview proxy origin, the health route, the same-origin seam and the v0 fetch override), run on every pull request +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..2239108 --- /dev/null +++ b/tests/web/docs/architecture.md @@ -0,0 +1,13 @@ +# web-tests — architecture + +A test package at `tests/web`. Its lane runs the suite before it builds. + +## Suites (7) + +- `design-mode-message.test.tsx` +- `design-mode-route.test.ts` +- `health.test.ts` +- `origins.test.ts` +- `preview-design-mode.test.tsx` +- `same-origin.test.ts` +- `v0-fetch.test.ts` diff --git a/tests/web/docs/overview.md b/tests/web/docs/overview.md new file mode 100644 index 0000000..8a5e2c7 --- /dev/null +++ b/tests/web/docs/overview.md @@ -0,0 +1,20 @@ +# web-tests + +The host app's vitest suite (upstream's Design Mode tests, the preview proxy origin, the health route, the same-origin seam and the v0 fetch override), run on every pull request + +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/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())