create-signet-app 0.4.7 → 0.4.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,10 +4,18 @@ Scaffold a Vite + React 19 + TypeScript + Tailwind v4 app wired to
4
4
  `@dapplelight/signet-tokens`, `@dapplelight/signet-ui` and `@dapplelight/signet-lib`.
5
5
 
6
6
  ```bash
7
- bunx create-signet-app my-app --theme cinematic
8
- cd my-app && bun install && bun dev
7
+ npx create-signet-app@latest my-app --template full
8
+ cd my-app
9
+ npm install
10
+ npm run dev
9
11
  ```
10
12
 
13
+ With pnpm: `pnpm create signet-app my-app --template full`. With bun:
14
+ `bunx create-signet-app my-app --template full`. Then install and `run dev` with
15
+ the same manager. Open `http://localhost:5173`. `full` needs
16
+ [Bun](https://bun.sh) 1.3+ installed: `run dev` is a Bun script, whichever
17
+ package manager installs the app.
18
+
11
19
  `--theme` takes `editorial`, `cinematic` or `finance` (editorial plus the
12
20
  spend-category and money tokens; default `editorial`).
13
21
 
@@ -18,13 +26,47 @@ in `npm_config_user_agent`), else bun. With pnpm a `pnpm-workspace.yaml`
18
26
  approves esbuild's and workerd's build scripts, which pnpm 10+ otherwise refuses
19
27
  to install without. Tests stay on `bun test`, so CI sets up Bun too.
20
28
 
29
+ ## Which template
30
+
31
+ `--template` defaults to `web`.
32
+
33
+ | Template | Frontend | API | Database | Auth | MCP | Runs on |
34
+ |---|---|---|---|---|---|---|
35
+ | `web` | Vite + React + Signet UI, TanStack Router | none (a configured `createApiClient` for yours) | none | placeholder `/login` | no | any static host |
36
+ | `api` | none | Hono with the error envelope and request ids | none (add with `signet add db`) | none (add with `signet add auth`) | `/mcp`, default on | `--target` cloudflare, bun, node or vercel |
37
+ | `full` | the `web` app plus account, inbox, privacy, billing, admin | Hono on Bun, served with the built app | SQLite with migrations | phone codes, stored sessions, orgs | `/mcp`, default on | Bun (one process) |
38
+ | `cli` | none | none | none | device-code login | no | one compiled Bun binary |
39
+ | `extension` | Chrome MV3: popup, options, service worker | none | none | PKCE via `chrome.identity` | no | Chrome |
40
+ | `desktop` | Tauri v2 window and menu-bar app | none | none | browser sign-in (PKCE, loopback) | no | macOS, Windows, Linux |
41
+
42
+ ## AI-assisted planning: `--describe`
43
+
44
+ ```bash
45
+ bunx create-signet-app my-app --describe "a team inbox with settings and pricing"
46
+ ```
47
+
48
+ One sentence picks the template (`web`, `api` or `full`) and theme, splits the
49
+ sentence into pages, asks signet-mcp's `plan_page` about each, scaffolds the
50
+ app, and writes `PLAN.md` (the pages, with blocks, components, data and files
51
+ for each) and `AGENTS.md` (the instructions an agent working in the app
52
+ should follow). It is deterministic and makes no LLM call: the same sentence
53
+ always gives the same files. Keyword lists choose between Signet's own
54
+ templates and themes; a sentence that names none gets `web` and `editorial`.
55
+
56
+ An explicit `--template` or `--theme` wins over what the sentence implies.
57
+ `--describe` applies to `web`, `api` and `full` only.
58
+
21
59
  ## `--template full`: web app + API in one project
22
60
 
23
61
  ```bash
24
- bunx create-signet-app my-app --template full --theme finance
25
- cd my-app && bun install && bun run dev
62
+ npx create-signet-app@latest my-app --template full
63
+ cd my-app
64
+ npm install
65
+ npm run dev
26
66
  ```
27
67
 
68
+ Add `--theme finance` (or `cinematic`) to pick a theme.
69
+
28
70
  One package, two halves: `src/` (the web template's Vite app) and `api/` (Hono
29
71
  on Bun), with `api/server.ts` serving the API under `/api` and the built app
30
72
  for every other path, so one process deploys it and the session cookie stays
@@ -52,9 +94,10 @@ same-origin. In dev, Vite proxies `/api` to it. What a fresh app has:
52
94
  `BILLING=fake` upgrades at once and is refused outside development; Razorpay
53
95
  webhooks go through signet-payments to `applyBillingEvent`), and admin
54
96
  (`/admin`, signet-db `defineAdmin` over the schema via `adminRoutes`, by
55
- role). Billing and admin are interim pages marked `TODO(billing-screen)` /
56
- `TODO(admin-screen)` until signet-ui's billing and admin screens are
57
- published.
97
+ role). Both pages use signet-ui's published `BillingScreen` and admin
98
+ screens; nothing in them is a placeholder. What you still write is the
99
+ product: your plans and limits (`api/plans.ts`), and a real gateway in
100
+ place of `BILLING=fake`.
58
101
  - **Organisations.** Sign-up creates a personal org; an org switcher in the
59
102
  header; `/org` (settings: name, theme, brand colour) and
60
103
  `/org/members` (roles, remove, invite links) on signet-ui's org screens;
@@ -79,10 +122,8 @@ The API runs on Bun whichever package manager installs it.
79
122
 
80
123
  ## Why
81
124
 
82
- The audit found this exact setup rebuilt by hand 13 times across 23 products,
83
- and the five-package eslint config copied as a block into **exactly 8 of 23**
84
- repos — the identical count for all five packages is the signature of
85
- copy-paste, not configuration.
125
+ This setup kept getting rebuilt by hand, and the same lint config kept getting
126
+ copied between repos as a block. Copy-paste is not configuration.
86
127
 
87
128
  ## What you get
88
129
 
@@ -124,10 +165,20 @@ files are written:
124
165
 
125
166
  | `--target` | Entry | Config | Rate limit store |
126
167
  |---|---|---|---|
127
- | `cloudflare` (default) | `src/index.ts` (Worker) | `wrangler.jsonc` | `RateLimitCounter` Durable Object: exact |
128
- | `bun` | `src/server.ts` (`Bun.serve`) | `Dockerfile` | in-process: exact for one process |
129
- | `node` | `src/server.ts` (`node:http`) | `engines.node >= 22.18` | in-process: exact for one process |
130
- | `vercel` | `index.ts` (default export) | `vercel.json` (Hono preset) | in-process: per function instance |
168
+ | `cloudflare` (default) | `src/index.ts` (Worker) | `wrangler.jsonc` | `RateLimitCounter` Durable Object: exact across all instances |
169
+ | `bun` | `src/server.ts` (`Bun.serve`) | `Dockerfile` | in-process: exact for one process only |
170
+ | `node` | `src/server.ts` (`node:http`) | `engines.node >= 22.18` | in-process: exact for one process only |
171
+ | `vercel` | `index.ts` (default export) | `vercel.json` (Hono preset) | in-process: per function instance, so not exact |
172
+
173
+ **Rate limits are not equivalent across targets.** An in-process store is safe
174
+ for a single `bun` or `node` process. Run more than one instance (replicas,
175
+ serverless, a load balancer) and each keeps its own count, so the real limit is
176
+ the configured one times the number of instances. When the limit is an abuse or
177
+ security control, use `cloudflare`, or pass a shared `store` (Redis; Vercel KV is
178
+ [Upstash](https://vercel.com/docs/redis)) to `rateLimit`. Behind a proxy,
179
+ the client IP is trusted only as far as you say: on `bun` and `node` set
180
+ `TRUSTED_PROXY_HOPS` to the number of proxies in front, otherwise the socket
181
+ address is used; on Vercel one forwarded hop is trusted.
131
182
 
132
183
  `node` runs `src/server.ts` as is through Node's type stripping (on by default
133
184
  from 22.18), so relative imports in the template carry `.ts`. It bridges
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-signet-app",
3
- "version": "0.4.7",
3
+ "version": "0.4.8",
4
4
  "license": "MIT",
5
5
  "description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
6
6
  "keywords": [
@@ -37,7 +37,10 @@
37
37
  ],
38
38
  "scripts": {
39
39
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
40
- "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts"
40
+ "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts"
41
+ },
42
+ "dependencies": {
43
+ "@dapplelight/signet-mcp": "^0.1.5"
41
44
  },
42
45
  "devDependencies": {
43
46
  "@types/bun": "^1.4.2",
@@ -0,0 +1,200 @@
1
+ /**
2
+ * `--describe "<sentence>"`: one sentence to a whole-app plan. Picks the
3
+ * template and theme, splits the sentence into pages, asks signet-mcp's
4
+ * `plan_page` about each, and renders PLAN.md and AGENTS.md. No LLM call: the
5
+ * same sentence always gives the same files.
6
+ *
7
+ * The keyword lists below only choose between Signet's own templates and
8
+ * themes. They are not about any product; an app's own vocabulary stays in the app.
9
+ */
10
+
11
+ import { INDEX } from "@dapplelight/signet-mcp/generated"
12
+ import { type PagePlan, planPage } from "@dapplelight/signet-mcp/plan"
13
+
14
+ export type DescribeTemplate = "web" | "api" | "full"
15
+ export type DescribeTheme = "editorial" | "cinematic" | "finance"
16
+ export type Page = { name: string; plan: PagePlan }
17
+ export type Described = { template: DescribeTemplate; theme: DescribeTheme; pages: Page[] }
18
+ /** How the chosen package manager spells running a script and a bin. */
19
+ export type Runner = { run: string; x: string }
20
+
21
+ // ponytail: keyword lists, not a classifier. A sentence that names none gets web and editorial.
22
+ const BACKEND =
23
+ /\b(api|backend|server|endpoints?|webhooks?|database|login|sign[- ]?(in|up)|accounts?|billing|payments?|subscriptions?|admin|auth\w*)\b/i
24
+ const FINANCE =
25
+ /\b(invoices?|expenses?|budgets?|bank\w*|ledger|accounting|finance|financial|payroll|money|transactions?|payments?)\b/i
26
+ const CINEMATIC =
27
+ /\b(videos?|films?|movies?|cinema\w*|stream\w*|gallery|photos?|music|trailers?|showcase|portfolio)\b/i
28
+
29
+ export const NO_PAGE_WORDS = "dashboard, settings, pricing, inbox"
30
+
31
+ /** Pieces of the sentence that can each name a page: "an inbox with settings and pricing". */
32
+ const segments = (sentence: string) =>
33
+ sentence
34
+ .split(/[,;&\n]|\b(?:and|with|plus|then|also)\b/i)
35
+ .map((s) => s.trim())
36
+ .filter(Boolean)
37
+
38
+ /** Each distinct page the sentence names, in the order it names them. */
39
+ function pagesFor(sentence: string, target: DescribeTemplate): Page[] {
40
+ const pages: Page[] = []
41
+ for (const part of segments(sentence)) {
42
+ const plan = planPage(INDEX, part, target)
43
+ // web and full pages are blocks; an api page is named by the route plan_page files it under.
44
+ const name = plan.blocks[0]?.name ?? /^src\/api\/(.+)\.ts$/.exec(plan.files[0]?.path ?? "")?.[1]
45
+ if (name && !pages.some((p) => p.name === name)) pages.push({ name, plan })
46
+ }
47
+ return pages
48
+ }
49
+
50
+ export function describeApp(
51
+ sentence: string,
52
+ want: { template?: DescribeTemplate; theme?: DescribeTheme },
53
+ ): Described {
54
+ let template = want.template
55
+ let pages: Page[] | undefined
56
+ if (!template) {
57
+ const web = pagesFor(sentence, "web")
58
+ template = !BACKEND.test(sentence) ? "web" : web.length ? "full" : "api"
59
+ if (template === "web") pages = web
60
+ }
61
+ pages ??= pagesFor(sentence, template)
62
+ const theme =
63
+ want.theme ??
64
+ (template === "api"
65
+ ? "editorial"
66
+ : FINANCE.test(sentence)
67
+ ? "finance"
68
+ : CINEMATIC.test(sentence)
69
+ ? "cinematic"
70
+ : "editorial")
71
+ return { template, theme, pages }
72
+ }
73
+
74
+ /** The order to build in: sign-in first, the catch-all pages last, the rest as named. */
75
+ const WEIGHT: Record<string, number> = { "auth-page": -1, "empty-page": 1, "error-page": 1 }
76
+ const buildOrder = (pages: Page[]) =>
77
+ [...pages].sort((a, b) => (WEIGHT[a.name] ?? 0) - (WEIGHT[b.name] ?? 0))
78
+
79
+ /** The plan's `data` lines that describe records, as `name: fields`, not callbacks or flags. */
80
+ function models(pages: Page[]) {
81
+ const out = new Map<string, { shape: string; pages: string[] }>()
82
+ for (const p of pages)
83
+ for (const line of p.plan.data) {
84
+ const m = /^(\w+): (.+)$/.exec(line)
85
+ if (!m || /^on[A-Z]/.test(m[1] as string) || /\b(called|calls|callback)\b/.test(line))
86
+ continue
87
+ if (!/\b(each|and)\b/.test(m[2] as string)) continue
88
+ const key = `${m[1]}`
89
+ const have = out.get(key)
90
+ if (have) have.pages.push(p.name)
91
+ else out.set(key, { shape: m[2] as string, pages: [p.name] })
92
+ }
93
+ return out
94
+ }
95
+
96
+ export function renderPlan(
97
+ appName: string,
98
+ sentence: string,
99
+ d: Described,
100
+ { run, x }: Runner,
101
+ ): string {
102
+ const head = `# Plan: ${appName}\n\n`
103
+ if (!d.pages.length)
104
+ return `${head}Template: ${d.template} · Theme: ${d.theme}\n\n## Pages\n\nNo page matched "${sentence}". Try words like ${NO_PAGE_WORDS}.\n`
105
+
106
+ const check = `${x} @dapplelight/signet-cli check`
107
+ const cmd = (c: string) => c.replace(/^npx /, `${x} `)
108
+ const quote = sentence
109
+ .split("\n")
110
+ .map((l) => `> ${l}`)
111
+ .join("\n")
112
+ const lines: string[] = [
113
+ `${head}${quote}\n\nTemplate: ${d.template} · Theme: ${d.theme}\n`,
114
+ "## Pages\n",
115
+ ]
116
+
117
+ d.pages.forEach((p, i) => {
118
+ const { plan } = p
119
+ lines.push(`### ${i + 1}. ${p.name}\n`)
120
+ lines.push("**Blocks**\n")
121
+ if (plan.blocks.length) {
122
+ for (const b of plan.blocks) lines.push(`- \`${b.name}\`: ${b.why}`)
123
+ lines.push("", "```bash", ...plan.blocks.map((b) => cmd(b.command)), "```\n")
124
+ } else lines.push("- None: this page is API only.\n")
125
+ lines.push("**Components**\n")
126
+ lines.push(
127
+ ...(plan.components.length
128
+ ? plan.components.map((c) => `- \`${c.name}\`: \`${c.importPath}\``)
129
+ : ["- None."]),
130
+ "",
131
+ )
132
+ lines.push("**Modules**\n")
133
+ lines.push(...(plan.modules.length ? plan.modules.map((m) => `- \`${m}\``) : ["- None."]), "")
134
+ lines.push("**Data**\n")
135
+ lines.push(...(plan.data.length ? plan.data.map((l) => `- ${l}`) : ["- None."]), "")
136
+ })
137
+
138
+ lines.push("## Data models\n")
139
+ const ms = models(d.pages)
140
+ lines.push(
141
+ ...(ms.size
142
+ ? [...ms].map(([k, v]) => `- \`${k}\`: ${v.shape} (${v.pages.join(", ")})`)
143
+ : ["- None: the pages take props only."]),
144
+ "",
145
+ )
146
+
147
+ lines.push("## Recipes\n")
148
+ const recipes = [...new Set(d.pages.map((p) => p.plan.recipe).filter((r): r is string => !!r))]
149
+ lines.push(
150
+ ...(recipes.length
151
+ ? recipes.map((id) => {
152
+ const title = INDEX.recipes.find((r) => r.id === id)?.title ?? id
153
+ return `- \`${id}\`: ${title}. Call \`recipe({ task: "${id}" })\`.`
154
+ })
155
+ : ["- None matched."]),
156
+ "",
157
+ )
158
+
159
+ lines.push("## Build order\n")
160
+ buildOrder(d.pages).forEach((p, i) => {
161
+ lines.push(
162
+ p.plan.blocks.length
163
+ ? `${i + 1}. ${p.name}: run its block command, wire its data, then \`${check} --pages /${p.name}\`.`
164
+ : `${i + 1}. ${p.name}: add \`src/api/${p.name}.ts\`${p.plan.recipe ? `, following the \`${p.plan.recipe}\` recipe` : ""}, then \`${check}\`.`,
165
+ )
166
+ })
167
+ lines.push("")
168
+
169
+ lines.push(
170
+ "## After each page\n",
171
+ "Fix every finding before you start the next page.\n",
172
+ "```bash",
173
+ `${check} --pages /<page>`,
174
+ `${run} test`,
175
+ "```\n",
176
+ `\`check\` typechecks, runs Biome, checks Signet's conventions and, with \`--pages\`, screenshots the page at 390 and 1280 px with axe. Start the dev server first (\`${run} dev\`). Or call \`check_app({ path: "." })\` on the Signet MCP server.`,
177
+ )
178
+ return `${lines.join("\n")}\n`
179
+ }
180
+
181
+ export function renderAgents(appName: string, d: Described, { run }: Runner): string {
182
+ return `${[
183
+ `# ${appName}: notes for coding agents`,
184
+ "",
185
+ "This app is built from PLAN.md, one page at a time.",
186
+ "",
187
+ "1. Read PLAN.md. Build the pages in its Build order and never skip ahead.",
188
+ "2. For each page: run its block command, wire the data it lists, then run the check from After each page.",
189
+ "3. Fix every finding before you move on. Never edit a page before the previous one passes.",
190
+ "4. Use `@dapplelight/signet-ui` components and `@dapplelight/signet-tokens` themes only.",
191
+ d.template === "api"
192
+ ? "5. No hand-rolled validation or error shapes: use `@dapplelight/signet-server`."
193
+ : "5. No hand-rolled buttons, inputs or fetch wrappers: use the typed client in `src/lib/api.ts`.",
194
+ "6. To look up a component, theme or convention, add the Signet MCP server:",
195
+ " `claude mcp add signet -- bunx @dapplelight/signet-mcp`",
196
+ `7. Run \`${run} lint\`, \`${run} typecheck\` and \`${run} test\` before you finish.`,
197
+ "",
198
+ "If PLAN.md lists no pages, ask for a description of the first page before you build anything.",
199
+ ].join("\n")}\n`
200
+ }
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@ const TEMPLATES = ["web", "api", "full", "cli", "extension", "desktop"] as const
22
22
  type Template = (typeof TEMPLATES)[number]
23
23
  const TARGETS = ["cloudflare", "bun", "node", "vercel"] as const
24
24
  type Target = (typeof TARGETS)[number]
25
+ const DESCRIBE_TEMPLATES: readonly Template[] = ["web", "api", "full"]
25
26
  const PMS = ["bun", "npm", "pnpm"] as const
26
27
  type Pm = (typeof PMS)[number]
27
28
 
@@ -98,7 +99,7 @@ const TEMPLATE_DIRS: Record<Template, string> = {
98
99
  const API_DEPS = {
99
100
  "@dapplelight/signet-server": "^0.5.0",
100
101
  hono: "^4.13.8",
101
- zod: "^4.6.5",
102
+ zod: "^4.6.7",
102
103
  }
103
104
 
104
105
  // Added with MCP (--mcp, the default): signet-server's optional peer for /mcp.
@@ -281,6 +282,9 @@ function parseArgs(argv: string[]) {
281
282
  let target: Target | undefined
282
283
  let mcp: boolean | undefined
283
284
  let pm: Pm | undefined
285
+ let describe: string | undefined
286
+ let themeGiven: Theme | undefined
287
+ let templateGiven: Template | undefined
284
288
 
285
289
  for (let i = 0; i < args.length; i++) {
286
290
  const a = args[i]
@@ -289,13 +293,20 @@ function parseArgs(argv: string[]) {
289
293
  if (!THEMES.includes(v as Theme)) {
290
294
  throw new Error(`Unknown theme "${v}". Available: ${THEMES.join(", ")}`)
291
295
  }
292
- theme = v as Theme
296
+ theme = themeGiven = v as Theme
293
297
  } else if (a === "--template") {
294
298
  const v = args[++i]
295
299
  if (!TEMPLATES.includes(v as Template)) {
296
300
  throw new Error(`Unknown template "${v}". Available: ${TEMPLATES.join(", ")}`)
297
301
  }
298
- template = v as Template
302
+ template = templateGiven = v as Template
303
+ } else if (a === "--describe") {
304
+ const v = args[++i]
305
+ if (!v?.trim() || v.startsWith("--"))
306
+ throw new Error(
307
+ '--describe needs a sentence, e.g. --describe "a team inbox with settings".',
308
+ )
309
+ describe = v
299
310
  } else if (a === "--target") {
300
311
  const v = args[++i]
301
312
  if (!TARGETS.includes(v as Target)) {
@@ -339,6 +350,9 @@ Options:
339
350
  -t, --theme <name> ${THEMES.join(" | ")} (default: editorial; web and full)
340
351
  --pm <name> ${PMS.join(" | ")} (default: the one that ran this, else bun)
341
352
  Sets the commands in CI, the README and below.
353
+ --describe "<sentence>" Pick template and theme from one sentence, scaffold,
354
+ write PLAN.md and AGENTS.md (web, api and full; an explicit
355
+ --template or --theme wins)
342
356
  -h, --help
343
357
 
344
358
  Examples:
@@ -348,6 +362,7 @@ Examples:
348
362
  bun create-signet-app my-app --template full --theme finance
349
363
  bun create-signet-app my-cli --template cli
350
364
  npm create signet-app my-app -- --template full --pm npm
365
+ bun create-signet-app my-app --describe "a team inbox with settings and pricing"
351
366
  `)
352
367
  process.exit(0)
353
368
  } else if (!a.startsWith("-")) {
@@ -358,6 +373,27 @@ Examples:
358
373
  }
359
374
 
360
375
  if (!name) throw new Error("Missing target directory.\nUsage: create-signet-app <directory>")
376
+ if (describe !== undefined) {
377
+ if (templateGiven && !DESCRIBE_TEMPLATES.includes(templateGiven))
378
+ throw new Error("--describe applies to --template web, api and full only.")
379
+ // The template and theme come from the sentence, so these are checked once they are known.
380
+ return {
381
+ name,
382
+ theme,
383
+ template,
384
+ target: target ?? "cloudflare",
385
+ targetGiven: target,
386
+ mcp,
387
+ pm: pm ?? detectPm(),
388
+ describe: { sentence: describe, template: templateGiven, theme: themeGiven },
389
+ }
390
+ }
391
+ checkCombo(template, theme, target, mcp)
392
+ return { name, theme, template, target: target ?? "cloudflare", mcp, pm: pm ?? detectPm() }
393
+ }
394
+
395
+ /** Flags that only fit some templates. */
396
+ function checkCombo(template: Template, theme: Theme, target?: Target, mcp?: boolean) {
361
397
  if (target && template !== "api") throw new Error("--target applies to --template api only.")
362
398
  if (
363
399
  mcp !== undefined &&
@@ -366,7 +402,6 @@ Examples:
366
402
  throw new Error("--mcp / --no-mcp apply to --template api and full only.")
367
403
  if (theme !== "editorial" && template === "api")
368
404
  throw new Error("--theme applies to --template web and full only.")
369
- return { name, theme, template, target: target ?? "cloudflare", mcp, pm: pm ?? detectPm() }
370
405
  }
371
406
 
372
407
  /** Replace placeholders in every text file under dir. */
@@ -402,10 +437,24 @@ async function askMcp(): Promise<boolean> {
402
437
  }
403
438
 
404
439
  async function main() {
405
- const { name, theme, template, target, pm, ...flags } = parseArgs(process.argv)
440
+ const parsed = parseArgs(process.argv)
441
+ const { name, target, pm, ...flags } = parsed
442
+ let { theme, template } = parsed
406
443
  const dest = resolve(process.cwd(), name)
407
444
  const appName = basename(dest)
408
445
 
446
+ // Loaded only here: it pulls in signet-mcp's index, which a plain scaffold never needs.
447
+ const described = parsed.describe
448
+ ? await (await import("./describe.js")).describeApp(parsed.describe.sentence, {
449
+ template: parsed.describe.template as "web" | "api" | "full" | undefined,
450
+ theme: parsed.describe.theme,
451
+ })
452
+ : undefined
453
+ if (described) {
454
+ ;({ theme, template } = described)
455
+ checkCombo(template, theme, parsed.targetGiven, flags.mcp)
456
+ }
457
+
409
458
  if (existsSync(dest) && (await readdir(dest)).length > 0) {
410
459
  throw new Error(`${dest} already exists and is not empty.`)
411
460
  }
@@ -532,10 +581,32 @@ async function main() {
532
581
  : pkg
533
582
  await writeFile(
534
583
  join(dest, "package.json"),
535
- `${JSON.stringify({ name: appName, private: true, version: "0.1.0", type: "module", ...(template === "desktop" ? DESKTOP_PKG : final) }, null, 2)}\n`,
584
+ `${JSON.stringify(
585
+ {
586
+ name: appName,
587
+ private: true,
588
+ version: "0.1.0",
589
+ type: "module",
590
+ ...(template === "desktop" ? DESKTOP_PKG : final),
591
+ // npm 11 warns on unreviewed install scripts and will block them later.
592
+ // esbuild (under Vite and wrangler) needs its postinstall to fetch its binary.
593
+ ...(pm === "npm" && template !== "cli" ? { allowScripts: { esbuild: true } } : {}),
594
+ },
595
+ null,
596
+ 2,
597
+ )}\n`,
536
598
  )
537
599
 
538
600
  const { install, run } = PM[pm]
601
+ if (described && parsed.describe) {
602
+ const { renderAgents, renderPlan } = await import("./describe.js")
603
+ const runner = { run, x: PM[pm].x }
604
+ await writeFile(
605
+ join(dest, "PLAN.md"),
606
+ renderPlan(appName, parsed.describe.sentence, described, runner),
607
+ )
608
+ await writeFile(join(dest, "AGENTS.md"), renderAgents(appName, described, runner))
609
+ }
539
610
  const steps = `cd ${name}\n ${install}\n ${run} dev`
540
611
  console.log(
541
612
  template === "cli"
@@ -591,6 +662,15 @@ async function main() {
591
662
  Switch themes by editing the @dapplelight/signet-tokens import in src/app.css.
592
663
  `,
593
664
  )
665
+ if (described) {
666
+ const names = described.pages.map((p) => p.name)
667
+ const more = names.length - 5
668
+ console.log(
669
+ names.length
670
+ ? ` Planned ${names.length} page${names.length === 1 ? "" : "s"} in PLAN.md: ${names.slice(0, 5).join(", ")}${more > 0 ? ` and ${more} more` : ""}. Hand AGENTS.md to your coding agent.\n`
671
+ : " No pages matched; PLAN.md lists words to try.\n",
672
+ )
673
+ }
594
674
  }
595
675
 
596
676
  main().catch((err: unknown) => {
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -148,6 +148,17 @@ Before production:
148
148
  Fulfil them with `privacy.fulfil(id, { actor })` (export returns the data to
149
149
  send; erasure deletes the user's rows listed in `userTables`).
150
150
 
151
+ ## Observability
152
+
153
+ Off by default. Set `OBSERVABILITY=on` and the API writes a JSON log line pair
154
+ per request (`request.started`, then `request.completed` or `request.failed`)
155
+ with the request id and trace id, opens an OpenTelemetry span per request, and
156
+ answers `/health/live` and `/health/ready` (the database). Probes are left out
157
+ of spans and logs. Spans are no-ops until you register an OpenTelemetry SDK or
158
+ turn on Cloudflare tracing; Signet adds no exporter. To put the trace id on
159
+ every log line, pass `mixin` in `api/server.ts`. Prompts, bodies, cookies and
160
+ headers are never recorded.
161
+
151
162
  ## Themes
152
163
 
153
164
  `src/app.css` imports the __THEME__ theme from `@dapplelight/signet-tokens`.
@@ -11,6 +11,10 @@ import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
11
11
  import { csrfMiddleware } from "@dapplelight/signet-server/middleware/csrf"
12
12
  import { memoryStore, rateLimit } from "@dapplelight/signet-server/middleware/rate-limit"
13
13
  import { requestId } from "@dapplelight/signet-server/middleware/request-id"
14
+ import { healthRoutes } from "@dapplelight/signet-server/observability/health"
15
+ import { createLogger } from "@dapplelight/signet-server/observability/logger"
16
+ import { requestLog } from "@dapplelight/signet-server/observability/request-log"
17
+ import { traceMiddleware } from "@dapplelight/signet-server/observability/trace"
14
18
  import { inArray } from "drizzle-orm"
15
19
  import { Hono } from "hono"
16
20
  import { type User, users } from "./db/schema.ts"
@@ -33,6 +37,9 @@ const SIGNED_IN = [
33
37
  "/api/admin",
34
38
  ]
35
39
 
40
+ /** Probes stay out of spans and logs. */
41
+ const HEALTH_PATHS = ["/health/live", "/health/ready"]
42
+
36
43
  /** An invite link can be looked at before signing in; everything else under /api/orgs needs a user. */
37
44
  const INVITE_PREVIEW = /^\/api\/orgs\/invites\/[^/]+$/
38
45
 
@@ -42,12 +49,25 @@ const INVITE_PREVIEW = /^\/api\/orgs\/invites\/[^/]+$/
42
49
  */
43
50
  export function createApp(deps: Deps) {
44
51
  const s = createServices(deps)
45
- const base = new Hono<AppEnv>()
46
- .use("*", requestId())
47
- // Blocks cross-site form posts riding the session cookie. The web app is
48
- // served from this same origin, so nothing else needs trusting.
49
- .use("/api/*", csrfMiddleware())
50
- .use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
52
+ const base = new Hono<AppEnv>().use("*", requestId())
53
+ // Off unless server.ts passes `observability` (OBSERVABILITY=on): then a span
54
+ // and a JSON log line pair per request, both carrying the trace id, and
55
+ // /health/live and /health/ready below. Without an OpenTelemetry SDK the
56
+ // spans are no-ops; Signet adds no exporter (see the observability guide).
57
+ const obs = deps.observability
58
+ if (obs) {
59
+ const log = createLogger({
60
+ level: obs.level ?? "info",
61
+ base: { service: obs.serviceName },
62
+ mixin: obs.mixin,
63
+ })
64
+ base.use("*", traceMiddleware({ serviceName: obs.serviceName, skipPaths: HEALTH_PATHS }))
65
+ base.use("*", requestLog({ logger: log, skipPaths: HEALTH_PATHS, slowMs: 1000 }))
66
+ }
67
+ // Blocks cross-site form posts riding the session cookie. The web app is
68
+ // served from this same origin, so nothing else needs trusting.
69
+ base.use("/api/*", csrfMiddleware())
70
+ base.use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
51
71
  for (const path of SIGNED_IN) base.use(`${path}/*`, requireUser(s))
52
72
  const gate = requireUser(s)
53
73
  base.use("/api/orgs/*", (c, next) =>
@@ -104,6 +124,21 @@ export function createApp(deps: Deps) {
104
124
  )
105
125
  .onError(errorHandler({ isProduction }))
106
126
 
127
+ if (obs) {
128
+ // Ready means the database answers. Add a check per dependency you add.
129
+ app.route(
130
+ "/health",
131
+ healthRoutes({
132
+ checks: {
133
+ db: async () => {
134
+ deps.query("select 1", [])
135
+ return true
136
+ },
137
+ },
138
+ }),
139
+ )
140
+ }
141
+
107
142
  // mcp:begin
108
143
  // MCP: every route validated with zValidator is a tool at /mcp that runs
109
144
  // as the caller (their cookie or API key goes with it). GET routes are read
@@ -29,6 +29,11 @@ export const envSchema = z.object({
29
29
  * x-org header or the switch cookie, which is all local development needs.
30
30
  */
31
31
  ORG_ROOT_DOMAIN: z.string().optional(),
32
+ /**
33
+ * "on": JSON request logs, a span per request and /health/live and
34
+ * /health/ready (server.ts). Off by default. See observability in app.ts.
35
+ */
36
+ OBSERVABILITY: z.enum(["on", "off"]).default("off"),
32
37
  RAZORPAY_KEY_ID: z.string().optional(),
33
38
  RAZORPAY_KEY_SECRET: z.string().optional(),
34
39
  RAZORPAY_WEBHOOK_SECRET: z.string().optional(),
@@ -9,7 +9,9 @@ import { openDb } from "./db/open.ts"
9
9
  import { env } from "./env.ts"
10
10
 
11
11
  const { db, query } = openDb(env.DATABASE_PATH)
12
- const app = createApp({ db, query, kv: sqlKv(db.orm) })
12
+ // OBSERVABILITY=on adds request logs, spans and /health/live and /health/ready.
13
+ const observability = env.OBSERVABILITY === "on" ? { serviceName: "__APP_NAME__" } : undefined
14
+ const app = createApp({ db, query, kv: sqlKv(db.orm), observability })
13
15
  setInterval(() => pruneKv(db.orm), 60 * 60 * 1000)
14
16
 
15
17
  const DIST = join(import.meta.dirname, "../dist")
@@ -18,7 +20,11 @@ const server = Bun.serve({
18
20
  port: env.PORT,
19
21
  async fetch(req, srv) {
20
22
  const { pathname } = new URL(req.url)
21
- if (pathname.startsWith("/api/") || pathname.startsWith("/mcp")) {
23
+ if (
24
+ pathname.startsWith("/api/") ||
25
+ pathname.startsWith("/mcp") ||
26
+ (observability && pathname.startsWith("/health/"))
27
+ ) {
22
28
  // Overwrite, never append: a client-set x-forwarded-for must not pick its
23
29
  // own rate-limit bucket. Behind a proxy of your own, pass the proxy's
24
30
  // header through instead and raise TRUST's hops in services.ts.
@@ -15,6 +15,7 @@ import {
15
15
  defineTemplates,
16
16
  kvNotifyStore,
17
17
  } from "@dapplelight/signet-server/notify/notifier"
18
+ import type { LevelSetting } from "@dapplelight/signet-server/observability/logger"
18
19
  import { eq } from "drizzle-orm"
19
20
  import { z } from "zod"
20
21
  import type { Db } from "./db/index.ts"
@@ -94,6 +95,21 @@ export type Deps = {
94
95
  kv: KeyValue
95
96
  /** Sends one-time codes. Default: printed to the console, development only. */
96
97
  sms?: SmsSender
98
+ /** Request logs, spans and health routes. Absent: none of them, and no /health. */
99
+ observability?: ObservabilityConfig
100
+ }
101
+
102
+ export type ObservabilityConfig = {
103
+ /** Set on every log line and span as the service name. */
104
+ serviceName: string
105
+ /** Log level. Default "info". */
106
+ level?: LevelSetting
107
+ /**
108
+ * Fields added to every log line, e.g. the trace id of the active span:
109
+ * `() => ({ traceId: trace.getActiveSpan()?.spanContext().traceId })` with
110
+ * `trace` from `@opentelemetry/api`. Default: none.
111
+ */
112
+ mixin?: () => Record<string, unknown>
97
113
  }
98
114
 
99
115
  /** Everything the routes use, built once per process. */
@@ -1,5 +1,5 @@
1
1
  {
2
- "$schema": "https://biomejs.dev/schemas/2.5.14/schema.json",
2
+ "$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
3
3
  "vcs": {
4
4
  "enabled": true,
5
5
  "clientKind": "git",
@@ -1,4 +1,4 @@
1
- import { expect, test } from "bun:test"
1
+ import { expect, spyOn, test } from "bun:test"
2
2
 
3
3
  // The env is read on first use, so set it before the app is imported. CI has
4
4
  // no env file; these are throwaway test values.
@@ -187,3 +187,52 @@ test("sign-up makes a personal org; another org's data is 404", async () => {
187
187
  })
188
188
  expect(patch.status).toBe(403)
189
189
  })
190
+
191
+ test("observability is off unless configured: no /health, no log lines", async () => {
192
+ const lines: string[] = []
193
+ const spy = spyOn(console, "log").mockImplementation((l: string) => void lines.push(l))
194
+ try {
195
+ expect((await app.request("/health/live")).status).toBe(404)
196
+ expect((await app.request("/api/health")).status).toBe(200)
197
+ } finally {
198
+ spy.mockRestore()
199
+ }
200
+ expect(lines).toEqual([])
201
+ })
202
+
203
+ test("observability on: request logs, probes left out, /health/ready checks the database", async () => {
204
+ const lines: string[] = []
205
+ const spy = spyOn(console, "log").mockImplementation((l: string) => void lines.push(l))
206
+ try {
207
+ const { db, query } = openDb(":memory:")
208
+ const on = createApp({
209
+ db,
210
+ query,
211
+ kv: sqlKv(db.orm),
212
+ observability: { serviceName: "demo", mixin: () => ({ region: "test" }) },
213
+ })
214
+ const live = await on.request("/health/live")
215
+ expect(live.status).toBe(200)
216
+ expect(await live.json()).toEqual({ ok: true })
217
+ const ready = await on.request("/health/ready")
218
+ expect(ready.status).toBe(200)
219
+ expect(await ready.json()).toEqual({ ok: true, checks: { db: true } })
220
+ expect(lines).toEqual([]) // probes are not logged
221
+ const headers = { cookie: "session=s" }
222
+ const res = await on.request("/api/health?token=abc", { headers })
223
+ expect([res.status, await res.text()]).toEqual([200, '{"ok":true}'])
224
+ } finally {
225
+ spy.mockRestore()
226
+ }
227
+ const logged = lines.map((l) => JSON.parse(l) as Record<string, unknown>)
228
+ expect(logged.map((l) => l.msg)).toEqual(["request.started", "request.completed"])
229
+ expect(logged[1]).toMatchObject({
230
+ service: "demo",
231
+ region: "test",
232
+ method: "GET",
233
+ route: "/api/health",
234
+ status: 200,
235
+ })
236
+ expect(typeof logged[1]?.reqId).toBe("string")
237
+ expect(lines.join("\n")).not.toMatch(/token=abc|session=s/)
238
+ })