@wwchen/stack 0.2.2 → 0.3.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.
package/README.md CHANGED
@@ -1,13 +1,8 @@
1
1
  # @wwchen/stack
2
2
 
3
- Shared building blocks for Next.js 16 apps on Neon, Better Auth, Resend and lew-ds. Apps are
4
- normally created from the Copier template in
5
- [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below;
6
- this README is the package's reference.
3
+ Shared building blocks for Next.js 16 apps on Neon, Better Auth, Resend and lew-ds. Apps are normally created from the Copier template in [wwchen/bootstrap-stack](https://github.com/wwchen/bootstrap-stack), which wires everything below; this README is the package's reference.
7
4
 
8
- Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`,
9
- `drizzle-orm`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`. `@electric-sql/pglite` and
10
- `@electric-sql/pglite-socket` are optional peers for tests and local development.
5
+ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `drizzle-orm`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`. `@electric-sql/pglite` and `@electric-sql/pglite-socket` are optional peers for tests and local development.
11
6
 
12
7
  ## Entry points
13
8
 
@@ -27,15 +22,11 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
27
22
  | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
28
23
  | `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
29
24
 
30
- Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the
31
- email is unique, trimmed and lower-cased.
25
+ Sign-in never creates users: every user is added first (`stack user:create`), has an email, and the email is unique, trimmed and lower-cased.
32
26
 
33
27
  ### Connected accounts
34
28
 
35
- An app that works on someone's behalf at another service (ifttt reads Foursquare check-ins) has the
36
- person connect that account after signing in. A connection never signs anyone in and never creates
37
- a user. Wiring, with `TOKEN_ENCRYPTION_KEY` set (`openssl rand -base64 32`, and kept forever: a new
38
- key makes every stored token unreadable):
29
+ An app that works on someone's behalf at another service (reading their Foursquare check-ins, say) has the person connect that account after signing in. A connection never signs anyone in and never creates a user. Wiring, with `TOKEN_ENCRYPTION_KEY` set (`openssl rand -base64 32`, and kept forever: a new key makes every stored token unreadable):
39
30
 
40
31
  ```ts
41
32
  // src/db/schema.ts
@@ -53,12 +44,7 @@ export const connections = createConnections({
53
44
  // return connections.callback(request, session?.user.id ?? null);
54
45
  ```
55
46
 
56
- The callback lands on `next` with `?connection=<provider>&result=<code>`, where the code is one of
57
- `connected`, `invalid`, `expired`, `wrong_user`, `denied`, `exchange` or `taken`. It accepts a code
58
- only when the signed state holds, has not expired (10 minutes), this browser started the flow (a
59
- one-off HttpOnly cookie) and the same person is still signed in. Register
60
- `<APP_URL>/api/connections/<provider>/callback` as the provider's redirect URL. One account at a
61
- provider can be connected to one person here; removing a person removes their connections.
47
+ The callback lands on `next` with `?connection=<provider>&result=<code>`, where the code is one of `connected`, `invalid`, `expired`, `wrong_user`, `denied`, `exchange` or `taken`. It accepts a code only when the signed state holds, has not expired (10 minutes), this browser started the flow (a one-off HttpOnly cookie) and the same person is still signed in. Register `<APP_URL>/api/connections/<provider>/callback` as the provider's redirect URL. One account at a provider can be connected to one person here; removing a person removes their connections.
62
48
 
63
49
  ## The `stack` command
64
50
 
@@ -66,15 +52,18 @@ provider can be connected to one person here; removing a person removes their co
66
52
  |---|---|
67
53
  | `stack dev-setup` | creates your Neon dev branch from `seed` and migrates it |
68
54
  | `stack with-neon <cmd>` | runs `<cmd>` against your dev branch; refuses production, `seed` and `preview` |
55
+ | `stack dev [--pglite]` | `next dev` on your dev branch; `--pglite`: on PGlite in `.local-db/` (migrated, seeded once), no Neon |
56
+ | `stack run <script> [args]` | runs an app script with Node (type stripping) and the app's database and `.env`; `ENV_FILE` opts in to another |
69
57
  | `stack neon seed` | rebuilds the `seed` branch (fake data) and runs the app's `db/seed.ts` |
70
- | `stack neon reset-preview` | re-cuts the shared `preview` branch from `seed` |
58
+ | `stack neon reset-preview [--set-vercel]` | re-cuts the shared `preview` branch from `seed`; `--set-vercel` writes its URLs as Vercel's sensitive Preview `DATABASE_URL`/`DATABASE_URL_UNPOOLED` |
71
59
  | `stack vercel-build` | Vercel's build command: migrate the deployment's database, then `next build` |
60
+ | `stack doctor` | read-only audit of the linked Vercel project (framework, Neon integration, shared secrets, database variables); exits 1 on an error |
72
61
  | `stack user:create <email> [--admin]` | adds a user through the app's `src/lib/auth.ts` |
62
+ | `stack user:role <email> <admin\|user>` | changes a user's role through the app's `src/lib/auth.ts`; never leaves the app without an admin |
73
63
  | `stack sync-blocks [--check]` | refreshes the stack blocks in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example` |
74
64
 
75
65
  `NEON_PROJECT_ID` comes from the environment; nothing in the package names a project or domain.
76
66
 
77
67
  ## Versioning
78
68
 
79
- The package, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`.
80
- Releases are published to npm with provenance.
69
+ The package, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
package/blocks/AGENTS.md CHANGED
@@ -7,6 +7,8 @@
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
9
9
  | Your own Neon dev branch | `stack dev-setup` once; `stack with-neon <command>` runs a command against it |
10
+ | Dev server with no Neon | `stack dev --pglite` (PGlite in `.local-db/`, migrated and seeded) |
11
+ | Run an app script | `stack run <script> [args]` (your dev branch and `.env`, like `with-neon`) |
10
12
  | Build | `pnpm build` |
11
13
  | Typecheck | `pnpm typecheck` |
12
14
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
@@ -14,6 +16,8 @@
14
16
  | Migrate | `pnpm db:migrate` (your dev branch) |
15
17
  | Rebuild the `seed` branch (fake data; every dev and preview branch is cut from it) | `pnpm exec stack neon seed` |
16
18
  | Add a user | `stack user:create <email> [--admin]` (on your dev branch; production: the runbook's "First admin") |
19
+ | Change a user's role | `stack user:role <email> <admin\|user>` |
20
+ | Check the Vercel project's setup | `stack doctor` (read-only; exits 1 on an error) |
17
21
  | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
18
22
 
19
23
  **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done.
@@ -21,58 +25,42 @@
21
25
  ## Stack rules
22
26
 
23
27
  1. Never commit secrets or `.env`. `.env.example` lists names only, with empty values.
24
- 2. Never edit a generated migration by hand. Migrations run in the build or as an explicit command,
25
- never on app boot, and every migration is expand-then-contract.
26
- 3. Relative imports carry `.ts`. The `@/` alias is only for `src/app/**`, `src/components/**` and
27
- `tests/**`; code the CLI imports as plain Node (`src/lib/**`, `src/db/**`, `db/seed.ts`) uses
28
- relative imports.
29
- 4. Server components by default. `"use client"` only for state, effects or event handlers, on the
30
- smallest leaf, never on a layout.
28
+ 2. Never edit a generated migration by hand. Migrations run in the build or as an explicit command, never on app boot, and every migration is expand-then-contract.
29
+ 3. Relative imports carry `.ts`. The `@/` alias is only for `src/app/**`, `src/components/**` and `tests/**`; code the CLI imports as plain Node (`src/lib/**`, `src/db/**`, `db/seed.ts`) uses relative imports.
30
+ 4. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf, never on a layout.
31
31
  5. Validate at the edge: parse every route handler's input with zod before any logic.
32
32
  6. Authorization is server-side on every request. Another user's row answers 404, never 403.
33
33
  7. Everyone signs in by email; sign-in never creates a user.
34
34
 
35
35
  ## Next.js notes
36
36
 
37
- The request hook is `src/proxy.ts`, not `middleware.ts`. Next's own agent rules block
38
- (written by `next dev`) lives outside this block; leave it alone.
37
+ The request hook is `src/proxy.ts`, not `middleware.ts`. Next's own agent rules block (written by `next dev`) lives outside this block; leave it alone.
39
38
 
40
39
  ## Design system
41
40
 
42
- The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@lew-ds/lds-react`
43
- and `@lew-ds/open-icons`, pinned exactly in `package.json`.
41
+ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@lew-ds/lds-react` and `@lew-ds/open-icons`, pinned exactly in `package.json`.
44
42
 
45
- - Components come from `@lew-ds/lds-react`, imported through `@wwchen/stack/ui`, which routes
46
- `Button`, `Link` and `Row` hrefs through `next/link`. An icon-only action is `IconButton`.
47
- - Never hand-roll a pill, button, input, table or banner. If LDS lacks something, fix it upstream
48
- in LDS, never at a call site.
49
- - LDS paints through its own class names; the app never restyles them. The app's own `app.css` is
50
- the only place it fills a gap.
51
- - Tailwind is for layout only. Its colour, type, radius and shadow utilities resolve to LDS roles
52
- through the stack's `globals.css`. No raw hex or px in a component.
43
+ - Components come from `@lew-ds/lds-react`, imported through `@wwchen/stack/ui`, which routes `Button`, `Link` and `Row` hrefs through `next/link`. An icon-only action is `IconButton`.
44
+ - Never hand-roll a pill, button, input, table or banner. If LDS lacks something, fix it upstream in LDS, never at a call site.
45
+ - LDS paints through its own class names; the app never restyles them. The app's own `app.css` is the only place it fills a gap.
46
+ - Tailwind is for layout only. Its colour, type, radius and shadow utilities resolve to LDS roles through the stack's `globals.css`. No raw hex or px in a component.
53
47
  - A design change lands in the component and its stories in the same change.
54
48
 
55
49
  ## Database
56
50
 
57
- - Postgres on Neon, with Drizzle. Local dev runs on your own Neon branch cut from `seed`, never
58
- from production; previews get their own branch, also from `seed`. Other people's data stays out
59
- of dev and previews.
51
+ - Postgres on Neon, with Drizzle. Local dev runs on your own Neon branch cut from `seed`, never from production; previews get their own branch, also from `seed`. Other people's data stays out of dev and previews.
60
52
  - Local tooling refuses the production database unless you opt in deliberately.
61
53
  - Tests run on PGlite (one connection only) and, in CI, a real Postgres.
62
54
  - Every user has an email: required, unique, lower-cased and trimmed.
63
- - Schema changes go through `pnpm db:generate` and a reviewed migration, never through the Neon
64
- console or a database MCP server.
55
+ - Schema changes go through `pnpm db:generate` and a reviewed migration, never through the Neon console or a database MCP server.
65
56
 
66
57
  ## Security
67
58
 
68
59
  1. `CRON_SECRET` can only trigger scheduled jobs; admin and data access never accept it.
69
60
  2. Never render free text from a URL; redirects carry short codes.
70
- 3. Sign-in links are single-use and expire. OAuth `state` is signed and bound to the browser that
71
- started the flow.
72
- 4. Sessions are HttpOnly, Secure (when https), SameSite=Lax. Mutations require JSON and a
73
- same-origin request.
61
+ 3. Sign-in links are single-use and expire. OAuth `state` is signed and bound to the browser that started the flow.
62
+ 4. Sessions are HttpOnly, Secure (when https), SameSite=Lax. Mutations require JSON and a same-origin request.
74
63
  5. Magic links are anti-enumeration, with hashed tokens and sign-in rate limits.
75
64
  6. Connected-account tokens are encrypted at rest; Better Auth never stores third-party API tokens.
76
65
  7. Previews get their own secrets and no production third-party keys.
77
- 8. Never write a deployment's domain in the repo. Name variables (`APP_URL`, `EMAIL_FROM`), never
78
- a host.
66
+ 8. Never write a deployment's domain in the repo. Name variables (`APP_URL`, `EMAIL_FROM`), never a host.
package/blocks/CLAUDE.md CHANGED
@@ -7,107 +7,77 @@
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
9
9
  | Local database | Your own Neon dev branch: `stack dev-setup` once, then `stack with-neon <command>` |
10
+ | No Neon at hand | `stack dev --pglite`: PGlite in `.local-db/`, migrated and seeded, then `next dev` |
11
+ | Run an app script | `stack run <script> [args]` (your dev branch and `.env`, like `with-neon`) |
10
12
  | Build | `pnpm build` · on Vercel: `stack vercel-build` (migrates the deployment's own database first) |
11
13
  | Typecheck | `pnpm typecheck` |
12
14
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
13
15
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
14
16
  | DB generate / apply migration | `pnpm db:generate` · `pnpm db:migrate` |
15
17
  | Seed the shared `seed` branch | `stack neon seed` (runs the app's `db/seed.ts`) |
16
- | Reset the shared preview branch | `stack neon reset-preview` |
18
+ | Reset the shared preview branch | `stack neon reset-preview` (`--set-vercel` also writes its URLs into Vercel's Preview variables) |
19
+ | Check the Vercel project's setup | `stack doctor` (read-only; exits 1 on an error) |
17
20
  | Add a user / an admin | `stack user:create <email> [--admin]` (on your dev branch; production: the runbook's "First admin") |
21
+ | Change a user's role | `stack user:role <email> <admin\|user>` (keeps at least one admin) |
18
22
  | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
19
23
 
20
- **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done. Never
21
- mark a task done with a failing gate command.
24
+ **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done. Never mark a task done with a failing gate command.
22
25
 
23
- Node is pinned in `.nvmrc`; pnpm is installed with `npm install -g pnpm@<version from packageManager>`,
24
- not through Corepack. Dependency versions live in `pnpm-lock.yaml`: read it, never guess one.
26
+ Node is pinned in `.nvmrc`; pnpm is installed with `npm install -g pnpm@<version from packageManager>`, not through Corepack. Dependency versions live in `pnpm-lock.yaml`: read it, never guess one.
25
27
 
26
28
  ## Stack
27
29
 
28
- Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme
29
- (`@lew-ds/lds`) · Postgres on Neon (PGlite in tests) · Drizzle ORM · Better Auth, self-hosted
30
- (email magic link through Resend, optional Google for added users) · Vercel · `@wwchen/stack` for
31
- the shared code, configs and CLI.
30
+ Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme (`@lew-ds/lds`) · Postgres on Neon (PGlite in tests) · Drizzle ORM · Better Auth, self-hosted (email magic link through Resend, optional Google for added users) · Vercel · `@wwchen/stack` for the shared code, configs and CLI.
32
31
 
33
- **Local dev runs on a Neon dev branch** (`dev/<os-user>`), cut from `seed`, which holds fake users and
34
- fixture data. `stack with-neon` reads the branch's connection strings on every run and refuses the
35
- production database. Check the `[neon] <branch>` line it prints before running a database command.
32
+ **Local dev runs on a Neon dev branch** (`dev/<os-user>`), cut from `seed`, which holds fake users and fixture data. `stack with-neon` reads the branch's connection strings on every run and refuses the production database. Check the `[neon] <branch>` line it prints before running a database command.
36
33
 
37
- **One connection on PGlite.** The tests run on PGlite: a single backend. A script run while another
38
- process holds that connection is refused; stop the other process first.
34
+ **One connection on PGlite.** The tests run on PGlite: a single backend. A script run while another process holds that connection is refused; stop the other process first.
39
35
 
40
36
  ## Code rules
41
37
 
42
- 1. Relative imports carry `.ts`. The `@/` alias is allowed only in `src/app/**`,
43
- `src/components/**` and `tests/**`; in `src/lib/**`, `src/db/**`, `db/seed.ts` and `scripts/**`
44
- it is forbidden, because those files also run as plain Node.
45
- 2. Server components by default. `"use client"` only for state, effects or event handlers, on the
46
- smallest leaf. Never on a layout.
47
- 3. Validate at the edge: every route handler reads its body with `readJson(req, schema)` (a zod
48
- schema) before any logic. It answers a failed parse with 422 `invalid_input` and a `details`
49
- array, and a body that is not JSON with 400 `invalid_json`. A parse error anywhere else is a bug:
50
- `apiHandler` logs it and answers 500.
51
- 4. Authorization is server-side on every request. A hidden button is not a permission. Another
52
- user's row answers 404, never 403.
38
+ 1. Relative imports carry `.ts`. The `@/` alias is allowed only in `src/app/**`, `src/components/**` and `tests/**`; in `src/lib/**`, `src/db/**`, `db/seed.ts` and `scripts/**` it is forbidden, because those files also run as plain Node.
39
+ 2. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf. Never on a layout.
40
+ 3. Validate at the edge: every route handler reads its body with `readJson(req, schema)` (a zod schema) before any logic. It answers a failed parse with 422 `invalid_input` and a `details` array, and a body that is not JSON with 400 `invalid_json`. A parse error anywhere else is a bug: `apiHandler` logs it and answers 500.
41
+ 4. Authorization is server-side on every request. A hidden button is not a permission. Another user's row answers 404, never 403.
53
42
  5. 300 lines is the component ceiling. Past that, split by responsibility.
54
43
  6. No new dependency without a reason in the commit message. Check the standard library first.
55
- 7. Never write a CDN- or vendor-specific client-IP header name in app code; the client IP comes
56
- from the stack's one helper.
44
+ 7. Never write a CDN- or vendor-specific client-IP header name in app code; the client IP comes from the stack's one helper.
57
45
  8. Never write a `"use server"` module in shared code; the app's own `actions.ts` marks wrappers.
58
46
 
59
47
  ## Design system
60
48
 
61
- The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@lew-ds/lds-react`
62
- and `@lew-ds/open-icons`, pinned exactly. LDS paints through its own class names; the app never
63
- restyles them, and the app's `app.css` is the only place it fills a gap.
64
-
65
- - Components come from `@lew-ds/lds-react`, imported through `@wwchen/stack/ui`. An icon-only
66
- action is `IconButton`. `<IconSprite>` in the root layout inlines the glyphs the app names and
67
- what LDS's components draw, nothing else; `checkIcons` guards it in a test.
68
- - **Never hand-roll a pill, button, input, table or banner.** If LDS lacks something, fix it
69
- upstream in LDS, never at a call site.
70
- - **Tailwind is for layout only.** Its colour, type, radius and shadow utilities resolve to LDS
71
- roles through `@wwchen/stack/ui/globals.css`. No raw hex or px in a component.
49
+ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@lew-ds/lds-react` and `@lew-ds/open-icons`, pinned exactly. LDS paints through its own class names; the app never restyles them, and the app's `app.css` is the only place it fills a gap.
50
+
51
+ - Components come from `@lew-ds/lds-react`, imported through `@wwchen/stack/ui`. An icon-only action is `IconButton`. `<IconSprite>` in the root layout inlines the glyphs the app names and what LDS's components draw, nothing else; `checkIcons` guards it in a test.
52
+ - **Never hand-roll a pill, button, input, table or banner.** If LDS lacks something, fix it upstream in LDS, never at a call site.
53
+ - **Tailwind is for layout only.** Its colour, type, radius and shadow utilities resolve to LDS roles through `@wwchen/stack/ui/globals.css`. No raw hex or px in a component.
72
54
  - Layouts respond to the width a component has (container queries), never to the device.
73
55
  - Theme is a cookie (`theme-product mode-*`) read and written through the stack's `/ui` helpers.
74
- - A design change lands in the component and its stories (narrow and wide) in the same change, and
75
- carries to every component that shows the same thing.
56
+ - A design change lands in the component and its stories (narrow and wide) in the same change, and carries to every component that shows the same thing.
76
57
 
77
58
  ## Database rules
78
59
 
79
- - Drizzle schema and migrations: generate with `pnpm db:generate`, review the SQL, never edit a
80
- generated migration by hand. Every migration is expand-then-contract, because the old deployment
81
- serves while the build migrates.
82
- - Migrations run in the Vercel build (`stack vercel-build`) or as an explicit command, never on app
83
- boot. A preview build migrates its own Neon branch and refuses production's endpoint; a production
84
- build migrates production's database before building.
60
+ - Drizzle schema and migrations: generate with `pnpm db:generate`, review the SQL, never edit a generated migration by hand. Every migration is expand-then-contract, because the old deployment serves while the build migrates.
61
+ - Migrations run in the Vercel build (`stack vercel-build`) or as an explicit command, never on app boot. A preview build migrates its own Neon branch and refuses production's endpoint; a production build migrates production's database before building.
85
62
  - The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
86
- - Dev and preview branches come from `seed`, never from production, so other people's data stays
87
- out of dev and previews. Previews get their own secrets and no production third-party keys.
63
+ - Dev and preview branches come from `seed`, never from production, so other people's data stays out of dev and previews. Previews get their own secrets and no production third-party keys.
88
64
  - Money, if any, is integer cents; reconcile from source rows, never increment.
89
65
  - Every user has an email: required, unique, lower-cased and trimmed.
90
66
 
91
67
  ## Security rules
92
68
 
93
- 1. `CRON_SECRET` can only trigger scheduled jobs (counts-only responses); admin and data access
94
- never accept it.
69
+ 1. `CRON_SECRET` can only trigger scheduled jobs (counts-only responses); admin and data access never accept it.
95
70
  2. No free text from URLs is ever rendered; redirects carry short codes.
96
- 3. Sign-in links are single-use and expire; OAuth `state` is signed and bound to the browser that
97
- started the flow.
71
+ 3. Sign-in links are single-use and expire; OAuth `state` is signed and bound to the browser that started the flow.
98
72
  4. Sessions: HttpOnly, Secure (when https), SameSite=Lax; mutations require JSON and same-origin.
99
73
  5. Anti-enumeration on magic links; hashed tokens; sign-in rate limits.
100
74
  6. Local tooling refuses the production database unless explicitly opted in.
101
- 7. Connected-account tokens are encrypted at rest (AES-256-GCM); Better Auth never stores
102
- third-party API tokens.
75
+ 7. Connected-account tokens are encrypted at rest (AES-256-GCM); Better Auth never stores third-party API tokens.
103
76
  8. Other people's data stays out of dev and previews.
104
- 9. Never commit secrets, `.env` or build output. No deployment's domain, Neon project id or key in
105
- the repo: code, docs and this file name variables (`APP_URL`, `EMAIL_FROM`, `NEON_PROJECT_ID`),
106
- never a value. `.env.example` is committed and stays in sync; `.env` never is.
77
+ 9. Never commit secrets, `.env` or build output. No deployment's domain, Neon project id or key in the repo: code, docs and this file name variables (`APP_URL`, `EMAIL_FROM`, `NEON_PROJECT_ID`), never a value. `.env.example` is committed and stays in sync; `.env` never is.
107
78
 
108
79
  ## Non-negotiable
109
80
 
110
81
  1. Never commit secrets or `.env`. Never edit a generated migration by hand.
111
82
  2. Never mark a task done with a failing gate command.
112
- 3. Never merge a pull request into `main` for the owner. Open the PR, get its checks green, and
113
- stop; the owner merges.
83
+ 3. Never merge a pull request into `main` for the owner. Open the PR, get its checks green, and stop; the owner merges.
package/blocks/gitignore CHANGED
@@ -11,6 +11,7 @@ storybook-static
11
11
  .neon
12
12
  .pglite/
13
13
  .pglite.lock
14
+ .local-db/
14
15
  .magic-links.log
15
16
 
16
17
  # Secrets: only the example is committed. Keep this last.
@@ -10,7 +10,7 @@ import type { AuthTables } from "./tables.ts";
10
10
  * `AuthProvider`.
11
11
  *
12
12
  * Invite-only throughout: no sign-in path creates a user. Off unless the app opts in —
13
- * - `emailAndPassword`: passwords, for an app that keeps one (cc does). Sign-up is forced off, and
13
+ * - `emailAndPassword`: passwords, for an app that keeps them. Sign-up is forced off, and
14
14
  * the HTTP password routes stay unserved (`createAuth`'s handler answers 404 for sign-in/email,
15
15
  * change-password and verify-password): the app calls `provider.instance.api.signInEmail /
16
16
  * setPassword / changePassword / verifyPassword` from its own server action, behind a budget of
@@ -6,7 +6,7 @@ import { boolean, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-c
6
6
  * migrates anything itself.
7
7
  *
8
8
  * **One user table.** Better Auth's user model *is* the app's user table (`app_user`, or the name
9
- * the app passes — cc keeps `user`): there is no second identity table to keep in sync, so removing
9
+ * the app passes, such as `user`): there is no second identity table to keep in sync, so removing
10
10
  * a person cannot leave a sign-in-able account behind. App tables reference `appUser.id`, a uuid.
11
11
  * `role` is declared to Better Auth as an additional field it never takes from a caller, and is set
12
12
  * only by `users.ts`.
@@ -16,7 +16,7 @@ import { boolean, check, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-c
16
16
  const createdAt = () => timestamp("created_at", { withTimezone: true }).notNull().defaultNow();
17
17
  const updatedAt = () => timestamp("updated_at", { withTimezone: true }).notNull().defaultNow();
18
18
  export function authTables(opts = {}) {
19
- // The name stays a literal type ("app_user", or cc's "user"): Drizzle keys a joined select's
19
+ // The name stays a literal type ("app_user", or the one the app passes, such as "user"): Drizzle keys a joined select's
20
20
  // result by table name, so a plain `string` would merge every joined table's columns into one.
21
21
  const userTable = (opts.userTable ?? "app_user");
22
22
  const appUser = pgTable(userTable, {
@@ -17,7 +17,7 @@ const navigation = () => import("next/navigation");
17
17
  const SIGN_IN_BUDGET_PATH = "/api/auth/sign-in/magic-link";
18
18
  /**
19
19
  * Better Auth's password routes. Passwords are off unless an app opts in with
20
- * `betterAuthProvider({ emailAndPassword })` (as cc needs); it then calls
20
+ * `betterAuthProvider({ emailAndPassword })`; it then calls
21
21
  * `provider.instance.api.signInEmail / changePassword / verifyPassword` in-process from its own
22
22
  * server action, with a budget of its own. Served here too, each would be a second door with its
23
23
  * own budget, multiplying the guesses an attacker gets. Answered 404 whether or not the option is
@@ -8,6 +8,15 @@ export type ExecOptions = {
8
8
  env?: Env;
9
9
  /** Hand the child this terminal (a dev server, a build) instead of capturing its stdout. */
10
10
  inherit?: boolean;
11
+ /**
12
+ * Written to the child's stdin, then closed: how a secret reaches another CLI without appearing in its arguments. Pass a value already held in full, never a stream still arriving: a CLI that reads stdin at start-up takes whatever is there, which may be nothing yet.
13
+ */
14
+ input?: string;
15
+ };
16
+ /** A Postgres served on loopback for `stack dev --pglite`. */
17
+ export type LocalDatabase = {
18
+ url: string;
19
+ stop(): Promise<void>;
11
20
  };
12
21
  /**
13
22
  * Everything the CLI touches outside its own process, so a test can replace it. Only the entry
@@ -26,6 +35,12 @@ export type CliDeps = {
26
35
  importModule?(specifier: string): Promise<Record<string, unknown>>;
27
36
  /** Runs one SQL statement against a database, for emptying the new `seed` branch. */
28
37
  sql?(url: string, statement: string): Promise<Record<string, unknown>[]>;
38
+ /** The Node binary `stack run` starts an app script with. */
39
+ execPath?: string;
40
+ /**
41
+ * Serves PGlite on a free loopback port with its data in `dataDir`, for `stack dev --pglite`. PGlite and pglite-socket are loaded from the app (its devDependencies), never from this package.
42
+ */
43
+ startLocalDatabase?(dataDir: string): Promise<LocalDatabase>;
29
44
  };
30
45
  export type Cli = Required<CliDeps>;
31
46
  export declare function resolveDeps(deps: CliDeps): Cli;
@@ -11,12 +11,15 @@ import { join } from "node:path";
11
11
  import { pathToFileURL } from "node:url";
12
12
  import pg from "pg";
13
13
  import { explicitSslMode } from "../db/ssl.js";
14
+ import { startPgliteServer } from "../db/testing/pglite.js";
14
15
  import { loadEnvFile } from "../env/index.js";
15
16
  export function resolveDeps(deps) {
16
17
  return {
17
18
  log: (message) => console.log(message),
18
19
  error: (message) => console.error(message),
19
20
  username: userInfo().username,
21
+ execPath: process.execPath,
22
+ startLocalDatabase: (dataDir) => startPgliteServer({ dataDir, resolveFrom: deps.cwd }),
20
23
  importModule: (specifier) => import(__rewriteRelativeImportExtension(specifier)),
21
24
  sql: async (url, statement) => {
22
25
  const client = new pg.Client({ connectionString: explicitSslMode(url) });
@@ -0,0 +1,4 @@
1
+ import { type Cli } from "./context.ts";
2
+ /** Where `--pglite` keeps its database, at the app's root; git-ignored by the stack's block. */
3
+ export declare const LOCAL_DB_DIR = ".local-db";
4
+ export declare function dev(cli: Cli, args: string[]): Promise<number>;
@@ -0,0 +1,70 @@
1
+ // `stack dev [--pglite] [next dev args]` — the app's dev server.
2
+ //
3
+ // - Plain: `next dev` on your Neon dev branch, as `stack with-neon next dev`.
4
+ // - `--pglite`: no Neon at all. PGlite (the app's own devDependency) is served on a free loopback port with its data in `.local-db/`, migrated with the app's migrations, seeded with its `db/seed.ts` the first time, and `next dev` runs against it. The server stops when `next dev` exits. Delete `.local-db/` to start again from the seed.
5
+ //
6
+ // PGlite serves one connection at a time: while `next dev` runs, nothing else (a script, a migration) can use the database.
7
+ import { existsSync, mkdirSync, rmSync } from "node:fs";
8
+ import { join } from "node:path";
9
+ import { loadAppEnv } from "./context.js";
10
+ import { migrate, runAppSeed, withNeon } from "./neon.js";
11
+ /** Where `--pglite` keeps its database, at the app's root; git-ignored by the stack's block. */
12
+ export const LOCAL_DB_DIR = ".local-db";
13
+ export async function dev(cli, args) {
14
+ const local = args.includes("--pglite");
15
+ const nextArgs = args.filter((arg) => arg !== "--pglite");
16
+ if (!local)
17
+ return withNeon(cli, ["pnpm", "exec", "next", "dev", ...nextArgs]);
18
+ return devPglite(cli, nextArgs);
19
+ }
20
+ async function devPglite(cli, nextArgs) {
21
+ const dataDir = join(cli.cwd, LOCAL_DB_DIR);
22
+ const fresh = !existsSync(dataDir);
23
+ mkdirSync(dataDir, { recursive: true });
24
+ const server = await cli.startLocalDatabase(dataDir).catch((error) => {
25
+ if (fresh)
26
+ rmSync(dataDir, { recursive: true, force: true });
27
+ throw error;
28
+ });
29
+ let ready = false;
30
+ // Ctrl-C reaches every process in the terminal's group: `next dev` and a migration stop on their own, and this one waits for them, then stops the database and removes a new one it could not finish.
31
+ let interrupted = false;
32
+ const onSignal = () => {
33
+ interrupted = true;
34
+ };
35
+ process.on("SIGINT", onSignal);
36
+ process.on("SIGTERM", onSignal);
37
+ try {
38
+ cli.error(`[local] PGlite on ${server.url}, data in ${LOCAL_DB_DIR}/`);
39
+ // Every child, and the app's modules imported here, read this database and never Neon's: what is set here wins over `.env`, and an empty UNPOOLED keeps one from `.env` (a Neon branch's direct URL) from sending the migration elsewhere.
40
+ Object.assign(cli.env, { DATABASE_URL: server.url, DATABASE_URL_UNPOOLED: "" });
41
+ loadAppEnv(cli);
42
+ const migrated = await migrate(cli, cli.env);
43
+ if (migrated !== 0) {
44
+ cli.error(`[local] the migration failed (exit ${migrated}); not starting next dev.`);
45
+ return migrated;
46
+ }
47
+ if (interrupted)
48
+ return 130;
49
+ if (fresh) {
50
+ await runAppSeed(cli);
51
+ cli.error("[local] seeded from db/seed.ts");
52
+ }
53
+ if (interrupted)
54
+ return 130;
55
+ ready = true;
56
+ const { code } = await cli.exec("pnpm", ["exec", "next", "dev", ...nextArgs], {
57
+ env: cli.env,
58
+ inherit: true,
59
+ });
60
+ return code;
61
+ }
62
+ finally {
63
+ process.off("SIGINT", onSignal);
64
+ process.off("SIGTERM", onSignal);
65
+ await server.stop();
66
+ // A database this run created but could not migrate or seed would never be seeded again.
67
+ if (fresh && !ready)
68
+ rmSync(dataDir, { recursive: true, force: true });
69
+ }
70
+ }
@@ -0,0 +1,40 @@
1
+ import { type Cli } from "./context.ts";
2
+ export type Severity = "error" | "warning" | "info";
3
+ export type Finding = {
4
+ severity: Severity;
5
+ message: string;
6
+ };
7
+ export type Target = "production" | "preview" | "development";
8
+ /** One Vercel environment variable, metadata only: there is deliberately no `value`. */
9
+ export type EnvVarMeta = {
10
+ id: string;
11
+ key: string;
12
+ type: string;
13
+ target: string[];
14
+ gitBranch?: string;
15
+ configurationId?: string;
16
+ comment?: string;
17
+ };
18
+ export type Hosting = {
19
+ project: string;
20
+ /** The project's framework preset; null is Vercel's "Other". */
21
+ framework: string | null;
22
+ /** `vercel.json`'s `framework`, which overrides the preset; undefined when it sets none. */
23
+ vercelJsonFramework?: string | null;
24
+ envs: EnvVarMeta[];
25
+ /** The API had more pages of variables than were read. */
26
+ truncated?: boolean;
27
+ };
28
+ /** What the Neon Vercel integration writes on every variable it creates. */
29
+ export declare const NEON_INTEGRATION_COMMENT = "The Neon Postgres integration sets this environment variable automatically";
30
+ /** Secrets a preview must hold its own value of, never production's (runbook §3). */
31
+ export declare const PREVIEW_OWN_SECRETS: readonly ["BETTER_AUTH_SECRET", "TOKEN_ENCRYPTION_KEY", "CRON_SECRET", "RESEND_API_KEY", "GOOGLE_CLIENT_SECRET"];
32
+ /** The metadata of one API variable; its value (and anything else) is not copied. */
33
+ export declare function envVarMeta(raw: unknown): EnvVarMeta;
34
+ /** Every check, on metadata alone. Sorted: errors, then warnings, then notes. */
35
+ export declare function audit(h: Hosting): Finding[];
36
+ /**
37
+ * The linked project (`.vercel/project.json`, written by `vercel link`), its preset and its variables' metadata from the Vercel API, and the app's `vercel.json`.
38
+ */
39
+ export declare function readHosting(cli: Cli): Promise<Hosting>;
40
+ export declare function doctor(cli: Cli): Promise<number>;