@wwchen/stack 0.10.1 → 0.11.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 (71) hide show
  1. package/README.md +42 -25
  2. package/blocks/AGENTS.md +8 -20
  3. package/blocks/CLAUDE.md +9 -27
  4. package/blocks/env.example +1 -7
  5. package/blocks/gitignore +0 -6
  6. package/dist/cli/builtin.d.ts +4 -3
  7. package/dist/cli/builtin.js +31 -36
  8. package/dist/cli/check.d.ts +5 -0
  9. package/dist/cli/check.js +39 -0
  10. package/dist/cli/context.d.ts +1 -18
  11. package/dist/cli/context.js +0 -22
  12. package/dist/cli/discover.d.ts +15 -0
  13. package/dist/cli/discover.js +156 -0
  14. package/dist/cli/generate.d.ts +6 -0
  15. package/dist/cli/generate.js +94 -0
  16. package/dist/cli/host.d.ts +1 -1
  17. package/dist/cli/host.js +90 -72
  18. package/dist/cli/owned.d.ts +33 -0
  19. package/dist/cli/owned.js +151 -0
  20. package/dist/cli/{sync-blocks.d.ts → sync.d.ts} +6 -2
  21. package/dist/cli/{sync-blocks.js → sync.js} +46 -18
  22. package/dist/configs/vitest.d.ts +3 -1
  23. package/dist/configs/vitest.js +8 -6
  24. package/dist/index.d.ts +2 -2
  25. package/dist/index.js +1 -1
  26. package/dist/next/config.d.ts +2 -0
  27. package/dist/next/config.js +10 -6
  28. package/dist/next/health.d.ts +1 -1
  29. package/dist/next/health.js +1 -1
  30. package/dist/stack/contracts.d.ts +65 -15
  31. package/dist/stack/contracts.js +30 -6
  32. package/files/.claude/rules/stack-ui.md +24 -0
  33. package/files/next.config.ts +6 -0
  34. package/files/src/app/api/health/route.ts +9 -0
  35. package/package.json +6 -37
  36. package/dist/cli/db.d.ts +0 -4
  37. package/dist/cli/db.js +0 -43
  38. package/dist/cli/dev.d.ts +0 -4
  39. package/dist/cli/dev.js +0 -70
  40. package/dist/cli/neon.d.ts +0 -79
  41. package/dist/cli/neon.js +0 -394
  42. package/dist/cli/run.d.ts +0 -2
  43. package/dist/cli/run.js +0 -29
  44. package/dist/db/branches.d.ts +0 -11
  45. package/dist/db/branches.js +0 -19
  46. package/dist/db/doctor.d.ts +0 -9
  47. package/dist/db/doctor.js +0 -120
  48. package/dist/db/env.d.ts +0 -14
  49. package/dist/db/env.js +0 -15
  50. package/dist/db/explaining-pool.d.ts +0 -11
  51. package/dist/db/explaining-pool.js +0 -55
  52. package/dist/db/health.d.ts +0 -10
  53. package/dist/db/health.js +0 -26
  54. package/dist/db/index.d.ts +0 -21
  55. package/dist/db/index.js +0 -32
  56. package/dist/db/migration-status.d.ts +0 -5
  57. package/dist/db/migration-status.js +0 -38
  58. package/dist/db/schema-changes.d.ts +0 -13
  59. package/dist/db/schema-changes.js +0 -99
  60. package/dist/db/ssl.d.ts +0 -4
  61. package/dist/db/ssl.js +0 -17
  62. package/dist/db/target.d.ts +0 -19
  63. package/dist/db/target.js +0 -66
  64. package/dist/db/testing/index.d.ts +0 -23
  65. package/dist/db/testing/index.js +0 -67
  66. package/dist/db/testing/isolate.d.ts +0 -1
  67. package/dist/db/testing/isolate.js +0 -3
  68. package/dist/db/testing/pglite.d.ts +0 -20
  69. package/dist/db/testing/pglite.js +0 -79
  70. package/dist/env/testing.d.ts +0 -6
  71. package/dist/env/testing.js +0 -13
package/README.md CHANGED
@@ -1,20 +1,16 @@
1
1
  # @wwchen/stack
2
2
 
3
- Shared building blocks for Next.js 16 apps on Neon and lew-ds, and the `stack` command that runs the packages an app composes. Sign-in is [`@wwchen/stack-auth`](../auth), mail is [`@wwchen/stack-notify`](../notify) and hosting on Vercel is [`@wwchen/stack-infra`](../infra), released with this package under the same version, as is [`@wwchen/stack-upgrade`](../upgrade), which moves an app onto a release. 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.
3
+ Shared building blocks for Next.js 16 apps on lew-ds, and the `stack` command that runs the packages an app composes. The database is [`@wwchen/stack-db`](../db), sign-in is [`@wwchen/stack-auth`](../auth), mail is [`@wwchen/stack-notify`](../notify) and hosting on Vercel is [`@wwchen/stack-infra`](../infra), released with this package under the same version, as is [`@wwchen/stack-upgrade`](../upgrade), which moves an app onto a release. 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.
4
4
 
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`; `typescript` takes patch releases (`~`). `@electric-sql/pglite` and `@electric-sql/pglite-socket` are optional peers for tests and local development, and `storybook` and `@storybook/nextjs-vite` for an app's Storybook.
5
+ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-dom`, `@lew-ds/lds`, `@lew-ds/lds-react`, `@lew-ds/open-icons`; `typescript` takes patch releases (`~`). `drizzle-orm` is an optional peer, for connected accounts, and `storybook` and `@storybook/nextjs-vite` for an app's Storybook.
6
6
 
7
7
  ## Entry points
8
8
 
9
9
  | Import | What it gives you |
10
10
  |---|---|
11
- | `@wwchen/stack` | `defineStack({ packages })` for the app's `stack.config.ts`, and the types a package implements for it (`StackPackage`, `Command`, `BuildStep`, `DoctorCheck`, `EnvFragment`, `Gate`, `HealthCheck`, …) |
11
+ | `@wwchen/stack` | `defineStack({ settings })` for the app's `stack.config.ts`, and the types a package implements for it (`StackPackage`, `Command`, `BuildStep`, `DoctorCheck`, `EnvFragment`, `Gate`, `HealthCheck`, …) |
12
12
  | `@wwchen/stack/env` | `defineEnv({ fragments, schema })`: the app's variables, validated, from each package's env fragment plus the app's own `schema` (a name defined twice is an error naming both); `coreEnv`, the shared variables (production requires `APP_URL`, derived on Vercel when unset). `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
13
- | `@wwchen/stack/db/env` | `dbEnv`: `DATABASE_URL` (required in production, a placeholder during a build), `DATABASE_URL_UNPOOLED`, `PRODUCTION_DATABASE_HOST` |
14
- | `@wwchen/stack/db/branches` | `databaseEnv(ctx, { preview })`, for a package's `stack` command that reaches the app's database: your Neon dev branch's connection variables (nothing when `DATABASE_URL` or `ENV_FILE` already names one), or with `preview` the shared `preview` branch's; never part of the app's runtime |
15
- | `@wwchen/stack/db` | the pooled client, `migrationStatus`, `databaseCheck(db)` (the database's `HealthCheck` for `healthRoute`), the dev-database guard that refuses production |
16
- | `@wwchen/stack/db/testing`, `/db/testing/isolate` | test databases: PGlite by default, a real Postgres when `TEST_DATABASE_URL` is set |
17
- | `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler({ label, gate }, fn)` (the `Gate` decides the caller: its 401 answers `unauthenticated`, its 404 `not_found`, its principal reaches `fn`) and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute({ token, checks })` (each `HealthCheck`'s fields join the answer for the token) |
13
+ | `@wwchen/stack/next` | `withStack(appConfig, { tracing })` for `next.config.ts`, `apiHandler({ label, gate }, fn)` (the `Gate` decides the caller: its 401 answers `unauthenticated`, its 404 `not_found`, its principal reaches `fn`) and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute({ token, checks })` (each `HealthCheck`'s fields join the answer for the token) |
18
14
  | `@wwchen/stack/http` | `safeNext(raw, fallback?)` (a `?next=` kept only when it is a path on this site) and `clientIp(headers, hops)` (the caller, read from `X-Forwarded-For` counted from the right) |
19
15
  | `@wwchen/stack/vercel` | the linked Vercel project's metadata through the Vercel CLI, for a package's `stack` command: `linkedProject` (`.vercel/project.json`), `vercelApi`, `listEnvs` and `envVarMeta` (each variable's metadata, never its value), `readJsonFile`; never part of the app's runtime |
20
16
  | `@wwchen/stack/connections` | connected accounts (not sign-in): `connectionTable`, `createConnections` (start and callback route handlers, `token`, `list`, `connected`, `disconnect`), the `ConnectionProvider` type each app implements for its own services, AES-256-GCM token encryption under `TOKEN_ENCRYPTION_KEY` |
@@ -22,10 +18,10 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
22
18
  | `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
23
19
  | `@wwchen/stack/ui`, `/ui/icons`, `/ui/globals.css`, `/ui/app.css` | lew-ds wiring, theme cookie, icon sprite and its usage check, and the CSS partials |
24
20
  | `@wwchen/stack/storybook` | an app's Storybook set up as its root layout sets up a page: `stackPreview({ icons, fontVariable, bodyClassName })` (the `<html>` theme classes with a light/dark toolbar, the icon sprite, a logging stand-in for the App Router's `useRouter()`, the viewports), and `PHONE` and `SMALL_PHONE` story globals |
25
- | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
21
+ | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import; `/configs/vitest` is `stackVitestConfig(overrides, { fragments })`, whose `fragments` are required (an app passes the generated `src/stack/env.ts`'s, whatever packages it has, so each package's test values reach its tests; a package's own test config passes its own list or `[]`) |
26
22
  | `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
27
23
 
28
- Sign-in and mail are [`@wwchen/stack-auth`](../auth) and [`@wwchen/stack-notify`](../notify); the old paths (`@wwchen/stack/auth`, `/auth/better-auth`, `/auth/proxy`, `/mail`) are gone, and [`@wwchen/stack-upgrade`](../upgrade) moves an app's imports off them. Sign-in never creates users: every user is added first (`stack user:create`, a command of `@wwchen/stack-auth`), has an email, and the email is unique, trimmed and lower-cased.
24
+ Sign-in and mail are [`@wwchen/stack-auth`](../auth) and [`@wwchen/stack-notify`](../notify). Sign-in never creates users: every user is added first (`stack user:create`, a command of `@wwchen/stack-auth`), has an email, and the email is unique, trimmed and lower-cased.
29
25
 
30
26
  ### Connected accounts
31
27
 
@@ -53,25 +49,46 @@ The callback lands on `next` with `?connection=<provider>&result=<code>`, where
53
49
 
54
50
  | Command | Does |
55
51
  |---|---|
56
- | `stack dev-setup` | creates your Neon dev branch from `seed` and migrates it |
57
- | `stack with-neon <cmd>` | runs `<cmd>` against your dev branch; refuses production, `seed` and `preview` |
58
- | `stack dev [--pglite]` | `next dev` on your dev branch; `--pglite`: on PGlite in `.local-db/` (migrated, seeded once), no Neon |
59
- | `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 |
60
- | `stack neon seed` | rebuilds the `seed` branch (fake data) and runs the app's `db/seed.ts` |
61
- | `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` |
62
- | `stack db:check` | fails when the app's `src/db/schema.ts` has changes `drizzle/` has no migration for; app CI runs it |
63
- | `stack db:generate <name> [drizzle-kit flags]` | the app's `pnpm db:generate`: drizzle-kit generate under a snake_case name that says what the migration does (`stack_` names are the upgrade's) |
64
- | `stack db:upgrade` | generates the migration for the stack's tables' changes into `drizzle/` as `stack_<version>`; Copier's task runs it after the upgrade |
65
- | `stack sync-blocks [--check]` | writes each composed package's marked block (`stack` first, then `stack.config.ts`'s order) in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example`, and removes the block of a package the app no longer composes, saying each one it removes; `--check` exits 1 when any block is missing, stale or orphaned |
52
+ | `stack check` | runs `stack sync --check`, then every composed package's checks in package order (each package's check of the files it reads from the app, below, and the database package's `db:check` among them), all of them even after a failure; names each failure as `<package>: <check>: <message>` and exits 1 if any failed; app CI runs it |
53
+ | `stack sync [--check]` | writes each composed package's marked block (`stack` first, then the packages in the order `package.json`'s dependencies need) in `AGENTS.md`, `CLAUDE.md`, `.gitignore`, `.env.example`; the files each package owns, recorded in `stack.files.json`; and the generated modules `src/stack/env.ts` (the `fragments` the app's `defineEnv` and `stackVitestConfig` take), `src/stack/health.ts` and `src/stack/next.ts`. It removes the block and the files of a package the app no longer composes, saying each one it removes; `--check` exits 1 when anything is missing, stale or orphaned. It refuses, changing nothing, an existing file at an owned path that `stack.files.json` does not record (move your code out of it or delete it), and a path two packages own. `stack sync-blocks` is the same command under a second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists it once, as `sync` |
66
54
 
67
- Each package the app's `stack.config.ts` composes adds its own commands: `@wwchen/stack-auth` gives `stack user:create` and `stack user:role`, and `@wwchen/stack-infra` gives `stack vercel-build` and `stack doctor` (their READMEs). When two composed packages give one command, `stack` runs nothing and names both; so too for an entry of `packages` that is not a package, such as a factory listed without its call (`infra` for `infra()`), which `defineStack` also makes a type error.
55
+ The `stack` command finds the app's packages in `package.json`: each package in its `dependencies` or `devDependencies` whose `package.json` has `exports["./stack"]` is composed, and the core reads nothing else of a package but npm's fields.
68
56
 
69
- `stack` also says on stderr what the app does not compose, without changing what runs, its exit code or its stdout. With no `stack.config.ts`, every command first prints one line: ``stack.config.ts is missing: the app composes no packages, so only the stack's built-in commands run and `stack sync-blocks` writes only the stack's own blocks.`` With one, it prints a line for each dependency in the app's `package.json` (`dependencies` and `devDependencies`) whose installed package has a `./stack` entry that `stack.config.ts` does not compose: ``<name> is installed but stack.config.ts does not compose it: add its `/stack` entry to `packages`, or remove the dependency.``
57
+ Any dependency that exports `./stack` is composed, whoever publishes it, and is held to the suite's version: `stack` runs nothing until it is at the version `@wwchen/stack` is.
70
58
 
71
- This package gives those two its share: the `migrate` build step, which `stack vercel-build` runs before `next build` (a Preview or Production deployment migrates its own database, and a preview whose database URL is production's is refused; anything else does nothing), and `stack doctor`'s checks of the Neon integration, the database variables and the shared `CRON_SECRET` and `TOKEN_ENCRYPTION_KEY`.
59
+ It runs only from the app's root: a folder with no `package.json` is refused, with nothing written. It refuses, one line per problem with its fix and exit 1, a stack peer the app does not list, a listed package that is not installed, two versions of the suite and a dependency cycle. Each stack package the app's `package.json` lists adds its own commands: `@wwchen/stack-db` gives the Neon branch and migration commands (`stack with-neon`, `stack dev`, `stack dev-setup`, `stack run`, `stack neon`, `stack db:check`, `stack db:generate`, `stack db:upgrade`), `@wwchen/stack-auth` gives `stack user:create` and `stack user:role`, and `@wwchen/stack-infra` gives `stack vercel-build` and `stack doctor` (their READMEs). When two composed packages give one command, `stack` runs nothing and names both; so too for a package whose `./stack` entry's default export is not a factory, or whose factory throws or returns something other than a package named as its `package.json`.
72
60
 
73
- `NEON_PROJECT_ID` comes from the environment; nothing in the package names a project or domain.
61
+ The core owns `next.config.ts` (the app's own settings are in `next.config.app.ts`), `src/app/api/health/route.ts` and `.claude/rules/stack-ui.md` in an app (the route imports the app's `src/lib/env.ts`, and `next.config.ts` its `next.config.app.ts`: "Files the app writes", below), and its blocks hold the rules every app follows. It has no database code, text or variable. The core gives `stack doctor` one check of its own: a warning when `CRON_SECRET` or `TOKEN_ENCRYPTION_KEY` is one variable for Production and Preview, so a preview never holds production's secret. Each composed package checks its own variables (`@wwchen/stack-db` the database's and the Neon integration's, `@wwchen/stack-auth` sign-in's secrets, `@wwchen/stack-notify` `RESEND_API_KEY`).
62
+
63
+ `stack.config.ts` is optional: it gives the listed packages their settings (`defineStack({ settings: [authSettings({ … })] })`), and `stack` refuses settings for a package `package.json` does not list. A package that needs settings and has none refuses to build, saying what to write.
64
+
65
+ ## Files the app writes
66
+
67
+ The core's owned files import two files that are the app's own code, which `stack sync` never writes. `stack check` names either one that is missing (`@wwchen/stack: src/lib/env.ts: missing: …`), and the template writes both.
68
+
69
+ `src/lib/env.ts` exports `env`, the app's validated variables. The health route imports it as `@/lib/env`, reads `env.HEALTH_TOKEN` and hands `env` to each package's health check, so it is `defineEnv` over the generated `fragments` plus the app's own variables:
70
+
71
+ ```ts
72
+ // The app's one validated config. Imported by the CLI with Node's type stripping, so imports here are relative and carry `.ts` (no `@/`).
73
+ import { defineEnv } from "@wwchen/stack/env";
74
+ import { fragments } from "../stack/env.ts";
75
+
76
+ export const env = defineEnv({
77
+ fragments,
78
+ schema: {},
79
+ });
80
+ ```
81
+
82
+ `next.config.app.ts` default-exports the app's own Next config, which the owned `next.config.ts` imports and wraps with `withStack`:
83
+
84
+ ```ts
85
+ import type { NextConfig } from "next";
86
+
87
+ const appConfig: NextConfig = {};
88
+
89
+ export default appConfig;
90
+ ```
74
91
 
75
92
  ## Versioning
76
93
 
77
- The package, `@wwchen/stack-auth`, `@wwchen/stack-notify`, `@wwchen/stack-infra`, `@wwchen/stack-upgrade`, the Copier template and the shared CI workflow share one version, tagged `vX.Y.Z`. Releases are published to npm with provenance.
94
+ The package, `@wwchen/stack-db`, `@wwchen/stack-auth`, `@wwchen/stack-notify`, `@wwchen/stack-infra`, `@wwchen/stack-upgrade`, 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
@@ -1,4 +1,4 @@
1
- <!-- Owned by @wwchen/stack: `stack sync-blocks` rewrites everything between these markers. Put your own text outside them. -->
1
+ <!-- Owned by @wwchen/stack: `stack sync` rewrites everything between these markers. Put your own text outside them. -->
2
2
 
3
3
  ## Commands (stack apps)
4
4
 
@@ -6,28 +6,23 @@
6
6
  |---|---|
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
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`) |
12
9
  | Build | `pnpm build` |
13
10
  | Typecheck | `pnpm typecheck` |
14
11
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
15
12
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
16
13
  | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
17
- | Migrate | `pnpm db:migrate` (your dev branch) |
18
- | Rebuild the `seed` branch (fake data; every dev and preview branch is cut from it) | `pnpm exec stack neon seed` |
19
- | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
14
+ | Refresh what the stack writes: its blocks in this file, the files it owns and its generated modules (recorded in `stack.files.json`) | `stack sync` |
15
+ | Check the app against the stack: `stack sync --check`, then every package's checks (what CI runs) | `stack check` |
20
16
 
21
17
  **Gate:** `pnpm typecheck && pnpm lint && pnpm test` must pass before any task is marked done.
22
18
 
23
19
  ## Stack rules
24
20
 
25
21
  1. Never commit secrets or `.env`. `.env.example` lists names only, with empty values.
26
- 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.
27
- 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.
28
- 4. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf, never on a layout.
29
- 5. Validate at the edge: parse every route handler's input with zod before any logic.
30
- 6. Authorization is server-side on every request. Another user's row answers 404, never 403.
22
+ 2. Relative imports carry `.ts`. The `@/` alias is only for `src/app/**`, `src/components/**` and `tests/**`; code the CLI imports as plain Node (`src/lib/**`) uses relative imports.
23
+ 3. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf, never on a layout.
24
+ 4. Validate at the edge: parse every route handler's input with zod before any logic.
25
+ 5. Authorization is server-side on every request. Another user's row answers 404, never 403.
31
26
 
32
27
  ## Next.js notes
33
28
 
@@ -44,13 +39,6 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
44
39
  - 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.
45
40
  - Stories live beside their component as `*.stories.tsx` and render the real components from fixture data; a story never hand-builds a look. `PHONE` (390px) and `SMALL_PHONE` (320px) from `@wwchen/stack/storybook` open a story narrow, and the toolbar switches light and dark.
46
41
 
47
- ## Database
48
-
49
- - 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.
50
- - Local tooling refuses the production database unless you opt in deliberately.
51
- - Tests run on PGlite (one connection only) and, in CI, a real Postgres.
52
- - Schema changes go through `pnpm db:generate <name>` and a reviewed migration, never through the Neon console or a database MCP server.
53
-
54
42
  ## Security
55
43
 
56
44
  1. `CRON_SECRET` can only trigger scheduled jobs; admin and data access never accept it.
@@ -58,4 +46,4 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
58
46
  3. Mutations require JSON and a same-origin request.
59
47
  4. Connected-account tokens are encrypted at rest.
60
48
  5. Previews get their own secrets and no production third-party keys.
61
- 6. Never write a deployment's domain in the repo. Name variables (`APP_URL`, `NEON_PROJECT_ID`), never a host.
49
+ 6. Never write a deployment's domain in the repo. Name variables (`APP_URL`), never a host.
package/blocks/CLAUDE.md CHANGED
@@ -1,4 +1,4 @@
1
- <!-- Owned by @wwchen/stack: `stack sync-blocks` rewrites everything between these markers. Put your own text outside them. -->
1
+ <!-- Owned by @wwchen/stack: `stack sync` rewrites everything between these markers. Put your own text outside them. -->
2
2
 
3
3
  ## Commands
4
4
 
@@ -6,17 +6,12 @@
6
6
  |---|---|
7
7
  | Install | `pnpm install --frozen-lockfile` |
8
8
  | Dev server | `pnpm dev` (http://localhost:3000) |
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`) |
12
9
  | Typecheck | `pnpm typecheck` |
13
10
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
14
11
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
15
12
  | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
16
- | DB generate / apply migration | `pnpm db:generate <name>` (snake_case, what it does: `add_widgets`) · `pnpm db:migrate` |
17
- | Seed the shared `seed` branch | `stack neon seed` (runs the app's `db/seed.ts`) |
18
- | Reset the shared preview branch | `stack neon reset-preview` (`--set-vercel` also writes its URLs into Vercel's Preview variables) |
19
- | Refresh the stack blocks in this file | `stack sync-blocks` (`--check` in CI) |
13
+ | Refresh what the stack writes: its blocks in this file, the files it owns and its generated modules (recorded in `stack.files.json`) | `stack sync` |
14
+ | Check the app against the stack: `stack sync --check`, then every package's checks (what CI runs) | `stack check` |
20
15
 
21
16
  **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
17
 
@@ -24,15 +19,11 @@ Node is pinned in `.nvmrc`; pnpm is installed with `npm install -g pnpm@<version
24
19
 
25
20
  ## Stack
26
21
 
27
- Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme (`@lew-ds/lds`) · Postgres on Neon (PGlite in tests) · Drizzle ORM · Vercel · `@wwchen/stack` for the shared code, configs and CLI.
28
-
29
- **Local dev runs on a Neon dev branch** (`dev/<os-user>`), cut from `seed`, which holds fake 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.
30
-
31
- **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.
22
+ Next.js (App Router) · TypeScript · Tailwind CSS v4 (layout only) · LDS, product theme (`@lew-ds/lds`) · Vercel · `@wwchen/stack` for the shared code, configs and CLI.
32
23
 
33
24
  ## Code rules
34
25
 
35
- 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.
26
+ 1. Relative imports carry `.ts`. The `@/` alias is allowed only in `src/app/**`, `src/components/**` and `tests/**`; in `src/lib/**` and `scripts/**` it is forbidden, because those files also run as plain Node.
36
27
  2. Server components by default. `"use client"` only for state, effects or event handlers, on the smallest leaf. Never on a layout.
37
28
  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.
38
29
  4. Authorization is server-side on every request. A hidden button is not a permission. Another user's row answers 404, never 403.
@@ -54,26 +45,17 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
54
45
  - 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.
55
46
  - Stories live beside their component as `*.stories.tsx` and render the real components from fixture data; a story never hand-builds a look. `PHONE` (390px) and `SMALL_PHONE` (320px) from `@wwchen/stack/storybook` open a story narrow, and the toolbar switches light and dark.
56
47
 
57
- ## Database rules
58
-
59
- - Drizzle schema and migrations: generate with `pnpm db:generate <name>`, 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.
60
- - 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.
61
- - The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
62
- - 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.
63
- - Money, if any, is stored as integer minor units, never floats.
64
-
65
48
  ## Security rules
66
49
 
67
50
  1. `CRON_SECRET` can only trigger scheduled jobs (counts-only responses); admin and data access never accept it.
68
51
  2. No free text from URLs is ever rendered; redirects carry short codes.
69
52
  3. Mutations require JSON and same-origin.
70
- 4. Local tooling refuses the production database unless explicitly opted in.
71
- 5. Connected-account tokens are encrypted at rest (AES-256-GCM).
72
- 6. Other people's data stays out of dev and previews.
73
- 7. 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`, `NEON_PROJECT_ID`), never a value. `.env.example` is committed and stays in sync; `.env` never is.
53
+ 4. Connected-account tokens are encrypted at rest (AES-256-GCM).
54
+ 5. Previews get their own secrets and no production third-party keys.
55
+ 6. Never commit secrets, `.env` or build output. No deployment's domain or key in the repo: code, docs and this file name variables (`APP_URL`), never a value. `.env.example` is committed and stays in sync; `.env` never is.
74
56
 
75
57
  ## Non-negotiable
76
58
 
77
- 1. Never commit secrets or `.env`. Never edit a generated migration by hand.
59
+ 1. Never commit secrets or `.env`.
78
60
  2. Never mark a task done with a failing gate command.
79
61
  3. Never merge a pull request into `main` for the owner. Open the PR, get its checks green, and stop; the owner merges.
@@ -2,17 +2,11 @@
2
2
 
3
3
  # Public URL of this deployment (default http://localhost:3000; on Vercel, derived from its domain when unset)
4
4
  APP_URL=
5
- # Pooled Postgres URL (required)
6
- DATABASE_URL=
7
- # Direct (unpooled) URL, used by migrations when set
8
- DATABASE_URL_UNPOOLED=
9
- # Production database host, so local tooling can refuse it
10
- PRODUCTION_DATABASE_HOST=
11
5
  # Bearer secret for scheduled jobs only
12
6
  CRON_SECRET=
13
7
  # Encrypts connected-account tokens: openssl rand -base64 32. Keep it forever (a new key orphans every token)
14
8
  TOKEN_ENCRYPTION_KEY=
15
- # Bearer token for the health route's database probe
9
+ # Bearer token for the health route's detailed checks
16
10
  HEALTH_TOKEN=
17
11
  # Proxy hops to trust for the client IP (0 on Vercel)
18
12
  TRUSTED_PROXY_HOPS=
package/blocks/gitignore CHANGED
@@ -7,12 +7,6 @@ next-env.d.ts
7
7
  .vercel
8
8
  storybook-static
9
9
 
10
- # Local state
11
- .neon
12
- .pglite/
13
- .pglite.lock
14
- .local-db/
15
-
16
10
  # Secrets: only the example is committed. No pattern after these may match `.env.example`.
17
11
  .env*
18
12
  !.env.example
@@ -1,6 +1,7 @@
1
1
  import { type StackPackage } from "../stack/contracts.ts";
2
- import type { Cli } from "./context.ts";
2
+ /** `sync`'s second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists the command once, as `sync`. */
3
+ export declare const SYNC_SECOND_NAME = "sync-blocks";
3
4
  /**
4
- * The core's own commands, build step, doctor checks and blocks, as the package the host always runs first. Each loader imports its command's module when that command runs. A command that needs the full `Cli` closes over it (its `sql`, `startLocalDatabase` and `username` are the built-in commands' own, not the context's); `sync-blocks` takes the context, whose `packages` it writes the blocks of.
5
+ * The core's own commands, checks, doctor check, blocks and files, as the package the host always runs first: `sync` (also run as `sync-blocks`), which loads its module when it runs and writes every composed package's blocks, files and generated modules; `check`, which loads its module when it runs, checks that sync is current and runs every package's checks; its checks that the app has the files its owned files import; the check of the core's secrets, which a hosting package's `stack doctor` runs; the core's blocks; `next.config.ts`, the health route and its UI rules, which it owns; and its env fragment, for the app's generated env module.
5
6
  */
6
- export declare function builtinPackage(cli: Cli): StackPackage;
7
+ export declare function builtinPackage(): StackPackage;
@@ -1,47 +1,42 @@
1
- import { BLOCK_FILES, BUILTIN_PACKAGE, packageBlocks, } from "../stack/contracts.js";
1
+ import { BLOCK_FILES, BUILTIN_PACKAGE, CORE_PACKAGE, packageBlocks, starterFileChecks, } from "../stack/contracts.js";
2
2
  /** The package's `blocks/`, beside `src/` and `dist/`, so one relative path serves both and an installed package. */
3
3
  const BLOCKS = new URL("../../blocks/", import.meta.url);
4
- /** The database's and the core's variables, checked by `stack doctor`; named, so a failure names it. */
5
- const databaseChecks = async (facts) => (await import("../db/doctor.js")).databaseChecks(facts);
4
+ /** The package's `files/`, which mirrors the app's paths, beside `src/` and `dist/`. */
5
+ const FILES = new URL("../../files/", import.meta.url);
6
+ /** The core's secrets, which a preview must hold its own values of. */
7
+ const PREVIEW_OWN_SECRETS = [
8
+ "CRON_SECRET",
9
+ "TOKEN_ENCRYPTION_KEY",
10
+ ];
11
+ /** `stack doctor`'s check of the core's secrets, which a preview must hold its own values of, never production's (runbook §3); named, so a failure names it. The Vercel reader loads only when the doctor runs it. */
12
+ const previewOwnSecrets = async (facts) => (await import("../vercel/index.js")).previewOwnSecretsCheck(PREVIEW_OWN_SECRETS)(facts);
13
+ /** The files the core owns in an app, each read from `files/` at its own path. */
14
+ const OWNED_FILES = [
15
+ "next.config.ts",
16
+ "src/app/api/health/route.ts",
17
+ ".claude/rules/stack-ui.md",
18
+ ];
19
+ /** `sync`'s second name, which the copier-update workflow and the tests of apps made before 0.11 run; the bare `stack` lists the command once, as `sync`. */
20
+ export const SYNC_SECOND_NAME = "sync-blocks";
21
+ /** The app's own files the core's owned files import: the health route's `env` (`@/lib/env`) and `next.config.ts`'s `next.config.app.ts`. */
22
+ const STARTER_FILES = ["src/lib/env.ts", "next.config.app.ts"];
23
+ /** The section of the core's README that shows its starter files. */
24
+ const STARTER_SECTION = "Files the app writes";
6
25
  /**
7
- * The core's own commands, build step, doctor checks and blocks, as the package the host always runs first. Each loader imports its command's module when that command runs. A command that needs the full `Cli` closes over it (its `sql`, `startLocalDatabase` and `username` are the built-in commands' own, not the context's); `sync-blocks` takes the context, whose `packages` it writes the blocks of.
26
+ * The core's own commands, checks, doctor check, blocks and files, as the package the host always runs first: `sync` (also run as `sync-blocks`), which loads its module when it runs and writes every composed package's blocks, files and generated modules; `check`, which loads its module when it runs, checks that sync is current and runs every package's checks; its checks that the app has the files its owned files import; the check of the core's secrets, which a hosting package's `stack doctor` runs; the core's blocks; `next.config.ts`, the health route and its UI rules, which it owns; and its env fragment, for the app's generated env module.
8
27
  */
9
- export function builtinPackage(cli) {
10
- const command = (load) => async () => {
11
- const run = await load();
12
- return (_ctx, args) => run(cli, args);
13
- };
28
+ export function builtinPackage() {
14
29
  return {
15
30
  name: BUILTIN_PACKAGE,
16
31
  commands: {
17
- "with-neon": command(async () => (await import("./neon.js")).withNeon),
18
- dev: command(async () => (await import("./dev.js")).dev),
19
- "dev-setup": command(async () => (await import("./neon.js")).devSetup),
20
- run: command(async () => (await import("./run.js")).runScript),
21
- neon: command(async () => {
22
- const { neonSeed, resetPreview } = await import("./neon.js");
23
- return async (c, [sub, ...rest]) => {
24
- if (sub === "seed")
25
- return neonSeed(c);
26
- if (sub === "reset-preview")
27
- return resetPreview(c, rest);
28
- c.error("usage: stack neon seed | stack neon reset-preview [--set-vercel]");
29
- return 2;
30
- };
31
- }),
32
- "sync-blocks": async () => (await import("./sync-blocks.js")).syncBlocksCommand,
33
- "db:check": command(async () => (await import("./db.js")).dbCheck),
34
- "db:generate": command(async () => (await import("./db.js")).dbGenerate),
35
- "db:upgrade": command(async () => (await import("./db.js")).dbUpgrade),
32
+ sync: async () => (await import("./sync.js")).syncCommand,
33
+ [SYNC_SECOND_NAME]: async () => (await import("./sync.js")).syncCommand,
34
+ check: async () => (await import("./check.js")).checkCommand,
36
35
  },
37
- // A composed hosting package's `stack vercel-build` and `stack doctor` run these; each loads the database's module only when it runs.
38
- buildSteps: [
39
- {
40
- name: "migrate",
41
- run: async (ctx) => (await import("../db/doctor.js")).migrateStep.run(ctx),
42
- },
43
- ],
44
- doctorChecks: [databaseChecks],
36
+ checks: starterFileChecks(CORE_PACKAGE, STARTER_SECTION, STARTER_FILES),
37
+ doctorChecks: [previewOwnSecrets],
45
38
  blocks: packageBlocks(BLOCKS, Object.values(BLOCK_FILES)),
39
+ files: OWNED_FILES.map((path) => ({ path, source: new URL(path, FILES) })),
40
+ runtime: { env: { from: "@wwchen/stack/env", name: "coreEnv" } },
46
41
  };
47
42
  }
@@ -0,0 +1,5 @@
1
+ import { type Command } from "../stack/contracts.ts";
2
+ /**
3
+ * `stack check`: `stack sync --check`, then every composed package's checks in package order, all of them even after a failure. Each failure prints as `<package>: <check>: <message>` on stderr; exit 1 when any failed.
4
+ */
5
+ export declare const checkCommand: Command;
@@ -0,0 +1,39 @@
1
+ import { CORE_PACKAGE } from "../stack/contracts.js";
2
+ import { CliError } from "./context.js";
3
+ import { ownerOf, syncCommand } from "./sync.js";
4
+ /** What a thrown value says: an Error's message, anything else as text. */
5
+ const messageOf = (thrown) => (thrown instanceof Error ? thrown.message : String(thrown));
6
+ /**
7
+ * `stack check`: `stack sync --check`, then every composed package's checks in package order, all of them even after a failure. Each failure prints as `<package>: <check>: <message>` on stderr; exit 1 when any failed.
8
+ */
9
+ export const checkCommand = async (ctx, args) => {
10
+ if (args.length > 0)
11
+ throw new CliError(`check: unknown argument ${args[0]}`);
12
+ const failures = [];
13
+ try {
14
+ if ((await syncCommand(ctx, ["--check"])) !== 0) {
15
+ failures.push(`${CORE_PACKAGE}: sync --check: files are stale: run \`stack sync\``);
16
+ }
17
+ }
18
+ catch (error) {
19
+ failures.push(`${CORE_PACKAGE}: sync --check: ${messageOf(error)}`);
20
+ }
21
+ for (const pkg of ctx.packages) {
22
+ for (const check of pkg.checks ?? []) {
23
+ try {
24
+ await check.run(ctx);
25
+ }
26
+ catch (error) {
27
+ failures.push(`${ownerOf(pkg)}: ${check.name}: ${messageOf(error)}`);
28
+ }
29
+ }
30
+ }
31
+ if (failures.length === 0) {
32
+ ctx.log("stack check: all passed");
33
+ return 0;
34
+ }
35
+ for (const failure of failures)
36
+ ctx.error(failure);
37
+ ctx.error(`stack check: ${failures.length} failed`);
38
+ return 1;
39
+ };
@@ -4,11 +4,6 @@ export declare const STACK_PACKAGE: {
4
4
  version: string;
5
5
  };
6
6
  export type { Env, ExecOptions, ExecResult };
7
- /** A Postgres served on loopback for `stack dev --pglite`. */
8
- export type LocalDatabase = {
9
- url: string;
10
- stop(): Promise<void>;
11
- };
12
7
  /**
13
8
  * Everything the CLI touches outside its own process, so a test can replace it. Only the entry point reads `process.env`: it passes it in as `env`, and nothing below reads it directly. `exec` runs a program with an argument array, never a shell string.
14
9
  */
@@ -16,25 +11,13 @@ export type CliDeps = {
16
11
  env: Env;
17
12
  exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
18
13
  cwd: string;
19
- /** The OS user, for the default `dev/<user>` branch name. */
20
- username?: string;
21
14
  log?(message: string): void;
22
15
  error?(message: string): void;
23
- /** Imports the app's own TypeScript (`stack.config.ts`, `db/seed.ts`) with Node's type stripping. */
16
+ /** Imports the app's own TypeScript (`stack.config.ts`, a package's `./stack` entry) with Node's type stripping. */
24
17
  importModule?(specifier: string): Promise<Record<string, unknown>>;
25
- /** Runs one SQL statement against a database, for emptying the new `seed` branch. */
26
- sql?(url: string, statement: string): Promise<Record<string, unknown>[]>;
27
- /** The Node binary `stack run` starts an app script with. */
28
- execPath?: string;
29
- /**
30
- * 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.
31
- */
32
- startLocalDatabase?(dataDir: string): Promise<LocalDatabase>;
33
18
  };
34
19
  export type Cli = Required<CliDeps>;
35
20
  export declare function resolveDeps(deps: CliDeps): Cli;
36
- /** Loads the app's `.env` (or the file `ENV_FILE` names, the deliberate production opt-in) into `env`; real variables always win. */
37
- export declare function loadAppEnv(cli: Pick<Cli, "cwd" | "env">): void;
38
21
  /** Imports a file of the app by path relative to its root. */
39
22
  export declare function importApp(cli: Cli, path: string): Promise<Record<string, unknown>>;
40
23
  /** A failure the CLI reports as one line and a non-zero exit, with no stack trace. */
@@ -7,40 +7,18 @@ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExte
7
7
  return path;
8
8
  };
9
9
  import { readFileSync } from "node:fs";
10
- import { userInfo } from "node:os";
11
10
  import { join } from "node:path";
12
11
  import { pathToFileURL } from "node:url";
13
- import pg from "pg";
14
- import { explicitSslMode } from "../db/ssl.js";
15
- import { startPgliteServer } from "../db/testing/pglite.js";
16
- import { loadEnvFile } from "../env/index.js";
17
12
  /** The stack's own package.json, for the installed version. It sits two levels above both `src/cli/` and `dist/cli/`. */
18
13
  export const STACK_PACKAGE = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8"));
19
14
  export function resolveDeps(deps) {
20
15
  return {
21
16
  log: (message) => console.log(message),
22
17
  error: (message) => console.error(message),
23
- username: userInfo().username,
24
- execPath: process.execPath,
25
- startLocalDatabase: (dataDir) => startPgliteServer({ dataDir, resolveFrom: deps.cwd }),
26
18
  importModule: (specifier) => import(__rewriteRelativeImportExtension(specifier)),
27
- sql: async (url, statement) => {
28
- const client = new pg.Client({ connectionString: explicitSslMode(url) });
29
- await client.connect();
30
- try {
31
- return (await client.query(statement)).rows;
32
- }
33
- finally {
34
- await client.end();
35
- }
36
- },
37
19
  ...deps,
38
20
  };
39
21
  }
40
- /** Loads the app's `.env` (or the file `ENV_FILE` names, the deliberate production opt-in) into `env`; real variables always win. */
41
- export function loadAppEnv(cli) {
42
- loadEnvFile(cli.env.ENV_FILE?.trim() ? undefined : join(cli.cwd, ".env"), cli.env);
43
- }
44
22
  /** Imports a file of the app by path relative to its root. */
45
23
  export function importApp(cli, path) {
46
24
  return cli.importModule(pathToFileURL(join(cli.cwd, path)).href);
@@ -0,0 +1,15 @@
1
+ /** A stack package an app lists and has installed. */
2
+ export type Installed = {
3
+ name: string;
4
+ version: string;
5
+ /** The installed package's real path. */
6
+ dir: string;
7
+ /** The file the app resolves for `<name>/stack`. */
8
+ entry: string;
9
+ /** The stack packages among its non-optional peers. */
10
+ needs: string[];
11
+ };
12
+ /**
13
+ * The stack packages the app at `cwd` lists in `dependencies` and `devDependencies`, each after the ones it needs (ties by name). Refuses with a `CliError` when `cwd` has no package.json, a listed package is not installed, a package is not at `coreVersion`, a stack peer is not listed, packages need each other, a package.json does not parse, or a package's `./stack` entry does not exist.
14
+ */
15
+ export declare function discover(cwd: string, coreVersion: string): Installed[];