@wwchen/stack 0.9.0 → 0.10.1

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 (68) hide show
  1. package/README.md +23 -13
  2. package/blocks/AGENTS.md +4 -12
  3. package/blocks/CLAUDE.md +8 -15
  4. package/blocks/env.example +0 -11
  5. package/blocks/gitignore +1 -2
  6. package/dist/cli/builtin.d.ts +6 -0
  7. package/dist/cli/builtin.js +47 -0
  8. package/dist/cli/context.d.ts +6 -20
  9. package/dist/cli/context.js +2 -2
  10. package/dist/cli/host.d.ts +8 -0
  11. package/dist/cli/host.js +128 -0
  12. package/dist/cli/index.js +4 -71
  13. package/dist/cli/neon.d.ts +5 -5
  14. package/dist/cli/neon.js +20 -10
  15. package/dist/cli/run.js +1 -1
  16. package/dist/cli/sync-blocks.d.ts +9 -8
  17. package/dist/cli/sync-blocks.js +157 -47
  18. package/dist/configs/vitest.js +1 -6
  19. package/dist/connections/env.d.ts +8 -0
  20. package/dist/connections/env.js +15 -0
  21. package/dist/connections/index.d.ts +1 -1
  22. package/dist/connections/index.js +1 -1
  23. package/dist/connections/table.d.ts +5 -3
  24. package/dist/connections/table.js +3 -3
  25. package/dist/db/branches.d.ts +11 -0
  26. package/dist/db/branches.js +19 -0
  27. package/dist/db/doctor.d.ts +9 -0
  28. package/dist/db/doctor.js +120 -0
  29. package/dist/db/env.d.ts +14 -0
  30. package/dist/db/env.js +15 -0
  31. package/dist/db/health.d.ts +10 -0
  32. package/dist/db/health.js +26 -0
  33. package/dist/db/index.d.ts +1 -0
  34. package/dist/db/index.js +1 -0
  35. package/dist/db/target.js +2 -1
  36. package/dist/env/core-env.d.ts +23 -0
  37. package/dist/env/core-env.js +24 -0
  38. package/dist/env/define-env.d.ts +22 -10
  39. package/dist/env/define-env.js +72 -17
  40. package/dist/env/index.d.ts +2 -2
  41. package/dist/env/index.js +1 -1
  42. package/dist/http/client-ip.d.ts +6 -0
  43. package/dist/http/client-ip.js +21 -0
  44. package/dist/http/index.d.ts +2 -0
  45. package/dist/http/index.js +2 -0
  46. package/dist/http/safe-next.d.ts +11 -0
  47. package/dist/http/safe-next.js +30 -0
  48. package/dist/index.d.ts +2 -1
  49. package/dist/index.js +1 -1
  50. package/dist/next/api.d.ts +9 -8
  51. package/dist/next/api.js +10 -8
  52. package/dist/next/health.d.ts +5 -7
  53. package/dist/next/health.js +16 -17
  54. package/dist/stack/contracts.d.ts +152 -0
  55. package/dist/stack/contracts.js +42 -0
  56. package/dist/vercel/index.d.ts +28 -0
  57. package/dist/vercel/index.js +90 -0
  58. package/package.json +22 -4
  59. package/dist/cli/doctor.d.ts +0 -40
  60. package/dist/cli/doctor.js +0 -166
  61. package/dist/cli/migrate-suite.d.ts +0 -2
  62. package/dist/cli/migrate-suite.js +0 -491
  63. package/dist/cli/user-create.d.ts +0 -6
  64. package/dist/cli/user-create.js +0 -77
  65. package/dist/cli/vercel-build.d.ts +0 -4
  66. package/dist/cli/vercel-build.js +0 -61
  67. package/dist/env/stack-env.d.ts +0 -37
  68. package/dist/env/stack-env.js +0 -54
@@ -1,77 +0,0 @@
1
- import { CliError, importApp, loadAppEnv } from "./context.js";
2
- import { devBranchEnv, PREVIEW, previewBranchEnv } from "./neon.js";
3
- const PREVIEW_FLAG = "--preview";
4
- /**
5
- * The app's `auth.users`, with the database every command here uses: the dev branch's connection (when nothing else names a database), or the `preview` branch's with `--preview`, wins over `.env`, which fills in only what is still unset. The app's modules read process.env, so this sets it before importing them.
6
- */
7
- async function appUsers(cli, preview) {
8
- Object.assign(cli.env, preview ? await previewBranchEnv(cli) : await devBranchEnv(cli));
9
- loadAppEnv(cli);
10
- const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
11
- if (!auth?.users)
12
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
13
- return auth.users;
14
- }
15
- export async function userCreate(cli, args) {
16
- const admin = args.includes("--admin");
17
- const preview = args.includes(PREVIEW_FLAG);
18
- const [email, ...rest] = args.filter((arg) => arg !== "--admin" && arg !== PREVIEW_FLAG);
19
- if (!email || rest.length > 0) {
20
- cli.error("usage: stack user:create <email> [--admin] [--preview]");
21
- return 2;
22
- }
23
- const users = await appUsers(cli, preview);
24
- if (!users.add)
25
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
26
- try {
27
- const user = await users.add(email, admin ? "admin" : "user");
28
- cli.log(preview
29
- ? `created ${user.email}${admin ? " as an admin" : ""} on ${PREVIEW}: sign in on a preview with a magic link. \`stack neon reset-preview\` drops it.`
30
- : `created ${user.email}${admin ? " as an admin" : ""}. They can sign in now.`);
31
- return 0;
32
- }
33
- catch (error) {
34
- if (error instanceof Error && error.name === "DuplicateUserError") {
35
- throw new CliError(`${error.message}. Nothing changed.`);
36
- }
37
- throw error;
38
- }
39
- }
40
- const ROLES = ["admin", "user"];
41
- const isRole = (value) => ROLES.includes(value);
42
- /**
43
- * `stack user:role <email> <admin|user>`. The email is matched as it is stored (trimmed, lower-cased). The rule that the app always keeps an admin is `setRole`'s, enforced in its own transaction: its refusal is reported as is, and nothing changes.
44
- */
45
- export async function userRole(cli, args) {
46
- const preview = args.includes(PREVIEW_FLAG);
47
- const [email, role, ...rest] = args.filter((arg) => arg !== PREVIEW_FLAG);
48
- if (!email || !isRole(role) || rest.length > 0) {
49
- cli.error("usage: stack user:role <email> <admin|user> [--preview]");
50
- return 2;
51
- }
52
- const users = await appUsers(cli, preview);
53
- if (!users.list || !users.setRole) {
54
- throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
55
- }
56
- const wanted = email.trim().toLowerCase();
57
- const user = (await users.list()).find((u) => u.email === wanted);
58
- if (!user) {
59
- throw new CliError(`no user with the email ${wanted}; add them with \`stack user:create\`. Nothing changed.`);
60
- }
61
- const as = role === "admin" ? "an admin" : "a user";
62
- if (user.role === role) {
63
- cli.log(`${user.email} is already ${as}. Nothing changed.`);
64
- return 0;
65
- }
66
- try {
67
- await users.setRole(user.id, role);
68
- }
69
- catch (error) {
70
- if (error instanceof Error && error.name === "LastAdminError") {
71
- throw new CliError(`${error.message}: ${user.email} is the only admin. Make someone else an admin first. Nothing changed.`);
72
- }
73
- throw error;
74
- }
75
- cli.log(`${user.email} is now ${as}.`);
76
- return 0;
77
- }
@@ -1,4 +0,0 @@
1
- import { type Cli } from "./context.ts";
2
- /** Every variable the stack's env reads a database connection from. */
3
- export declare const DATABASE_URL_VARIABLES: readonly ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
4
- export declare function vercelBuild(cli: Cli): Promise<number>;
@@ -1,61 +0,0 @@
1
- // `stack vercel-build` — Vercel's build command. Neon's documented pattern: the build applies the migrations, so the deployment never goes live on a schema it was not built for.
2
- //
3
- // - Preview: migrates the one shared `preview` branch (see `stack neon reset-preview`), which lacks this PR's new migrations. Refuses if any of its database URLs turns out to be production.
4
- // - Production: migrates production's database, then builds. A failed migration fails the build, so the new code never goes live on a schema it was not built for. The old deployment keeps serving while this runs, which is why every migration must be expand-then-contract.
5
- // - Anything else (a local run): only builds.
6
- import { endpointOf } from "../db/index.js";
7
- import { CliError } from "./context.js";
8
- import { migrate } from "./neon.js";
9
- /** Every variable the stack's env reads a database connection from. */
10
- export const DATABASE_URL_VARIABLES = ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
11
- const hostOf = (url) => {
12
- try {
13
- return new URL(url).hostname;
14
- }
15
- catch {
16
- return "(unparseable URL)";
17
- }
18
- };
19
- /**
20
- * A deployment that migrates needs a database URL. drizzle.config.ts migrates through the direct (unpooled) endpoint when it is set, bypassing PgBouncer; without it, through the pooler.
21
- */
22
- function requireDatabaseUrl(cli, environment) {
23
- if (!cli.env.DATABASE_URL_UNPOOLED && !cli.env.DATABASE_URL) {
24
- // Not the Neon integration: its preview branches are cut from production, with its data.
25
- const where = environment === "Preview"
26
- ? "the `preview` branch's URL from `stack neon reset-preview`, scoped to Preview"
27
- : "production's URL, scoped to Production";
28
- throw new CliError(`[build] ${environment} deployment with no DATABASE_URL: set it in Vercel (${where}).`);
29
- }
30
- if (!cli.env.DATABASE_URL_UNPOOLED) {
31
- cli.error(`[build] ${environment}: no DATABASE_URL_UNPOOLED; migrating through the pooler.`);
32
- }
33
- }
34
- export async function vercelBuild(cli) {
35
- const environment = cli.env.VERCEL_ENV;
36
- if (environment === "preview" || environment === "production") {
37
- requireDatabaseUrl(cli, environment === "preview" ? "Preview" : "Production");
38
- if (environment === "preview") {
39
- // A backstop for a mis-scoped variable: a preview must never migrate or serve production. Every database URL is checked, not just the one migrate uses: the running preview reads DATABASE_URL, and Vercel previews run with NODE_ENV=production, so assertDevDatabase does not catch it at runtime. Pooled and direct hosts of one endpoint compare equal (endpointOf), whichever form each variable holds. Not optional: without production's host there is nothing to check against, and the host is not a secret, so it is set for every environment.
40
- const productionHost = cli.env.PRODUCTION_DATABASE_HOST ?? "";
41
- if (productionHost.trim() === "") {
42
- throw new CliError("[build] PRODUCTION_DATABASE_HOST is not set on Preview, so this build cannot tell the " +
43
- "preview database from production. Set it in Vercel for all environments " +
44
- "(production's direct host, not a secret); see the runbook.");
45
- }
46
- for (const name of DATABASE_URL_VARIABLES) {
47
- const value = cli.env[name];
48
- if (value && endpointOf(value) === endpointOf(productionHost)) {
49
- throw new CliError(`[build] This preview's ${name} (${hostOf(value)}) is production (${productionHost.trim()}). ` +
50
- "Refusing to migrate or build; scope it to the `preview` branch (see the runbook).");
51
- }
52
- }
53
- }
54
- cli.log(`[build] ${environment}: migrating before the build.`);
55
- // The database is remote by design; the guard's opt-in says this command means it.
56
- const status = await migrate(cli, { ...cli.env, ALLOW_REMOTE_DATABASE: "1" });
57
- if (status !== 0)
58
- return status;
59
- }
60
- return (await cli.exec("pnpm", ["exec", "next", "build"], { env: cli.env, inherit: true })).code;
61
- }
@@ -1,37 +0,0 @@
1
- import { z } from "zod";
2
- import { type EnvSource } from "./define-env.ts";
3
- /**
4
- * The variables every stack app shares. Apps extend it: `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
5
- */
6
- export declare const stackEnvSchema: {
7
- NODE_ENV: z.ZodDefault<z.ZodEnum<{
8
- production: "production";
9
- development: "development";
10
- test: "test";
11
- }>>;
12
- APP_URL: z.ZodDefault<z.ZodString>;
13
- DATABASE_URL: z.ZodString;
14
- DATABASE_URL_UNPOOLED: z.ZodOptional<z.ZodString>;
15
- PRODUCTION_DATABASE_HOST: z.ZodOptional<z.ZodString>;
16
- BETTER_AUTH_SECRET: z.ZodDefault<z.ZodString>;
17
- RESEND_API_KEY: z.ZodOptional<z.ZodString>;
18
- EMAIL_FROM: z.ZodDefault<z.ZodString>;
19
- MAGIC_LINK_SINK_PATH: z.ZodDefault<z.ZodString>;
20
- CRON_SECRET: z.ZodOptional<z.ZodString>;
21
- TOKEN_ENCRYPTION_KEY: z.ZodOptional<z.ZodString>;
22
- HEALTH_TOKEN: z.ZodOptional<z.ZodString>;
23
- GOOGLE_CLIENT_ID: z.ZodOptional<z.ZodString>;
24
- GOOGLE_CLIENT_SECRET: z.ZodOptional<z.ZodString>;
25
- TRUSTED_PROXY_HOPS: z.ZodDefault<z.ZodCoercedNumber<unknown>>;
26
- LOG_LEVEL: z.ZodDefault<z.ZodString>;
27
- };
28
- /** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
29
- export declare const stackProductionRequired: readonly ["APP_URL", "DATABASE_URL", "BETTER_AUTH_SECRET", "RESEND_API_KEY", "EMAIL_FROM"];
30
- /** All-or-none groups. Spread it to extend. */
31
- export declare const stackGroups: {
32
- readonly google: readonly ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"];
33
- };
34
- export type StackEnv = z.infer<z.ZodObject<typeof stackEnvSchema>>;
35
- export declare function stackEnv(source?: EnvSource): StackEnv;
36
- /** Whether this is a production run. For the build-time config, which loads before any env schema. */
37
- export declare function isProductionEnv(source?: EnvSource): boolean;
@@ -1,54 +0,0 @@
1
- import { z } from "zod";
2
- import { defineEnv } from "./define-env.js";
3
- /**
4
- * The variables every stack app shares. Apps extend it: `defineEnv({ schema: { ...stackEnvSchema, MY_VAR: z.string() }, ... })`. Blank values are treated as absent by `defineEnv`, so no field needs its own preprocessing.
5
- */
6
- export const stackEnvSchema = {
7
- // Set by tooling, never by `.env`: next dev/build set it, Vitest sets `test`, Vercel's runtime sets `production`.
8
- NODE_ENV: z.enum(["development", "test", "production"]).default("development"),
9
- APP_URL: z.string().default("http://localhost:3000"),
10
- DATABASE_URL: z.string().min(1),
11
- DATABASE_URL_UNPOOLED: z.string().optional(),
12
- // Production's database host, so local tooling can refuse it.
13
- PRODUCTION_DATABASE_HOST: z.string().optional(),
14
- // Signs session cookies and tokens. Better Auth warns on fewer than 32 characters.
15
- BETTER_AUTH_SECRET: z.string().min(32).default("dev-only-better-auth-secret-change-me"),
16
- // Sign-in mail. Production sends through Resend; elsewhere the link goes to the sink file.
17
- RESEND_API_KEY: z.string().optional(),
18
- EMAIL_FROM: z.string().default("App <no-reply@example.invalid>"),
19
- MAGIC_LINK_SINK_PATH: z.string().default(".magic-links.log"),
20
- CRON_SECRET: z.string().optional(),
21
- // Encrypts connected-account tokens (`@wwchen/stack/connections`): 32 bytes, base64 (`openssl rand -base64 32`). Keep it forever: a new key makes every stored token unreadable.
22
- TOKEN_ENCRYPTION_KEY: z
23
- .string()
24
- .refine((v) => Buffer.from(v, "base64").length === 32, {
25
- message: "must be 32 bytes, base64-encoded (openssl rand -base64 32)",
26
- })
27
- .optional(),
28
- HEALTH_TOKEN: z.string().optional(),
29
- // Sign in with Google. Both or neither (group `google`).
30
- GOOGLE_CLIENT_ID: z.string().optional(),
31
- GOOGLE_CLIENT_SECRET: z.string().optional(),
32
- // For `clientIp`: 0 on Vercel, which terminates the proxy chain itself.
33
- TRUSTED_PROXY_HOPS: z.coerce.number().int().nonnegative().default(0),
34
- LOG_LEVEL: z.string().default("info"),
35
- };
36
- /** Required (raw, non-blank) when NODE_ENV is production. Spread it to extend. */
37
- export const stackProductionRequired = [
38
- "APP_URL",
39
- "DATABASE_URL",
40
- "BETTER_AUTH_SECRET",
41
- "RESEND_API_KEY",
42
- "EMAIL_FROM",
43
- ];
44
- /** All-or-none groups. Spread it to extend. */
45
- export const stackGroups = {
46
- google: ["GOOGLE_CLIENT_ID", "GOOGLE_CLIENT_SECRET"],
47
- };
48
- export function stackEnv(source = process.env) {
49
- return defineEnv({ schema: stackEnvSchema, productionRequired: stackProductionRequired, groups: stackGroups }, source);
50
- }
51
- /** Whether this is a production run. For the build-time config, which loads before any env schema. */
52
- export function isProductionEnv(source = process.env) {
53
- return source.NODE_ENV === "production";
54
- }