@wwchen/stack 0.4.0 → 0.6.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
@@ -2,13 +2,13 @@
2
2
 
3
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.
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`. `@electric-sql/pglite` and `@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, 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/env` | `stackEnvSchema` and `stackEnv()`: the shared variables, validated; production requires `APP_URL`, `DATABASE_URL`, `BETTER_AUTH_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM`. `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
11
+ | `@wwchen/stack/env` | `stackEnvSchema` and `stackEnv()`: the shared variables, validated; production requires `APP_URL` (derived on Vercel when unset), `DATABASE_URL`, `BETTER_AUTH_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM`. `SKIP_ENV_VALIDATION=1` skips it in builds (never at production runtime). |
12
12
  | `@wwchen/stack/db` | the pooled client, `migrationStatus`, the dev-database guard that refuses production |
13
13
  | `@wwchen/stack/db/testing`, `/db/testing/isolate` | test databases: PGlite by default, a real Postgres when `TEST_DATABASE_URL` is set |
14
14
  | `@wwchen/stack/mail` | Resend through one `fetch`; development writes links to a sink file |
@@ -16,9 +16,10 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
16
16
  | `@wwchen/stack/auth/better-auth` | the Better Auth provider (magic link, optional Google for existing users, opt-in `emailAndPassword` reached in-process through `provider.instance`) |
17
17
  | `@wwchen/stack/auth/proxy` | the `proxy.ts` helpers and `proxyMatcher` |
18
18
  | `@wwchen/stack/next` | `withStack(appConfig)` for `next.config.ts`, `apiHandler` and `readJson`, `cronRoute` (answers 500 when the job returns `alerting: true`) and `healthRoute` |
19
- | `@wwchen/stack/connections` | connected accounts (not sign-in): `connectionTable`, `createConnections` (start and callback route handlers, `token`, `list`, `connected`, `disconnect`), the `foursquare` provider, AES-256-GCM token encryption under `TOKEN_ENCRYPTION_KEY` |
19
+ | `@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` |
20
20
  | `@wwchen/stack/jobs` | multi-person scheduled jobs: `failingSince` and `isNewFailure` (alert on a failure's first 24 hours only), `mapLimit` |
21
21
  | `@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 |
22
+ | `@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 |
22
23
  | `@wwchen/stack/configs/tsconfig.next.json`, `/configs/biome.json`, `/configs/vitest` | shared tool configs, consumed with `extends` or an import |
23
24
  | `@wwchen/stack/testing/next` | tests only: `inServerAction` runs a function in a real Next server-action scope, `thrownBy` reads a `redirect()`/`notFound()` |
24
25
 
@@ -26,7 +27,7 @@ Sign-in never creates users: every user is added first (`stack user:create`), ha
26
27
 
27
28
  ### Connected accounts
28
29
 
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):
30
+ An app that works on someone's behalf at another service (reading their data there through its OAuth API) 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):
30
31
 
31
32
  ```ts
32
33
  // src/db/schema.ts
@@ -34,7 +35,7 @@ export const connection = connectionTable(appUser);
34
35
 
35
36
  // src/lib/connections.ts
36
37
  export const connections = createConnections({
37
- db, table: connection, providers: [foursquare({ clientId, clientSecret })],
38
+ db, table: connection, providers: [myService({ clientId, clientSecret })], // the app's own ConnectionProvider
38
39
  secret: env.BETTER_AUTH_SECRET, encryptionKey: env.TOKEN_ENCRYPTION_KEY, baseURL: env.APP_URL,
39
40
  });
40
41
 
package/blocks/AGENTS.md CHANGED
@@ -13,6 +13,7 @@
13
13
  | Typecheck | `pnpm typecheck` |
14
14
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
15
15
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
16
+ | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
16
17
  | Migrate | `pnpm db:migrate` (your dev branch) |
17
18
  | Rebuild the `seed` branch (fake data; every dev and preview branch is cut from it) | `pnpm exec stack neon seed` |
18
19
  | Add a user | `stack user:create <email> [--admin]` (on your dev branch; production: the runbook's "First admin") |
@@ -45,7 +46,8 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
45
46
  - Never hand-roll a pill, button, input, table or banner. If LDS lacks something, fix it upstream in LDS, never at a call site.
46
47
  - 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.
47
48
  - 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.
48
- - A design change lands in the component and its stories in the same change.
49
+ - 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.
50
+ - 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.
49
51
 
50
52
  ## Database
51
53
 
package/blocks/CLAUDE.md CHANGED
@@ -13,6 +13,7 @@
13
13
  | Typecheck | `pnpm typecheck` |
14
14
  | Lint / format | `pnpm lint` · `pnpm lint:fix` |
15
15
  | Tests | `pnpm test` · one file: `pnpm test tests/unit/<name>.test.ts` |
16
+ | Storybook | `pnpm storybook` (http://localhost:6006) · every story built, as CI does: `pnpm storybook:build` |
16
17
  | DB generate / apply migration | `pnpm db:generate` · `pnpm db:migrate` |
17
18
  | Seed the shared `seed` branch | `stack neon seed` (runs the app's `db/seed.ts`) |
18
19
  | Reset the shared preview branch | `stack neon reset-preview` (`--set-vercel` also writes its URLs into Vercel's Preview variables) |
@@ -55,6 +56,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
55
56
  - Layouts respond to the width a component has (container queries), never to the device.
56
57
  - Theme is a cookie (`theme-product mode-*`) read and written through the stack's `/ui` helpers.
57
58
  - 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.
59
+ - 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.
58
60
 
59
61
  ## Database rules
60
62
 
@@ -62,7 +64,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
62
64
  - 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.
63
65
  - The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
64
66
  - 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.
65
- - Money, if any, is integer cents; reconcile from source rows, never increment.
67
+ - Money, if any, is stored as integer minor units, never floats.
66
68
  - Every user has an email: required, unique, lower-cased and trimmed.
67
69
 
68
70
  ## Security rules
@@ -1,7 +1,7 @@
1
1
  # Names only: copy to .env and fill in. Never put a real value in this file.
2
2
  # A blank value counts as unset. NODE_ENV is set by tooling, never here.
3
3
 
4
- # Public URL of this deployment (default http://localhost:3000)
4
+ # Public URL of this deployment (default http://localhost:3000; on Vercel, derived from its domain when unset)
5
5
  APP_URL=
6
6
  # Pooled Postgres URL (required)
7
7
  DATABASE_URL=
@@ -14,7 +14,8 @@
14
14
  "!**/.vercel",
15
15
  "!**/drizzle",
16
16
  "!**/dist",
17
- "!**/coverage"
17
+ "!**/coverage",
18
+ "!**/storybook-static"
18
19
  ]
19
20
  },
20
21
  "formatter": {
package/dist/cli/neon.js CHANGED
@@ -32,7 +32,7 @@ export function projectId(env) {
32
32
  export function assertDevBranchName(name, production) {
33
33
  const yours = "set NEON_DEV_BRANCH to your own branch (default dev/<os user>)";
34
34
  if (name === production.name || name === "production") {
35
- throw new CliError(`${name} is production, not a dev branch: production commands use ENV_FILE=.env.neon; ${yours}.`);
35
+ throw new CliError(`${name} is production, not a dev branch: production commands use ENV_FILE=<production env file>; ${yours}.`);
36
36
  }
37
37
  if (name === SEED || name === SEED_NEXT || name === PREVIEW) {
38
38
  throw new CliError(`${name} is a shared branch, not a dev branch; ${yours}.`);
@@ -57,5 +57,5 @@ export type Connections = {
57
57
  };
58
58
  export declare function createConnections(opts: ConnectionsOptions): Connections;
59
59
  export { decryptToken, encryptToken, parseEncryptionKey, TokenKeyError } from "./crypto.ts";
60
- export { type ConnectionProvider, FOURSQUARE_API_VERSION, foursquare } from "./providers.ts";
60
+ export type { ConnectionProvider } from "./providers.ts";
61
61
  export { type ConnectionTable, connectionTable } from "./table.ts";
@@ -206,5 +206,4 @@ export function createConnections(opts) {
206
206
  };
207
207
  }
208
208
  export { decryptToken, encryptToken, parseEncryptionKey, TokenKeyError } from "./crypto.js";
209
- export { FOURSQUARE_API_VERSION, foursquare } from "./providers.js";
210
209
  export { connectionTable } from "./table.js";
@@ -19,12 +19,3 @@ export type ConnectionProvider = {
19
19
  name: string | null;
20
20
  }>;
21
21
  };
22
- export declare const FOURSQUARE_API_VERSION = "20240101";
23
- /**
24
- * Foursquare (Swarm). Its tokens do not expire. `subject` is the Foursquare user id, read from the
25
- * legacy v2 `users/self`, the endpoint family that also returns a person's own check-ins.
26
- */
27
- export declare function foursquare(opts: {
28
- clientId: string;
29
- clientSecret: string;
30
- }): ConnectionProvider;
@@ -1,47 +1 @@
1
- const FOURSQUARE_OAUTH = "https://foursquare.com/oauth2";
2
- const FOURSQUARE_API = "https://api.foursquare.com/v2";
3
- export const FOURSQUARE_API_VERSION = "20240101";
4
- /**
5
- * Foursquare (Swarm). Its tokens do not expire. `subject` is the Foursquare user id, read from the
6
- * legacy v2 `users/self`, the endpoint family that also returns a person's own check-ins.
7
- */
8
- export function foursquare(opts) {
9
- return {
10
- id: "foursquare",
11
- authorizeUrl({ redirectUri, state }) {
12
- const params = new URLSearchParams({
13
- client_id: opts.clientId,
14
- response_type: "code",
15
- redirect_uri: redirectUri,
16
- state,
17
- });
18
- return `${FOURSQUARE_OAUTH}/authenticate?${params}`;
19
- },
20
- async exchange({ code, redirectUri, fetch }) {
21
- const params = new URLSearchParams({
22
- client_id: opts.clientId,
23
- client_secret: opts.clientSecret,
24
- grant_type: "authorization_code",
25
- redirect_uri: redirectUri,
26
- code,
27
- });
28
- const res = await fetch(`${FOURSQUARE_OAUTH}/access_token?${params}`);
29
- const body = (await res.json().catch(() => null));
30
- const token = typeof body?.access_token === "string" ? body.access_token : "";
31
- if (!token) {
32
- const reason = typeof body?.error === "string" ? body.error : "no token returned";
33
- throw new Error(`Foursquare token exchange failed (HTTP ${res.status}): ${reason}`);
34
- }
35
- const self = new URLSearchParams({ oauth_token: token, v: FOURSQUARE_API_VERSION });
36
- const me = await fetch(`${FOURSQUARE_API}/users/self?${self}`);
37
- const user = (await me.json().catch(() => null))?.response?.user;
38
- if (typeof user?.id !== "string" || !user.id) {
39
- throw new Error(`Foursquare did not say who connected (HTTP ${me.status})`);
40
- }
41
- const name = [user.firstName, user.lastName]
42
- .filter((part) => typeof part === "string" && part.length > 0)
43
- .join(" ");
44
- return { token, subject: user.id, name: name || null };
45
- },
46
- };
47
- }
1
+ export {};
@@ -10,7 +10,7 @@ export type DatabaseTargetOptions = {
10
10
  nodeEnv: string | undefined;
11
11
  /** `ALLOW_REMOTE_DATABASE`; only "1" opens the guard. */
12
12
  allowRemote: string | undefined;
13
- /** `ENV_FILE`: set when the caller named an env file on purpose (e.g. `.env.neon`). */
13
+ /** `ENV_FILE`: set when the caller named an env file on purpose (e.g. `.env.production-admin`). */
14
14
  envFile: string | undefined;
15
15
  /** `PRODUCTION_DATABASE_HOST`: production's Neon host, pooled or direct. */
16
16
  productionHost: string | undefined;
package/dist/db/target.js CHANGED
@@ -56,7 +56,7 @@ export function assertDevDatabase(connectionString, { nodeEnv, allowRemote, envF
56
56
  if ((envFile ?? "").trim() !== "")
57
57
  return;
58
58
  const host = connectionString ? hostOf(connectionString) : "(not set)";
59
- const optIn = "Use `ENV_FILE=.env.neon …` for a deliberate production command.";
59
+ const optIn = "Use `ENV_FILE=<production env file> …` for a deliberate production command.";
60
60
  if (!connectionString) {
61
61
  throw new Error(`Refusing to run with no DATABASE_URL. Point it at your Neon dev branch. ${optIn}`);
62
62
  }
@@ -30,8 +30,9 @@ export interface EnvSpec<S extends z.ZodRawShape> {
30
30
  * build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
31
31
  * enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
32
32
  * `SKIP_ENV_VALIDATION` is ignored outside the build phase.
33
- * - When the schema has `APP_URL`, it is derived from VERCEL_BRANCH_URL / VERCEL_URL on a Vercel
34
- * preview, so apps that extend the stack schema get it for free.
33
+ * - When the schema has `APP_URL` and it is unset, it is derived on Vercel: from
34
+ * VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview,
35
+ * so apps that extend the stack schema get it for free.
35
36
  * - Throws one `ConfigError` listing every problem.
36
37
  */
37
38
  export declare function defineEnv<S extends z.ZodRawShape>(spec: EnvSpec<S>, rawSource?: EnvSource): z.infer<z.ZodObject<S>>;
@@ -49,21 +49,26 @@ function resolve(name, source, problems) {
49
49
  return value;
50
50
  }
51
51
  /**
52
- * On a Vercel preview the platform's own hostnames are the only addresses the app has, so APP_URL
53
- * may be derived from them. Deliberately not a schema default: the derived value is placed in the
54
- * source, so it satisfies the production requirement on a preview and nowhere else.
52
+ * On Vercel an unset APP_URL is derived from the platform's own hostnames, so a new project boots
53
+ * before anyone knows its domain. Deliberately not a schema default: the derived value is placed in
54
+ * the source, so it satisfies the production requirement on Vercel and nowhere else. An explicit
55
+ * APP_URL (or APP_URL_FILE) always wins.
55
56
  *
56
- * The branch alias comes first, the deployment URL only without one. Deployment Protection's
57
- * Vercel sign-in is per hostname, so a magic link pointing at the other hostname makes the owner
58
- * sign in to Vercel again first.
57
+ * - Production: `VERCEL_PROJECT_PRODUCTION_URL`, the project's production domain (its shortest
58
+ * custom domain, else its `vercel.app` one). Never `VERCEL_URL`, which names one deployment, not
59
+ * the address people use.
60
+ * - Preview: the branch alias first, the deployment URL only without one. Deployment Protection's
61
+ * Vercel sign-in is per hostname, so a magic link pointing at the other hostname makes the owner
62
+ * sign in to Vercel again first.
59
63
  */
60
- function withPreviewAppUrl(source) {
61
- if (source.VERCEL_ENV !== "preview" ||
62
- !isBlank(source.APP_URL) ||
63
- !isBlank(source.APP_URL_FILE)) {
64
+ function withVercelAppUrl(source) {
65
+ if (!isBlank(source.APP_URL) || !isBlank(source.APP_URL_FILE))
64
66
  return source;
65
- }
66
- const host = (source.VERCEL_BRANCH_URL ?? "").trim() || (source.VERCEL_URL ?? "").trim();
67
+ const host = source.VERCEL_ENV === "production"
68
+ ? (source.VERCEL_PROJECT_PRODUCTION_URL ?? "").trim()
69
+ : source.VERCEL_ENV === "preview"
70
+ ? (source.VERCEL_BRANCH_URL ?? "").trim() || (source.VERCEL_URL ?? "").trim()
71
+ : "";
67
72
  return host === "" ? source : { ...source, APP_URL: `https://${host}` };
68
73
  }
69
74
  /**
@@ -76,12 +81,13 @@ function withPreviewAppUrl(source) {
76
81
  * build is not a boot: production requirements, groups and a missing `DATABASE_URL` are not
77
82
  * enforced (a placeholder stands in), but defaults still apply. With `NODE_ENV=production`,
78
83
  * `SKIP_ENV_VALIDATION` is ignored outside the build phase.
79
- * - When the schema has `APP_URL`, it is derived from VERCEL_BRANCH_URL / VERCEL_URL on a Vercel
80
- * preview, so apps that extend the stack schema get it for free.
84
+ * - When the schema has `APP_URL` and it is unset, it is derived on Vercel: from
85
+ * VERCEL_PROJECT_PRODUCTION_URL in production, from VERCEL_BRANCH_URL / VERCEL_URL on a preview,
86
+ * so apps that extend the stack schema get it for free.
81
87
  * - Throws one `ConfigError` listing every problem.
82
88
  */
83
89
  export function defineEnv(spec, rawSource = process.env) {
84
- const source = "APP_URL" in spec.schema ? withPreviewAppUrl(rawSource) : rawSource;
90
+ const source = "APP_URL" in spec.schema ? withVercelAppUrl(rawSource) : rawSource;
85
91
  const problems = [];
86
92
  const resolved = {};
87
93
  for (const name of Object.keys(spec.schema)) {
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Helpers for scheduled jobs that work for many people (one run syncs everyone).
2
+ * Helpers for scheduled jobs that work for many people (one run does the work for everyone).
3
3
  *
4
4
  * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
- * If every failure answered 500, one person whose sync is broken would hold the monitor down for
5
+ * If every failure answered 500, one person whose runs keep failing would hold the monitor down for
6
6
  * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
7
  * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
8
  * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
@@ -18,8 +18,8 @@ export type RunOutcome = {
18
18
  };
19
19
  /**
20
20
  * When `run`'s failure streak began: the previous run's streak start when that one failed too,
21
- * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
22
- * dry-run) run before this one.
21
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's run before this
22
+ * one.
23
23
  */
24
24
  export declare function failingSince(run: {
25
25
  ok: boolean;
@@ -1,8 +1,8 @@
1
1
  /**
2
- * Helpers for scheduled jobs that work for many people (one run syncs everyone).
2
+ * Helpers for scheduled jobs that work for many people (one run does the work for everyone).
3
3
  *
4
4
  * **Alert on new failures only.** An uptime monitor that calls the job alerts when it answers 500.
5
- * If every failure answered 500, one person whose sync is broken would hold the monitor down for
5
+ * If every failure answered 500, one person whose runs keep failing would hold the monitor down for
6
6
  * good, and the next person to break would raise no alert. So a failure counts as *new* for its
7
7
  * first `ALERT_FOR_HOURS` (24h) and the job answers 500 only while someone's failure is new
8
8
  * (`cronRoute` does that when the job returns `alerting: true`). The person stays marked failing in
@@ -13,8 +13,8 @@ const ms = (t) => (typeof t === "string" ? Date.parse(t) : t.getTime());
13
13
  const iso = (t) => (typeof t === "string" ? t : t.toISOString());
14
14
  /**
15
15
  * When `run`'s failure streak began: the previous run's streak start when that one failed too,
16
- * otherwise `run` itself. Null for a successful run. `previous` is the person's last real (not
17
- * dry-run) run before this one.
16
+ * otherwise `run` itself. Null for a successful run. `previous` is the person's run before this
17
+ * one.
18
18
  */
19
19
  export function failingSince(run, previous) {
20
20
  if (run.ok)
@@ -0,0 +1,98 @@
1
+ import type { Preview } from "@storybook/nextjs-vite";
2
+ import { type AppRouterInstance } from "next/dist/shared/lib/app-router-context.shared-runtime.js";
3
+ import { type Theme } from "../ui/theme.ts";
4
+ /**
5
+ * An app's Storybook, set up the way its root layout sets up a page: the same classes on `<html>` (theme, mode and font), the same inline icon sprite, and a router for `useRouter()`. An app's `.storybook/preview.tsx` imports its own stylesheet and font and spreads `stackPreview(...)`.
6
+ *
7
+ * Storybook's packages are optional peers: only an app's Storybook imports this module.
8
+ */
9
+ export type StackPreviewOptions = {
10
+ /** The app's `APP_ICONS`: the glyphs its components name, inlined as the root layout does. */
11
+ icons: readonly string[];
12
+ /** The `next/font` class the root layout passes to `htmlClassName` (`inter.variable`). */
13
+ fontVariable?: string;
14
+ /** The classes the root layout puts on `<body>`, added to Storybook's own `<body>` beside its layout classes. */
15
+ bodyClassName?: string;
16
+ };
17
+ /** The toolbar's light/dark switch, as a story global. Anything but `"dark"` is light. */
18
+ export declare function storyTheme(value: unknown): Theme;
19
+ /**
20
+ * Writes what the root layout writes on the server. Storybook has no request, so the theme comes from the toolbar instead of the cookie, and the classes are set on the live document. `<html>` is the stack's alone; `<body>` also carries Storybook's layout classes, so the app's are added beside them.
21
+ */
22
+ export declare function applyStoryTheme(document: {
23
+ documentElement: {
24
+ className: string;
25
+ };
26
+ body: {
27
+ classList: {
28
+ add(...tokens: string[]): void;
29
+ };
30
+ };
31
+ }, theme: Theme, options?: Pick<StackPreviewOptions, "fontVariable" | "bodyClassName">): void;
32
+ /**
33
+ * The router `useRouter()` reads in a story. Storybook's own app-router mode does not render under Next 16.4 (its RedirectBoundary reads a context it never sets), so stories get Next's context directly. A navigation or refresh is logged to the browser console instead of happening.
34
+ */
35
+ export declare const storyRouter: AppRouterInstance;
36
+ /**
37
+ * The viewport toolbar: a current phone (390 × 844, the width phone layouts are checked at), the 320px floor every page must fit with no horizontal scroll, then Storybook's minimal set. Storybook's own 320px entry is the stack's `smallPhone`, so it is listed once, under a name the stack owns.
38
+ */
39
+ export declare const STORY_VIEWPORTS: {
40
+ readonly mobile2: {
41
+ readonly name: "Large mobile";
42
+ readonly styles: {
43
+ readonly height: "896px";
44
+ readonly width: "414px";
45
+ };
46
+ readonly type: "mobile";
47
+ };
48
+ readonly tablet: {
49
+ readonly name: "Tablet";
50
+ readonly styles: {
51
+ readonly height: "1112px";
52
+ readonly width: "834px";
53
+ };
54
+ readonly type: "tablet";
55
+ };
56
+ readonly desktop: {
57
+ readonly name: "Desktop";
58
+ readonly styles: {
59
+ readonly height: "1024px";
60
+ readonly width: "1280px";
61
+ };
62
+ readonly type: "desktop";
63
+ };
64
+ readonly phone: {
65
+ readonly name: "Phone";
66
+ readonly styles: {
67
+ readonly width: "390px";
68
+ readonly height: "844px";
69
+ };
70
+ readonly type: "mobile";
71
+ };
72
+ readonly smallPhone: {
73
+ readonly name: "Small phone";
74
+ readonly styles: {
75
+ readonly height: "568px";
76
+ readonly width: "320px";
77
+ };
78
+ readonly type: "mobile";
79
+ };
80
+ };
81
+ /** A story's `globals` that open it at a phone's width: `export const Narrow = { globals: PHONE }`. */
82
+ export declare const PHONE: {
83
+ readonly viewport: {
84
+ readonly value: "phone";
85
+ readonly isRotated: false;
86
+ };
87
+ };
88
+ /** A story's `globals` that open it at the 320px floor: `export const Narrowest = { globals: SMALL_PHONE }`. */
89
+ export declare const SMALL_PHONE: {
90
+ readonly viewport: {
91
+ readonly value: "smallPhone";
92
+ readonly isRotated: false;
93
+ };
94
+ };
95
+ /**
96
+ * The stack's part of an app's `.storybook/preview.tsx`: the theme toolbar (light and dark), the viewports, and a decorator that renders every story inside the root layout's set-up. Spread it, then add the app's own parameters or decorators.
97
+ */
98
+ export declare function stackPreview(options: StackPreviewOptions): Preview;
@@ -0,0 +1,72 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { AppRouterContext, } from "next/dist/shared/lib/app-router-context.shared-runtime.js";
3
+ import { useEffect } from "react";
4
+ import { MINIMAL_VIEWPORTS } from "storybook/viewport";
5
+ import { StackRoot } from "../ui/index.js";
6
+ import { htmlClassName } from "../ui/theme.js";
7
+ /** The toolbar's light/dark switch, as a story global. Anything but `"dark"` is light. */
8
+ export function storyTheme(value) {
9
+ return value === "dark" ? "dark" : "light";
10
+ }
11
+ /**
12
+ * Writes what the root layout writes on the server. Storybook has no request, so the theme comes from the toolbar instead of the cookie, and the classes are set on the live document. `<html>` is the stack's alone; `<body>` also carries Storybook's layout classes, so the app's are added beside them.
13
+ */
14
+ export function applyStoryTheme(document, theme, options = {}) {
15
+ document.documentElement.className = htmlClassName(theme, options.fontVariable);
16
+ const body = options.bodyClassName?.split(/\s+/).filter(Boolean) ?? [];
17
+ if (body.length > 0)
18
+ document.body.classList.add(...body);
19
+ }
20
+ /**
21
+ * The router `useRouter()` reads in a story. Storybook's own app-router mode does not render under Next 16.4 (its RedirectBoundary reads a context it never sets), so stories get Next's context directly. A navigation or refresh is logged to the browser console instead of happening.
22
+ */
23
+ export const storyRouter = {
24
+ refresh: () => console.info("[storybook] router.refresh()"),
25
+ push: (href) => console.info("[storybook] router.push", href),
26
+ replace: (href) => console.info("[storybook] router.replace", href),
27
+ back: () => console.info("[storybook] router.back()"),
28
+ forward: () => console.info("[storybook] router.forward()"),
29
+ prefetch: () => { },
30
+ bfcacheId: "story",
31
+ };
32
+ const { mobile1, ...minimalViewports } = MINIMAL_VIEWPORTS;
33
+ /**
34
+ * The viewport toolbar: a current phone (390 × 844, the width phone layouts are checked at), the 320px floor every page must fit with no horizontal scroll, then Storybook's minimal set. Storybook's own 320px entry is the stack's `smallPhone`, so it is listed once, under a name the stack owns.
35
+ */
36
+ export const STORY_VIEWPORTS = {
37
+ phone: { name: "Phone", styles: { width: "390px", height: "844px" }, type: "mobile" },
38
+ smallPhone: { name: "Small phone", styles: mobile1.styles, type: "mobile" },
39
+ ...minimalViewports,
40
+ };
41
+ /** A story's `globals` that open it at a phone's width: `export const Narrow = { globals: PHONE }`. */
42
+ export const PHONE = { viewport: { value: "phone", isRotated: false } };
43
+ /** A story's `globals` that open it at the 320px floor: `export const Narrowest = { globals: SMALL_PHONE }`. */
44
+ export const SMALL_PHONE = { viewport: { value: "smallPhone", isRotated: false } };
45
+ function StoryRoot({ theme, options, children, }) {
46
+ const { fontVariable, bodyClassName } = options;
47
+ useEffect(() => {
48
+ applyStoryTheme(document, theme, { fontVariable, bodyClassName });
49
+ }, [theme, fontVariable, bodyClassName]);
50
+ return (_jsx(AppRouterContext.Provider, { value: storyRouter, children: _jsx(StackRoot, { icons: options.icons, children: children }) }));
51
+ }
52
+ /**
53
+ * The stack's part of an app's `.storybook/preview.tsx`: the theme toolbar (light and dark), the viewports, and a decorator that renders every story inside the root layout's set-up. Spread it, then add the app's own parameters or decorators.
54
+ */
55
+ export function stackPreview(options) {
56
+ return {
57
+ parameters: {
58
+ layout: "padded",
59
+ viewport: { options: STORY_VIEWPORTS },
60
+ },
61
+ globalTypes: {
62
+ theme: {
63
+ description: "Light or dark",
64
+ toolbar: { title: "Theme", icon: "mirror", items: ["light", "dark"], dynamicTitle: true },
65
+ },
66
+ },
67
+ initialGlobals: { theme: "light" },
68
+ decorators: [
69
+ (Story, context) => (_jsx(StoryRoot, { theme: storyTheme(context.globals.theme), options: options, children: _jsx(Story, {}) })),
70
+ ],
71
+ };
72
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwchen/stack",
3
- "version": "0.4.0",
3
+ "version": "0.6.0",
4
4
  "description": "Shared Next.js, Neon, Better Auth, Resend and lew-ds building blocks.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -79,6 +79,10 @@
79
79
  },
80
80
  "./ui/globals.css": "./dist/ui/globals.css",
81
81
  "./ui/app.css": "./dist/ui/app.css",
82
+ "./storybook": {
83
+ "types": "./dist/storybook/index.d.ts",
84
+ "default": "./dist/storybook/index.js"
85
+ },
82
86
  "./configs/tsconfig.next.json": "./configs/tsconfig.next.json",
83
87
  "./configs/biome.json": "./configs/biome.json",
84
88
  "./configs/vitest": {
@@ -108,10 +112,12 @@
108
112
  "@lew-ds/lds": "1.2.0",
109
113
  "@lew-ds/lds-react": "2.0.0",
110
114
  "@lew-ds/open-icons": "1.1.0",
115
+ "@storybook/nextjs-vite": "10.6.2",
111
116
  "drizzle-orm": "0.45.4",
112
117
  "next": "16.4.6",
113
118
  "react": "19.3.1",
114
- "react-dom": "19.3.1"
119
+ "react-dom": "19.3.1",
120
+ "storybook": "10.6.2"
115
121
  },
116
122
  "peerDependenciesMeta": {
117
123
  "@electric-sql/pglite": {
@@ -119,16 +125,24 @@
119
125
  },
120
126
  "@electric-sql/pglite-socket": {
121
127
  "optional": true
128
+ },
129
+ "@storybook/nextjs-vite": {
130
+ "optional": true
131
+ },
132
+ "storybook": {
133
+ "optional": true
122
134
  }
123
135
  },
124
136
  "devDependencies": {
125
137
  "@electric-sql/pglite": "0.5.10",
126
138
  "@electric-sql/pglite-socket": "0.2.13",
139
+ "@storybook/nextjs-vite": "10.6.2",
127
140
  "@types/node": "^24.19.2",
128
141
  "@types/pg": "^8.23.1",
129
142
  "@types/react": "19.3.0",
130
143
  "@types/react-dom": "19.3.0",
131
144
  "drizzle-kit": "0.31.11",
145
+ "storybook": "10.6.2",
132
146
  "tailwindcss": "4.3.3",
133
147
  "typescript": "~6.0.3",
134
148
  "vitest": "5.0.5"