@wwchen/stack 0.9.1 → 0.11.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 +50 -23
- package/blocks/AGENTS.md +11 -31
- package/blocks/CLAUDE.md +10 -36
- package/blocks/env.example +1 -18
- package/blocks/gitignore +1 -8
- package/dist/cli/builtin.d.ts +7 -0
- package/dist/cli/builtin.js +42 -0
- package/dist/cli/check.d.ts +5 -0
- package/dist/cli/check.js +39 -0
- package/dist/cli/context.d.ts +4 -35
- package/dist/cli/context.js +1 -23
- package/dist/cli/discover.d.ts +15 -0
- package/dist/cli/discover.js +156 -0
- package/dist/cli/generate.d.ts +6 -0
- package/dist/cli/generate.js +94 -0
- package/dist/cli/host.d.ts +8 -0
- package/dist/cli/host.js +146 -0
- package/dist/cli/index.js +4 -71
- package/dist/cli/owned.d.ts +33 -0
- package/dist/cli/owned.js +151 -0
- package/dist/cli/sync.d.ts +19 -0
- package/dist/cli/sync.js +231 -0
- package/dist/configs/vitest.d.ts +3 -1
- package/dist/configs/vitest.js +8 -11
- package/dist/connections/env.d.ts +8 -0
- package/dist/connections/env.js +15 -0
- package/dist/connections/index.d.ts +1 -1
- package/dist/connections/index.js +1 -1
- package/dist/connections/table.d.ts +5 -3
- package/dist/connections/table.js +3 -3
- package/dist/env/core-env.d.ts +23 -0
- package/dist/env/core-env.js +24 -0
- package/dist/env/define-env.d.ts +22 -10
- package/dist/env/define-env.js +72 -17
- package/dist/env/index.d.ts +2 -2
- package/dist/env/index.js +1 -1
- package/dist/http/client-ip.d.ts +6 -0
- package/dist/http/client-ip.js +21 -0
- package/dist/http/index.d.ts +2 -0
- package/dist/http/index.js +2 -0
- package/dist/http/safe-next.d.ts +11 -0
- package/dist/http/safe-next.js +30 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.js +1 -1
- package/dist/next/api.d.ts +9 -8
- package/dist/next/api.js +10 -8
- package/dist/next/config.d.ts +2 -0
- package/dist/next/config.js +10 -6
- package/dist/next/health.d.ts +5 -7
- package/dist/next/health.js +16 -17
- package/dist/stack/contracts.d.ts +202 -0
- package/dist/stack/contracts.js +66 -0
- package/dist/vercel/index.d.ts +28 -0
- package/dist/vercel/index.js +90 -0
- package/files/.claude/rules/stack-ui.md +24 -0
- package/files/next.config.ts +6 -0
- package/files/src/app/api/health/route.ts +9 -0
- package/package.json +16 -29
- package/dist/cli/db.d.ts +0 -4
- package/dist/cli/db.js +0 -43
- package/dist/cli/dev.d.ts +0 -4
- package/dist/cli/dev.js +0 -70
- package/dist/cli/doctor.d.ts +0 -40
- package/dist/cli/doctor.js +0 -166
- package/dist/cli/migrate-suite.d.ts +0 -2
- package/dist/cli/migrate-suite.js +0 -491
- package/dist/cli/neon.d.ts +0 -79
- package/dist/cli/neon.js +0 -384
- package/dist/cli/run.d.ts +0 -2
- package/dist/cli/run.js +0 -29
- package/dist/cli/sync-blocks.d.ts +0 -14
- package/dist/cli/sync-blocks.js +0 -93
- package/dist/cli/user-create.d.ts +0 -6
- package/dist/cli/user-create.js +0 -77
- package/dist/cli/vercel-build.d.ts +0 -4
- package/dist/cli/vercel-build.js +0 -61
- package/dist/db/explaining-pool.d.ts +0 -11
- package/dist/db/explaining-pool.js +0 -55
- package/dist/db/index.d.ts +0 -20
- package/dist/db/index.js +0 -31
- package/dist/db/migration-status.d.ts +0 -5
- package/dist/db/migration-status.js +0 -38
- package/dist/db/schema-changes.d.ts +0 -13
- package/dist/db/schema-changes.js +0 -99
- package/dist/db/ssl.d.ts +0 -4
- package/dist/db/ssl.js +0 -17
- package/dist/db/target.d.ts +0 -19
- package/dist/db/target.js +0 -65
- package/dist/db/testing/index.d.ts +0 -23
- package/dist/db/testing/index.js +0 -67
- package/dist/db/testing/isolate.d.ts +0 -1
- package/dist/db/testing/isolate.js +0 -3
- package/dist/db/testing/pglite.d.ts +0 -20
- package/dist/db/testing/pglite.js +0 -79
- package/dist/env/stack-env.d.ts +0 -37
- package/dist/env/stack-env.js +0 -54
- package/dist/env/testing.d.ts +0 -6
- package/dist/env/testing.js +0 -13
package/dist/cli/vercel-build.js
DELETED
|
@@ -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,11 +0,0 @@
|
|
|
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, and after any SQL error the server drops that connection and briefly resets the next one while it tears the old one down. So a refused or reset checkout is retried for a few seconds — the other holder (a script, the dev server, the socket being torn down) lets go within milliseconds — and then fails with a hint that names the likely cause. `pool.query` checks out through `connect(callback)`, so both call shapes go through one path.
|
|
6
|
-
*/
|
|
7
|
-
export declare const PGLITE_HINT: string;
|
|
8
|
-
export declare class ExplainingPool extends Pool {
|
|
9
|
-
connect(): Promise<PoolClient>;
|
|
10
|
-
connect(callback: Parameters<Pool["connect"]>[0] & object): void;
|
|
11
|
-
}
|
|
@@ -1,55 +0,0 @@
|
|
|
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, and after any SQL error the server drops that connection and briefly resets the next one while it tears the old one down. So a refused or reset checkout is retried for a few seconds — the other holder (a script, the dev server, the socket being torn down) lets go within milliseconds — and then fails with a hint that names the likely cause. `pool.query` checks out through `connect(callback)`, so both call shapes go through one path.
|
|
6
|
-
*/
|
|
7
|
-
export const PGLITE_HINT = "Could not get the PGlite connection (it serves exactly one). Is the local PGlite database running? If it is, " +
|
|
8
|
-
"another process (the dev server, a script) holds the connection — stop it or wait; or a query " +
|
|
9
|
-
"inside a transaction used `db` instead of `tx`.";
|
|
10
|
-
const RETRY_FOR_MS = 5_000;
|
|
11
|
-
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
12
|
-
// The connection never became usable: refused, reset, or (on Linux) terminated by the server while it tears down the connection an earlier SQL error dropped. A SQL error is not one of these.
|
|
13
|
-
function refused(error) {
|
|
14
|
-
const code = error?.code;
|
|
15
|
-
if (code === "ECONNREFUSED" || code === "ECONNRESET")
|
|
16
|
-
return true;
|
|
17
|
-
return error instanceof Error && /Connection terminated unexpectedly/.test(error.message);
|
|
18
|
-
}
|
|
19
|
-
// A checked-out client is probed before it is handed out, so a connection lost to that teardown fails here — where it is safe to retry — rather than on the caller's statement.
|
|
20
|
-
async function usable(client) {
|
|
21
|
-
try {
|
|
22
|
-
await client.query("select 1");
|
|
23
|
-
return client;
|
|
24
|
-
}
|
|
25
|
-
catch (error) {
|
|
26
|
-
client.release(error instanceof Error ? error : true);
|
|
27
|
-
throw error;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
export class ExplainingPool extends Pool {
|
|
31
|
-
connect(callback) {
|
|
32
|
-
const connect = super.connect;
|
|
33
|
-
const checkout = async () => {
|
|
34
|
-
const deadline = Date.now() + RETRY_FOR_MS;
|
|
35
|
-
for (;;) {
|
|
36
|
-
try {
|
|
37
|
-
return await usable(await connect.call(this));
|
|
38
|
-
}
|
|
39
|
-
catch (error) {
|
|
40
|
-
const timedOut = error instanceof Error && /timeout exceeded when trying to connect/.test(error.message);
|
|
41
|
-
if (timedOut || (refused(error) && Date.now() >= deadline)) {
|
|
42
|
-
throw new Error(PGLITE_HINT, { cause: error });
|
|
43
|
-
}
|
|
44
|
-
if (!refused(error))
|
|
45
|
-
throw error;
|
|
46
|
-
await sleep(50);
|
|
47
|
-
}
|
|
48
|
-
}
|
|
49
|
-
};
|
|
50
|
-
if (!callback)
|
|
51
|
-
return checkout();
|
|
52
|
-
checkout().then((client) => callback(undefined, client, ((release) => client.release(release))), (error) => callback(error, undefined, (() => { })));
|
|
53
|
-
return undefined;
|
|
54
|
-
}
|
|
55
|
-
}
|
package/dist/db/index.d.ts
DELETED
|
@@ -1,20 +0,0 @@
|
|
|
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 transaction mode); migrations use the direct endpoint and do not come through here. Reads no environment: the caller passes `url` and decides `pglite` (a loopback server outside production).
|
|
5
|
-
*/
|
|
6
|
-
export declare function createDb<S extends Record<string, unknown>>(opts: {
|
|
7
|
-
url: string;
|
|
8
|
-
schema: S;
|
|
9
|
-
/** The URL is a PGlite server: one connection, retried and explained by `ExplainingPool`. */
|
|
10
|
-
pglite?: boolean;
|
|
11
|
-
/** Neon only: connections this instance may hold. Defaults to 5. */
|
|
12
|
-
max?: number;
|
|
13
|
-
}): {
|
|
14
|
-
db: NodePgDatabase<S>;
|
|
15
|
-
pool: Pool;
|
|
16
|
-
};
|
|
17
|
-
export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.ts";
|
|
18
|
-
export { migrationStatus } from "./migration-status.ts";
|
|
19
|
-
export { explicitSslMode } from "./ssl.ts";
|
|
20
|
-
export { assertDevDatabase, type DatabaseTargetOptions, endpointOf, isLoopbackUrl, } from "./target.ts";
|
package/dist/db/index.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
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
|
-
import { explicitSslMode } from "./ssl.js";
|
|
6
|
-
/**
|
|
7
|
-
* The one place a connection pool is created. Pass Neon's **pooled** URL (`-pooler`, PgBouncer in transaction mode); migrations use the direct endpoint and do not come through here. Reads no environment: the caller passes `url` and decides `pglite` (a loopback server outside production).
|
|
8
|
-
*/
|
|
9
|
-
export function createDb(opts) {
|
|
10
|
-
const pglite = opts.pglite === true;
|
|
11
|
-
const pool = new (pglite ? ExplainingPool : Pool)({
|
|
12
|
-
// Neon: `sslmode=require` spelled out as the `verify-full` pg already applies (`ssl.ts`).
|
|
13
|
-
connectionString: pglite ? opts.url : explicitSslMode(opts.url),
|
|
14
|
-
// Neon: a Vercel instance serves a handful of concurrent requests, and many instances share Neon's pooler, so each holds few connections. PGlite allows exactly one.
|
|
15
|
-
max: pglite ? 1 : (opts.max ?? 5),
|
|
16
|
-
connectionTimeoutMillis: 5_000,
|
|
17
|
-
// (PGlite: 100 ms, so its one connection is free for the next process almost at once.) Serverless instances are suspended between requests; a socket idle across a suspension comes back dead, so idle sockets are retired quickly rather than handed to the next query.
|
|
18
|
-
idleTimeoutMillis: pglite ? 100 : 10_000,
|
|
19
|
-
});
|
|
20
|
-
// Vercel Fluid compute: lets the platform close idle clients before it suspends the instance, so connections do not leak against Neon's pooler. A no-op outside Vercel (dev, tests, scripts).
|
|
21
|
-
attachDatabasePool(pool);
|
|
22
|
-
// An unhandled `error` event on a pg Pool takes the whole process down — the web server and, worse, a cron route, which has to survive a database blip. Log it and let the pool retire the socket: the next checkout opens a fresh connection.
|
|
23
|
-
pool.on("error", (error) => {
|
|
24
|
-
console.error("[db] idle client error — the pool will retire this connection", error);
|
|
25
|
-
});
|
|
26
|
-
return { db: drizzle(pool, { schema: opts.schema }), pool };
|
|
27
|
-
}
|
|
28
|
-
export { ExplainingPool, PGLITE_HINT } from "./explaining-pool.js";
|
|
29
|
-
export { migrationStatus } from "./migration-status.js";
|
|
30
|
-
export { explicitSslMode } from "./ssl.js";
|
|
31
|
-
export { assertDevDatabase, endpointOf, isLoopbackUrl, } from "./target.js";
|
|
@@ -1,5 +0,0 @@
|
|
|
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 liveness probe: "unknown" is the honest answer whenever it cannot tell — the journal is unreadable (a deploy that did not bundle `drizzle/`), the journal is empty, or the query fails for a reason other than a missing journal table (never migrated: "pending") — rather than a confident "current".
|
|
4
|
-
*/
|
|
5
|
-
export declare function migrationStatus(db: NodePgDatabase<any>, migrationsFolder: string): Promise<"current" | "pending" | "unknown">;
|
|
@@ -1,38 +0,0 @@
|
|
|
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 liveness probe: "unknown" is the honest answer whenever it cannot tell — the journal is unreadable (a deploy that did not bundle `drizzle/`), the journal is empty, or the query fails for a reason other than a missing journal table (never migrated: "pending") — rather than a confident "current".
|
|
6
|
-
*/
|
|
7
|
-
export async function migrationStatus(
|
|
8
|
-
// biome-ignore lint/suspicious/noExplicitAny: any schema
|
|
9
|
-
db, migrationsFolder) {
|
|
10
|
-
let onDisk;
|
|
11
|
-
try {
|
|
12
|
-
const journal = JSON.parse(await readFile(path.join(migrationsFolder, "meta", "_journal.json"), "utf8"));
|
|
13
|
-
onDisk = journal.entries?.length ?? 0;
|
|
14
|
-
}
|
|
15
|
-
catch {
|
|
16
|
-
return "unknown";
|
|
17
|
-
}
|
|
18
|
-
if (onDisk === 0)
|
|
19
|
-
return "unknown";
|
|
20
|
-
try {
|
|
21
|
-
const result = await db.execute(sql `select count(*)::int as count from drizzle.__drizzle_migrations`);
|
|
22
|
-
const applied = Number(result.rows[0]?.count ?? 0);
|
|
23
|
-
return applied >= onDisk ? "current" : "pending";
|
|
24
|
-
}
|
|
25
|
-
catch (error) {
|
|
26
|
-
// No journal table yet: nothing has ever been migrated. Any other failure is not an answer.
|
|
27
|
-
return undefinedTable(error) ? "pending" : "unknown";
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
// Postgres 42P01 (undefined_table); drizzle wraps the driver error as `cause`.
|
|
31
|
-
function undefinedTable(error) {
|
|
32
|
-
for (let e = error; e;) {
|
|
33
|
-
if (e.code === "42P01")
|
|
34
|
-
return true;
|
|
35
|
-
e = e.cause;
|
|
36
|
-
}
|
|
37
|
-
return false;
|
|
38
|
-
}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The SQL `drizzle-kit generate` would write for `schema` (the app's `src/db/schema.ts` exports) against the latest migration in `migrationsFolder`: empty when the migrations are current. Only tables in `public` count, as in the template's drizzle config. Assumes that config sets no `casing` (the template's does not): with one, the names here would differ from what `generate` writes.
|
|
3
|
-
*/
|
|
4
|
-
export declare function pendingStatements(schema: Record<string, unknown>, migrationsFolder: string): Promise<string[]>;
|
|
5
|
-
/**
|
|
6
|
-
* The statements in a drizzle-kit migration that an old deployment cannot survive. The old deployment keeps serving while the build migrates, so a migration may only add what the old code ignores. Flagged:
|
|
7
|
-
* - each `DROP` (a table, column, index, constraint, default…), except `DROP NOT NULL`, which only loosens a column;
|
|
8
|
-
* - each `RENAME`;
|
|
9
|
-
* - `ADD COLUMN … NOT NULL` without a default: the old code's inserts leave it empty;
|
|
10
|
-
* - `SET NOT NULL` and `SET DATA TYPE` on an existing column: the old code's writes may no longer fit;
|
|
11
|
-
* - `ADD CONSTRAINT` (any kind) and `CREATE UNIQUE INDEX` on a table the same migration did not create: they can reject the old code's inserts. drizzle-kit writes a new table's foreign keys as separate `ADD CONSTRAINT` statements, and those pass.
|
|
12
|
-
*/
|
|
13
|
-
export declare function contractStatements(sql: string): string[];
|
|
@@ -1,99 +0,0 @@
|
|
|
1
|
-
import { readFile } from "node:fs/promises";
|
|
2
|
-
import { join } from "node:path";
|
|
3
|
-
/** The schemas an app's migrations cover: the template's `schemaFilter`. */
|
|
4
|
-
const SCHEMA_FILTER = ["public"];
|
|
5
|
-
/** drizzle-kit is an optional peer: only drift detection loads it, so an app without it can still use the rest of the stack. */
|
|
6
|
-
async function loadDrizzleKit() {
|
|
7
|
-
try {
|
|
8
|
-
return await import("drizzle-kit/api");
|
|
9
|
-
}
|
|
10
|
-
catch (error) {
|
|
11
|
-
throw new Error("drizzle-kit could not be loaded: install drizzle-kit 0.31.11 as a devDependency of the app and run `pnpm install`.", { cause: error });
|
|
12
|
-
}
|
|
13
|
-
}
|
|
14
|
-
/** The snapshot of the migration the journal lists last (drizzle-kit names it by the tag's prefix), or undefined when nothing has been generated. */
|
|
15
|
-
async function latestSnapshot(migrationsFolder) {
|
|
16
|
-
let journal;
|
|
17
|
-
try {
|
|
18
|
-
journal = JSON.parse(await readFile(join(migrationsFolder, "meta", "_journal.json"), "utf8"));
|
|
19
|
-
}
|
|
20
|
-
catch (error) {
|
|
21
|
-
if (error.code === "ENOENT")
|
|
22
|
-
return undefined;
|
|
23
|
-
throw error;
|
|
24
|
-
}
|
|
25
|
-
const last = journal.entries?.at(-1);
|
|
26
|
-
if (!last)
|
|
27
|
-
return undefined;
|
|
28
|
-
const file = join(migrationsFolder, "meta", `${last.tag.split("_")[0]}_snapshot.json`);
|
|
29
|
-
return JSON.parse(await readFile(file, "utf8"));
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* The SQL `drizzle-kit generate` would write for `schema` (the app's `src/db/schema.ts` exports) against the latest migration in `migrationsFolder`: empty when the migrations are current. Only tables in `public` count, as in the template's drizzle config. Assumes that config sets no `casing` (the template's does not): with one, the names here would differ from what `generate` writes.
|
|
33
|
-
*/
|
|
34
|
-
export async function pendingStatements(schema, migrationsFolder) {
|
|
35
|
-
const kit = await loadDrizzleKit();
|
|
36
|
-
const current = kit.generateDrizzleJson(schema, undefined, SCHEMA_FILTER);
|
|
37
|
-
const previous = (await latestSnapshot(migrationsFolder)) ??
|
|
38
|
-
kit.generateDrizzleJson({}, undefined, SCHEMA_FILTER);
|
|
39
|
-
try {
|
|
40
|
-
return await kit.generateMigration(previous, current);
|
|
41
|
-
}
|
|
42
|
-
catch (error) {
|
|
43
|
-
// drizzle-kit asks whether a dropped and an added table or column are a rename, and cannot ask without a terminal.
|
|
44
|
-
if (error instanceof Error && /Interactive prompts require a TTY/.test(error.message)) {
|
|
45
|
-
throw new Error("the schema both drops and adds a table or column, and only a person can say whether it is a rename: run `pnpm db:generate <name>` in a terminal.", { cause: error });
|
|
46
|
-
}
|
|
47
|
-
throw error;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
/** Quoted identifiers and string literals, blanked so a name or value never reads as a keyword. */
|
|
51
|
-
const QUOTED = /"(?:[^"]|"")*"|'(?:[^']|'')*'/g;
|
|
52
|
-
/** A table name as drizzle-kit writes it: `"t"` or `"schema"."t"`, quoted or bare. */
|
|
53
|
-
const NAME = String.raw `(?:"(?:[^"]|"")*"|\w+)`;
|
|
54
|
-
const TABLE = String.raw `(${NAME}(?:\s*\.\s*${NAME})?)`;
|
|
55
|
-
const CREATE_TABLE = new RegExp(String.raw `^CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?${TABLE}`, "i");
|
|
56
|
-
const ADD_CONSTRAINT = new RegExp(String.raw `^ALTER\s+TABLE\s+(?:ONLY\s+)?${TABLE}\s+ADD\s+CONSTRAINT\b`, "i");
|
|
57
|
-
const UNIQUE_INDEX = new RegExp(String.raw `^CREATE\s+UNIQUE\s+INDEX\b[\s\S]*?\bON\s+(?:ONLY\s+)?${TABLE}`, "i");
|
|
58
|
-
/** One spelling per table: unquoted, and without the default `public.` schema. */
|
|
59
|
-
function tableKey(name) {
|
|
60
|
-
const parts = name
|
|
61
|
-
.split(/\s*\.\s*/)
|
|
62
|
-
.map((part) => part.replace(/^"|"$/g, "").replaceAll('""', '"'));
|
|
63
|
-
if (parts.length === 2 && parts[0] === "public")
|
|
64
|
-
parts.shift();
|
|
65
|
-
return parts.join(".");
|
|
66
|
-
}
|
|
67
|
-
/**
|
|
68
|
-
* The statements in a drizzle-kit migration that an old deployment cannot survive. The old deployment keeps serving while the build migrates, so a migration may only add what the old code ignores. Flagged:
|
|
69
|
-
* - each `DROP` (a table, column, index, constraint, default…), except `DROP NOT NULL`, which only loosens a column;
|
|
70
|
-
* - each `RENAME`;
|
|
71
|
-
* - `ADD COLUMN … NOT NULL` without a default: the old code's inserts leave it empty;
|
|
72
|
-
* - `SET NOT NULL` and `SET DATA TYPE` on an existing column: the old code's writes may no longer fit;
|
|
73
|
-
* - `ADD CONSTRAINT` (any kind) and `CREATE UNIQUE INDEX` on a table the same migration did not create: they can reject the old code's inserts. drizzle-kit writes a new table's foreign keys as separate `ADD CONSTRAINT` statements, and those pass.
|
|
74
|
-
*/
|
|
75
|
-
export function contractStatements(sql) {
|
|
76
|
-
const statements = sql
|
|
77
|
-
.split("--> statement-breakpoint")
|
|
78
|
-
.map((statement) => statement.trim())
|
|
79
|
-
.filter(Boolean);
|
|
80
|
-
const created = new Set(statements.flatMap((statement) => {
|
|
81
|
-
const name = CREATE_TABLE.exec(statement)?.[1];
|
|
82
|
-
return name ? [tableKey(name)] : [];
|
|
83
|
-
}));
|
|
84
|
-
return statements.filter((statement) => {
|
|
85
|
-
const code = statement.replace(QUOTED, '""');
|
|
86
|
-
if (/\bDROP\b(?!\s+NOT\s+NULL\b)/i.test(code))
|
|
87
|
-
return true;
|
|
88
|
-
if (/\bRENAME\b/i.test(code))
|
|
89
|
-
return true;
|
|
90
|
-
if (/\bSET\s+(NOT\s+NULL|DATA\s+TYPE)\b/i.test(code))
|
|
91
|
-
return true;
|
|
92
|
-
const constrained = (ADD_CONSTRAINT.exec(statement) ?? UNIQUE_INDEX.exec(statement))?.[1];
|
|
93
|
-
if (constrained !== undefined && !created.has(tableKey(constrained)))
|
|
94
|
-
return true;
|
|
95
|
-
return (/\bADD\s+COLUMN\b/i.test(code) &&
|
|
96
|
-
/\bNOT\s+NULL\b/i.test(code) &&
|
|
97
|
-
!/\b(DEFAULT|GENERATED|SERIAL|SMALLSERIAL|BIGSERIAL)\b/i.test(code));
|
|
98
|
-
});
|
|
99
|
-
}
|
package/dist/db/ssl.d.ts
DELETED
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start. Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
3
|
-
*/
|
|
4
|
-
export declare function explicitSslMode(connectionString: string): string;
|
package/dist/db/ssl.js
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Neon's connection strings say `sslmode=require`. pg 8 already treats `prefer`, `require` and `verify-ca` as `verify-full`, and says so on every new connection with a "SECURITY WARNING" that v9 will weaken them; on Vercel that lands in the runtime logs at error level on every cold start. Spelling out `verify-full` keeps exactly today's checking and silences the warning. Any other mode, or no mode, is left as it is; so is a string that is not a URL.
|
|
3
|
-
*/
|
|
4
|
-
export function explicitSslMode(connectionString) {
|
|
5
|
-
let url;
|
|
6
|
-
try {
|
|
7
|
-
url = new URL(connectionString);
|
|
8
|
-
}
|
|
9
|
-
catch {
|
|
10
|
-
return connectionString;
|
|
11
|
-
}
|
|
12
|
-
const mode = url.searchParams.get("sslmode");
|
|
13
|
-
if (mode !== "prefer" && mode !== "require" && mode !== "verify-ca")
|
|
14
|
-
return connectionString;
|
|
15
|
-
url.searchParams.set("sslmode", "verify-full");
|
|
16
|
-
return url.toString();
|
|
17
|
-
}
|
package/dist/db/target.d.ts
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
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: `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database. Accepts a bare host or a whole connection string.
|
|
5
|
-
*/
|
|
6
|
-
export declare function endpointOf(hostOrUrl: string): string;
|
|
7
|
-
export type DatabaseTargetOptions = {
|
|
8
|
-
nodeEnv: string | undefined;
|
|
9
|
-
/** `ALLOW_REMOTE_DATABASE`; only "1" opens the guard. */
|
|
10
|
-
allowRemote: string | undefined;
|
|
11
|
-
/** `ENV_FILE`: set when the caller named an env file on purpose (e.g. `.env.production-admin`). */
|
|
12
|
-
envFile: string | undefined;
|
|
13
|
-
/** `PRODUCTION_DATABASE_HOST`: production's Neon host, pooled or direct. */
|
|
14
|
-
productionHost: string | undefined;
|
|
15
|
-
};
|
|
16
|
-
/**
|
|
17
|
-
* Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must not reach production by accident — a dev branch's URL and production's differ only in the endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests' PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1` is deliberate. Throws; the message names the host only, never the credentials.
|
|
18
|
-
*/
|
|
19
|
-
export declare function assertDevDatabase(connectionString: string | undefined, { nodeEnv, allowRemote, envFile, productionHost }: DatabaseTargetOptions): void;
|
package/dist/db/target.js
DELETED
|
@@ -1,65 +0,0 @@
|
|
|
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: `ep-x-123-pooler.us-east-2.aws.neon.tech` and `ep-x-123.us-east-2.aws.neon.tech` are one database. Accepts a bare host or a whole connection string.
|
|
25
|
-
*/
|
|
26
|
-
export function endpointOf(hostOrUrl) {
|
|
27
|
-
let host = hostOrUrl.trim().toLowerCase();
|
|
28
|
-
if (host.includes("://")) {
|
|
29
|
-
try {
|
|
30
|
-
host = new URL(host).hostname;
|
|
31
|
-
}
|
|
32
|
-
catch {
|
|
33
|
-
return host;
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
const [first, ...rest] = host.split(".");
|
|
37
|
-
return [first.replace(/-pooler$/, ""), ...rest].join(".");
|
|
38
|
-
}
|
|
39
|
-
/**
|
|
40
|
-
* Local tooling (dev server, scripts, drizzle-kit, psql) works against a Neon dev branch, and must not reach production by accident — a dev branch's URL and production's differ only in the endpoint. So a remote database is allowed only when `PRODUCTION_DATABASE_HOST` names production and this URL is a different endpoint. Production itself is exempt, a loopback database (the tests' PGlite) always passes, and a command that opted in with `ENV_FILE=…` or `ALLOW_REMOTE_DATABASE=1` is deliberate. Throws; the message names the host only, never the credentials.
|
|
41
|
-
*/
|
|
42
|
-
export function assertDevDatabase(connectionString, { nodeEnv, allowRemote, envFile, productionHost }) {
|
|
43
|
-
if (nodeEnv === "production")
|
|
44
|
-
return;
|
|
45
|
-
if (isLoopbackUrl(connectionString))
|
|
46
|
-
return;
|
|
47
|
-
if (allowRemote === "1")
|
|
48
|
-
return;
|
|
49
|
-
if ((envFile ?? "").trim() !== "")
|
|
50
|
-
return;
|
|
51
|
-
const host = connectionString ? hostOf(connectionString) : "(not set)";
|
|
52
|
-
const optIn = "Use `ENV_FILE=<production env file> …` for a deliberate production command.";
|
|
53
|
-
if (!connectionString) {
|
|
54
|
-
throw new Error(`Refusing to run with no DATABASE_URL. Point it at your Neon dev branch. ${optIn}`);
|
|
55
|
-
}
|
|
56
|
-
if ((productionHost ?? "").trim() === "") {
|
|
57
|
-
throw new Error(`Refusing to use a remote database (host: ${host}) without PRODUCTION_DATABASE_HOST: set it ` +
|
|
58
|
-
"to production's Neon host so local tooling can tell your dev branch from production. " +
|
|
59
|
-
optIn);
|
|
60
|
-
}
|
|
61
|
-
if (endpointOf(connectionString) === endpointOf(productionHost ?? "")) {
|
|
62
|
-
throw new Error(`Refusing to use the production database (host: ${host}) from local tooling. Point ` +
|
|
63
|
-
`DATABASE_URL at your Neon dev branch. ${optIn}`);
|
|
64
|
-
}
|
|
65
|
-
}
|
|
@@ -1,23 +0,0 @@
|
|
|
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 programmatic migrator.
|
|
4
|
-
*
|
|
5
|
-
* Two engines, one helper:
|
|
6
|
-
* - default: an in-memory PGlite served over the wire protocol (no Docker, no image pull);
|
|
7
|
-
* - `TEST_DATABASE_URL` set (a CI job with real Postgres): a fresh `t_<hex>` database on that server, dropped on `stop()`.
|
|
8
|
-
*
|
|
9
|
-
* **Never the development database.** Either way the test gets its own database, so a run cannot see, change or truncate what `pnpm dev` is pointed at — and `url` is exposed so a test can assert exactly that. PGlite allows one connection: a test must not open a second pool on `url`.
|
|
10
|
-
*/
|
|
11
|
-
export type TestDatabase<S extends Record<string, unknown>> = {
|
|
12
|
-
db: NodePgDatabase<S>;
|
|
13
|
-
/** The throwaway database's connection string — assert it is not `process.env.DATABASE_URL`. */
|
|
14
|
-
url: string;
|
|
15
|
-
stop: () => Promise<void>;
|
|
16
|
-
};
|
|
17
|
-
export declare function startTestDatabase<S extends Record<string, unknown>>(opts: {
|
|
18
|
-
schema: S;
|
|
19
|
-
migrationsFolder: string;
|
|
20
|
-
/** A Postgres server to create the database on; defaults to `TEST_DATABASE_URL`, else PGlite. */
|
|
21
|
-
adminUrl?: string;
|
|
22
|
-
}): Promise<TestDatabase<S>>;
|
|
23
|
-
export { PGLITE_MAX_CONNECTIONS, type PgliteServer, startPgliteServer } from "./pglite.ts";
|
package/dist/db/testing/index.js
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
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 the retrying single-connection pool.
|
|
41
|
-
const { db, pool } = createDb({ url: backend.url, schema: opts.schema, pglite: backend.pglite });
|
|
42
|
-
// An idle client's socket can die between tests — PGlite drops it after a SQL error, and on real Postgres `drop database … with (force)` terminates it (57P01) while `stop()` is ending the pool. The pool retires the client either way; the next query reports anything real.
|
|
43
|
-
pool.on("error", () => { });
|
|
44
|
-
try {
|
|
45
|
-
// The committed SQL migrations are the schema's history; the harness applies the same ones production does rather than a parallel definition that could drift.
|
|
46
|
-
await migrate(db, { migrationsFolder: opts.migrationsFolder });
|
|
47
|
-
}
|
|
48
|
-
catch (error) {
|
|
49
|
-
// Do not leak the database (real Postgres) or the server and its open handles (PGlite).
|
|
50
|
-
await pool.end().catch(() => { });
|
|
51
|
-
await backend.stop().catch(() => { });
|
|
52
|
-
throw error;
|
|
53
|
-
}
|
|
54
|
-
return {
|
|
55
|
-
db,
|
|
56
|
-
url: backend.url,
|
|
57
|
-
stop: async () => {
|
|
58
|
-
try {
|
|
59
|
-
await pool.end();
|
|
60
|
-
}
|
|
61
|
-
finally {
|
|
62
|
-
await backend.stop();
|
|
63
|
-
}
|
|
64
|
-
},
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
export { PGLITE_MAX_CONNECTIONS, startPgliteServer } from "./pglite.js";
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* PGlite served over the Postgres wire protocol, so the app's `pg` pool talks to it like any other Postgres. Used by the test helper and a template's dev server.
|
|
3
|
-
*
|
|
4
|
-
* `1` because pglite-socket serialises every connection onto PGlite's single session: with more, one connection's open transaction blocks the others and there is no per-connection isolation. At the limit a second connection is refused outright, so a pool pointed at this server must use `max: PGLITE_MAX_CONNECTIONS` and nothing may open another pool against it.
|
|
5
|
-
*/
|
|
6
|
-
export declare const PGLITE_MAX_CONNECTIONS = 1;
|
|
7
|
-
export type PgliteServer = {
|
|
8
|
-
url: string;
|
|
9
|
-
port: number;
|
|
10
|
-
stop(): Promise<void>;
|
|
11
|
-
};
|
|
12
|
-
/**
|
|
13
|
-
* In-memory when `dataDir` is absent. `port` 0 (or absent) picks a free one. `resolveFrom` loads PGlite from that directory's dependencies (an app's root) rather than this package's.
|
|
14
|
-
*/
|
|
15
|
-
export declare function startPgliteServer(options?: {
|
|
16
|
-
dataDir?: string;
|
|
17
|
-
host?: string;
|
|
18
|
-
port?: number;
|
|
19
|
-
resolveFrom?: string;
|
|
20
|
-
}): Promise<PgliteServer>;
|