[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M79GGJYBB8J41YJMS6AT11PX":3,"skill-same:01M79GGJYBB8J41YJMS6AT11PX":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M79GGJYBB8J41YJMS6AT11PX","saasaloy-api",null,"Runbook for the api capability — Hono on Cloudflare Workers with a statically chained, RPC-typed route table. Use when adding, changing, or debugging routes in apps\u002Fapi, building a typed client with hc\u003CAppType>, wiring bindings (c.env), logging from a route (c.get(\"log\")), running the Worker locally, testing a route with Vitest in Node (app.request), or deploying it. Covers the chained-route registration convention, the mount-relative path rule, explicit status codes, and how features add their own wrangler bindings.","mimukit\u002Fsaasaloy","mimukit","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F11677026?v=4","01M79GFSERAQQ77QPQMC1N0Y6M","Mukitul Islam Mukit","01M79GFSFA4WMGEEBHA68N59WV",4,"MIT","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fapi\u002Fskills\u002Fsaasaloy-api\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: saasaloy-api\ndescription: Runbook for the api capability — Hono on Cloudflare Workers with a statically chained, RPC-typed route table. Use when adding, changing, or debugging routes in apps\u002Fapi, building a typed client with hc\u003CAppType>, wiring bindings (c.env), logging from a route (c.get(\"log\")), running the Worker locally, testing a route with Vitest in Node (app.request), or deploying it. Covers the chained-route registration convention, the mount-relative path rule, explicit status codes, and how features add their own wrangler bindings.\n---\n\n# api — Hono on Cloudflare Workers\n\n`apps\u002Fapi` is the backend spine, shared by `web` and `admin`. It's a [Hono](https:\u002F\u002Fhono.dev)\napp running on Cloudflare Workers, built and served with Vite via `@cloudflare\u002Fvite-plugin` (so\n`vite dev` runs the real `workerd` runtime locally). Its defining convention is the **statically\nchained route table**: every mounted route is one `.route()` link in a single expression in\n`src\u002Findex.ts`, and the type of that expression is exported as `AppType`.\n\nThe chain is what makes the api typed end to end. A client built with `hc\u003CAppType>` reads every\npath, request body, and per-status response shape straight off that type. A route discovered at\nbuild time by scanning a folder carries none of that, which is why registration is an edit to the\nchain rather than a file drop.\n\n## The entry, in shape\n\n```ts\n\u002F\u002F src\u002Findex.ts\nexport const base: Hono\u003C{ Bindings: Bindings; Variables: Variables }> = new Hono\u003C{\n  Bindings: Bindings;\n  Variables: Variables;\n}>()\n  .use(\"*\", cors({ \u002F* … *\u002F }))\n  .use(\"*\", requestCorrelation) \u002F\u002F binds c.get(\"log\") — see Logging, below\n  .onError((err, c) => { \u002F* every thrown error leaves as the error envelope *\u002F });\n\nconst app = base.route(\"\u002Fhealth\", health);\n\nexport type AppType = typeof app;\nexport default app;\n```\n\n`src\u002Findex.ts` is the Hono app and nothing else. The Worker entry is `src\u002Fworker.ts`, which is what `wrangler.jsonc`'s `main` points at:\n\n```ts\n\u002F\u002F src\u002Fworker.ts\nimport app from \".\u002Findex\";\n\nexport function defineWorker(config: WorkerConfig): ExportedHandler\u003Cnever> {\n  \u002F* folds every handler set's queue and scheduled hooks into one object *\u002F\n}\n\nexport const worker: ExportedHandler\u003Cnever> = defineWorker({\n  fetch: app.fetch,\n  handlers: [],\n});\n\nexport default worker;\n```\n\nTwo bindings, and the split between them is the point:\n\n- **`base`** carries app-wide middleware and anything whose routes must stay opaque to the\n  client, such as a catch-all auth handler. Its type annotation is written out on purpose. That\n  freezes `base` at `Hono\u003C{ Bindings: Bindings; Variables: Variables }>`, so mounting on it cannot widen `AppType`.\n- **`app`** is the typed chain. Everything a caller should see through `hc` goes here.\n\n**Keep every app-wide middleware as a link in `base`'s chain**, not as a `base.use(\"*\", …)`\nstatement underneath. A `chained-route` patch with `exportName: \"base\"` appends to that\ninitializer, and Hono runs the handlers a request matches in registration order. Written as a\nstatement, the middleware would register *after* the catch-all it is meant to wrap: `\u002Fauth`\nresponses would come back with no CORS headers, and `c.get(\"log\")` would be undefined inside that\nhandler.\n\n### `\u002Fauth` and `\u002Fadmin\u002Fauth` are the auth module's\n\nThe `auth` module mounts two catch-all forwards on `base`, one per Better Auth instance: `authRoute` at `\u002Fauth` for the client session and `adminAuthRoute` at `\u002Fadmin\u002Fauth` for the admin session. The second sits under `\u002Fadmin` on purpose, so one edge rule (WAF, Access, a log filter) covers the whole admin group. That makes `\u002Fadmin\u002Fauth\u002F*` a reserved prefix. Do not mount a route under it, and a middleware a project adds on `\u002Fadmin\u002F*` (an IP allowlist, an audit log, a session check) must skip `\u002Fadmin\u002Fauth\u002F*`, or the admin sign-in endpoint itself demands what it exists to hand out:\n\n```ts\n.use(\"\u002Fadmin\u002F*\", async (c, next) => {\n  if (c.req.path.startsWith(\"\u002Fadmin\u002Fauth\u002F\")) return next();\n  \u002F\u002F ... the project's own check\n  return next();\n})\n```\n\nAn `\u002Fadmin\u002F*` route that `admin` or another module registers on the typed chain (`GET \u002Fadmin\u002Fusers`) is a normal route and goes through such a middleware. See the `saasaloy-auth` skill for the two sessions and the `x-auth-audience` header.\n\n## Add a route\n\nTwo steps. The handler is still a file; only its registration changed.\n\n**1. Write `src\u002Froutes\u002F\u003Cfeature>.ts` as one chained expression**, under a named export that\nmatches the file:\n\n```ts\n\u002F\u002F src\u002Froutes\u002Fwidgets.ts  →  mounted at \u002Fwidgets\nimport { Hono } from \"hono\";\n\nexport const widgets = new Hono()\n  .get(\"\u002F\", (c) => c.json({ widgets: [] }, 200)) \u002F\u002F         GET  \u002Fwidgets\n  .post(\"\u002F\", (c) => c.json({ created: true }, 201)) \u002F\u002F      POST \u002Fwidgets\n  .get(\"\u002F:id\", (c) => c.json({ id: c.req.param(\"id\") }, 200)); \u002F\u002F GET \u002Fwidgets\u002F:id\n```\n\n**Named, not default.** The `chained-route` codemod writes a named import for the handler and\nrefuses to wire a link whose binding resolves to a default import, so `export default widgets`\nleaves the route unmountable by patch.\n\n**2. Add the link to the chain** in `src\u002Findex.ts`:\n\n```ts\nimport { widgets } from \".\u002Froutes\u002Fwidgets\";\n\nconst app = base.route(\"\u002Fhealth\", health).route(\"\u002Fwidgets\", widgets);\n```\n\nA module does step 2 through a **`chained-route` patch** in its `registry-item.json`, not by hand:\n\n```json\n{\n  \"kind\": \"chained-route\",\n  \"file\": \"apps\u002Fapi\u002Fsrc\u002Findex.ts\",\n  \"exportName\": \"default\",\n  \"path\": \"\u002Fwidgets\",\n  \"call\": \"widgets\",\n  \"import\": { \"name\": \"widgets\", \"from\": \".\u002Froutes\u002Fwidgets\" }\n}\n```\n\n`saasaloy add` appends the link and its import; `saasaloy remove` takes both back out, leaving the\nfile byte-identical to its pre-add state. `exportName: \"default\"` resolves through\n`export default app` to the `const app = …` declarator, so the chain is edited and the export line\nis untouched. Use `exportName: \"base\"` for a handler that must stay out of `AppType`.\n\n### Keep the chain unbroken\n\nThe chain is a type, not a style. These two are not equivalent:\n\n```ts\nconst widgets = new Hono().get(\"\u002F\", handler); \u002F\u002F ✅ the type carries GET \u002Fwidgets\n```\n\n```ts\nconst widgets = new Hono();\nwidgets.get(\"\u002F\", handler); \u002F\u002F ❌ `typeof widgets` forgot the route\n```\n\nThe second form still serves the request at runtime and still typechecks. It just hands the\nclient an empty type, so `api.widgets.$get()` stops existing with no error anywhere in `apps\u002Fapi`.\nThe same holds in `src\u002Findex.ts`: a route mounted with a bare `app.route(...)` statement is\ninvisible to `AppType`.\n\n### Pass the status code explicitly\n\n`c.json(body, 200)` and `c.json(body)` differ on the client. `hc` keys the response type by status,\nso an omitted code leaves the caller with a looser type than the route actually has. Write the\ncode every time, on the success path as well as the error path.\n\n### The one rule that trips people up: paths are relative to the mount\n\nA route file is mounted at the `path` its chain link gives, so its internal paths are **relative to\nthat mount**:\n\n- `widgets.get(\"\u002F\")` → `GET \u002Fwidgets` ✅\n- `widgets.get(\"\u002Fwidgets\")` → `GET \u002Fwidgets\u002Fwidgets` ❌ (double prefix)\n\nName the Hono instance after the file (`const widgets = new Hono()`) so the file reads clearly.\nThe folder is **flat**, one level of `routes\u002F*.ts`. To nest, nest *inside* a sub-app\n(`.route(\"\u002Farchived\", archivedSub)`), not with subdirectories.\n\n## The typed client\n\n`apps\u002Fapi` exposes one type-only export, `@repo\u002Fapi\u002Fclient`, which re-exports `AppType` and\nnothing else. `package.json` maps it under a `types` condition alone, so there is no runtime entry\nand the Worker never enters a browser bundle.\n\nEach consumer owns its own three-line client:\n\n```ts\nimport { hc } from \"hono\u002Fclient\";\nimport type { AppType } from \"@repo\u002Fapi\u002Fclient\";\n\nconst api = hc\u003CAppType>(import.meta.env.PUBLIC_API_URL ?? \"http:\u002F\u002Flocalhost:4000\");\n\nconst res = await api.health.$get();\nconst body = await res.json(); \u002F\u002F { status: string }\n```\n\nA consumer needs `hono` and `@repo\u002Fapi` in its `package.json`. A module that adds a caller adds\nboth through `package-json-dependency` patches.\n\n### What a wide chain costs to typecheck\n\nMeasured 2026-08-28 on the reference dev box (6-core Intel Haswell container, Node 24.19.0,\nTypeScript 7.0.2), with 30 synthetic routes generated alongside `health`. Each synthetic route\nchains a `GET \u002F`, a `GET \u002F:id`, and a `zValidator(\"json\", …)` `POST \u002F`, so the numbers include zod\ninference rather than bare handlers.\n\n| What | 1 route | 31 routes |\n|---|---|---|\n| `apps\u002Fapi` alone (`tsc --noEmit`) | **0.59 s** | **1.02 s** |\n| Whole project (`pnpm exec turbo run typecheck --force`) | **6.6 s** | **7.2 s** |\n\nRoughly **14 ms per route**, and adding a file that calls `hc\u003CAppType>` against the 31-route chain\ncost nothing measurable on top (1.05 s). Reproduce it by generating the routes and their chain\nlinks in `apps\u002Fapi`, then timing `tsc --noEmit` in that workspace.\n\nSo a single shared `AppType` is the right default, and it stays right well past the route count any\nof these projects has. If a chain ever does get expensive, the mitigation is a **per-feature\nclient**: export a narrower type for one slice of the chain and point that feature's `hc` at it,\nrather than splitting the api. Reach for it on a measured number, not a hunch.\n\n## Bindings: use `c.env`, never `process.env`\n\nCloudflare bindings (D1, R2, KV, Queues, secrets) arrive on the Worker's `env` and are threaded\nthrough Hono context as `c.env`. Never reach for `process.env` — it doesn't exist on Workers.\n\n```ts\nconst app = new Hono\u003C{ Bindings: { DB: D1Database } }>();\napp.get(\"\u002F\", (c) => c.env.DB.prepare(\"select 1\").first());\n```\n\nBase `api` ships **zero bindings**. A capability or feature that needs one:\n\n1. **Patches `wrangler.jsonc`** to add its binding (via the jsonc-parser patch engine) — e.g. a\n   `d1_databases` entry from `database`, an `r2_buckets` entry from `storage`.\n2. **Extends the `Bindings` type** where its code reads the binding.\n\nAdding a binding is a structural edit to `api`'s scaffold, the same class of edit as adding a link\nto the chain.\n\nA nested binding is patched by the same `wrangler-binding` kind with a dotted `bindingType`. `queues.producers`, `queues.consumers` and `triggers.crons` all live under a parent object, so the patch names the full path; the engine creates the missing parent on `add` and takes it away again on `remove`, leaving the file byte-identical. There is no separate patch kind for it (ADR 0033).\n\n## The handler table: non-`fetch` exports register in `src\u002Fworker.ts`\n\nA Worker exports more than `fetch`. A queue consumer is a `queue` export, a Cron Trigger is a `scheduled` export, and both are the Worker's, not any one route's. They register in the `handlers` array in `src\u002Fworker.ts`, which is a registration table for the same reason the route chain is one: a table yields a type, and a `remove` that takes the line back out.\n\nA module that owns such an export ships a function returning a `HandlerSet`, then appends the call with a `plugin-array` patch:\n\n```jsonc\n{\n  \"kind\": \"plugin-array\",\n  \"file\": \"apps\u002Fapi\u002Fsrc\u002Fworker.ts\",\n  \"exportName\": \"worker\",\n  \"arrayProp\": \"handlers\",\n  \"call\": \"cloudflareQueueHandlers\",\n  \"import\": { \"name\": \"cloudflareQueueHandlers\", \"from\": \"@repo\u002Fqueue\u002Fproviders\u002Fcloudflare\" },\n}\n```\n\nFour rules hold here:\n\n- **The `import.from` is the package export, not a scaffold alias.** `apps\u002Fapi` reaches into another workspace, so the specifier is `@repo\u002Fqueue\u002Fproviders\u002Fcloudflare`, resolved by the `\".\u002Fproviders\u002F*\"` entry in `packages\u002Fqueue`'s `exports` map. `@queue` is a descriptor-target alias the CLI uses to place files; it is not a TypeScript path and does not resolve at runtime.\n- **`HandlerSet` is declared in `worker.ts`, not imported from a capability.** `api` depends on no capability, and every capability that registers a handler depends on `api`. An import the other way would invert that.\n- **`defineWorker` exports a hook only when a set declares it.** Cloudflare reads a `queue` export as a promise that the Worker consumes a queue, so an empty stub would claim a consumer that does not exist.\n- **The deploy tooling is not the registration path.** A provider patches `wrangler.jsonc` and `worker.ts` directly. `pnpm deploy:production` hands that config to `wrangler deploy` as it is, and wrangler creates the resources the bindings name.\n\n## Logging: `c.get(\"log\")`, never `console.log`\n\n`api` depends on `logger`, so every project gets `packages\u002Flogger` and the `logger-console`\nprovider from `saasaloy add api` — nothing to install, nothing to wire. `src\u002Findex.ts` mounts a\ncorrelation middleware right after CORS that binds a request id to a child logger and puts it on\nthe context:\n\n```ts\nconst requestId = c.req.header(\"cf-ray\") ?? crypto.randomUUID();\nc.set(\"log\", createLogger(c.env).child({ requestId }));\n```\n\nRead it in a route with `c.get(\"log\")`. Compose `LoggerVariables` into the sub-app's generic so\nit's typed — the same move `database` asks for with `DbBindings`, and for the same reason: a route\ncan't import the entry's types without creating a cycle.\n\n```ts\n\u002F\u002F src\u002Froutes\u002Fwidgets.ts\nimport { Hono } from \"hono\";\nimport type { LoggerVariables } from \"@repo\u002Flogger\";\n\nconst widgets = new Hono\u003C{ Variables: LoggerVariables }>().post(\"\u002F\", async (c) => {\n  const log = c.get(\"log\");\n  log.info(\"creating widget\", { plan: \"pro\" }); \u002F\u002F → one line, carrying this request's requestId\n  try {\n    \u002F\u002F …\n  } catch (err) {\n    log.error(\"widget creation failed\", { err }); \u002F\u002F `err` is serialized, not `{}`\n    throw err;\n  }\n  return c.json({ ok: true }, 201);\n});\n\nexport default widgets;\n```\n\nEvery line from one request shares its `requestId`, so a single query in Workers Logs reconstructs\nthe whole request. The message comes **first** and the structured data second — `log.info(msg,\nfields?)` — and the fields are what get indexed, so put values in `fields` rather than\ninterpolating them into the message.\n\n`createLogger(c.env)` (from `@repo\u002Flogger`) is the uncorrelated escape hatch for code that runs\noutside a request — a module-scope singleton, a scheduled handler, a queue consumer. Inside a\nroute, prefer `c.get(\"log\")`; a fresh `createLogger` there loses the request id.\n\n`LOG_LEVEL` sets the threshold (default `info`), and `wrangler.jsonc`'s `observability` block is\nwhat makes the output queryable in the dashboard — `head_sampling_rate` is its cost dial. The\n`saasaloy-logger` skill covers levels, redaction, reading logs, and writing another provider.\n\n## Request validation lives in `@repo\u002Fvalidators`\n\nA route does not define its own input shape inline. The schema belongs in `packages\u002Fvalidators`\n(`@repo\u002Fvalidators\u002F\u003Cfeature>`), which the `validators` capability scaffolds, and the route wraps it\nwith `zValidator` from `@hono\u002Fzod-validator`. `c.req.valid(\"json\")` then carries the inferred type\ninto the handler, with the target matching the one `zValidator` was given. Error bodies use the\nshared `{ error: { code, message } }` envelope from `@repo\u002Fvalidators\u002Fcommon`. See the\n`saasaloy-validators` skill for the full convention.\n\nKeep the three layers apart: request shapes in `@repo\u002Fvalidators`, database column shapes in\n`packages\u002Fdb`, HTTP wiring here in `apps\u002Fapi`.\n\nOn an admin route, `adminGate` from `@repo\u002Fauth\u002Fserver` goes before the validator: `.put(\"\u002F:key\", adminGate, validateValue, handler)`. Hono runs the handlers in the order they are listed, so a validator listed first answers a caller with no session with a 400 that names the rejected field. With the gate first, that caller gets a 401 whatever the body says. The handler still calls `requireAdmin` for the session value. The `admin` module's `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-gate.test.ts` checks every `\u002Fadmin\u002F*` route for this; see the `saasaloy-admin` skill.\n\n## Errors: one envelope, including the ones you did not throw\n\n`base` ends in an `onError` handler, and it is there because a route cannot cover every error it\nanswers with. A `zValidator` failure hook returns the envelope for a body that *parses* and fails\nthe schema. A body that does not parse never reaches the hook: Hono's json validator throws\n`HTTPException(400, \"Malformed JSON in request body\")` first, and an unhandled `HTTPException`\nanswers as **plain text**. That is a second 400 shape behind one declared type, and `hc` publishes\nonly the first — a caller branching on `res.status === 400` and calling `res.json()` would throw.\n\nThe handler converts every `HTTPException` to `{ error: { code, message } }` with the status it\ncarried, and any other throw to a 500 with a fixed message (the real error goes to `console.error`,\nbecause it can carry a binding value or a query). A sub-app mounted with `.route()` inherits the\nhandler, so a route module writes no error plumbing of its own.\n\n`apps\u002Fapi` writes the envelope out by hand instead of importing `errorBody` from\n`@repo\u002Fvalidators\u002Fcommon`, because `validators` declares `dependsOn: [\"api\"]` — the dependency runs\none way. The two shapes are identical and each names the other. Change one, change the other.\n\nA handler that *returns* a response is untouched by `onError`; only throws land there.\n\nA miss has its own slot. `base` also ends in a `notFound` handler, and it answers the same\nenvelope with status 404 and code `not_found`, so a caller parses one body shape for every failure\nthis api can produce. A wrong method on a real path answers 404 too, not 405: Hono matches on the\n(method, path) pair, so `POST \u002Fhealth` matches nothing, and distinguishing the two would tell an\nunauthenticated caller which paths exist.\n\nA feature module inherits that handler and **must not register a second one**. `notFound`, like\n`onError`, is a single slot: a sub-app mounted with `.route()` uses `base`'s handler as long as it\nsets none of its own, and a `notFound` on your own sub-app takes over every miss under its mount\nfor no gain. Nothing in a route module needs miss plumbing.\n\nOne mount is outside all of this, and it is worth knowing before you test a miss. A sub-app that\nmounts a catch-all answers every path under its prefix itself, so nothing under that prefix is ever\na Hono miss and `base`'s `notFound` never runs there. The `auth` module is the case in the base: it mounts `.on([\"GET\", \"POST\"], \"\u002F*\", ...)` at `\u002Fauth` and again at `\u002Fadmin\u002Fauth`, and hands each subtree to better-auth, so `GET \u002Fauth\u002Fnope` and `GET \u002Fadmin\u002Fauth\u002Fnope` come back as a bare 404 with an empty body rather than the envelope. Every other\nmount answers the envelope on a miss.\n\n## Run it locally\n\n```sh\npnpm --filter @repo\u002Fapi dev       # vite dev → serves on workerd, hot-reloads routes\ncurl http:\u002F\u002Flocalhost:4000\u002Fhealth # → {\"status\":\"ok\"}\n```\n\n`vite dev` runs the actual Workers runtime, so local behavior matches the edge closely. Editing a\nroute file is picked up on the next request with no restart.\n\n## Test it: Vitest in Node\n\n`pnpm test` from the repo root runs the api's tests with Vitest, in Node rather than in workerd. Put a `*.test.ts` file beside the route, or under `apps\u002Fapi\u002Ftest\u002F`, and call the app directly:\n\n```ts\nimport { describe, expect, it } from \"vitest\";\nimport app from \"..\u002Findex\";\n\ndescribe(\"GET \u002Fhealth\", () => {\n  it(\"answers\", async () => {\n    const res = await app.request(\"\u002Fhealth\", {}, {});\n    expect(res.status).toBe(200);\n  });\n});\n```\n\nThe third argument to `app.request` is `c.env` for that request, so the test decides every binding. `apps\u002Fapi\u002Fvitest.config.ts` is what makes this work, and it is why Vitest never reads `vite.config.ts`, whose Cloudflare plugin would boot the whole Worker first:\n\n- **`cloudflare:workers` resolves to `test\u002Fcloudflare-workers.ts`.** Code that imports `env` from it at module scope, such as Better Auth's options in `@repo\u002Fauth`, loads unchanged. The stand-in's `env` holds the values in `apps\u002Fapi\u002F.env`, so run `pnpm env:setup` when a test fails on a missing key.\n- **Every file in `test\u002Fsetup\u002F` is a Vitest global setup**, run once per `pnpm test`. A module drops one there rather than editing the config. The database driver ships `test\u002Fsetup\u002Fdatabase.ts`, which prepares a seeded test database; read the driver skill's \"Route tests\" section for `testDatabase()`, the helper a route test that touches the database uses.\n\nDo not add a `test` script to `apps\u002Fapi\u002Fpackage.json`: the root `vitest.config.ts` already runs this workspace, and a second script would run every file twice.\n\n## Ports are fixed, on purpose\n\n| Service | Port | Pinned in |\n|---|---|---|\n| `apps\u002Fweb` (Astro) | **3000** | `astro.config.mjs` (`server.port` + `vite.server.strictPort`) |\n| `apps\u002Fadmin` (Vite SPA) | **3001** | `vite.config.ts` (`server.port` + `strictPort`), allowlisted in `DEV_ORIGINS` |\n| `apps\u002Fapp` (Vite SPA) | **3002** | `vite.config.ts` (`server.port` + `strictPort`), allowlisted in `DEV_ORIGINS` |\n| `apps\u002Fapi` (Worker) | **4000** | `vite.config.ts` (`server.port` + `strictPort`) and `wrangler.jsonc` (`dev.port`) |\n\nFrontends take 3xxx, backends 4xxx. These aren't cosmetic: `DEV_ORIGINS` in `src\u002Findex.ts` (and\n`auth`'s `trustedOrigins`, and `waitlist`'s `PUBLIC_API_URL` fallback) hardcode them as the\nkeyless dev fallback, so a drifting port turns into a CORS rejection that looks like a code bug.\n`strictPort` makes a busy port fail loudly instead of quietly shifting to the next one.\n\nBecause `wrangler.jsonc` pins the same `4000`, `wrangler dev` is a drop-in swap for the Vite loop.\n\n## CORS lives here, in the spine\n\n`src\u002Findex.ts` mounts credentialed `hono\u002Fcors` on `base` for the whole app: the `origin` callback\nreflects the caller's origin only if it's in `CORS_ORIGINS` (comma-separated) or, when that's\nunset, in `DEV_ORIGINS`. It never answers `*`, because `credentials: true` and `*` are\nincompatible.\n\n`cors()` sets no `allowHeaders`, so a preflight's `Access-Control-Request-Headers` is echoed back. That is what lets the admin app send `x-auth-audience: admin` with no CORS change. Keep it that way, or add `x-auth-audience` to the list if you ever pin `allowHeaders`.\n\n**Keep `server.cors: false` in `vite.config.ts`.** Vite's own dev CORS middleware otherwise\nintercepts CORS in two ways that both mislead: it reflects `Access-Control-Allow-Origin` for\n*every* loopback origin (Vite 8's default `server.cors.origin` is a localhost regex), so a\ndisallowed `http:\u002F\u002Flocalhost:9999` looks allowed; and it **terminates every `OPTIONS` preflight\nitself** without emitting `Access-Control-Allow-Credentials`, which breaks any\n`credentials: \"include\"` fetch under `vite dev` while the identical request works under\n`wrangler dev`. With the middleware off, `hono\u002Fcors` is the only responder and both dev paths\nagree.\n\n```sh\ncurl -i -H 'Origin: http:\u002F\u002Flocalhost:3000' http:\u002F\u002Flocalhost:4000\u002Fhealth # → header reflected\ncurl -i -H 'Origin: http:\u002F\u002Flocalhost:9999' http:\u002F\u002Flocalhost:4000\u002Fhealth # → no ACAO header\n```\n\n## Deploy\n\n`pnpm deploy:production` at the repository root deploys this Worker with every other one. Its\n`deploy` script is `env-deploy api`: it loads the `api` service's production values and the\nCloudflare credentials from the value source, builds with them, and runs `wrangler deploy\n--secrets-file`, so the secrets land in the same Worker version as the code. A key the\n`wrangler.jsonc` `vars` block already sets stays a plain var and is not sent as a secret.\n\nThe api deploys first. `saasaloy add api` appends `{ service: \"api\", order: 10 }` to `DEPLOY_TARGETS` in `packages\u002Ftooling\u002Fsrc\u002Ftargets.ts`, so a frontend never goes live ahead of the route it calls. It also appends the `api-health` smoke check: `GET \u002Fhealth` must answer 200 with `\"ok\"` in the body. The check runs only once `apps\u002Fapi\u002Fwrangler.jsonc` has a `routes[]` entry with `custom_domain: true`, and the dry run says so while it has none. `pnpm deploy:production --only api` deploys this Worker alone after the gates, and writes no deploy tag. Do not deploy it with `pnpm --filter @repo\u002Fapi run deploy`, which skips the gates and the smoke checks. No deploy migrates the database unless you pass `--migrate`. See the `saasaloy-deploy` and `saasaloy-env` skills.\n\n## Conventions to honor\n\n- **Register a route with a `chained-route` patch**, not a file drop. The entry is edited on\n  purpose, and `saasaloy remove` reverses the edit.\n- **Build every sub-app as one unbroken chain.** A statement-per-route file typechecks and serves\n  correctly while handing the client an empty type.\n- **Pass the status code to `c.json`** on every path, success included.\n- **One route file = one mounted prefix**, named after the file, under a named `export const`.\n  Keep the folder flat.\n- **Internal paths are mount-relative** (`get(\"\u002F\")` for the index of the mount).\n- **Mount on `base`, not on the chain**, when a handler must stay out of `AppType`.\n- **`c.env` for bindings, never `process.env`.**\n- **`c.get(\"log\")` for logging, never `console.log`** — a bare console call is unlevelled and\n  uncorrelated, and it bypasses redaction.\n- **Inherit `base`'s `onError` and `notFound`.** A feature module registers neither of its own; a\n  miss under a normally mounted sub-app already answers the 404 envelope. A mount with a catch-all\n  route (`auth` at `\u002Fauth` and `\u002Fadmin\u002Fauth`) answers its own misses and never reaches that handler.\n- **`\u002Fadmin\u002Fauth\u002F*` is reserved for the admin auth instance.** Mount nothing under it, and make any `\u002Fadmin\u002F*` middleware skip it.\n- **A new binding patches `wrangler.jsonc`**; it does not hand-edit another module's files.\n- **Request validation belongs in `@repo\u002Fvalidators`**, not in an inline schema in the route.\n- **Test a route in Node with `app.request(path, init, env)`.** A setup step goes in `test\u002Fsetup\u002F`, not in `vitest.config.ts`.\n\n## Next\n\nRun `saasaloy-app` to add the customer screens that call these routes, or `saasaloy-admin` for staff screens.\n","# api — Hono on Cloudflare Workers\n\n`apps\u002Fapi` is the backend spine, shared by `web` and `admin`. It's a [Hono](https:\u002F\u002Fhono.dev)\napp running on Cloudflare Workers, built and served with Vite via `@cloudflare\u002Fvite-plugin` (so\n`vite dev` runs the real `workerd` runtime locally). Its defining convention is the **statically\nchained route table**: every mounted route is one `.route()` link in a single expression in\n`src\u002Findex.ts`, and the type of that expression is exported as `AppType`.\n\nThe chain is what makes the api typed end to end. A client built with `hc\u003CAppType>` reads every\npath, request body, and per-status response shape straight off that type. A route discovered at\nbuild time by scanning a folder carries none of that, which is why registration is an edit to the\nchain rather than a file drop.\n\n## The entry, in shape\n\n```ts\n\u002F\u002F src\u002Findex.ts\nexport const base: Hono\u003C{ Bindings: Bindings; Variables: Variables }> = new Hono\u003C{\n  Bindings: Bindings;\n  Variables: Variables;\n}>()\n  .use(\"*\", cors({ \u002F* … *\u002F }))\n  .use(\"*\", requestCorrelation) \u002F\u002F binds c.get(\"log\") — see Logging, below\n  .onError((err, c) => { \u002F* every thrown error leaves as the error envelope *\u002F });\n\nconst app = base.route(\"\u002Fhealth\", health);\n\nexport type AppType = typeof app;\nexport default app;\n```\n\n`src\u002Findex.ts` is the Hono app and nothing else. The Worker entry is `src\u002Fworker.ts`, which is what `wrangler.jsonc`'s `main` points at:\n\n```ts\n\u002F\u002F src\u002Fworker.ts\nimport app from \".\u002Findex\";\n\nexport function defineWorker(config: WorkerConfig): ExportedHandler\u003Cnever> {\n  \u002F* folds every handler set's queue and scheduled hooks into one object *\u002F\n}\n\nexport const worker: ExportedHandler\u003Cnever> = defineWorker({\n  fetch: app.fetch,\n  handlers: [],\n});\n\nexport default worker;\n```\n\nTwo bindings, and the split between them is the point:\n\n- **`base`** carries app-wide middleware and anything whose routes must stay opaque to the\n  client, such as a catch-all auth handler. Its type annotation is written out on purpose. That\n  freezes `base` at `Hono\u003C{ Bindings: Bindings; Variables: Variables }>`, so mounting on it cannot widen `AppType`.\n- **`app`** is the typed chain. Everything a caller should see through `hc` goes here.\n\n**Keep every app-wide middleware as a link in `base`'s chain**, not as a `base.use(\"*\", …)`\nstatement underneath. A `chained-route` patch with `exportName: \"base\"` appends to that\ninitializer, and Hono runs the handlers a request matches in registration order. Written as a\nstatement, the middleware would register *after* the catch-all it is meant to wrap: `\u002Fauth`\nresponses would come back with no CORS headers, and `c.get(\"log\")` would be undefined inside that\nhandler.\n\n### `\u002Fauth` and `\u002Fadmin\u002Fauth` are the auth module's\n\nThe `auth` module mounts two catch-all forwards on `base`, one per Better Auth instance: `authRoute` at `\u002Fauth` for the client session and `adminAuthRoute` at `\u002Fadmin\u002Fauth` for the admin session. The second sits under `\u002Fadmin` on purpose, so one edge rule (WAF, Access, a log filter) covers the whole admin group. That makes `\u002Fadmin\u002Fauth\u002F*` a reserved prefix. Do not mount a route under it, and a middleware a project adds on `\u002Fadmin\u002F*` (an IP allowlist, an audit log, a session check) must skip `\u002Fadmin\u002Fauth\u002F*`, or the admin sign-in endpoint itself demands what it exists to hand out:\n\n```ts\n.use(\"\u002Fadmin\u002F*\", async (c, next) => {\n  if (c.req.path.startsWith(\"\u002Fadmin\u002Fauth\u002F\")) return next();\n  \u002F\u002F ... the project's own check\n  return next();\n})\n```\n\nAn `\u002Fadmin\u002F*` route that `admin` or another module registers on the typed chain (`GET \u002Fadmin\u002Fusers`) is a normal route and goes through such a middleware. See the `saasaloy-auth` skill for the two sessions and the `x-auth-audience` header.\n\n## Add a route\n\nTwo steps. The handler is still a file; only its registration changed.\n\n**1. Write `src\u002Froutes\u002F\u003Cfeature>.ts` as one chained expression**, under a named export that\nmatches the file:\n\n```ts\n\u002F\u002F src\u002Froutes\u002Fwidgets.ts  →  mounted at \u002Fwidgets\nimport { Hono } from \"hono\";\n\nexport const widgets = new Hono()\n  .get(\"\u002F\", (c) => c.json({ widgets: [] }, 200)) \u002F\u002F         GET  \u002Fwidgets\n  .post(\"\u002F\", (c) => c.json({ created: true }, 201)) \u002F\u002F      POST \u002Fwidgets\n  .get(\"\u002F:id\", (c) => c.json({ id: c.req.param(\"id\") }, 200)); \u002F\u002F GET \u002Fwidgets\u002F:id\n```\n\n**Named, not default.** The `chained-route` codemod writes a named import for the handler and\nrefuses to wire a link whose binding resolves to a default import, so `export default widgets`\nleaves the route unmountable by patch.\n\n**2. Add the link to the chain** in `src\u002Findex.ts`:\n\n```ts\nimport { widgets } from \".\u002Froutes\u002Fwidgets\";\n\nconst app = base.route(\"\u002Fhealth\", health).route(\"\u002Fwidgets\", widgets);\n```\n\nA module does step 2 through a **`chained-route` patch** in its `registry-item.json`, not by hand:\n\n```json\n{\n  \"kind\": \"chained-route\",\n  \"file\": \"apps\u002Fapi\u002Fsrc\u002Findex.ts\",\n  \"exportName\": \"default\",\n  \"path\": \"\u002Fwidgets\",\n  \"call\": \"widgets\",\n  \"import\": { \"name\": \"widgets\", \"from\": \".\u002Froutes\u002Fwidgets\" }\n}\n```\n\n`saasaloy add` appends the link and its import; `saasaloy remove` takes both back out, leaving the\nfile byte-identical to its pre-add state. `exportName: \"default\"` resolves through\n`export default app` to the `const app = …` declarator, so the chain is edited and the export line\nis untouched. Use `exportName: \"base\"` for a handler that must stay out of `AppType`.\n\n### Keep the chain unbroken\n\nThe chain is a type, not a style. These two are not equivalent:\n\n```ts\nconst widgets = new Hono().get(\"\u002F\", handler); \u002F\u002F ✅ the type carries GET \u002Fwidgets\n```\n\n```ts\nconst widgets = new Hono();\nwidgets.get(\"\u002F\", handler); \u002F\u002F ❌ `typeof widgets` forgot the route\n```\n\nThe second form still serves the request at runtime and still typechecks. It just hands the\nclient an empty type, so `api.widgets.$get()` stops existing with no error anywhere in `apps\u002Fapi`.\nThe same holds in `src\u002Findex.ts`: a route mounted with a bare `app.route(...)` statement is\ninvisible to `AppType`.\n\n### Pass the status code explicitly\n\n`c.json(body, 200)` and `c.json(body)` differ on the client. `hc` keys the response type by status,\nso an omitted code leaves the caller with a looser type than the route actually has. Write the\ncode every time, on the success path as well as the error path.\n\n### The one rule that trips people up: paths are relative to the mount\n\nA route file is mounted at the `path` its chain link gives, so its internal paths are **relative to\nthat mount**:\n\n- `widgets.get(\"\u002F\")` → `GET \u002Fwidgets` ✅\n- `widgets.get(\"\u002Fwidgets\")` → `GET \u002Fwidgets\u002Fwidgets` ❌ (double prefix)\n\nName the Hono instance after the file (`const widgets = new Hono()`) so the file reads clearly.\nThe folder is **flat**, one level of `routes\u002F*.ts`. To nest, nest *inside* a sub-app\n(`.route(\"\u002Farchived\", archivedSub)`), not with subdirectories.\n\n## The typed client\n\n`apps\u002Fapi` exposes one type-only export, `@repo\u002Fapi\u002Fclient`, which re-exports `AppType` and\nnothing else. `package.json` maps it under a `types` condition alone, so there is no runtime entry\nand the Worker never enters a browser bundle.\n\nEach consumer owns its own three-line client:\n\n```ts\nimport { hc } from \"hono\u002Fclient\";\nimport type { AppType } from \"@repo\u002Fapi\u002Fclient\";\n\nconst api = hc\u003CAppType>(import.meta.env.PUBLIC_API_URL ?? \"http:\u002F\u002Flocalhost:4000\");\n\nconst res = await api.health.$get();\nconst body = await res.json(); \u002F\u002F { status: string }\n```\n\nA consumer needs `hono` and `@repo\u002Fapi` in its `package.json`. A module that adds a caller adds\nboth through `package-json-dependency` patches.\n\n### What a wide chain costs to typecheck\n\nMeasured 2026-08-28 on the reference dev box (6-core Intel Haswell container, Node 24.19.0,\nTypeScript 7.0.2), with 30 synthetic routes generated alongside `health`. Each synthetic route\nchains a `GET \u002F`, a `GET \u002F:id`, and a `zValidator(\"json\", …)` `POST \u002F`, so the numbers include zod\ninference rather than bare handlers.\n\n| What | 1 route | 31 routes |\n|---|---|---|\n| `apps\u002Fapi` alone (`tsc --noEmit`) | **0.59 s** | **1.02 s** |\n| Whole project (`pnpm exec turbo run typecheck --force`) | **6.6 s** | **7.2 s** |\n\nRoughly **14 ms per route**, and adding a file that calls `hc\u003CAppType>` against the 31-route chain\ncost nothing measurable on top (1.05 s). Reproduce it by generating the routes and their chain\nlinks in `apps\u002Fapi`, then timing `tsc --noEmit` in that workspace.\n\nSo a single shared `AppType` is the right default, and it stays right well past the route count any\nof these projects has. If a chain ever does get expensive, the mitigation is a **per-feature\nclient**: export a narrower type for one slice of the chain and point that feature's `hc` at it,\nrather than splitting the api. Reach for it on a measured number, not a hunch.\n\n## Bindings: use `c.env`, never `process.env`\n\nCloudflare bindings (D1, R2, KV, Queues, secrets) arrive on the Worker's `env` and are threaded\nthrough Hono context as `c.env`. Never reach for `process.env` — it doesn't exist on Workers.\n\n```ts\nconst app = new Hono\u003C{ Bindings: { DB: D1Database } }>();\napp.get(\"\u002F\", (c) => c.env.DB.prepare(\"select 1\").first());\n```\n\nBase `api` ships **zero bindings**. A capability or feature that needs one:\n\n1. **Patches `wrangler.jsonc`** to add its binding (via the jsonc-parser patch engine) — e.g. a\n   `d1_databases` entry from `database`, an `r2_buckets` entry from `storage`.\n2. **Extends the `Bindings` type** where its code reads the binding.\n\nAdding a binding is a structural edit to `api`'s scaffold, the same class of edit as adding a link\nto the chain.\n\nA nested binding is patched by the same `wrangler-binding` kind with a dotted `bindingType`. `queues.producers`, `queues.consumers` and `triggers.crons` all live under a parent object, so the patch names the full path; the engine creates the missing parent on `add` and takes it away again on `remove`, leaving the file byte-identical. There is no separate patch kind for it (ADR 0033).\n\n## The handler table: non-`fetch` exports register in `src\u002Fworker.ts`\n\nA Worker exports more than `fetch`. A queue consumer is a `queue` export, a Cron Trigger is a `scheduled` export, and both are the Worker's, not any one route's. They register in the `handlers` array in `src\u002Fworker.ts`, which is a registration table for the same reason the route chain is one: a table yields a type, and a `remove` that takes the line back out.\n\nA module that owns such an export ships a function returning a `HandlerSet`, then appends the call with a `plugin-array` patch:\n\n```jsonc\n{\n  \"kind\": \"plugin-array\",\n  \"file\": \"apps\u002Fapi\u002Fsrc\u002Fworker.ts\",\n  \"exportName\": \"worker\",\n  \"arrayProp\": \"handlers\",\n  \"call\": \"cloudflareQueueHandlers\",\n  \"import\": { \"name\": \"cloudflareQueueHandlers\", \"from\": \"@repo\u002Fqueue\u002Fproviders\u002Fcloudflare\" },\n}\n```\n\nFour rules hold here:\n\n- **The `import.from` is the package export, not a scaffold alias.** `apps\u002Fapi` reaches into another workspace, so the specifier is `@repo\u002Fqueue\u002Fproviders\u002Fcloudflare`, resolved by the `\".\u002Fproviders\u002F*\"` entry in `packages\u002Fqueue`'s `exports` map. `@queue` is a descriptor-target alias the CLI uses to place files; it is not a TypeScript path and does not resolve at runtime.\n- **`HandlerSet` is declared in `worker.ts`, not imported from a capability.** `api` depends on no capability, and every capability that registers a handler depends on `api`. An import the other way would invert that.\n- **`defineWorker` exports a hook only when a set declares it.** Cloudflare reads a `queue` export as a promise that the Worker consumes a queue, so an empty stub would claim a consumer that does not exist.\n- **The deploy tooling is not the registration path.** A provider patches `wrangler.jsonc` and `worker.ts` directly. `pnpm deploy:production` hands that config to `wrangler deploy` as it is, and wrangler creates the resources the bindings name.\n\n## Logging: `c.get(\"log\")`, never `console.log`\n\n`api` depends on `logger`, so every project gets `packages\u002Flogger` and the `logger-console`\nprovider from `saasaloy add api` — nothing to install, nothing to wire. `src\u002Findex.ts` mounts a\ncorrelation middleware right after CORS that binds a request id to a child logger and puts it on\nthe context:\n\n```ts\nconst requestId = c.req.header(\"cf-ray\") ?? crypto.randomUUID();\nc.set(\"log\", createLogger(c.env).child({ requestId }));\n```\n\nRead it in a route with `c.get(\"log\")`. Compose `LoggerVariables` into the sub-app's generic so\nit's typed — the same move `database` asks for with `DbBindings`, and for the same reason: a route\ncan't import the entry's types without creating a cycle.\n\n```ts\n\u002F\u002F src\u002Froutes\u002Fwidgets.ts\nimport { Hono } from \"hono\";\nimport type { LoggerVariables } from \"@repo\u002Flogger\";\n\nconst widgets = new Hono\u003C{ Variables: LoggerVariables }>().post(\"\u002F\", async (c) => {\n  const log = c.get(\"log\");\n  log.info(\"creating widget\", { plan: \"pro\" }); \u002F\u002F → one line, carrying this request's requestId\n  try {\n    \u002F\u002F …\n  } catch (err) {\n    log.error(\"widget creation failed\", { err }); \u002F\u002F `err` is serialized, not `{}`\n    throw err;\n  }\n  return c.json({ ok: true }, 201);\n});\n\nexport default widgets;\n```\n\nEvery line from one request shares its `requestId`, so a single query in Workers Logs reconstructs\nthe whole request. The message comes **first** and the structured data second — `log.info(msg,\nfields?)` — and the fields are what get indexed, so put values in `fields` rather than\ninterpolating them into the message.\n\n`createLogger(c.env)` (from `@repo\u002Flogger`) is the uncorrelated escape hatch for code that runs\noutside a request — a module-scope singleton, a scheduled handler, a queue consumer. Inside a\nroute, prefer `c.get(\"log\")`; a fresh `createLogger` there loses the request id.\n\n`LOG_LEVEL` sets the threshold (default `info`), and `wrangler.jsonc`'s `observability` block is\nwhat makes the output queryable in the dashboard — `head_sampling_rate` is its cost dial. The\n`saasaloy-logger` skill covers levels, redaction, reading logs, and writing another provider.\n\n## Request validation lives in `@repo\u002Fvalidators`\n\nA route does not define its own input shape inline. The schema belongs in `packages\u002Fvalidators`\n(`@repo\u002Fvalidators\u002F\u003Cfeature>`), which the `validators` capability scaffolds, and the route wraps it\nwith `zValidator` from `@hono\u002Fzod-validator`. `c.req.valid(\"json\")` then carries the inferred type\ninto the handler, with the target matching the one `zValidator` was given. Error bodies use the\nshared `{ error: { code, message } }` envelope from `@repo\u002Fvalidators\u002Fcommon`. See the\n`saasaloy-validators` skill for the full convention.\n\nKeep the three layers apart: request shapes in `@repo\u002Fvalidators`, database column shapes in\n`packages\u002Fdb`, HTTP wiring here in `apps\u002Fapi`.\n\nOn an admin route, `adminGate` from `@repo\u002Fauth\u002Fserver` goes before the validator: `.put(\"\u002F:key\", adminGate, validateValue, handler)`. Hono runs the handlers in the order they are listed, so a validator listed first answers a caller with no session with a 400 that names the rejected field. With the gate first, that caller gets a 401 whatever the body says. The handler still calls `requireAdmin` for the session value. The `admin` module's `apps\u002Fapi\u002Fsrc\u002Froutes\u002Fadmin-gate.test.ts` checks every `\u002Fadmin\u002F*` route for this; see the `saasaloy-admin` skill.\n\n## Errors: one envelope, including the ones you did not throw\n\n`base` ends in an `onError` handler, and it is there because a route cannot cover every error it\nanswers with. A `zValidator` failure hook returns the envelope for a body that *parses* and fails\nthe schema. A body that does not parse never reaches the hook: Hono's json validator throws\n`HTTPException(400, \"Malformed JSON in request body\")` first, and an unhandled `HTTPException`\nanswers as **plain text**. That is a second 400 shape behind one declared type, and `hc` publishes\nonly the first — a caller branching on `res.status === 400` and calling `res.json()` would throw.\n\nThe handler converts every `HTTPException` to `{ error: { code, message } }` with the status it\ncarried, and any other throw to a 500 with a fixed message (the real error goes to `console.error`,\nbecause it can carry a binding value or a query). A sub-app mounted with `.route()` inherits the\nhandler, so a route module writes no error plumbing of its own.\n\n`apps\u002Fapi` writes the envelope out by hand instead of importing `errorBody` from\n`@repo\u002Fvalidators\u002Fcommon`, because `validators` declares `dependsOn: [\"api\"]` — the dependency runs\none way. The two shapes are identical and each names the other. Change one, change the other.\n\nA handler that *returns* a response is untouched by `onError`; only throws land there.\n\nA miss has its own slot. `base` also ends in a `notFound` handler, and it answers the same\nenvelope with status 404 and code `not_found`, so a caller parses one body shape for every failure\nthis api can produce. A wrong method on a real path answers 404 too, not 405: Hono matches on the\n(method, path) pair, so `POST \u002Fhealth` matches nothing, and distinguishing the two would tell an\nunauthenticated caller which paths exist.\n\nA feature module inherits that handler and **must not register a second one**. `notFound`, like\n`onError`, is a single slot: a sub-app mounted with `.route()` uses `base`'s handler as long as it\nsets none of its own, and a `notFound` on your own sub-app takes over every miss under its mount\nfor no gain. Nothing in a route module needs miss plumbing.\n\nOne mount is outside all of this, and it is worth knowing before you test a miss. A sub-app that\nmounts a catch-all answers every path under its prefix itself, so nothing under that prefix is ever\na Hono miss and `base`'s `notFound` never runs there. The `auth` module is the case in the base: it mounts `.on([\"GET\", \"POST\"], \"\u002F*\", ...)` at `\u002Fauth` and again at `\u002Fadmin\u002Fauth`, and hands each subtree to better-auth, so `GET \u002Fauth\u002Fnope` and `GET \u002Fadmin\u002Fauth\u002Fnope` come back as a bare 404 with an empty body rather than the envelope. Every other\nmount answers the envelope on a miss.\n\n## Run it locally\n\n```sh\npnpm --filter @repo\u002Fapi dev       # vite dev → serves on workerd, hot-reloads routes\ncurl http:\u002F\u002Flocalhost:4000\u002Fhealth # → {\"status\":\"ok\"}\n```\n\n`vite dev` runs the actual Workers runtime, so local behavior matches the edge closely. Editing a\nroute file is picked up on the next request with no restart.\n\n## Test it: Vitest in Node\n\n`pnpm test` from the repo root runs the api's tests with Vitest, in Node rather than in workerd. Put a `*.test.ts` file beside the route, or under `apps\u002Fapi\u002Ftest\u002F`, and call the app directly:\n\n```ts\nimport { describe, expect, it } from \"vitest\";\nimport app from \"..\u002Findex\";\n\ndescribe(\"GET \u002Fhealth\", () => {\n  it(\"answers\", async () => {\n    const res = await app.request(\"\u002Fhealth\", {}, {});\n    expect(res.status).toBe(200);\n  });\n});\n```\n\nThe third argument to `app.request` is `c.env` for that request, so the test decides every binding. `apps\u002Fapi\u002Fvitest.config.ts` is what makes this work, and it is why Vitest never reads `vite.config.ts`, whose Cloudflare plugin would boot the whole Worker first:\n\n- **`cloudflare:workers` resolves to `test\u002Fcloudflare-workers.ts`.** Code that imports `env` from it at module scope, such as Better Auth's options in `@repo\u002Fauth`, loads unchanged. The stand-in's `env` holds the values in `apps\u002Fapi\u002F.env`, so run `pnpm env:setup` when a test fails on a missing key.\n- **Every file in `test\u002Fsetup\u002F` is a Vitest global setup**, run once per `pnpm test`. A module drops one there rather than editing the config. The database driver ships `test\u002Fsetup\u002Fdatabase.ts`, which prepares a seeded test database; read the driver skill's \"Route tests\" section for `testDatabase()`, the helper a route test that touches the database uses.\n\nDo not add a `test` script to `apps\u002Fapi\u002Fpackage.json`: the root `vitest.config.ts` already runs this workspace, and a second script would run every file twice.\n\n## Ports are fixed, on purpose\n\n| Service | Port | Pinned in |\n|---|---|---|\n| `apps\u002Fweb` (Astro) | **3000** | `astro.config.mjs` (`server.port` + `vite.server.strictPort`) |\n| `apps\u002Fadmin` (Vite SPA) | **3001** | `vite.config.ts` (`server.port` + `strictPort`), allowlisted in `DEV_ORIGINS` |\n| `apps\u002Fapp` (Vite SPA) | **3002** | `vite.config.ts` (`server.port` + `strictPort`), allowlisted in `DEV_ORIGINS` |\n| `apps\u002Fapi` (Worker) | **4000** | `vite.config.ts` (`server.port` + `strictPort`) and `wrangler.jsonc` (`dev.port`) |\n\nFrontends take 3xxx, backends 4xxx. These aren't cosmetic: `DEV_ORIGINS` in `src\u002Findex.ts` (and\n`auth`'s `trustedOrigins`, and `waitlist`'s `PUBLIC_API_URL` fallback) hardcode them as the\nkeyless dev fallback, so a drifting port turns into a CORS rejection that looks like a code bug.\n`strictPort` makes a busy port fail loudly instead of quietly shifting to the next one.\n\nBecause `wrangler.jsonc` pins the same `4000`, `wrangler dev` is a drop-in swap for the Vite loop.\n\n## CORS lives here, in the spine\n\n`src\u002Findex.ts` mounts credentialed `hono\u002Fcors` on `base` for the whole app: the `origin` callback\nreflects the caller's origin only if it's in `CORS_ORIGINS` (comma-separated) or, when that's\nunset, in `DEV_ORIGINS`. It never answers `*`, because `credentials: true` and `*` are\nincompatible.\n\n`cors()` sets no `allowHeaders`, so a preflight's `Access-Control-Request-Headers` is echoed back. That is what lets the admin app send `x-auth-audience: admin` with no CORS change. Keep it that way, or add `x-auth-audience` to the list if you ever pin `allowHeaders`.\n\n**Keep `server.cors: false` in `vite.config.ts`.** Vite's own dev CORS middleware otherwise\nintercepts CORS in two ways that both mislead: it reflects `Access-Control-Allow-Origin` for\n*every* loopback origin (Vite 8's default `server.cors.origin` is a localhost regex), so a\ndisallowed `http:\u002F\u002Flocalhost:9999` looks allowed; and it **terminates every `OPTIONS` preflight\nitself** without emitting `Access-Control-Allow-Credentials`, which breaks any\n`credentials: \"include\"` fetch under `vite dev` while the identical request works under\n`wrangler dev`. With the middleware off, `hono\u002Fcors` is the only responder and both dev paths\nagree.\n\n```sh\ncurl -i -H 'Origin: http:\u002F\u002Flocalhost:3000' http:\u002F\u002Flocalhost:4000\u002Fhealth # → header reflected\ncurl -i -H 'Origin: http:\u002F\u002Flocalhost:9999' http:\u002F\u002Flocalhost:4000\u002Fhealth # → no ACAO header\n```\n\n## Deploy\n\n`pnpm deploy:production` at the repository root deploys this Worker with every other one. Its\n`deploy` script is `env-deploy api`: it loads the `api` service's production values and the\nCloudflare credentials from the value source, builds with them, and runs `wrangler deploy\n--secrets-file`, so the secrets land in the same Worker version as the code. A key the\n`wrangler.jsonc` `vars` block already sets stays a plain var and is not sent as a secret.\n\nThe api deploys first. `saasaloy add api` appends `{ service: \"api\", order: 10 }` to `DEPLOY_TARGETS` in `packages\u002Ftooling\u002Fsrc\u002Ftargets.ts`, so a frontend never goes live ahead of the route it calls. It also appends the `api-health` smoke check: `GET \u002Fhealth` must answer 200 with `\"ok\"` in the body. The check runs only once `apps\u002Fapi\u002Fwrangler.jsonc` has a `routes[]` entry with `custom_domain: true`, and the dry run says so while it has none. `pnpm deploy:production --only api` deploys this Worker alone after the gates, and writes no deploy tag. Do not deploy it with `pnpm --filter @repo\u002Fapi run deploy`, which skips the gates and the smoke checks. No deploy migrates the database unless you pass `--migrate`. See the `saasaloy-deploy` and `saasaloy-env` skills.\n\n## Conventions to honor\n\n- **Register a route with a `chained-route` patch**, not a file drop. The entry is edited on\n  purpose, and `saasaloy remove` reverses the edit.\n- **Build every sub-app as one unbroken chain.** A statement-per-route file typechecks and serves\n  correctly while handing the client an empty type.\n- **Pass the status code to `c.json`** on every path, success included.\n- **One route file = one mounted prefix**, named after the file, under a named `export const`.\n  Keep the folder flat.\n- **Internal paths are mount-relative** (`get(\"\u002F\")` for the index of the mount).\n- **Mount on `base`, not on the chain**, when a handler must stay out of `AppType`.\n- **`c.env` for bindings, never `process.env`.**\n- **`c.get(\"log\")` for logging, never `console.log`** — a bare console call is unlevelled and\n  uncorrelated, and it bypasses redaction.\n- **Inherit `base`'s `onError` and `notFound`.** A feature module registers neither of its own; a\n  miss under a normally mounted sub-app already answers the 404 envelope. A mount with a catch-all\n  route (`auth` at `\u002Fauth` and `\u002Fadmin\u002Fauth`) answers its own misses and never reaches that handler.\n- **`\u002Fadmin\u002Fauth\u002F*` is reserved for the admin auth instance.** Mount nothing under it, and make any `\u002Fadmin\u002F*` middleware skip it.\n- **A new binding patches `wrangler.jsonc`**; it does not hand-edit another module's files.\n- **Request validation belongs in `@repo\u002Fvalidators`**, not in an inline schema in the route.\n- **Test a route in Node with `app.request(path, init, env)`.** A setup step goes in `test\u002Fsetup\u002F`, not in `vitest.config.ts`.\n\n## Next\n\nRun `saasaloy-app` to add the customer screens that call these routes, or `saasaloy-admin` for staff screens.\n",{"name":5,"description":7},"main","5ecf3d110b216ef678e06a1630f6b63a8e730bb5","modules\u002Fapi\u002Fskills\u002Fsaasaloy-api",0,"https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy","https:\u002F\u002Fsaasaloy.com","https:\u002F\u002Fgithub.com\u002Fmimukit","https:\u002F\u002Fmimukit.com","Senior Software Engineer · 9+ yrs Fullstack (TS\u002FNode\u002FReact) · AI integrations, distributed systems · Building @saasaloy & @codealoy · Bangladesh 🇧🇩 \u002F Remote","2026-11-13 20:39:28",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add mimukit\u002Fsaasaloy --skill saasaloy-api",{"tool":40,"command":41},"bunx","bunx skills add mimukit\u002Fsaasaloy --skill saasaloy-api",{"tool":43,"command":44},"pnpm","pnpm dlx skills add mimukit\u002Fsaasaloy --skill saasaloy-api","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fapi\u002Fskills\u002Fsaasaloy-api\u002FSKILL.md",true,[],[49,56,63,70,77,83],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":19},"01M7BE75C34XHSPVJNQC8FY4Q0","saasaloy-subscription","Runbook for the subscription capability — provider-agnostic subscriptions in packages\u002Fsubscription, with a plan file, a projection table, a billable-subject file, plan entitlements and per-provider modules. Use when adding a plan, adding a plan feature or a numeric limit, gating an API route with requireFeature or requireWithinLimit, reading the 402 it returns, working out why a subject resolves to the free plan, wiring a checkout or portal route, reading a SubscriptionError, choosing or switching SUBSCRIPTION_PROVIDER, registering a webhook in the vendor's dashboard, writing a third subscription provider, or upgrading a project that still has `billing` installed.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fsubscription\u002Fskills\u002Fsaasaloy-subscription\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":59,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":60,"categories":61,"keywords":62,"publishedAt":19},"01M7BE68MJ8H47JZKTBDFYR6JD","saasaloy-notification","Runbook for the notification module, in-app notifications for apps\u002Fapp. It owns the notifications and notification_opt_outs tables, notify() in apps\u002Fapi\u002Fsrc\u002Flib\u002Fnotify.ts, the \u002Fnotifications api routes, the bell in the app header, the sidebar badge, the \u002Fnotifications page with Inbox and Preferences tabs, the notification config section, and the daily prune. Use when sending a notification from an api route, adding or changing a category, changing retention, debugging a badge or bell count that does not move, or removing the module.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fnotification\u002Fskills\u002Fsaasaloy-notification\u002FSKILL.md",[],[],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":19},"01M7BE53PDQV0YDPG8RNVGTPEQ","saasaloy-cms","Runbook for the cms module, the in-house CMS behind apps\u002Fadmin. Covers code-defined collections, the Tiptap editor, drafts, revisions and redirects, the publish-time renderer, the public blog on apps\u002Fweb and its 60-second cache. Use when adding a collection or a field, rendering a stored body, reusing the editor, renderer or media field from another module, moving the blog to another path, re-rendering live posts after a renderer upgrade or a STORAGE_PUBLIC_URL change, or working out why a published post is not live yet.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fmodules\u002Fcms\u002Fskills\u002Fsaasaloy-cms\u002FSKILL.md",[],[],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M79GQ03M63V5EKSST92B3S5X","saasaloy-beta","The beta module's own procedure.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-clean\u002Fbeta\u002Fsaasaloy-beta\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M79GPXV3K8YF3M4VA0KGVE0B","helper","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftest\u002Ffixtures\u002Fregistry-broken\u002Fbad-skill\u002Fhelper\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M79GPR8EVS1YX0W8X33Q9YD8","saasaloy-update","Runbook for an AI agent that updates this project to a newer Saasaloy CLI and newer module versions with saasaloy update. Use when the owner says \"update saasaloy\", \"upgrade the CLI\", \"pull the latest modules\", \"update the base template\", \"work the merge plan\", \"clear the update notes\", when saasaloy update or saasaloy outdated --check exits 3 or 2, when a merge plan or .saasaloy\u002Fmerge-plan.md is handed to you, or when an adopted project takes its first update. Covers the CLI upgrade, the preview, --out, the file merges, the update notes and \"Notes that may apply\", --resolved and --done, a file deleted locally and --restore, a three-way or two-way base, an update that skips releases, --from, the verify commands, and the exit codes.","https:\u002F\u002Fgithub.com\u002Fmimukit\u002Fsaasaloy\u002Fblob\u002Fmain\u002Fpackages\u002Fcli\u002Ftemplates\u002Fbase\u002F_agents\u002Fskills\u002Fsaasaloy-update\u002FSKILL.md",[],[]]