create-signet-app 0.2.2 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. package/README.md +128 -7
  2. package/package.json +4 -3
  3. package/src/index.ts +338 -66
  4. package/template-api/_github/workflows/ci.yml +0 -3
  5. package/template-api/_mcp/test/mcp-off.test.ts +13 -0
  6. package/template-api/_mcp/test/mcp.test.ts +49 -0
  7. package/template-api/_targets/bun/Dockerfile +13 -0
  8. package/template-api/_targets/bun/_dockerignore +10 -0
  9. package/template-api/_targets/bun/src/server.ts +32 -0
  10. package/template-api/_targets/cloudflare/_github/workflows/ci.yml +24 -0
  11. package/template-api/_targets/cloudflare/src/index.ts +17 -0
  12. package/template-api/_targets/node/src/server.ts +55 -0
  13. package/template-api/_targets/vercel/index.ts +16 -0
  14. package/template-api/_targets/vercel/vercel.json +4 -0
  15. package/template-api/src/app.ts +77 -0
  16. package/template-api/src/env.ts +4 -0
  17. package/template-api/tsconfig.json +2 -1
  18. package/template-api/tsconfig.test.json +1 -1
  19. package/template-full/README.md +155 -0
  20. package/template-full/_github/workflows/ci.yml +22 -0
  21. package/template-full/_gitignore +9 -0
  22. package/template-full/_mcp/test/mcp.test.ts +55 -0
  23. package/template-full/api/app.ts +132 -0
  24. package/template-full/api/db/index.ts +10 -0
  25. package/template-full/api/db/kv.ts +54 -0
  26. package/template-full/api/db/open.ts +33 -0
  27. package/template-full/api/db/schema.ts +57 -0
  28. package/template-full/api/env.ts +44 -0
  29. package/template-full/api/plans.ts +23 -0
  30. package/template-full/api/routes/account.ts +63 -0
  31. package/template-full/api/routes/auth.ts +134 -0
  32. package/template-full/api/routes/billing.ts +44 -0
  33. package/template-full/api/routes/notifications.ts +59 -0
  34. package/template-full/api/routes/privacy.ts +52 -0
  35. package/template-full/api/server.ts +44 -0
  36. package/template-full/api/services.ts +185 -0
  37. package/template-full/biome.json +50 -0
  38. package/template-full/drizzle/0000_init.sql +155 -0
  39. package/template-full/drizzle/0001_orgs.sql +47 -0
  40. package/template-full/drizzle/meta/0000_snapshot.json +974 -0
  41. package/template-full/drizzle/meta/0001_snapshot.json +1270 -0
  42. package/template-full/drizzle/meta/_journal.json +20 -0
  43. package/template-full/drizzle.config.ts +9 -0
  44. package/template-full/e2e/smoke.spec.ts +152 -0
  45. package/template-full/index.html +17 -0
  46. package/template-full/playwright.config.ts +10 -0
  47. package/template-full/scripts/dev.ts +17 -0
  48. package/template-full/src/app.css +9 -0
  49. package/template-full/src/components/toaster.tsx +13 -0
  50. package/template-full/src/lib/api.ts +40 -0
  51. package/template-full/src/main.tsx +36 -0
  52. package/template-full/src/routeTree.gen.ts +297 -0
  53. package/template-full/src/router.test.ts +23 -0
  54. package/template-full/src/router.ts +17 -0
  55. package/template-full/src/routes/__root.tsx +9 -0
  56. package/template-full/src/routes/_app/account.tsx +64 -0
  57. package/template-full/src/routes/_app/admin.tsx +38 -0
  58. package/template-full/src/routes/_app/billing.tsx +40 -0
  59. package/template-full/src/routes/_app/index.tsx +33 -0
  60. package/template-full/src/routes/_app/notifications.tsx +72 -0
  61. package/template-full/src/routes/_app/org/index.tsx +38 -0
  62. package/template-full/src/routes/_app/org/members.tsx +86 -0
  63. package/template-full/src/routes/_app/org/new.tsx +45 -0
  64. package/template-full/src/routes/_app/privacy.tsx +48 -0
  65. package/template-full/src/routes/_app.tsx +88 -0
  66. package/template-full/src/routes/invite.$token.tsx +55 -0
  67. package/template-full/src/routes/login.tsx +36 -0
  68. package/template-full/test/api.test.ts +189 -0
  69. package/template-full/tsconfig.api.json +19 -0
  70. package/template-full/tsconfig.app.json +26 -0
  71. package/template-full/tsconfig.json +9 -0
  72. package/template-full/tsconfig.node.json +16 -0
  73. package/template-full/tsconfig.test.json +8 -0
  74. package/template-full/vite.config.ts +24 -0
  75. package/template-api/src/index.ts +0 -55
  76. /package/template-api/{wrangler.jsonc → _targets/cloudflare/wrangler.jsonc} +0 -0
package/src/index.ts CHANGED
@@ -13,34 +13,153 @@
13
13
  import { existsSync } from "node:fs"
14
14
  import { cp, mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises"
15
15
  import { basename, join, resolve } from "node:path"
16
+ import { createInterface } from "node:readline/promises"
16
17
 
17
- const THEMES = ["editorial", "cinematic"] as const
18
+ const THEMES = ["editorial", "cinematic", "finance"] as const
18
19
  type Theme = (typeof THEMES)[number]
19
- const TEMPLATES = ["web", "api"] as const
20
+ const TEMPLATES = ["web", "api", "full"] as const
20
21
  type Template = (typeof TEMPLATES)[number]
22
+ const TARGETS = ["cloudflare", "bun", "node", "vercel"] as const
23
+ type Target = (typeof TARGETS)[number]
24
+ const PMS = ["bun", "npm", "pnpm"] as const
25
+ type Pm = (typeof PMS)[number]
26
+
27
+ /** `npm create` / `pnpm create` say who ran them; bun otherwise. */
28
+ function detectPm(): Pm {
29
+ const agent = process.env.npm_config_user_agent ?? ""
30
+ return agent.startsWith("pnpm/") ? "pnpm" : agent.startsWith("npm/") ? "npm" : "bun"
31
+ }
32
+
33
+ /** How each package manager spells install, a frozen install and running a script or a bin. */
34
+ const PM: Record<Pm, { install: string; ci: string; run: string; x: string; lock: string }> = {
35
+ bun: {
36
+ install: "bun install",
37
+ ci: "bun install --frozen-lockfile",
38
+ run: "bun run",
39
+ x: "bunx",
40
+ lock: "bun.lock",
41
+ },
42
+ npm: {
43
+ install: "npm install",
44
+ ci: "npm ci",
45
+ run: "npm run",
46
+ x: "npx",
47
+ lock: "package-lock.json",
48
+ },
49
+ pnpm: {
50
+ install: "pnpm install",
51
+ ci: "pnpm install --frozen-lockfile",
52
+ run: "pnpm run",
53
+ x: "pnpm exec",
54
+ lock: "pnpm-lock.yaml",
55
+ },
56
+ }
57
+
58
+ /**
59
+ * The CI workflow is written for bun; for npm or pnpm, install and run with
60
+ * that instead. Bun stays for `bun test` (and the full template's API).
61
+ */
62
+ function applyPm(ci: string, pm: Pm): string {
63
+ if (pm === "bun") return ci
64
+ const p = PM[pm]
65
+ const setup = [
66
+ ...(pm === "pnpm"
67
+ ? [" - uses: pnpm/action-setup@v4", " with:", " version: 10"]
68
+ : []),
69
+ " - uses: actions/setup-node@v4",
70
+ " with:",
71
+ " node-version: 22",
72
+ ` cache: ${pm}`,
73
+ " - uses: oven-sh/setup-bun@v2",
74
+ ].join("\n")
75
+ return ci
76
+ .replace(/^ {6}- uses: oven-sh\/setup-bun@v2$/m, setup)
77
+ .replace(
78
+ /Commit bun\.lock: --frozen-lockfile fails/,
79
+ `Commit ${p.lock}: a frozen install fails`,
80
+ )
81
+ .replace("bun install --frozen-lockfile", p.ci)
82
+ .replaceAll("bun run ", `${p.run} `)
83
+ .replaceAll("bunx ", `${p.x} `)
84
+ }
85
+
86
+ const TEMPLATE_DIRS: Record<Template, string> = {
87
+ web: "template",
88
+ api: "template-api",
89
+ full: "template-full",
90
+ }
21
91
 
22
92
  // The api template: a Hono Worker with Signet's request id, error envelope,
23
93
  // validation and exact Durable Object rate limiting already wired.
24
94
  const API_DEPS = {
25
- "@dapplelight/signet-server": "^0.3.0",
95
+ "@dapplelight/signet-server": "^0.5.0",
26
96
  hono: "^4.13.8",
27
97
  zod: "^4.6.5",
28
98
  }
29
99
 
100
+ // Added with MCP (--mcp, the default): signet-server's optional peer for /mcp.
101
+ const MCP_DEPS = {
102
+ "@modelcontextprotocol/server": "^2.1.0",
103
+ }
104
+
105
+ /**
106
+ * The api template marks MCP-only lines with `// mcp:begin` / `// mcp:end`
107
+ * lines: with MCP the markers go, without it the blocks go.
108
+ */
109
+ function applyMcp(text: string, mcp: boolean): string {
110
+ return mcp
111
+ ? text.replace(/^[ \t]*\/\/ mcp:(begin|end)\n/gm, "")
112
+ : text.replace(/^[ \t]*\/\/ mcp:begin\n[\s\S]*?^[ \t]*\/\/ mcp:end\n/gm, "")
113
+ }
114
+
30
115
  const API_DEV_DEPS = {
31
116
  "@biomejs/biome": "^2.5.14",
32
117
  "@types/bun": "^1.4.2",
33
118
  typescript: "^7.0.2",
34
- wrangler: "^4.136.3",
119
+ }
120
+
121
+ // What each --target adds over the shared api template: its own files (from
122
+ // template-api/_targets/<target>, copied over the shared ones), scripts and dev deps.
123
+ const API_TARGETS: Record<
124
+ Target,
125
+ {
126
+ scripts: Record<string, string>
127
+ devDeps?: Record<string, string>
128
+ engines?: Record<string, string>
129
+ }
130
+ > = {
131
+ cloudflare: {
132
+ scripts: { dev: "wrangler dev", deploy: "wrangler deploy" },
133
+ devDeps: { wrangler: "^4.136.3" },
134
+ },
135
+ bun: { scripts: { dev: "bun --watch src/server.ts", start: "bun src/server.ts" } },
136
+ node: {
137
+ scripts: { dev: "node --watch src/server.ts", start: "node src/server.ts" },
138
+ devDeps: { "@types/node": "^26.6.2" },
139
+ // Runs src/server.ts as is: type stripping is on by default from 22.18.
140
+ engines: { node: ">=22.18" },
141
+ },
142
+ vercel: { scripts: { dev: "bunx vercel dev", deploy: "bunx vercel deploy" } },
143
+ }
144
+
145
+ const API_NEXT_STEPS: Record<Target, string> = {
146
+ cloudflare: `Rate limiting is exact and per IP, backed by the RateLimitCounter Durable
147
+ Object in wrangler.jsonc. Append migration tags; never edit a deployed one.`,
148
+ bun: `bun run start serves src/server.ts under Bun.serve; the Dockerfile runs the same.
149
+ Rate limiting is in-process and keyed by the socket address.`,
150
+ node: `bun run start runs src/server.ts with node 22.18+ (node:http, no extra dependency).
151
+ Rate limiting is in-process and keyed by the socket address.`,
152
+ vercel: `index.ts is the Vercel entry (Hono preset, vercel.json). Deploy with bun run deploy.
153
+ Rate limiting is per function instance; see the comment in index.ts.`,
35
154
  }
36
155
 
37
156
  const DEPS = {
38
157
  // Real ranges, not workspace:* — the packages are published, so a scaffolded
39
158
  // app installs from npm and works anywhere. Inside this monorepo bun still
40
159
  // links the local copies, because the range matches the workspace version.
41
- "@dapplelight/signet-lib": "^0.2.0",
42
- "@dapplelight/signet-tokens": "^0.2.0",
43
- "@dapplelight/signet-ui": "^0.2.0",
160
+ "@dapplelight/signet-lib": "^0.4.0",
161
+ "@dapplelight/signet-tokens": "^0.3.0",
162
+ "@dapplelight/signet-ui": "^0.3.0",
44
163
  "@tanstack/react-query": "^5.103.2",
45
164
  "@tanstack/react-router": "^1.170.39",
46
165
  "class-variance-authority": "^0.7.1",
@@ -66,11 +185,51 @@ const DEV_DEPS = {
66
185
  vite: "^8.3.0",
67
186
  }
68
187
 
188
+ // The full template: the web app's deps plus the API's, signet-db and
189
+ // signet-payments for plans, admin, privacy and billing, and the screens' peers.
190
+ const FULL_DEPS = {
191
+ ...DEPS,
192
+ ...API_DEPS,
193
+ "@base-ui/react": "^1.3.0",
194
+ "@dapplelight/signet-db": "^0.2.0",
195
+ "@dapplelight/signet-payments": "^0.1.0",
196
+ "drizzle-orm": "^0.45.4",
197
+ "input-otp": "^1.4.2",
198
+ }
199
+
200
+ const FULL_DEV_DEPS = {
201
+ ...DEV_DEPS,
202
+ "@playwright/test": "^1.65.1",
203
+ "drizzle-kit": "^0.31.11",
204
+ }
205
+
206
+ const FULL_SCRIPTS = {
207
+ // Both halves: the API (restarting on change) and Vite, which proxies /api to it.
208
+ dev: "bun scripts/dev.ts",
209
+ build: "tsc -b && vite build",
210
+ // One process serves the API and the built app from dist/.
211
+ start: "bun api/server.ts",
212
+ preview: "vite preview",
213
+ lint: "biome check .",
214
+ format: "biome check --write .",
215
+ typecheck: "tsc -b --noEmit",
216
+ test: "bun test src test",
217
+ "test:e2e": "playwright test",
218
+ "db:generate": "drizzle-kit generate",
219
+ "db:check": "signet-db-check drizzle",
220
+ }
221
+
222
+ /** A fresh 48-character secret for the generated env file. */
223
+ const secret = () => Buffer.from(crypto.getRandomValues(new Uint8Array(36))).toString("base64url")
224
+
69
225
  function parseArgs(argv: string[]) {
70
226
  const args = argv.slice(2)
71
227
  let name: string | undefined
72
228
  let theme: Theme = "editorial"
73
229
  let template: Template = "web"
230
+ let target: Target | undefined
231
+ let mcp: boolean | undefined
232
+ let pm: Pm | undefined
74
233
 
75
234
  for (let i = 0; i < args.length; i++) {
76
235
  const a = args[i]
@@ -86,21 +245,50 @@ function parseArgs(argv: string[]) {
86
245
  throw new Error(`Unknown template "${v}". Available: ${TEMPLATES.join(", ")}`)
87
246
  }
88
247
  template = v as Template
248
+ } else if (a === "--target") {
249
+ const v = args[++i]
250
+ if (!TARGETS.includes(v as Target)) {
251
+ throw new Error(`Unknown target "${v}". Available: ${TARGETS.join(", ")}`)
252
+ }
253
+ target = v as Target
254
+ } else if (a === "--pm") {
255
+ const v = args[++i]
256
+ if (!PMS.includes(v as Pm)) {
257
+ throw new Error(`Unknown package manager "${v}". Available: ${PMS.join(", ")}`)
258
+ }
259
+ pm = v as Pm
260
+ } else if (a === "--mcp" || a === "--no-mcp") {
261
+ mcp = a === "--mcp"
89
262
  } else if (a === "--help" || a === "-h") {
90
263
  console.log(`
91
264
  create-signet-app <directory> [options]
92
265
 
93
266
  Options:
94
- --template <kind> web | api (default: web)
267
+ --template <kind> web | api | full (default: web)
95
268
  web: Vite + React + Signet UI
96
269
  api: Hono Worker with the error envelope, request ids,
97
270
  validation and Durable Object rate limiting
98
- -t, --theme <name> ${THEMES.join(" | ")} (default: editorial; web only)
271
+ full: web + API in one project, typed client between
272
+ them, SQLite with migrations, phone sign-in,
273
+ account, inbox, privacy, billing and admin
274
+ --target <runtime> ${TARGETS.join(" | ")} (default: cloudflare; api only)
275
+ cloudflare: Worker entry + wrangler.jsonc
276
+ bun: Bun.serve entry + Dockerfile
277
+ node: node:http entry (Node 22.18+)
278
+ vercel: Vercel entry + vercel.json
279
+ --mcp, --no-mcp api and full: serve the routes to agents at /mcp
280
+ (default: asks when interactive, else --mcp)
281
+ -t, --theme <name> ${THEMES.join(" | ")} (default: editorial; web and full)
282
+ --pm <name> ${PMS.join(" | ")} (default: the one that ran this, else bun)
283
+ Sets the commands in CI, the README and below.
99
284
  -h, --help
100
285
 
101
286
  Examples:
102
287
  bun create-signet-app my-app --theme cinematic
103
288
  bun create-signet-app my-api --template api
289
+ bun create-signet-app my-api --template api --target bun
290
+ bun create-signet-app my-app --template full --theme finance
291
+ npm create signet-app my-app -- --template full --pm npm
104
292
  `)
105
293
  process.exit(0)
106
294
  } else if (!a.startsWith("-")) {
@@ -111,7 +299,12 @@ Examples:
111
299
  }
112
300
 
113
301
  if (!name) throw new Error("Missing target directory.\nUsage: create-signet-app <directory>")
114
- return { name, theme, template }
302
+ if (target && template !== "api") throw new Error("--target applies to --template api only.")
303
+ if (mcp !== undefined && template === "web")
304
+ throw new Error("--mcp / --no-mcp apply to --template api and full only.")
305
+ if (theme !== "editorial" && template === "api")
306
+ throw new Error("--theme applies to --template web and full only.")
307
+ return { name, theme, template, target: target ?? "cloudflare", mcp, pm: pm ?? detectPm() }
115
308
  }
116
309
 
117
310
  /** Replace placeholders in every text file under dir. */
@@ -134,84 +327,163 @@ async function substitute(dir: string, vars: Record<string, string>) {
134
327
  }
135
328
  }
136
329
 
330
+ /** "Add MCP for agents?", default yes; only asked on a terminal. */
331
+ async function askMcp(): Promise<boolean> {
332
+ if (!process.stdin.isTTY) return true
333
+ const rl = createInterface({ input: process.stdin, output: process.stdout })
334
+ try {
335
+ const answer = (await rl.question(" Add MCP for agents? (Y/n) ")).trim().toLowerCase()
336
+ return answer === "" || answer.startsWith("y")
337
+ } finally {
338
+ rl.close()
339
+ }
340
+ }
341
+
137
342
  async function main() {
138
- const { name, theme, template } = parseArgs(process.argv)
139
- const target = resolve(process.cwd(), name)
140
- const appName = basename(target)
343
+ const { name, theme, template, target, pm, ...flags } = parseArgs(process.argv)
344
+ const dest = resolve(process.cwd(), name)
345
+ const appName = basename(dest)
141
346
 
142
- if (existsSync(target) && (await readdir(target)).length > 0) {
143
- throw new Error(`${target} already exists and is not empty.`)
347
+ if (existsSync(dest) && (await readdir(dest)).length > 0) {
348
+ throw new Error(`${dest} already exists and is not empty.`)
144
349
  }
145
350
 
146
- const templateDir = resolve(
147
- import.meta.dirname,
148
- template === "api" ? "../template-api" : "../template",
149
- )
150
- await mkdir(target, { recursive: true })
151
- await cp(templateDir, target, { recursive: true })
351
+ const mcp = template !== "web" && (flags.mcp ?? (await askMcp()))
352
+ const templateDir = resolve(import.meta.dirname, `../${TEMPLATE_DIRS[template]}`)
353
+ await mkdir(dest, { recursive: true })
354
+ const targetsDir = join(templateDir, "_targets")
355
+ const mcpDir = join(templateDir, "_mcp")
356
+ await cp(templateDir, dest, {
357
+ recursive: true,
358
+ filter: (src) => src !== targetsDir && src !== mcpDir,
359
+ })
360
+ // Only the chosen runtime's files, laid over the shared ones; MCP's tests with MCP.
361
+ if (template === "api") await cp(join(targetsDir, target), dest, { recursive: true })
362
+ if (mcp && existsSync(mcpDir)) await cp(mcpDir, dest, { recursive: true })
363
+ const mcpFiles: Record<Template, string[]> = {
364
+ web: [],
365
+ api: ["src/app.ts", "src/env.ts"],
366
+ full: ["api/app.ts", "api/env.ts"],
367
+ }
368
+ for (const f of mcpFiles[template]) {
369
+ const path = join(dest, f)
370
+ await writeFile(path, applyMcp(await readFile(path, "utf8"), mcp))
371
+ }
152
372
 
153
373
  // npm strips a file literally named .gitignore from published packages, so
154
374
  // the template ships it as _gitignore and it is renamed on scaffold.
155
375
  // .github goes the same way: npm can drop dot-directories from a package, so
156
376
  // the CI workflow ships under _github.
157
- await rename(join(target, "_gitignore"), join(target, ".gitignore"))
158
- await rename(join(target, "_github"), join(target, ".github"))
377
+ await rename(join(dest, "_gitignore"), join(dest, ".gitignore"))
378
+ await rename(join(dest, "_github"), join(dest, ".github"))
379
+ if (template === "api" && target === "bun")
380
+ await rename(join(dest, "_dockerignore"), join(dest, ".dockerignore"))
381
+ // pnpm (10+) refuses to install until build scripts are reviewed; esbuild's
382
+ // (vite, drizzle-kit, wrangler) and workerd's are the ones these templates
383
+ // pull in. allowBuilds is pnpm 11+, onlyBuiltDependencies pnpm 10.
384
+ if (pm === "pnpm")
385
+ await writeFile(
386
+ join(dest, "pnpm-workspace.yaml"),
387
+ "allowBuilds:\n esbuild: true\n workerd: true\nonlyBuiltDependencies:\n - esbuild\n - workerd\n",
388
+ )
389
+ const ci = join(dest, ".github/workflows/ci.yml")
390
+ await writeFile(ci, applyPm(await readFile(ci, "utf8"), pm))
159
391
 
160
- await substitute(target, { __APP_NAME__: appName, __THEME__: theme })
392
+ await substitute(dest, {
393
+ __APP_NAME__: appName,
394
+ __THEME__: theme,
395
+ __PM_INSTALL__: PM[pm].install,
396
+ __PM_RUN__: PM[pm].run,
397
+ __PM_X__: PM[pm].x,
398
+ })
161
399
 
400
+ if (template === "full") {
401
+ // The API's secrets for this machine, fresh per app; gitignored. Bun loads
402
+ // it on its own. Production sets these on the host instead.
403
+ await writeFile(
404
+ join(dest, ".env"),
405
+ [
406
+ "APP_ENV=development",
407
+ `SESSION_SECRET=${secret()}`,
408
+ `OTP_SECRET=${secret()}`,
409
+ "# Phone numbers (E.164, comma-separated) that become admins on sign-in.",
410
+ "ADMIN_PHONES=",
411
+ "BILLING=fake",
412
+ "",
413
+ ].join("\n"),
414
+ )
415
+ }
416
+
417
+ // signet-mcp's index reads the scripts below from this source by their
418
+ // shape: the api object first, the web object as the next literal.
419
+ const pkg = {
420
+ scripts:
421
+ template === "api"
422
+ ? {
423
+ ...API_TARGETS[target].scripts,
424
+ lint: "biome check .",
425
+ format: "biome check --write .",
426
+ typecheck: "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
427
+ test: "bun test",
428
+ }
429
+ : template === "full"
430
+ ? FULL_SCRIPTS
431
+ : {
432
+ dev: "vite",
433
+ build: "tsc -b && vite build",
434
+ preview: "vite preview",
435
+ lint: "biome check .",
436
+ format: "biome check --write .",
437
+ typecheck: "tsc -b --noEmit",
438
+ test: "bun test",
439
+ },
440
+ dependencies:
441
+ template === "api"
442
+ ? { ...API_DEPS, ...(mcp ? MCP_DEPS : {}) }
443
+ : template === "full"
444
+ ? { ...FULL_DEPS, ...(mcp ? MCP_DEPS : {}) }
445
+ : DEPS,
446
+ devDependencies:
447
+ template === "api"
448
+ ? { ...API_DEV_DEPS, ...API_TARGETS[target].devDeps }
449
+ : template === "full"
450
+ ? FULL_DEV_DEPS
451
+ : DEV_DEPS,
452
+ ...(template === "api" && API_TARGETS[target].engines
453
+ ? { engines: API_TARGETS[target].engines }
454
+ : {}),
455
+ }
162
456
  await writeFile(
163
- join(target, "package.json"),
164
- `${JSON.stringify(
165
- {
166
- name: appName,
167
- private: true,
168
- version: "0.1.0",
169
- type: "module",
170
- scripts:
171
- template === "api"
172
- ? {
173
- dev: "wrangler dev",
174
- deploy: "wrangler deploy",
175
- lint: "biome check .",
176
- format: "biome check --write .",
177
- typecheck: "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
178
- test: "bun test",
179
- }
180
- : {
181
- dev: "vite",
182
- build: "tsc -b && vite build",
183
- preview: "vite preview",
184
- lint: "biome check .",
185
- format: "biome check --write .",
186
- typecheck: "tsc -b --noEmit",
187
- test: "bun test",
188
- },
189
- dependencies: template === "api" ? API_DEPS : DEPS,
190
- devDependencies: template === "api" ? API_DEV_DEPS : DEV_DEPS,
191
- },
192
- null,
193
- 2,
194
- )}\n`,
457
+ join(dest, "package.json"),
458
+ `${JSON.stringify({ name: appName, private: true, version: "0.1.0", type: "module", ...pkg }, null, 2)}\n`,
195
459
  )
196
460
 
461
+ const { install, run } = PM[pm]
462
+ const steps = `cd ${name}\n ${install}\n ${run} dev`
197
463
  console.log(
198
464
  template === "api"
199
465
  ? `
200
- Created ${appName}, a Worker API.
466
+ Created ${appName}, an API for ${target}${mcp ? ", with MCP at /mcp (MCP=off turns it off)" : ""}.
467
+
468
+ ${steps}
469
+
470
+ ${API_NEXT_STEPS[target]}
471
+ `
472
+ : template === "full"
473
+ ? `
474
+ Created ${appName}: web app + API with the ${theme} theme${mcp ? ", MCP at /mcp" : ""}.
201
475
 
202
- cd ${name}
203
- bun install
204
- bun dev
476
+ ${steps}
205
477
 
206
- Rate limiting is exact and per IP, backed by the RateLimitCounter Durable
207
- Object in wrangler.jsonc. Append migration tags; never edit a deployed one.
478
+ Open the URL Vite prints and sign in with any phone number; in development
479
+ the code is printed in this terminal. Put your number in ADMIN_PHONES (.env)
480
+ to see /admin. README.md walks through the first day. The API runs on Bun,
481
+ whichever package manager installs it.
208
482
  `
209
- : `
483
+ : `
210
484
  Created ${appName} with the ${theme} theme.
211
485
 
212
- cd ${name}
213
- bun install
214
- bun dev
486
+ ${steps}
215
487
 
216
488
  Switch themes by editing the @dapplelight/signet-tokens import in src/app.css.
217
489
  `,
@@ -19,6 +19,3 @@ jobs:
19
19
  - run: bun run lint
20
20
  - run: bun run typecheck
21
21
  - run: bun run test
22
- # Bundles the Worker exactly as a deploy would, without credentials or
23
- # uploading: catches a missing Durable Object export or a bad binding.
24
- - run: bun run deploy --dry-run --outdir dist
@@ -0,0 +1,13 @@
1
+ import { expect, test } from "bun:test"
2
+
3
+ test("MCP=off answers /mcp with a 404", () => {
4
+ // The env is validated once per process, so the app runs in its own here.
5
+ const code = `
6
+ const { createApp } = await import("./src/app.ts")
7
+ const { memoryStore } = await import("@dapplelight/signet-server/middleware/rate-limit")
8
+ const app = createApp({ store: memoryStore(), trust: "none" })
9
+ const res = await app.request("/mcp", { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })
10
+ console.log(res.status)`
11
+ const run = Bun.spawnSync(["bun", "-e", code], { env: { ...Bun.env, MCP: "off" } })
12
+ expect(run.stdout.toString().trim()).toBe("404")
13
+ })
@@ -0,0 +1,49 @@
1
+ import { expect, test } from "bun:test"
2
+ import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
3
+ import { createApp } from "../src/app"
4
+
5
+ // The MCP endpoint at /mcp, over plain JSON-RPC (stateless HTTP, so each call
6
+ // stands alone). MCP=off is checked in mcp-off.test.ts: env is read once per process.
7
+ const app = () => createApp<Record<string, never>>({ store: memoryStore(), trust: "none" })
8
+
9
+ const rpc = async (api: ReturnType<typeof app>, method: string, params = {}, env = {}) => {
10
+ const res = await api.request(
11
+ "/mcp",
12
+ {
13
+ method: "POST",
14
+ headers: {
15
+ "content-type": "application/json",
16
+ accept: "application/json, text/event-stream",
17
+ "mcp-protocol-version": "2025-11-25",
18
+ },
19
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
20
+ },
21
+ env,
22
+ )
23
+ const text = await res.text()
24
+ const data = text.startsWith("{")
25
+ ? text
26
+ : (
27
+ text
28
+ .split("\n")
29
+ .filter((l) => l.startsWith("data: "))
30
+ .pop() ?? ""
31
+ ).slice(6)
32
+ return { status: res.status, body: data ? JSON.parse(data) : null }
33
+ }
34
+
35
+ test("validated routes are MCP tools", async () => {
36
+ const { body } = await rpc(app(), "tools/list")
37
+ const echo = body.result.tools.find((t: { name: string }) => t.name === "post_api_echo")
38
+ expect(echo.description).toBe("Echo a message back")
39
+ expect(echo.inputSchema.properties.message).toBeDefined()
40
+ })
41
+
42
+ test("a write tool asks for approval first, and does nothing without it", async () => {
43
+ const { body } = await rpc(app(), "tools/call", {
44
+ name: "post_api_echo",
45
+ arguments: { message: "hi" },
46
+ })
47
+ expect(body.result.isError).toBe(true)
48
+ expect(body.result.structuredContent.code).toBe("APPROVAL_REQUIRED")
49
+ })
@@ -0,0 +1,13 @@
1
+ # Runs the API under Bun (src/server.ts), not as a Worker.
2
+ # docker build -t __APP_NAME__ .
3
+ # docker run -p 3000:3000 __APP_NAME__
4
+ FROM oven/bun:1
5
+ WORKDIR /app
6
+ # Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
7
+ COPY package.json bun.lock ./
8
+ RUN bun install --frozen-lockfile --production
9
+ COPY src ./src
10
+ ENV APP_ENV=production PORT=3000
11
+ EXPOSE 3000
12
+ USER bun
13
+ CMD ["bun", "src/server.ts"]
@@ -0,0 +1,10 @@
1
+ node_modules
2
+ dist
3
+ .out
4
+ .wrangler
5
+ .dev.vars
6
+ .env
7
+ .env.local
8
+ .git
9
+ .github
10
+ *.log
@@ -0,0 +1,32 @@
1
+ /// <reference types="bun" />
2
+ // Bun and Docker entry: the app in ./app.ts, served by Bun.serve.
3
+ // Run `bun src/server.ts`, or build the Dockerfile.
4
+ import { memoryStore } from "@dapplelight/signet-server/middleware/rate-limit"
5
+ import { createApp } from "./app.ts"
6
+
7
+ const hops = process.env.TRUSTED_PROXY_HOPS
8
+
9
+ const app = createApp<Record<string, never>>({
10
+ // One process, so an in-memory count is exact. Running several replicas?
11
+ // Share the count: upstashRateLimitStore from @dapplelight/signet-server/adapters/upstash.
12
+ store: memoryStore(),
13
+ // Behind proxies of your own (a load balancer, a PaaS router), set
14
+ // TRUSTED_PROXY_HOPS to how many, and the client IP comes from
15
+ // x-forwarded-for. Otherwise fetch below replaces that header with the
16
+ // socket's peer address, so one hop (this server) is all there is to trust.
17
+ trust: { forwardedHops: hops ? Number(hops) : 1 },
18
+ })
19
+
20
+ const server = Bun.serve({
21
+ port: Number(process.env.PORT ?? 3000),
22
+ fetch(req, srv) {
23
+ if (hops) return app.fetch(req)
24
+ // Overwrite, never append: a client-supplied x-forwarded-for must not pick its bucket.
25
+ // The rate limiter then groups an IPv6 peer by its /64, like any other client IP.
26
+ const headers = new Headers(req.headers)
27
+ headers.set("x-forwarded-for", srv.requestIP(req)?.address ?? "")
28
+ return app.fetch(new Request(req, { headers }))
29
+ },
30
+ })
31
+
32
+ console.log(`Listening on ${server.url}`)
@@ -0,0 +1,24 @@
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+
8
+ permissions:
9
+ contents: read
10
+
11
+ jobs:
12
+ verify:
13
+ runs-on: ubuntu-latest
14
+ steps:
15
+ - uses: actions/checkout@v4
16
+ - uses: oven-sh/setup-bun@v2
17
+ # Commit bun.lock: --frozen-lockfile fails the build if it is missing or stale.
18
+ - run: bun install --frozen-lockfile
19
+ - run: bun run lint
20
+ - run: bun run typecheck
21
+ - run: bun run test
22
+ # Bundles the Worker exactly as a deploy would, without credentials or
23
+ # uploading: catches a missing Durable Object export or a bad binding.
24
+ - run: bun run deploy --dry-run --outdir dist
@@ -0,0 +1,17 @@
1
+ import {
2
+ durableObjectStore,
3
+ type RateLimitNamespace,
4
+ } from "@dapplelight/signet-server/middleware/rate-limit-do"
5
+ import { createApp } from "./app.ts"
6
+
7
+ // The Durable Object behind the rate limiter. wrangler.jsonc binds it as
8
+ // RATE_LIMIT and its first migration creates it. A Worker entry may export only
9
+ // handlers and classes like this one — workerd rejects anything else (a string
10
+ // constant) with "Incorrect type for map entry".
11
+ export { RateLimitCounter } from "@dapplelight/signet-server/middleware/rate-limit-do"
12
+
13
+ // Exact per-IP limit: one Durable Object per scope:key.
14
+ export default createApp<{ RATE_LIMIT: RateLimitNamespace }>({
15
+ store: (c) => durableObjectStore(c.env.RATE_LIMIT),
16
+ trust: "cloudflare",
17
+ })