create-signet-app 0.4.8 → 0.5.0

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 (87) hide show
  1. package/README.md +114 -33
  2. package/{template-full → base/api}/api/app.ts +52 -9
  3. package/base/api/api/db/open.ts +121 -0
  4. package/{template-full → base/api}/api/db/schema.ts +22 -7
  5. package/{template-full → base/api}/api/env.ts +8 -0
  6. package/base/api/api/server.ts +157 -0
  7. package/{template-full → base/api}/api/services.ts +61 -8
  8. package/base/api/test/api.test.ts +51 -0
  9. package/base/api/test/helpers.ts +51 -0
  10. package/base/both/scripts/dev.ts +44 -0
  11. package/base/shared/README.md +298 -0
  12. package/{template-full → base/shared}/_github/workflows/ci.yml +1 -1
  13. package/{template-full → base/web}/src/lib/api.ts +28 -1
  14. package/{template-full → base/web}/src/main.tsx +4 -1
  15. package/{template-full → base/web}/src/routeTree.gen.ts +130 -90
  16. package/{template-full → base/web}/src/router.test.ts +12 -9
  17. package/base/web/src/routes/_app/index.tsx +55 -0
  18. package/{template-full → base/web}/src/routes/_app.tsx +39 -16
  19. package/{template-full → base/web}/vite.config.ts +3 -1
  20. package/package.json +5 -4
  21. package/parts/account/api/test/account.test.ts +30 -0
  22. package/parts/account/part.ts +6 -0
  23. package/parts/admin/api/test/admin.test.ts +35 -0
  24. package/parts/admin/part.ts +6 -0
  25. package/{template-full → parts/admin/web}/src/routes/_app/admin.tsx +2 -1
  26. package/{template-full → parts/auth/api}/api/routes/account.ts +32 -3
  27. package/{template-full → parts/auth/api}/api/routes/auth.ts +5 -3
  28. package/parts/auth/api/test/auth.test.ts +28 -0
  29. package/{template-full → parts/auth/both}/e2e/smoke.spec.ts +21 -7
  30. package/parts/auth/part.ts +22 -0
  31. package/parts/growth/part.ts +7 -0
  32. package/{template-full/_mcp → parts/mcp/api}/test/mcp.test.ts +25 -16
  33. package/parts/mcp/part.ts +8 -0
  34. package/parts/notifications/api/test/notifications.test.ts +18 -0
  35. package/parts/notifications/part.ts +6 -0
  36. package/{template-full → parts/notifications/web}/src/routes/_app/notifications.tsx +1 -1
  37. package/parts/orgs/api/test/orgs.test.ts +56 -0
  38. package/parts/orgs/part.ts +7 -0
  39. package/{template-full → parts/payments/api}/api/routes/billing.ts +3 -2
  40. package/parts/payments/api/test/payments.test.ts +31 -0
  41. package/parts/payments/part.ts +12 -0
  42. package/{template-full → parts/payments/web}/src/routes/_app/billing.tsx +6 -3
  43. package/parts/privacy/api/test/privacy.test.ts +20 -0
  44. package/parts/privacy/part.ts +7 -0
  45. package/src/compose.ts +369 -0
  46. package/src/desktop.ts +10 -10
  47. package/src/index.ts +368 -174
  48. package/template-api/_targets/deno/Dockerfile +12 -0
  49. package/template-api/_targets/deno/_dockerignore +10 -0
  50. package/template-api/_targets/deno/src/server.ts +43 -0
  51. package/template-full/README.md +0 -166
  52. package/template-full/api/db/open.ts +0 -33
  53. package/template-full/api/server.ts +0 -50
  54. package/template-full/scripts/dev.ts +0 -17
  55. package/template-full/src/routes/_app/index.tsx +0 -33
  56. package/template-full/test/api.test.ts +0 -238
  57. package/template-full/tsconfig.json +0 -9
  58. /package/{template-full → base/api}/api/db/index.ts +0 -0
  59. /package/{template-full → base/api}/api/db/kv.ts +0 -0
  60. /package/{template-full → base/api}/drizzle/0000_init.sql +0 -0
  61. /package/{template-full → base/api}/drizzle/0001_orgs.sql +0 -0
  62. /package/{template-full → base/api}/drizzle/meta/0000_snapshot.json +0 -0
  63. /package/{template-full → base/api}/drizzle/meta/0001_snapshot.json +0 -0
  64. /package/{template-full → base/api}/drizzle/meta/_journal.json +0 -0
  65. /package/{template-full → base/api}/drizzle.config.ts +0 -0
  66. /package/{template-full → base/api}/tsconfig.api.json +0 -0
  67. /package/{template-full → base/shared}/_gitignore +0 -0
  68. /package/{template-full → base/shared}/biome.json +0 -0
  69. /package/{template-full → base/web}/index.html +0 -0
  70. /package/{template-full → base/web}/src/app.css +0 -0
  71. /package/{template-full → base/web}/src/components/toaster.tsx +0 -0
  72. /package/{template-full → base/web}/src/router.ts +0 -0
  73. /package/{template-full → base/web}/src/routes/__root.tsx +0 -0
  74. /package/{template-full → base/web}/tsconfig.app.json +0 -0
  75. /package/{template-full → base/web}/tsconfig.node.json +0 -0
  76. /package/{template-full → base/web}/tsconfig.test.json +0 -0
  77. /package/{template-full → parts/account/web}/src/routes/_app/account.tsx +0 -0
  78. /package/{template-full → parts/auth/both}/playwright.config.ts +0 -0
  79. /package/{template-full → parts/auth/web}/src/routes/login.tsx +0 -0
  80. /package/{template-full → parts/notifications/api}/api/routes/notifications.ts +0 -0
  81. /package/{template-full → parts/orgs/web}/src/routes/_app/org/index.tsx +0 -0
  82. /package/{template-full → parts/orgs/web}/src/routes/_app/org/members.tsx +0 -0
  83. /package/{template-full → parts/orgs/web}/src/routes/_app/org/new.tsx +0 -0
  84. /package/{template-full → parts/orgs/web}/src/routes/invite.$token.tsx +0 -0
  85. /package/{template-full → parts/payments/api}/api/plans.ts +0 -0
  86. /package/{template-full → parts/privacy/api}/api/routes/privacy.ts +0 -0
  87. /package/{template-full → parts/privacy/web}/src/routes/_app/privacy.tsx +0 -0
package/README.md CHANGED
@@ -4,62 +4,131 @@ 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
- npx create-signet-app@latest my-app --template full
7
+ npx create-signet-app@latest my-app --starter full
8
8
  cd my-app
9
9
  npm install
10
10
  npm run dev
11
11
  ```
12
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
13
+ With pnpm: `pnpm create signet-app my-app --starter full`. With bun:
14
+ `bunx create-signet-app my-app --starter full`. Then install and `run dev` with
15
+ the same manager. Open `http://localhost:5173`. A composed app needs
16
16
  [Bun](https://bun.sh) 1.3+ installed: `run dev` is a Bun script, whichever
17
17
  package manager installs the app.
18
18
 
19
19
  `--theme` takes `editorial`, `cinematic` or `finance` (editorial plus the
20
20
  spend-category and money tokens; default `editorial`).
21
21
 
22
- `--pm bun|npm|pnpm` sets the commands printed after scaffolding, in the CI
23
- workflow (setup, frozen install, `<pm> run`) and in the full template's README.
24
- Default: the package manager that ran it (`npm create` / `pnpm create` say so
25
- in `npm_config_user_agent`), else bun. With pnpm a `pnpm-workspace.yaml`
26
- approves esbuild's and workerd's build scripts, which pnpm 10+ otherwise refuses
27
- to install without. Tests stay on `bun test`, so CI sets up Bun too.
28
-
29
- ## Which template
30
-
31
- `--template` defaults to `web`.
32
-
33
- | Template | Frontend | API | Database | Auth | MCP | Runs on |
22
+ `--pm bun|npm|pnpm|yarn|deno` sets the commands printed after scaffolding, in
23
+ the CI workflow (setup, frozen install, `<pm> run` or `deno task`) and in the
24
+ app's README. Default: the package manager that ran it (`npm create`, `pnpm
25
+ create`, `yarn create`, `bunx`, `deno run` say so in `npm_config_user_agent`),
26
+ else bun. With pnpm a `pnpm-workspace.yaml` approves esbuild's and workerd's
27
+ build scripts, which pnpm 10+ otherwise refuses to install without. With yarn
28
+ the app pins modern Yarn in `packageManager` (CI runs `corepack enable`), uses
29
+ a plain `node_modules` (`.yarnrc.yml`), and lists signet-ui's required peers,
30
+ which Yarn does not install on its own. Deno 2 installs and runs the
31
+ `package.json` scripts; `--platform cli` is refused with deno, as its build is
32
+ `bun build --compile`. Tests stay on `bun test`, so CI sets up Bun too.
33
+ `bun run test/scaffold-pm.ts` scaffolds the full starter and the web platform with each
34
+ manager installed on the machine, installs, typechecks and builds.
35
+
36
+ ## Which platform
37
+
38
+ `--platform` defaults to `web`. `--template` is its old name and still works;
39
+ `--template full` is `--starter full` (below).
40
+
41
+ | Platform | Frontend | API | Database | Auth | MCP | Runs on |
34
42
  |---|---|---|---|---|---|---|
35
43
  | `web` | Vite + React + Signet UI, TanStack Router | none (a configured `createApiClient` for yours) | none | placeholder `/login` | no | any static host |
36
44
  | `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
45
  | `cli` | none | none | none | device-code login | no | one compiled Bun binary |
39
46
  | `extension` | Chrome MV3: popup, options, service worker | none | none | PKCE via `chrome.identity` | no | Chrome |
40
47
  | `desktop` | Tauri v2 window and menu-bar app | none | none | browser sign-in (PKCE, loopback) | no | macOS, Windows, Linux |
41
48
 
49
+ ## Composed apps: parts, starters, `--ui` and `--api`
50
+
51
+ A web app and its API in one project, built from **parts**. Any of these flags
52
+ composes one (they do not mix with `--platform`):
53
+
54
+ ```bash
55
+ bunx create-signet-app my-app --starter full # every part, web + API
56
+ bunx create-signet-app my-app --with payments,notifications # those, plus what they need
57
+ bunx create-signet-app my-app --without admin,privacy # the full starter without them
58
+ bunx create-signet-app my-api --api --with orgs # the API half only
59
+ bunx create-signet-app my-ui --ui --with account # the web half only
60
+ bunx create-signet-app my-app --starter blank # no parts: shell, API, database
61
+ ```
62
+
63
+ - **Surfaces.** Both halves by default. `--ui` writes the web half only: its
64
+ client calls an API elsewhere (`VITE_API_URL`, else the same origin), untyped
65
+ until you point `src/lib/api.ts` at that API's `AppType`. `--api` writes the
66
+ API half only: no web files, no Vite. `--ui --api` together is an error (it
67
+ is the default).
68
+ - **Starters** are named mixes of parts: `full` (every part; `--template full`
69
+ is the same) and `blank` (none). `--with` adds to the starter, `--without`
70
+ takes away; `--without` alone starts from `full`.
71
+ - **Needs** come along on their own and the output says so (`--with payments`
72
+ prints `added auth for payments`). Leaving out a part another one needs is
73
+ an error.
74
+ - **Runtime.** `--target bun|deno|node` picks what runs the API (default
75
+ `bun`: Bun.serve and bun:sqlite, as before). `deno` (Deno 2) and `node`
76
+ (22.18+) get node:sqlite under Drizzle and a node:http server instead, and
77
+ their `dev`/`start` scripts run on that runtime with `.env` loaded. Tests stay
78
+ on `bun test` (Bun runs node:sqlite too). `bun run test/scaffold-runtime.ts` serves the
79
+ full starter on each runtime installed and checks `/api/health`, an MCP call
80
+ and the built page.
81
+ - **MCP** is the `mcp` part. As before it is asked for on a terminal (default
82
+ yes) unless `--mcp`, `--no-mcp`, `--with mcp` or `--without mcp` says.
83
+
84
+ | Part | What it adds | Needs |
85
+ |---|---|---|
86
+ | `auth` | phone one-time codes, stored sessions, `/login`, sign-out | |
87
+ | `account` | `/account`: profile, signed-in devices, API keys | auth |
88
+ | `orgs` | a personal org each, members, roles, invite links, `/org`, `/invite/$token`, tenant middleware | auth |
89
+ | `admin` | `/admin`: the operator's panel over every table, by platform role | auth, orgs |
90
+ | `notifications` | the in-app inbox and preferences, `/notifications` | auth |
91
+ | `privacy` | DPDP consent and data export / erasure requests, `/privacy` | auth |
92
+ | `payments` | plans (`api/plans.ts`), entitlements, `/billing`, gateway webhooks | auth |
93
+ | `growth` | waitlist, invites, referral codes, referrals, feedback and marks tables, with signet-db's `createGrowth` (API only) | |
94
+ | `mcp` | the API's validated routes as tools at `/mcp` (API only) | |
95
+
96
+ ### How parts are put together
97
+
98
+ `base/` is the app with no parts; `parts/<name>/` holds what one part adds,
99
+ with a small typed manifest (`part.ts`: needs, dependencies, env lines, its
100
+ tables). Both are split into halves, each laid over the app root: `shared/`
101
+ (always), `web/`, `api/`, and `both/` (with both surfaces). Code several parts
102
+ share (`api/app.ts`, the schema, `services.ts`, the shell and nav, the route
103
+ tree, the tests' helpers) lives in `base/` once, with each part's lines marked
104
+ `// <part>:begin` / `// <part>:end` (or a single line ending in `// @<part>`;
105
+ `!<part>` means without it; `web` and `api` are the surfaces). The composer
106
+ keeps the chosen lines and drops every marker, so an app has no trace of the
107
+ parts it left out. The migrations in `base/api/drizzle/` cover every table; the
108
+ composer keeps the statements and snapshot entries for the chosen parts' tables,
109
+ so `db:check` passes and `db:generate` finds nothing to do.
110
+
42
111
  ## AI-assisted planning: `--describe`
43
112
 
44
113
  ```bash
45
114
  bunx create-signet-app my-app --describe "a team inbox with settings and pricing"
46
115
  ```
47
116
 
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`.
117
+ One sentence picks the platform (`web` or `api`) or the `full` starter and the
118
+ theme, splits the sentence into pages, asks signet-mcp's `plan_page` about each,
119
+ scaffolds the app, and writes `PLAN.md` (the pages, with blocks, components,
120
+ data and files for each) and `AGENTS.md` (the instructions an agent working in
121
+ the app should follow). It is deterministic and makes no LLM call: the same
122
+ sentence always gives the same files. Keyword lists choose between Signet's own
123
+ platforms and themes; a sentence that names none gets `web` and `editorial`.
55
124
 
56
- An explicit `--template` or `--theme` wins over what the sentence implies.
125
+ An explicit `--platform` or `--theme` wins over what the sentence implies.
57
126
  `--describe` applies to `web`, `api` and `full` only.
58
127
 
59
- ## `--template full`: web app + API in one project
128
+ ## `--starter full`: web app + API in one project
60
129
 
61
130
  ```bash
62
- npx create-signet-app@latest my-app --template full
131
+ npx create-signet-app@latest my-app --starter full
63
132
  cd my-app
64
133
  npm install
65
134
  npm run dev
@@ -107,9 +176,11 @@ same-origin. In dev, Vite proxies `/api` to it. What a fresh app has:
107
176
  across orgs.
108
177
  - **Env.** `api/env.ts` (`createEnv`), and a generated, gitignored env file
109
178
  with fresh `SESSION_SECRET` / `OTP_SECRET`.
110
- - **MCP** as in the api template (`--mcp` / `--no-mcp`).
111
- - **Tests.** `test/api.test.ts` drives sign-in, plans, inbox, admin roles,
112
- consent and sign-out against an in-memory database; `src/router.test.ts`
179
+ - **MCP** as in the api platform (`--mcp` / `--no-mcp`).
180
+ - **Tests.** One file per part under `test/` (`auth.test.ts`,
181
+ `payments.test.ts`, …, sharing `test/helpers.ts`) drives sign-in, plans,
182
+ inbox, admin roles, consent, API keys, orgs and sign-out against an in-memory
183
+ database; `src/router.test.ts`
113
184
  resolves every page; `e2e/smoke.spec.ts` (Playwright, `test:e2e`) starts the
114
185
  server with a throwaway database, reads the code from its console and goes
115
186
  sign-in → admin → billing → inbox → account → privacy in headless Chromium,
@@ -156,9 +227,9 @@ copied between repos as a block. Copy-paste is not configuration.
156
227
  paint — React mounts too late, and without it there is a visible flash
157
228
  - `src/lib/api.ts` with a configured `createApiClient`
158
229
 
159
- ## `--template api`: a Hono API on the runtime you pick
230
+ ## `--platform api`: a Hono API on the runtime you pick
160
231
 
161
- `bun create-signet-app my-api --template api [--target cloudflare|bun|node|vercel]`
232
+ `bun create-signet-app my-api --platform api [--target cloudflare|bun|node|vercel]`
162
233
  scaffolds a Hono API. Every target shares `src/app.ts`, `src/env.ts`, the tests
163
234
  and CI; `--target` decides the entry and its config, and only that target's
164
235
  files are written:
@@ -260,7 +331,17 @@ config into anything new produces a crash.
260
331
 
261
332
  ## Test
262
333
 
263
- `test/scaffold-full.ts` scaffolds the full template outside the monorepo with
334
+ `bun run test/scaffold-parts.ts` scaffolds each part alone (plus what it needs), no
335
+ parts and every part, on each surface (`--ui`, `--api`, both), and checks each
336
+ app: no markers or placeholders left, only its surfaces' files, every
337
+ dependency imported (or a peer of one that is) and every import declared, lint,
338
+ typecheck, its tests, and the build (web) or `db:check` plus a `drizzle-kit
339
+ generate` that finds nothing to do (api). Every app's dependencies are
340
+ installed once, into one shared directory each app links to; the apps run in
341
+ parallel, and a step over files identical to an earlier app's runs once.
342
+ `bun run test/scaffold-parts.ts api payments` runs one.
343
+
344
+ `test/scaffold-full.ts` scaffolds the full starter outside the monorepo with
264
345
  `--theme finance`, installs packs of every Signet package it uses, then lints,
265
346
  typechecks, runs the app's tests, builds, checks the finance tokens reached the
266
347
  CSS, and runs the app's Playwright smoke test headless. A `--no-mcp --pm pnpm`
@@ -1,9 +1,17 @@
1
+ // auth:begin
1
2
  import { sessionRoutes } from "@dapplelight/signet-server/auth/hono"
3
+ // auth:end
4
+ // orgs:begin
2
5
  import { maskPhone } from "@dapplelight/signet-server/auth/otp"
6
+ // orgs:end
3
7
  import { errorHandler } from "@dapplelight/signet-server/http"
8
+ // admin:begin
4
9
  import { adminRoutes } from "@dapplelight/signet-server/http/admin"
5
10
  import { ApiException } from "@dapplelight/signet-server/http/errors"
11
+ // admin:end
12
+ // orgs:begin
6
13
  import { orgRoutes, tenant } from "@dapplelight/signet-server/http/orgs"
14
+ // orgs:end
7
15
  // mcp:begin
8
16
  import { appTools } from "@dapplelight/signet-server/mcp"
9
17
  import { mountMcp } from "@dapplelight/signet-server/mcp/hono"
@@ -15,40 +23,59 @@ import { healthRoutes } from "@dapplelight/signet-server/observability/health"
15
23
  import { createLogger } from "@dapplelight/signet-server/observability/logger"
16
24
  import { requestLog } from "@dapplelight/signet-server/observability/request-log"
17
25
  import { traceMiddleware } from "@dapplelight/signet-server/observability/trace"
26
+ // orgs:begin
18
27
  import { inArray } from "drizzle-orm"
28
+ // orgs:end
19
29
  import { Hono } from "hono"
20
- import { type User, users } from "./db/schema.ts"
30
+ // auth:begin
31
+ import { type User, users } from "./db/schema.ts" // @orgs
32
+ import type { User } from "./db/schema.ts" // @!orgs
33
+ // auth:end
21
34
  import { env } from "./env.ts"
35
+ // auth:begin
22
36
  import { accountRoutes } from "./routes/account.ts"
23
37
  import { authRoutes, requireUser } from "./routes/auth.ts"
38
+ // auth:end
39
+ // payments:begin
24
40
  import { billingRoutes, billingWebhooks } from "./routes/billing.ts"
41
+ // payments:end
42
+ // notifications:begin
25
43
  import { notificationRoutes } from "./routes/notifications.ts"
44
+ // notifications:end
45
+ // privacy:begin
26
46
  import { privacyRoutes } from "./routes/privacy.ts"
27
- import { createServices, type Deps, TRUST } from "./services.ts"
47
+ // privacy:end
48
+ import { createServices, type Deps, TRUST } from "./services.ts" // @auth
49
+ import { type Deps, TRUST } from "./services.ts" // @!auth
28
50
 
29
- export type AppEnv = { Variables: { reqId: string; user: User } }
51
+ export type AppEnv = { Variables: { reqId: string; user: User } } // @auth
52
+ export type AppEnv = { Variables: { reqId: string } } // @!auth
30
53
 
54
+ // auth:begin
31
55
  /** Paths that need a signed-in user. Everything else under /api is public. */
32
56
  const SIGNED_IN = [
33
- "/api/account",
34
- "/api/notifications",
35
- "/api/privacy",
36
- "/api/billing",
37
- "/api/admin",
57
+ "/api/account", // the user, profile and API keys
58
+ "/api/notifications", // the inbox // @notifications
59
+ "/api/privacy", // consent and data requests // @privacy
60
+ "/api/billing", // plan and checkout // @payments
61
+ "/api/admin", // the operator's admin API // @admin
38
62
  ]
63
+ // auth:end
39
64
 
40
65
  /** Probes stay out of spans and logs. */
41
66
  const HEALTH_PATHS = ["/health/live", "/health/ready"]
42
67
 
68
+ // orgs:begin
43
69
  /** An invite link can be looked at before signing in; everything else under /api/orgs needs a user. */
44
70
  const INVITE_PREVIEW = /^\/api\/orgs\/invites\/[^/]+$/
71
+ // orgs:end
45
72
 
46
73
  /**
47
74
  * The API. server.ts serves it (and the built web app) under Bun; tests call
48
75
  * `createApp(deps).request(...)` with an in-memory database.
49
76
  */
50
77
  export function createApp(deps: Deps) {
51
- const s = createServices(deps)
78
+ const s = createServices(deps) // @auth
52
79
  const base = new Hono<AppEnv>().use("*", requestId())
53
80
  // Off unless server.ts passes `observability` (OBSERVABILITY=on): then a span
54
81
  // and a JSON log line pair per request, both carrying the trace id, and
@@ -68,7 +95,10 @@ export function createApp(deps: Deps) {
68
95
  // served from this same origin, so nothing else needs trusting.
69
96
  base.use("/api/*", csrfMiddleware())
70
97
  base.use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
98
+ // auth:begin
71
99
  for (const path of SIGNED_IN) base.use(`${path}/*`, requireUser(s))
100
+ // auth:end
101
+ // orgs:begin
72
102
  const gate = requireUser(s)
73
103
  base.use("/api/orgs/*", (c, next) =>
74
104
  c.req.method === "GET" && INVITE_PREVIEW.test(c.req.path) ? next() : gate(c, next),
@@ -77,16 +107,26 @@ export function createApp(deps: Deps) {
77
107
  // ORG_ROOT_DOMAIN, the x-org header, or the cookie the switcher sets. It
78
108
  // grants nothing: /api/orgs checks membership on every call.
79
109
  base.use("/api/*", tenant({ orgs: s.orgs, rootDomain: env.ORG_ROOT_DOMAIN }))
110
+ // orgs:end
80
111
 
81
112
  const app = base
82
113
  .get("/api/health", (c) => c.json({ ok: true }))
114
+ // auth:begin
83
115
  .route("/api/auth", authRoutes(s))
84
116
  .route("/api/sessions", sessionRoutes(s.sessions))
85
117
  .route("/api/account", accountRoutes(s))
118
+ // auth:end
119
+ // notifications:begin
86
120
  .route("/api/notifications", notificationRoutes(s))
121
+ // notifications:end
122
+ // privacy:begin
87
123
  .route("/api/privacy", privacyRoutes(s))
124
+ // privacy:end
125
+ // payments:begin
88
126
  .route("/api/billing", billingRoutes(s))
89
127
  .route("/api/webhooks", billingWebhooks(s))
128
+ // payments:end
129
+ // orgs:begin
90
130
  // Orgs: switch, settings, members, invites (signet-server orgRoutes).
91
131
  // Guard your own org routes the same way: orgGuards({ orgs: s.orgs, userId })
92
132
  // .requirePermission("projects:write"), then scoped(s.db, { orgId: currentTenant(c).id }).
@@ -108,6 +148,8 @@ export function createApp(deps: Deps) {
108
148
  ),
109
149
  }),
110
150
  )
151
+ // orgs:end
152
+ // admin:begin
111
153
  // The operator's admin API over every org (signet-db defineAdmin, config
112
154
  // in services.ts): platform roles readonly, staff and admin (ADMIN_PHONES)
113
155
  // only; everyone else gets 403. Org owners manage their org under /org.
@@ -122,6 +164,7 @@ export function createApp(deps: Deps) {
122
164
  },
123
165
  }),
124
166
  )
167
+ // admin:end
125
168
  .onError(errorHandler({ isProduction }))
126
169
 
127
170
  if (obs) {
@@ -0,0 +1,121 @@
1
+ import { Database } from "bun:sqlite" // @bun
2
+ import { mkdirSync } from "node:fs"
3
+ import { dirname, join } from "node:path"
4
+ import { DatabaseSync } from "node:sqlite" // @!bun
5
+ import { fromDrizzle } from "@dapplelight/signet-db" // @!bun
6
+ import { createDb } from "@dapplelight/signet-db/sqlite" // @bun
7
+ import { paymentsSchema } from "@dapplelight/signet-payments" // @payments
8
+ // !bun:begin
9
+ import { createTableRelationsHelpers, extractTablesRelationalConfig } from "drizzle-orm"
10
+ import { migrate } from "drizzle-orm/better-sqlite3/migrator"
11
+ import { BetterSQLiteSession } from "drizzle-orm/better-sqlite3/session"
12
+ import { BaseSQLiteDatabase, SQLiteSyncDialect } from "drizzle-orm/sqlite-core"
13
+ // !bun:end
14
+ import { migrate } from "drizzle-orm/bun-sqlite/migrator" // @bun
15
+ import type { Db } from "./index.ts" // @bun
16
+ import type { Db, Orm } from "./index.ts" // @!bun
17
+ import * as schema from "./schema.ts"
18
+
19
+ const MIGRATIONS = join(import.meta.dirname, "../../drizzle")
20
+
21
+ /**
22
+ * Open (or create) the database and bring it up to date. `query` runs raw SQL
23
+ * with `?` placeholders, for signet-payments' store.
24
+ */
25
+ export function openDb(path: string): {
26
+ db: Db
27
+ query: (sql: string, params: unknown[]) => Record<string, unknown>[]
28
+ } {
29
+ if (path !== ":memory:") mkdirSync(dirname(path), { recursive: true })
30
+ // bun:begin
31
+ const sqlite = new Database(path)
32
+ if (path !== ":memory:") sqlite.run("pragma journal_mode = wal")
33
+ const db = createDb(sqlite, { schema, audit: schema.audit, idempotency: schema.idempotency })
34
+ // bun:end
35
+ // !bun:begin
36
+ // node:sqlite runs under Node 22.18+, Deno 2 and Bun alike (bun test uses it).
37
+ const sqlite = new DatabaseSync(path)
38
+ if (path !== ":memory:") sqlite.exec("pragma journal_mode = wal")
39
+ const db = fromDrizzle(orm(sqlite), {
40
+ dialect: "sqlite",
41
+ atomicity: "sync-transaction",
42
+ audit: schema.audit,
43
+ idempotency: schema.idempotency,
44
+ })
45
+ // !bun:end
46
+ // Your tables: the migrations drizzle-kit writes from api/db/schema.ts.
47
+ migrate(db.orm, { migrationsFolder: MIGRATIONS })
48
+ // payments:begin
49
+ // signet-payments' webhook inbox, payment records and ledger: its own
50
+ // CREATE TABLE IF NOT EXISTS statements, versioned with the package.
51
+ for (const statement of paymentsSchema("sqlite")) sqlite.run(statement) // @bun
52
+ for (const statement of paymentsSchema("sqlite")) sqlite.exec(statement) // @!bun
53
+ // payments:end
54
+ return {
55
+ db,
56
+ query: (s, p) => sqlite.query<Record<string, unknown>, never[]>(s).all(...(p as never[])), // @bun
57
+ query: (s, p) => sqlite.prepare(s).all(...(p as never[])) as Record<string, unknown>[], // @!bun
58
+ }
59
+ }
60
+ // !bun:begin
61
+
62
+ /**
63
+ * Drizzle over node:sqlite: the better-sqlite3 driver's session (its entry
64
+ * would load the better-sqlite3 package) on the client below.
65
+ */
66
+ function orm(sqlite: DatabaseSync): Orm {
67
+ const dialect = new SQLiteSyncDialect()
68
+ const tables = extractTablesRelationalConfig(schema, createTableRelationsHelpers)
69
+ const relational = {
70
+ fullSchema: schema,
71
+ schema: tables.tables,
72
+ tableNamesMap: tables.tableNamesMap,
73
+ }
74
+ const session = new BetterSQLiteSession(betterSqlite(sqlite), dialect, relational, {})
75
+ return new BaseSQLiteDatabase("sync", dialect, session as never, relational as never) as Orm
76
+ }
77
+
78
+ type Params = never[]
79
+
80
+ /**
81
+ * node:sqlite in the shape that session calls: prepare (run, all, get, and
82
+ * raw for rows as arrays) and transaction.
83
+ */
84
+ function betterSqlite(sqlite: DatabaseSync) {
85
+ const begin = (mode: string) => (fn: (...args: unknown[]) => unknown) => (...args: unknown[]) => {
86
+ sqlite.exec(`begin ${mode}`)
87
+ try {
88
+ const result = fn(...args)
89
+ sqlite.exec("commit")
90
+ return result
91
+ } catch (err) {
92
+ sqlite.exec("rollback")
93
+ throw err
94
+ }
95
+ }
96
+ return {
97
+ prepare(sql: string) {
98
+ const stmt = sqlite.prepare(sql)
99
+ let arrays: ReturnType<DatabaseSync["prepare"]> | undefined
100
+ const raw = () => {
101
+ if (!arrays) {
102
+ arrays = sqlite.prepare(sql)
103
+ arrays.setReturnArrays(true)
104
+ }
105
+ return arrays
106
+ }
107
+ return {
108
+ run: (...p: Params) => stmt.run(...p),
109
+ all: (...p: Params) => stmt.all(...p),
110
+ get: (...p: Params) => stmt.get(...p),
111
+ raw: () => ({ all: (...p: Params) => raw().all(...p), get: (...p: Params) => raw().get(...p) }),
112
+ }
113
+ },
114
+ transaction: (fn: (...args: unknown[]) => unknown) => ({
115
+ deferred: begin("deferred")(fn),
116
+ immediate: begin("immediate")(fn),
117
+ exclusive: begin("exclusive")(fn),
118
+ }),
119
+ } as never
120
+ }
121
+ // !bun:end
@@ -1,18 +1,28 @@
1
+ // auth:begin
2
+ // payments|growth|orgs|privacy:begin
1
3
  import {
2
4
  auditLog,
3
- entitlementTables,
4
- growthTables,
5
+ entitlementTables, // @payments
6
+ growthTables, // @growth
5
7
  id,
6
8
  idempotencyKeys,
7
- orgTables,
8
- privacyTables,
9
+ orgTables, // @orgs
10
+ privacyTables, // @privacy
9
11
  timestamps,
10
12
  } from "@dapplelight/signet-db/columns/sqlite"
13
+ // payments|growth|orgs|privacy:end
14
+ import { auditLog, id, idempotencyKeys, timestamps } from "@dapplelight/signet-db/columns/sqlite" // @!payments|growth|orgs|privacy
15
+ // auth:end
16
+ // !auth:begin
17
+ import { auditLog, growthTables, idempotencyKeys } from "@dapplelight/signet-db/columns/sqlite" // @growth
18
+ import { auditLog, idempotencyKeys } from "@dapplelight/signet-db/columns/sqlite" // @!growth
19
+ // !auth:end
11
20
  import { integer, sqliteTable, text } from "drizzle-orm/sqlite-core"
12
21
 
13
22
  // The whole database. Change a table here, then `db:generate` writes the
14
23
  // migration into drizzle/ and the API applies it on its next start.
15
24
 
25
+ // auth:begin
16
26
  export const ROLES = ["user", "readonly", "staff", "admin"] as const
17
27
 
18
28
  export const users = sqliteTable("users", {
@@ -25,6 +35,7 @@ export const users = sqliteTable("users", {
25
35
  ...timestamps(),
26
36
  })
27
37
 
38
+ // auth:end
28
39
  /**
29
40
  * Sessions, one-time codes, API keys, the notification inbox and prefs, and
30
41
  * rate-limit counters: signet-server keeps each in a key-value store, and this
@@ -43,9 +54,10 @@ export const audit = auditLog()
43
54
  /** Billing events apply once. */
44
55
  export const idempotency = idempotencyKeys()
45
56
 
46
- export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables()
47
- export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables()
48
- export const { consents, dataRequests } = privacyTables()
57
+ export const { subjectPlans, entitlementOverrides, usageCounters } = entitlementTables() // @payments
58
+ export const { waitlist, invites, referralCodes, referrals, marks, feedback } = growthTables() // @growth
59
+ export const { consents, dataRequests } = privacyTables() // @privacy
60
+ // orgs:begin
49
61
  /**
50
62
  * Organisations: every user gets a personal one at sign-up and can make more,
51
63
  * invite people and give them roles (api/services.ts, routes under /api/orgs).
@@ -53,5 +65,8 @@ export const { consents, dataRequests } = privacyTables()
53
65
  * them through `scoped(s.db, { orgId })`, so each org only sees its own rows.
54
66
  */
55
67
  export const { organizations, memberships, invitations, orgRoles } = orgTables()
68
+ // orgs:end
69
+ // auth:begin
56
70
 
57
71
  export type User = typeof users.$inferSelect
72
+ // auth:end
@@ -10,18 +10,23 @@ export const envSchema = z.object({
10
10
  PORT: z.coerce.number().default(3000),
11
11
  /** The SQLite file. ":memory:" for a throwaway database. */
12
12
  DATABASE_PATH: z.string().default("data/app.db"),
13
+ // auth:begin
13
14
  /** Signs session cookies. 32+ random characters, different per environment. */
14
15
  SESSION_SECRET: z.string().min(32),
15
16
  /** Keys the stored one-time-code hashes. 32+ random characters. */
16
17
  OTP_SECRET: z.string().min(32),
17
18
  /** Comma-separated phone numbers (E.164) that get the admin role on sign-in. */
18
19
  ADMIN_PHONES: z.string().default(""),
20
+ // auth:end
21
+ // payments:begin
19
22
  /**
20
23
  * "fake": Upgrade switches the plan at once and no money moves. Refused in
21
24
  * staging and production. "razorpay": webhooks through signet-payments
22
25
  * (see README).
23
26
  */
24
27
  BILLING: z.enum(["fake", "razorpay"]).default("fake"),
28
+ // payments:end
29
+ // orgs:begin
25
30
  /**
26
31
  * Your app's own domain, e.g. "app.example.com": then acme.app.example.com
27
32
  * opens the org with slug "acme". Hosts outside it are looked up as an
@@ -29,14 +34,17 @@ export const envSchema = z.object({
29
34
  * x-org header or the switch cookie, which is all local development needs.
30
35
  */
31
36
  ORG_ROOT_DOMAIN: z.string().optional(),
37
+ // orgs:end
32
38
  /**
33
39
  * "on": JSON request logs, a span per request and /health/live and
34
40
  * /health/ready (server.ts). Off by default. See observability in app.ts.
35
41
  */
36
42
  OBSERVABILITY: z.enum(["on", "off"]).default("off"),
43
+ // payments:begin
37
44
  RAZORPAY_KEY_ID: z.string().optional(),
38
45
  RAZORPAY_KEY_SECRET: z.string().optional(),
39
46
  RAZORPAY_WEBHOOK_SECRET: z.string().optional(),
47
+ // payments:end
40
48
  // mcp:begin
41
49
  /** The MCP endpoint at /mcp (api/app.ts). "off" answers it with a 404. */
42
50
  MCP: z.enum(["on", "off"]).default("on"),