@wwchen/stack 0.5.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
@@ -8,7 +8,7 @@ Requires Node 24. The peer dependencies are exact pins: `next`, `react`, `react-
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,7 +16,7 @@ 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
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 |
@@ -27,7 +27,7 @@ Sign-in never creates users: every user is added first (`stack user:create`), ha
27
27
 
28
28
  ### Connected accounts
29
29
 
30
- 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):
31
31
 
32
32
  ```ts
33
33
  // src/db/schema.ts
@@ -35,7 +35,7 @@ export const connection = connectionTable(appUser);
35
35
 
36
36
  // src/lib/connections.ts
37
37
  export const connections = createConnections({
38
- db, table: connection, providers: [foursquare({ clientId, clientSecret })],
38
+ db, table: connection, providers: [myService({ clientId, clientSecret })], // the app's own ConnectionProvider
39
39
  secret: env.BETTER_AUTH_SECRET, encryptionKey: env.TOKEN_ENCRYPTION_KEY, baseURL: env.APP_URL,
40
40
  });
41
41
 
package/blocks/CLAUDE.md CHANGED
@@ -64,7 +64,7 @@ The design system is LDS (Lew Design System), product theme: `@lew-ds/lds`, `@le
64
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.
65
65
  - The app uses `pg` on the pooled `DATABASE_URL`; migrations use `DATABASE_URL_UNPOOLED` when set.
66
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.
67
- - Money, if any, is integer cents; reconcile from source rows, never increment.
67
+ - Money, if any, is stored as integer minor units, never floats.
68
68
  - Every user has an email: required, unique, lower-cased and trimmed.
69
69
 
70
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=
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)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wwchen/stack",
3
- "version": "0.5.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": {