@wwchen/stack 0.0.0-stage → 0.1.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 (91) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +47 -2
  3. package/blocks/AGENTS.md +77 -0
  4. package/blocks/CLAUDE.md +113 -0
  5. package/blocks/env.example +32 -0
  6. package/blocks/gitignore +18 -0
  7. package/configs/biome.json +45 -0
  8. package/configs/tsconfig.next.json +22 -0
  9. package/dist/auth/better-auth/index.d.ts +316 -0
  10. package/dist/auth/better-auth/index.js +237 -0
  11. package/dist/auth/better-auth/tables.d.ts +628 -0
  12. package/dist/auth/better-auth/tables.js +74 -0
  13. package/dist/auth/better-auth/users.d.ts +27 -0
  14. package/dist/auth/better-auth/users.js +128 -0
  15. package/dist/auth/index.d.ts +58 -0
  16. package/dist/auth/index.js +120 -0
  17. package/dist/auth/proxy.d.ts +14 -0
  18. package/dist/auth/proxy.js +50 -0
  19. package/dist/auth/safe-next.d.ts +17 -0
  20. package/dist/auth/safe-next.js +36 -0
  21. package/dist/auth/types.d.ts +47 -0
  22. package/dist/auth/types.js +5 -0
  23. package/dist/cli/context.d.ts +38 -0
  24. package/dist/cli/context.js +43 -0
  25. package/dist/cli/index.d.ts +4 -0
  26. package/dist/cli/index.js +95 -0
  27. package/dist/cli/neon.d.ts +97 -0
  28. package/dist/cli/neon.js +334 -0
  29. package/dist/cli/sync-blocks.d.ts +16 -0
  30. package/dist/cli/sync-blocks.js +97 -0
  31. package/dist/cli/user-create.d.ts +2 -0
  32. package/dist/cli/user-create.js +35 -0
  33. package/dist/cli/vercel-build.d.ts +4 -0
  34. package/dist/cli/vercel-build.js +72 -0
  35. package/dist/configs/vitest.d.ts +4 -0
  36. package/dist/configs/vitest.js +50 -0
  37. package/dist/db/explaining-pool.d.ts +16 -0
  38. package/dist/db/explaining-pool.js +62 -0
  39. package/dist/db/index.d.ts +21 -0
  40. package/dist/db/index.js +36 -0
  41. package/dist/db/migration-status.d.ts +8 -0
  42. package/dist/db/migration-status.js +41 -0
  43. package/dist/db/target.d.ts +26 -0
  44. package/dist/db/target.js +72 -0
  45. package/dist/db/testing/index.d.ts +27 -0
  46. package/dist/db/testing/index.js +71 -0
  47. package/dist/db/testing/isolate.d.ts +1 -0
  48. package/dist/db/testing/isolate.js +4 -0
  49. package/dist/db/testing/pglite.d.ts +21 -0
  50. package/dist/db/testing/pglite.js +71 -0
  51. package/dist/env/define-env.d.ts +37 -0
  52. package/dist/env/define-env.js +134 -0
  53. package/dist/env/index.d.ts +3 -0
  54. package/dist/env/index.js +3 -0
  55. package/dist/env/load-env-file.d.ts +15 -0
  56. package/dist/env/load-env-file.js +52 -0
  57. package/dist/env/stack-env.d.ts +39 -0
  58. package/dist/env/stack-env.js +52 -0
  59. package/dist/env/testing.d.ts +8 -0
  60. package/dist/env/testing.js +16 -0
  61. package/dist/http/client-ip.d.ts +12 -0
  62. package/dist/http/client-ip.js +28 -0
  63. package/dist/http/guards.d.ts +17 -0
  64. package/dist/http/guards.js +57 -0
  65. package/dist/http/rate-limit.d.ts +34 -0
  66. package/dist/http/rate-limit.js +79 -0
  67. package/dist/index.d.ts +1 -0
  68. package/dist/index.js +1 -0
  69. package/dist/mail/index.d.ts +45 -0
  70. package/dist/mail/index.js +97 -0
  71. package/dist/next/api.d.ts +71 -0
  72. package/dist/next/api.js +118 -0
  73. package/dist/next/config.d.ts +8 -0
  74. package/dist/next/config.js +104 -0
  75. package/dist/next/cron.d.ts +11 -0
  76. package/dist/next/cron.js +33 -0
  77. package/dist/next/health.d.ts +19 -0
  78. package/dist/next/health.js +36 -0
  79. package/dist/next/index.d.ts +5 -0
  80. package/dist/next/index.js +4 -0
  81. package/dist/testing/next.d.ts +14 -0
  82. package/dist/testing/next.js +39 -0
  83. package/dist/ui/app.css +56 -0
  84. package/dist/ui/globals.css +152 -0
  85. package/dist/ui/icons.d.ts +17 -0
  86. package/dist/ui/icons.js +104 -0
  87. package/dist/ui/index.d.ts +33 -0
  88. package/dist/ui/index.js +41 -0
  89. package/dist/ui/theme.d.ts +18 -0
  90. package/dist/ui/theme.js +24 -0
  91. package/package.json +126 -4
@@ -0,0 +1,35 @@
1
+ // `stack user:create <email> [--admin]` — adds a real user to sign in as, through the app's own
2
+ // auth (`src/lib/auth.ts`, imported from the working directory with Node's type stripping, so it
3
+ // must use relative `.ts` imports). Sign-in never creates users; this is how the first admin
4
+ // exists. A duplicate email is an error, not a silent no-op.
5
+ //
6
+ // Where: like `stack with-neon`, your Neon dev branch unless DATABASE_URL or ENV_FILE says
7
+ // otherwise. Production is a deliberate `ENV_FILE=<production env file>` (docs/runbook.md).
8
+ import { CliError, importApp, loadAppEnv } from "./context.js";
9
+ import { devBranchEnv } from "./neon.js";
10
+ export async function userCreate(cli, args) {
11
+ const admin = args.includes("--admin");
12
+ const [email] = args.filter((arg) => arg !== "--admin");
13
+ if (!email) {
14
+ cli.error("usage: stack user:create <email> [--admin]");
15
+ return 2;
16
+ }
17
+ // The app's modules read process.env: the dev branch's connection (when nothing else names a
18
+ // database) wins over `.env`, which fills in only what is still unset.
19
+ Object.assign(cli.env, await devBranchEnv(cli));
20
+ loadAppEnv(cli);
21
+ const auth = (await importApp(cli, "src/lib/auth.ts")).auth;
22
+ if (!auth?.users)
23
+ throw new CliError("src/lib/auth.ts must export `auth` (a StackAuth).");
24
+ try {
25
+ const user = await auth.users.add(email, admin ? "admin" : "user");
26
+ cli.log(`created ${user.email}${admin ? " as an admin" : ""}. They sign in with a magic link or Google.`);
27
+ return 0;
28
+ }
29
+ catch (error) {
30
+ if (error instanceof Error && error.name === "DuplicateUserError") {
31
+ throw new CliError(`${error.message}. Nothing changed.`);
32
+ }
33
+ throw error;
34
+ }
35
+ }
@@ -0,0 +1,4 @@
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>;
@@ -0,0 +1,72 @@
1
+ // `stack vercel-build` — Vercel's build command. Neon's documented pattern: the build applies the
2
+ // migrations, so the deployment never goes live on a schema it was not built for.
3
+ //
4
+ // - Preview: migrates the one shared `preview` branch (see `stack neon reset-preview`), which lacks
5
+ // this PR's new migrations. Refuses if any of its database URLs turns out to be production.
6
+ // - Production: migrates production's database, then builds. A failed migration fails the build,
7
+ // so the new code never goes live on a schema it was not built for. The old deployment keeps
8
+ // serving while this runs, which is why every migration must be expand-then-contract.
9
+ // - Anything else (a local run): only builds.
10
+ import { endpointOf } from "../db/index.js";
11
+ import { CliError } from "./context.js";
12
+ import { migrate } from "./neon.js";
13
+ /** Every variable the stack's env reads a database connection from. */
14
+ export const DATABASE_URL_VARIABLES = ["DATABASE_URL", "DATABASE_URL_UNPOOLED"];
15
+ const hostOf = (url) => {
16
+ try {
17
+ return new URL(url).hostname;
18
+ }
19
+ catch {
20
+ return "(unparseable URL)";
21
+ }
22
+ };
23
+ /**
24
+ * A deployment that migrates needs a database URL. drizzle.config.ts migrates through the direct
25
+ * (unpooled) endpoint when it is set, bypassing PgBouncer; without it, through the pooler.
26
+ */
27
+ function requireDatabaseUrl(cli, environment) {
28
+ if (!cli.env.DATABASE_URL_UNPOOLED && !cli.env.DATABASE_URL) {
29
+ // Not the Neon integration: its preview branches are cut from production, with its data.
30
+ const where = environment === "Preview"
31
+ ? "the `preview` branch's URL from `stack neon reset-preview`, scoped to Preview"
32
+ : "production's URL, scoped to Production";
33
+ throw new CliError(`[build] ${environment} deployment with no DATABASE_URL: set it in Vercel (${where}).`);
34
+ }
35
+ if (!cli.env.DATABASE_URL_UNPOOLED) {
36
+ cli.error(`[build] ${environment}: no DATABASE_URL_UNPOOLED; migrating through the pooler.`);
37
+ }
38
+ }
39
+ export async function vercelBuild(cli) {
40
+ const environment = cli.env.VERCEL_ENV;
41
+ if (environment === "preview" || environment === "production") {
42
+ requireDatabaseUrl(cli, environment === "preview" ? "Preview" : "Production");
43
+ if (environment === "preview") {
44
+ // A backstop for a mis-scoped variable: a preview must never migrate or serve production.
45
+ // Every database URL is checked, not just the one migrate uses: the running preview reads
46
+ // DATABASE_URL, and Vercel previews run with NODE_ENV=production, so assertDevDatabase does
47
+ // not catch it at runtime. Pooled and direct hosts of one endpoint compare equal
48
+ // (endpointOf), whichever form each variable holds. Not optional: without production's host
49
+ // there is nothing to check against, and the host is not a secret, so it is set for every
50
+ // environment.
51
+ const productionHost = cli.env.PRODUCTION_DATABASE_HOST ?? "";
52
+ if (productionHost.trim() === "") {
53
+ throw new CliError("[build] PRODUCTION_DATABASE_HOST is not set on Preview, so this build cannot tell the " +
54
+ "preview database from production. Set it in Vercel for all environments " +
55
+ "(production's direct host, not a secret); see the runbook.");
56
+ }
57
+ for (const name of DATABASE_URL_VARIABLES) {
58
+ const value = cli.env[name];
59
+ if (value && endpointOf(value) === endpointOf(productionHost)) {
60
+ throw new CliError(`[build] This preview's ${name} (${hostOf(value)}) is production (${productionHost.trim()}). ` +
61
+ "Refusing to migrate or build; scope it to the `preview` branch (see the runbook).");
62
+ }
63
+ }
64
+ }
65
+ cli.log(`[build] ${environment}: migrating before the build.`);
66
+ // The database is remote by design; the guard's opt-in says this command means it.
67
+ const status = await migrate(cli, { ...cli.env, ALLOW_REMOTE_DATABASE: "1" });
68
+ if (status !== 0)
69
+ return status;
70
+ }
71
+ return (await cli.exec("pnpm", ["exec", "next", "build"], { env: cli.env, inherit: true })).code;
72
+ }
@@ -0,0 +1,4 @@
1
+ import type { ViteUserConfig as UserConfig } from "vitest/config";
2
+ export declare function stackVitestConfig(overrides?: UserConfig, options?: {
3
+ root?: string;
4
+ }): UserConfig;
@@ -0,0 +1,50 @@
1
+ import { resolve as resolvePath } from "node:path";
2
+ const toArray = (value) => value === undefined ? [] : Array.isArray(value) ? value : [value];
3
+ // Vitest settings shared by every app, ported from cc-rewards-tracker's vitest.config.ts.
4
+ // `overrides` is merged, not substituted: an app's `setupFiles`, `include`, `exclude` and `env`
5
+ // are added to the preset's, and any other key the app sets wins.
6
+ export function stackVitestConfig(overrides = {}, options = {}) {
7
+ const { test: appTest = {}, resolve: appResolve, ...appRest } = overrides;
8
+ const { root = process.cwd() } = options;
9
+ const alias = { "@": resolvePath(root, "src") };
10
+ const appAlias = appResolve?.alias;
11
+ const { setupFiles, include, exclude, env, ...appTestRest } = appTest;
12
+ return {
13
+ ...appRest,
14
+ resolve: {
15
+ ...appResolve,
16
+ // The `@/` alias exists for app and test code, matching `paths` in tsconfig.next.json.
17
+ // Worker, lib, db, server and script modules use relative `.ts` specifiers instead.
18
+ // `root` is the consuming project (default: the working directory Vitest runs from).
19
+ alias: Array.isArray(appAlias)
20
+ ? [{ find: "@", replacement: alias["@"] }, ...appAlias]
21
+ : { ...alias, ...appAlias },
22
+ },
23
+ test: {
24
+ environment: "node",
25
+ globals: false,
26
+ pool: "forks",
27
+ // Integration tests boot an in-memory PGlite and run every migration; a cold start can take
28
+ // several seconds on a busy CI runner.
29
+ testTimeout: 60000,
30
+ hookTimeout: 60000,
31
+ ...appTestRest,
32
+ // Runs before anything loads `.env`, so a test can never reach a real database.
33
+ setupFiles: ["@wwchen/stack/db/testing/isolate", ...toArray(setupFiles)],
34
+ include: [
35
+ "tests/unit/**/*.test.{ts,tsx}",
36
+ "tests/integration/**/*.test.{ts,tsx}",
37
+ "src/**/*.test.{ts,tsx}",
38
+ ...toArray(include),
39
+ ],
40
+ exclude: ["node_modules/**", ".next/**", "dist/**", "tests/e2e/**", ...toArray(exclude)],
41
+ env: {
42
+ TZ: "UTC",
43
+ // A fixed, test-only value so the suite is self-sufficient on a clean checkout (CI has no
44
+ // `.env`). It is not a secret and must never be used outside tests.
45
+ BETTER_AUTH_SECRET: "test-only-better-auth-secret-not-a-real-secret",
46
+ ...env,
47
+ },
48
+ },
49
+ };
50
+ }
@@ -0,0 +1,16 @@
1
+ import { Pool, type PoolClient } from "pg";
2
+ /**
3
+ * A `pg` Pool for PGlite (a local PGlite dev database, and the PGlite test database) — never built in production.
4
+ *
5
+ * PGlite over pglite-socket serves exactly one connection: a second client is refused, not queued,
6
+ * and after any SQL error the server drops that connection and briefly resets the next one while it
7
+ * tears the old one down. So a refused or reset checkout is retried for a few seconds — the other
8
+ * holder (a script, the dev server, the socket being torn down) lets go within milliseconds — and
9
+ * then fails with a hint that names the likely cause. `pool.query` checks out through
10
+ * `connect(callback)`, so both call shapes go through one path.
11
+ */
12
+ export declare const PGLITE_HINT: string;
13
+ export declare class ExplainingPool extends Pool {
14
+ connect(): Promise<PoolClient>;
15
+ connect(callback: Parameters<Pool["connect"]>[0] & object): void;
16
+ }
@@ -0,0 +1,62 @@
1
+ import { Pool } from "pg";
2
+ /**
3
+ * A `pg` Pool for PGlite (a local PGlite dev database, and the PGlite test database) — never built in production.
4
+ *
5
+ * PGlite over pglite-socket serves exactly one connection: a second client is refused, not queued,
6
+ * and after any SQL error the server drops that connection and briefly resets the next one while it
7
+ * tears the old one down. So a refused or reset checkout is retried for a few seconds — the other
8
+ * holder (a script, the dev server, the socket being torn down) lets go within milliseconds — and
9
+ * then fails with a hint that names the likely cause. `pool.query` checks out through
10
+ * `connect(callback)`, so both call shapes go through one path.
11
+ */
12
+ export const PGLITE_HINT = "Could not get the PGlite connection (it serves exactly one). Is the local PGlite database running? If it is, " +
13
+ "another process (the dev server, a script) holds the connection — stop it or wait; or a query " +
14
+ "inside a transaction used `db` instead of `tx`.";
15
+ const RETRY_FOR_MS = 5_000;
16
+ const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
17
+ // The connection never became usable: refused, reset, or (on Linux) terminated by the server while
18
+ // it tears down the connection an earlier SQL error dropped. A SQL error is not one of these.
19
+ function refused(error) {
20
+ const code = error?.code;
21
+ if (code === "ECONNREFUSED" || code === "ECONNRESET")
22
+ return true;
23
+ return error instanceof Error && /Connection terminated unexpectedly/.test(error.message);
24
+ }
25
+ // A checked-out client is probed before it is handed out, so a connection lost to that teardown
26
+ // fails here — where it is safe to retry — rather than on the caller's statement.
27
+ async function usable(client) {
28
+ try {
29
+ await client.query("select 1");
30
+ return client;
31
+ }
32
+ catch (error) {
33
+ client.release(error instanceof Error ? error : true);
34
+ throw error;
35
+ }
36
+ }
37
+ export class ExplainingPool extends Pool {
38
+ connect(callback) {
39
+ const connect = super.connect;
40
+ const checkout = async () => {
41
+ const deadline = Date.now() + RETRY_FOR_MS;
42
+ for (;;) {
43
+ try {
44
+ return await usable(await connect.call(this));
45
+ }
46
+ catch (error) {
47
+ const timedOut = error instanceof Error && /timeout exceeded when trying to connect/.test(error.message);
48
+ if (timedOut || (refused(error) && Date.now() >= deadline)) {
49
+ throw new Error(PGLITE_HINT, { cause: error });
50
+ }
51
+ if (!refused(error))
52
+ throw error;
53
+ await sleep(50);
54
+ }
55
+ }
56
+ };
57
+ if (!callback)
58
+ return checkout();
59
+ checkout().then((client) => callback(undefined, client, ((release) => client.release(release))), (error) => callback(error, undefined, (() => { })));
60
+ return undefined;
61
+ }
62
+ }
@@ -0,0 +1,21 @@
1
+ import { type NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ import { Pool } from "pg";
3
+ /**
4
+ * The one place a connection pool is created. Pass Neon's **pooled** URL (`-pooler`, PgBouncer in
5
+ * transaction mode); migrations use the direct endpoint and do not come through here. Reads no
6
+ * environment: the caller passes `url` and decides `pglite` (a loopback server outside production).
7
+ */
8
+ export declare function createDb<S extends Record<string, unknown>>(opts: {
9
+ url: string;
10
+ schema: S;
11
+ /** The URL is a PGlite server: one connection, retried and explained by `ExplainingPool`. */
12
+ pglite?: boolean;
13
+ /** Neon only: connections this instance may hold. Defaults to 5. */
14
+ max?: number;
15
+ }): {
16
+ db: NodePgDatabase<S>;
17
+ pool: Pool;
18
+ };
19
+ export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.ts";
20
+ export { migrationStatus } from "./migration-status.ts";
21
+ export { assertDevDatabase, type DatabaseTargetOptions, endpointOf, isLoopbackUrl, } from "./target.ts";
@@ -0,0 +1,36 @@
1
+ import { attachDatabasePool } from "@vercel/functions";
2
+ import { drizzle } from "drizzle-orm/node-postgres";
3
+ import { Pool } from "pg";
4
+ import { ExplainingPool } from "./explaining-pool.js";
5
+ /**
6
+ * The one place a connection pool is created. Pass Neon's **pooled** URL (`-pooler`, PgBouncer in
7
+ * transaction mode); migrations use the direct endpoint and do not come through here. Reads no
8
+ * environment: the caller passes `url` and decides `pglite` (a loopback server outside production).
9
+ */
10
+ export function createDb(opts) {
11
+ const pglite = opts.pglite === true;
12
+ const pool = new (pglite ? ExplainingPool : Pool)({
13
+ connectionString: opts.url,
14
+ // Neon: a Vercel instance serves a handful of concurrent requests, and many instances share
15
+ // Neon's pooler, so each holds few connections. PGlite allows exactly one.
16
+ max: pglite ? 1 : (opts.max ?? 5),
17
+ connectionTimeoutMillis: 5_000,
18
+ // (PGlite: 100 ms, so its one connection is free for the next process almost at once.)
19
+ // Serverless instances are suspended between requests; a socket idle across a suspension comes
20
+ // back dead, so idle sockets are retired quickly rather than handed to the next query.
21
+ idleTimeoutMillis: pglite ? 100 : 10_000,
22
+ });
23
+ // Vercel Fluid compute: lets the platform close idle clients before it suspends the instance, so
24
+ // connections do not leak against Neon's pooler. A no-op outside Vercel (dev, tests, scripts).
25
+ attachDatabasePool(pool);
26
+ // An unhandled `error` event on a pg Pool takes the whole process down — the web server and,
27
+ // worse, a cron route, which has to survive a database blip. Log it and let the pool retire the
28
+ // socket: the next checkout opens a fresh connection.
29
+ pool.on("error", (error) => {
30
+ console.error("[db] idle client error — the pool will retire this connection", error);
31
+ });
32
+ return { db: drizzle(pool, { schema: opts.schema }), pool };
33
+ }
34
+ export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.js";
35
+ export { migrationStatus } from "./migration-status.js";
36
+ export { assertDevDatabase, endpointOf, isLoopbackUrl, } from "./target.js";
@@ -0,0 +1,8 @@
1
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ /**
3
+ * Whether the database has every migration in `migrationsFolder` (drizzle-kit's output). For a
4
+ * liveness probe: "unknown" is the honest answer whenever it cannot tell — the journal is
5
+ * unreadable (a deploy that did not bundle `drizzle/`), the journal is empty, or the query fails for
6
+ * a reason other than a missing journal table (never migrated: "pending") — rather than a confident "current".
7
+ */
8
+ export declare function migrationStatus(db: NodePgDatabase<any>, migrationsFolder: string): Promise<"current" | "pending" | "unknown">;
@@ -0,0 +1,41 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { sql } from "drizzle-orm";
4
+ /**
5
+ * Whether the database has every migration in `migrationsFolder` (drizzle-kit's output). For a
6
+ * liveness probe: "unknown" is the honest answer whenever it cannot tell — the journal is
7
+ * unreadable (a deploy that did not bundle `drizzle/`), the journal is empty, or the query fails for
8
+ * a reason other than a missing journal table (never migrated: "pending") — rather than a confident "current".
9
+ */
10
+ export async function migrationStatus(
11
+ // biome-ignore lint/suspicious/noExplicitAny: any schema
12
+ db, migrationsFolder) {
13
+ let onDisk;
14
+ try {
15
+ const journal = JSON.parse(await readFile(path.join(migrationsFolder, "meta", "_journal.json"), "utf8"));
16
+ onDisk = journal.entries?.length ?? 0;
17
+ }
18
+ catch {
19
+ return "unknown";
20
+ }
21
+ if (onDisk === 0)
22
+ return "unknown";
23
+ try {
24
+ const result = await db.execute(sql `select count(*)::int as count from drizzle.__drizzle_migrations`);
25
+ const applied = Number(result.rows[0]?.count ?? 0);
26
+ return applied >= onDisk ? "current" : "pending";
27
+ }
28
+ catch (error) {
29
+ // No journal table yet: nothing has ever been migrated. Any other failure is not an answer.
30
+ return undefinedTable(error) ? "pending" : "unknown";
31
+ }
32
+ }
33
+ // Postgres 42P01 (undefined_table); drizzle wraps the driver error as `cause`.
34
+ function undefinedTable(error) {
35
+ for (let e = error; e;) {
36
+ if (e.code === "42P01")
37
+ return true;
38
+ e = e.cause;
39
+ }
40
+ return false;
41
+ }
@@ -0,0 +1,26 @@
1
+ /** True only when `connectionString` parses and its host is this machine. Unparseable is not local. */
2
+ export declare function isLoopbackUrl(connectionString: string | undefined): boolean;
3
+ /**
4
+ * A Neon endpoint's identity, the same for its pooled and direct hosts:
5
+ * `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database.
6
+ * Accepts a bare host or a whole connection string.
7
+ */
8
+ export declare function endpointOf(hostOrUrl: string): string;
9
+ export type DatabaseTargetOptions = {
10
+ nodeEnv: string | undefined;
11
+ /** `ALLOW_REMOTE_DATABASE`; only "1" opens the guard. */
12
+ allowRemote: string | undefined;
13
+ /** `ENV_FILE`: set when the caller named an env file on purpose (e.g. `.env.neon`). */
14
+ envFile: string | undefined;
15
+ /** `PRODUCTION_DATABASE_HOST`: production's Neon host, pooled or direct. */
16
+ productionHost: string | undefined;
17
+ };
18
+ /**
19
+ * Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must
20
+ * not reach production by accident — a dev branch's URL and production's differ only in the
21
+ * endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production
22
+ * and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests'
23
+ * PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1`
24
+ * is deliberate. Throws; the message names the host only, never the credentials.
25
+ */
26
+ export declare function assertDevDatabase(connectionString: string | undefined, { nodeEnv, allowRemote, envFile, productionHost }: DatabaseTargetOptions): void;
@@ -0,0 +1,72 @@
1
+ /** True only when `connectionString` parses and its host is this machine. Unparseable is not local. */
2
+ export function isLoopbackUrl(connectionString) {
3
+ if (!connectionString)
4
+ return false;
5
+ try {
6
+ // Non-special schemes (postgres:) keep the host's case, so lowercase it here.
7
+ const hostname = new URL(connectionString).hostname.toLowerCase();
8
+ return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]";
9
+ }
10
+ catch {
11
+ return false;
12
+ }
13
+ }
14
+ /** The host alone — never the userinfo — so it is safe to put in an error message. */
15
+ function hostOf(connectionString) {
16
+ try {
17
+ return new URL(connectionString).hostname || "(no host)";
18
+ }
19
+ catch {
20
+ return "(unparseable URL)";
21
+ }
22
+ }
23
+ /**
24
+ * A Neon endpoint's identity, the same for its pooled and direct hosts:
25
+ * `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database.
26
+ * Accepts a bare host or a whole connection string.
27
+ */
28
+ export function endpointOf(hostOrUrl) {
29
+ let host = hostOrUrl.trim().toLowerCase();
30
+ if (host.includes("://")) {
31
+ try {
32
+ host = new URL(host).hostname;
33
+ }
34
+ catch {
35
+ return host;
36
+ }
37
+ }
38
+ const [first, ...rest] = host.split(".");
39
+ return [first.replace(/-pooler$/, ""), ...rest].join(".");
40
+ }
41
+ /**
42
+ * Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must
43
+ * not reach production by accident — a dev branch's URL and production's differ only in the
44
+ * endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production
45
+ * and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests'
46
+ * PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1`
47
+ * is deliberate. Throws; the message names the host only, never the credentials.
48
+ */
49
+ export function assertDevDatabase(connectionString, { nodeEnv, allowRemote, envFile, productionHost }) {
50
+ if (nodeEnv === "production")
51
+ return;
52
+ if (isLoopbackUrl(connectionString))
53
+ return;
54
+ if (allowRemote === "1")
55
+ return;
56
+ if ((envFile ?? "").trim() !== "")
57
+ return;
58
+ const host = connectionString ? hostOf(connectionString) : "(not set)";
59
+ const optIn = "Use `ENV_FILE=.env.neon …` for a deliberate production command.";
60
+ if (!connectionString) {
61
+ throw new Error(`Refusing to run with no DATABASE_URL. Point it at your Neon dev branch. ${optIn}`);
62
+ }
63
+ if ((productionHost ?? "").trim() === "") {
64
+ throw new Error(`Refusing to use a remote database (host: ${host}) without PRODUCTION_DATABASE_HOST: set it ` +
65
+ "to production's Neon host so local tooling can tell your dev branch from production. " +
66
+ optIn);
67
+ }
68
+ if (endpointOf(connectionString) === endpointOf(productionHost ?? "")) {
69
+ throw new Error(`Refusing to use the production database (host: ${host}) from local tooling. Point ` +
70
+ `DATABASE_URL at your Neon dev branch. ${optIn}`);
71
+ }
72
+ }
@@ -0,0 +1,27 @@
1
+ import type { NodePgDatabase } from "drizzle-orm/node-postgres";
2
+ /**
3
+ * A throwaway Postgres per test file, migrated from the app's committed migrations with the
4
+ * programmatic migrator.
5
+ *
6
+ * Two engines, one helper:
7
+ * - default: an in-memory PGlite served over the wire protocol (no Docker, no image pull);
8
+ * - `TEST_DATABASE_URL` set (a CI job with real Postgres): a fresh `t_<hex>` database on that
9
+ * server, dropped on `stop()`.
10
+ *
11
+ * **Never the development database.** Either way the test gets its own database, so a run cannot
12
+ * see, change or truncate what `pnpm dev` is pointed at — and `url` is exposed so a test can
13
+ * assert exactly that. PGlite allows one connection: a test must not open a second pool on `url`.
14
+ */
15
+ export type TestDatabase<S extends Record<string, unknown>> = {
16
+ db: NodePgDatabase<S>;
17
+ /** The throwaway database's connection string — assert it is not `process.env.DATABASE_URL`. */
18
+ url: string;
19
+ stop: () => Promise<void>;
20
+ };
21
+ export declare function startTestDatabase<S extends Record<string, unknown>>(opts: {
22
+ schema: S;
23
+ migrationsFolder: string;
24
+ /** A Postgres server to create the database on; defaults to `TEST_DATABASE_URL`, else PGlite. */
25
+ adminUrl?: string;
26
+ }): Promise<TestDatabase<S>>;
27
+ export { PGLITE_MAX_CONNECTIONS, type PgliteServer, startPgliteServer } from "./pglite.ts";
@@ -0,0 +1,71 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import { migrate } from "drizzle-orm/node-postgres/migrator";
3
+ import { Pool } from "pg";
4
+ import { testDatabaseUrl } from "../../env/testing.js";
5
+ import { createDb } from "../index.js";
6
+ import { startPgliteServer } from "./pglite.js";
7
+ async function startRealPostgres(adminUrl) {
8
+ const name = `t_${randomBytes(8).toString("hex")}`;
9
+ const admin = new Pool({ connectionString: adminUrl, max: 1 });
10
+ try {
11
+ await admin.query(`create database ${name}`);
12
+ }
13
+ catch (error) {
14
+ await admin.end().catch(() => { });
15
+ throw error;
16
+ }
17
+ const url = new URL(adminUrl);
18
+ url.pathname = `/${name}`;
19
+ return {
20
+ url: url.toString(),
21
+ pglite: false,
22
+ stop: async () => {
23
+ try {
24
+ // `force` disconnects any straggler so the drop cannot fail on an open session.
25
+ await admin.query(`drop database if exists ${name} with (force)`);
26
+ }
27
+ finally {
28
+ await admin.end();
29
+ }
30
+ },
31
+ };
32
+ }
33
+ async function startPglite() {
34
+ const server = await startPgliteServer({ port: 0 });
35
+ return { url: server.url, pglite: true, stop: () => server.stop() };
36
+ }
37
+ export async function startTestDatabase(opts) {
38
+ const adminUrl = opts.adminUrl ?? testDatabaseUrl();
39
+ const backend = adminUrl ? await startRealPostgres(adminUrl) : await startPglite();
40
+ // The same client path apps use. On real Postgres the pool is Neon-sized (`max` 5); PGlite gets
41
+ // the retrying single-connection pool.
42
+ const { db, pool } = createDb({ url: backend.url, schema: opts.schema, pglite: backend.pglite });
43
+ // An idle client's socket can die between tests — PGlite drops it after a SQL error, and on real
44
+ // Postgres `drop database … with (force)` terminates it (57P01) while `stop()` is ending the pool.
45
+ // The pool retires the client either way; the next query reports anything real.
46
+ pool.on("error", () => { });
47
+ try {
48
+ // The committed SQL migrations are the schema's history; the harness applies the same ones
49
+ // production does rather than a parallel definition that could drift.
50
+ await migrate(db, { migrationsFolder: opts.migrationsFolder });
51
+ }
52
+ catch (error) {
53
+ // Do not leak the database (real Postgres) or the server and its open handles (PGlite).
54
+ await pool.end().catch(() => { });
55
+ await backend.stop().catch(() => { });
56
+ throw error;
57
+ }
58
+ return {
59
+ db,
60
+ url: backend.url,
61
+ stop: async () => {
62
+ try {
63
+ await pool.end();
64
+ }
65
+ finally {
66
+ await backend.stop();
67
+ }
68
+ },
69
+ };
70
+ }
71
+ export { PGLITE_MAX_CONNECTIONS, startPgliteServer } from "./pglite.js";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ // A side-effect module for a Vitest `setupFiles` entry: it must run before anything that loads
2
+ // `.env`, so it imports only the one function it runs. See `isolateTestEnv`.
3
+ import { isolateTestEnv } from "../../env/testing.js";
4
+ isolateTestEnv();
@@ -0,0 +1,21 @@
1
+ /**
2
+ * PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other
3
+ * Postgres. Used by the test helper and a template's dev server.
4
+ *
5
+ * `1` because pglite-socket serialises every connection onto PGlite's single session: with more,
6
+ * one connection's open transaction blocks the others and there is no per-connection isolation.
7
+ * At the limit a second connection is refused outright, so a pool pointed at this server must use
8
+ * `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
9
+ */
10
+ export declare const PGLITE_MAX_CONNECTIONS = 1;
11
+ export type PgliteServer = {
12
+ url: string;
13
+ port: number;
14
+ stop(): Promise<void>;
15
+ };
16
+ /** In-memory when `dataDir` is absent. `port` 0 (or absent) picks a free one. */
17
+ export declare function startPgliteServer(options?: {
18
+ dataDir?: string;
19
+ host?: string;
20
+ port?: number;
21
+ }): Promise<PgliteServer>;