@wwchen/stack 0.0.0-stage → 0.2.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 (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +79 -2
  3. package/blocks/AGENTS.md +77 -0
  4. package/blocks/CLAUDE.md +113 -0
  5. package/blocks/env.example +34 -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/connections/crypto.d.ts +8 -0
  38. package/dist/connections/crypto.js +50 -0
  39. package/dist/connections/index.d.ts +63 -0
  40. package/dist/connections/index.js +212 -0
  41. package/dist/connections/providers.d.ts +30 -0
  42. package/dist/connections/providers.js +47 -0
  43. package/dist/connections/table.d.ts +156 -0
  44. package/dist/connections/table.js +29 -0
  45. package/dist/db/explaining-pool.d.ts +16 -0
  46. package/dist/db/explaining-pool.js +62 -0
  47. package/dist/db/index.d.ts +21 -0
  48. package/dist/db/index.js +36 -0
  49. package/dist/db/migration-status.d.ts +8 -0
  50. package/dist/db/migration-status.js +41 -0
  51. package/dist/db/target.d.ts +26 -0
  52. package/dist/db/target.js +72 -0
  53. package/dist/db/testing/index.d.ts +27 -0
  54. package/dist/db/testing/index.js +71 -0
  55. package/dist/db/testing/isolate.d.ts +1 -0
  56. package/dist/db/testing/isolate.js +4 -0
  57. package/dist/db/testing/pglite.d.ts +21 -0
  58. package/dist/db/testing/pglite.js +71 -0
  59. package/dist/env/define-env.d.ts +37 -0
  60. package/dist/env/define-env.js +134 -0
  61. package/dist/env/index.d.ts +3 -0
  62. package/dist/env/index.js +3 -0
  63. package/dist/env/load-env-file.d.ts +15 -0
  64. package/dist/env/load-env-file.js +52 -0
  65. package/dist/env/stack-env.d.ts +40 -0
  66. package/dist/env/stack-env.js +60 -0
  67. package/dist/env/testing.d.ts +8 -0
  68. package/dist/env/testing.js +16 -0
  69. package/dist/http/client-ip.d.ts +12 -0
  70. package/dist/http/client-ip.js +28 -0
  71. package/dist/http/guards.d.ts +17 -0
  72. package/dist/http/guards.js +57 -0
  73. package/dist/http/rate-limit.d.ts +34 -0
  74. package/dist/http/rate-limit.js +79 -0
  75. package/dist/index.d.ts +1 -0
  76. package/dist/index.js +1 -0
  77. package/dist/jobs/index.d.ts +37 -0
  78. package/dist/jobs/index.js +51 -0
  79. package/dist/mail/index.d.ts +45 -0
  80. package/dist/mail/index.js +97 -0
  81. package/dist/next/api.d.ts +71 -0
  82. package/dist/next/api.js +118 -0
  83. package/dist/next/config.d.ts +8 -0
  84. package/dist/next/config.js +104 -0
  85. package/dist/next/cron.d.ts +14 -0
  86. package/dist/next/cron.js +40 -0
  87. package/dist/next/health.d.ts +19 -0
  88. package/dist/next/health.js +36 -0
  89. package/dist/next/index.d.ts +5 -0
  90. package/dist/next/index.js +4 -0
  91. package/dist/testing/next.d.ts +14 -0
  92. package/dist/testing/next.js +39 -0
  93. package/dist/ui/app.css +56 -0
  94. package/dist/ui/globals.css +152 -0
  95. package/dist/ui/icons.d.ts +17 -0
  96. package/dist/ui/icons.js +104 -0
  97. package/dist/ui/index.d.ts +33 -0
  98. package/dist/ui/index.js +41 -0
  99. package/dist/ui/theme.d.ts +18 -0
  100. package/dist/ui/theme.js +24 -0
  101. package/package.json +134 -4
@@ -0,0 +1,156 @@
1
+ import type { AuthTables } from "../auth/better-auth/tables.ts";
2
+ /**
3
+ * The `connection` table: an account at another service that a signed-in person connected so the
4
+ * app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
5
+ * the auth tables, so drizzle-kit generates it into the app's own migrations.
6
+ *
7
+ * - One connection per person per provider (reconnecting replaces the token).
8
+ * - One person per provider account (`subject`): an account already connected to someone else is
9
+ * refused, so two people can never share one account's data.
10
+ * - Removing the person removes their connections (the foreign key cascades in the same statement).
11
+ * - `token` is only ever ciphertext (`crypto.ts`).
12
+ */
13
+ export declare function connectionTable(appUser: AuthTables["appUser"]): import("drizzle-orm/pg-core").PgTableWithColumns<{
14
+ name: "connection";
15
+ schema: undefined;
16
+ columns: {
17
+ id: import("drizzle-orm/pg-core").PgColumn<{
18
+ name: "id";
19
+ tableName: "connection";
20
+ dataType: "string";
21
+ columnType: "PgUUID";
22
+ data: string;
23
+ driverParam: string;
24
+ notNull: true;
25
+ hasDefault: true;
26
+ isPrimaryKey: true;
27
+ isAutoincrement: false;
28
+ hasRuntimeDefault: false;
29
+ enumValues: undefined;
30
+ baseColumn: never;
31
+ identity: undefined;
32
+ generated: undefined;
33
+ }, {}, {}>;
34
+ userId: import("drizzle-orm/pg-core").PgColumn<{
35
+ name: "user_id";
36
+ tableName: "connection";
37
+ dataType: "string";
38
+ columnType: "PgUUID";
39
+ data: string;
40
+ driverParam: string;
41
+ notNull: true;
42
+ hasDefault: false;
43
+ isPrimaryKey: false;
44
+ isAutoincrement: false;
45
+ hasRuntimeDefault: false;
46
+ enumValues: undefined;
47
+ baseColumn: never;
48
+ identity: undefined;
49
+ generated: undefined;
50
+ }, {}, {}>;
51
+ provider: import("drizzle-orm/pg-core").PgColumn<{
52
+ name: "provider";
53
+ tableName: "connection";
54
+ dataType: "string";
55
+ columnType: "PgText";
56
+ data: string;
57
+ driverParam: string;
58
+ notNull: true;
59
+ hasDefault: false;
60
+ isPrimaryKey: false;
61
+ isAutoincrement: false;
62
+ hasRuntimeDefault: false;
63
+ enumValues: [string, ...string[]];
64
+ baseColumn: never;
65
+ identity: undefined;
66
+ generated: undefined;
67
+ }, {}, {}>;
68
+ subject: import("drizzle-orm/pg-core").PgColumn<{
69
+ name: "subject";
70
+ tableName: "connection";
71
+ dataType: "string";
72
+ columnType: "PgText";
73
+ data: string;
74
+ driverParam: string;
75
+ notNull: true;
76
+ hasDefault: false;
77
+ isPrimaryKey: false;
78
+ isAutoincrement: false;
79
+ hasRuntimeDefault: false;
80
+ enumValues: [string, ...string[]];
81
+ baseColumn: never;
82
+ identity: undefined;
83
+ generated: undefined;
84
+ }, {}, {}>;
85
+ name: import("drizzle-orm/pg-core").PgColumn<{
86
+ name: "name";
87
+ tableName: "connection";
88
+ dataType: "string";
89
+ columnType: "PgText";
90
+ data: string;
91
+ driverParam: string;
92
+ notNull: false;
93
+ hasDefault: false;
94
+ isPrimaryKey: false;
95
+ isAutoincrement: false;
96
+ hasRuntimeDefault: false;
97
+ enumValues: [string, ...string[]];
98
+ baseColumn: never;
99
+ identity: undefined;
100
+ generated: undefined;
101
+ }, {}, {}>;
102
+ token: import("drizzle-orm/pg-core").PgColumn<{
103
+ name: "token";
104
+ tableName: "connection";
105
+ dataType: "string";
106
+ columnType: "PgText";
107
+ data: string;
108
+ driverParam: string;
109
+ notNull: true;
110
+ hasDefault: false;
111
+ isPrimaryKey: false;
112
+ isAutoincrement: false;
113
+ hasRuntimeDefault: false;
114
+ enumValues: [string, ...string[]];
115
+ baseColumn: never;
116
+ identity: undefined;
117
+ generated: undefined;
118
+ }, {}, {}>;
119
+ createdAt: import("drizzle-orm/pg-core").PgColumn<{
120
+ name: "created_at";
121
+ tableName: "connection";
122
+ dataType: "date";
123
+ columnType: "PgTimestamp";
124
+ data: Date;
125
+ driverParam: string;
126
+ notNull: true;
127
+ hasDefault: true;
128
+ isPrimaryKey: false;
129
+ isAutoincrement: false;
130
+ hasRuntimeDefault: false;
131
+ enumValues: undefined;
132
+ baseColumn: never;
133
+ identity: undefined;
134
+ generated: undefined;
135
+ }, {}, {}>;
136
+ updatedAt: import("drizzle-orm/pg-core").PgColumn<{
137
+ name: "updated_at";
138
+ tableName: "connection";
139
+ dataType: "date";
140
+ columnType: "PgTimestamp";
141
+ data: Date;
142
+ driverParam: string;
143
+ notNull: true;
144
+ hasDefault: true;
145
+ isPrimaryKey: false;
146
+ isAutoincrement: false;
147
+ hasRuntimeDefault: false;
148
+ enumValues: undefined;
149
+ baseColumn: never;
150
+ identity: undefined;
151
+ generated: undefined;
152
+ }, {}, {}>;
153
+ };
154
+ dialect: "pg";
155
+ }>;
156
+ export type ConnectionTable = ReturnType<typeof connectionTable>;
@@ -0,0 +1,29 @@
1
+ import { pgTable, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
2
+ /**
3
+ * The `connection` table: an account at another service that a signed-in person connected so the
4
+ * app can work on their behalf (ifttt's Foursquare). The app re-exports it from its schema next to
5
+ * the auth tables, so drizzle-kit generates it into the app's own migrations.
6
+ *
7
+ * - One connection per person per provider (reconnecting replaces the token).
8
+ * - One person per provider account (`subject`): an account already connected to someone else is
9
+ * refused, so two people can never share one account's data.
10
+ * - Removing the person removes their connections (the foreign key cascades in the same statement).
11
+ * - `token` is only ever ciphertext (`crypto.ts`).
12
+ */
13
+ export function connectionTable(appUser) {
14
+ return pgTable("connection", {
15
+ id: uuid("id").primaryKey().defaultRandom(),
16
+ userId: uuid("user_id")
17
+ .notNull()
18
+ .references(() => appUser.id, { onDelete: "cascade" }),
19
+ provider: text("provider").notNull(),
20
+ subject: text("subject").notNull(),
21
+ name: text("name"),
22
+ token: text("token").notNull(),
23
+ createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
24
+ updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
25
+ }, (t) => [
26
+ unique("connection_user_provider").on(t.userId, t.provider),
27
+ unique("connection_provider_subject").on(t.provider, t.subject),
28
+ ]);
29
+ }
@@ -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>;