@rebasepro/server-postgres 0.32.0 → 0.33.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/dist/{BranchService-C8LtpMho.js → BranchService-Bdin0Wxh.js} +3 -3
- package/dist/{BranchService-C8LtpMho.js.map → BranchService-Bdin0Wxh.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +3 -0
- package/dist/{backup-cli-DtV6n3oB.js → backup-cli-BEAMPWMs.js} +3 -3
- package/dist/{backup-cli-DtV6n3oB.js.map → backup-cli-BEAMPWMs.js.map} +1 -1
- package/dist/{boot-ddl-CSYhSSZD.js → boot-ddl-Bu6gAY-2.js} +2 -2
- package/dist/{boot-ddl-CSYhSSZD.js.map → boot-ddl-Bu6gAY-2.js.map} +1 -1
- package/dist/{cli-console-Cu1DzqvR.js → cli-console-DjFiYlSe.js} +4 -4
- package/dist/{cli-console-Cu1DzqvR.js.map → cli-console-DjFiYlSe.js.map} +1 -1
- package/dist/cli-errors.d.ts +12 -0
- package/dist/cli-helpers.d.ts +20 -0
- package/dist/{cli-schema-dir-DuZIsF2e.js → cli-schema-dir-CjDH_31U.js} +111 -5
- package/dist/cli-schema-dir-CjDH_31U.js.map +1 -0
- package/dist/cli.js +28 -23
- package/dist/cli.js.map +1 -1
- package/dist/{database-preflight-CyTCWlfc.js → database-preflight-DKzsGnc4.js} +2 -2
- package/dist/{database-preflight-CyTCWlfc.js.map → database-preflight-DKzsGnc4.js.map} +1 -1
- package/dist/{deferred-index-build-ueYVUBZc.js → deferred-index-build-88bWtYgx.js} +4 -4
- package/dist/{deferred-index-build-ueYVUBZc.js.map → deferred-index-build-88bWtYgx.js.map} +1 -1
- package/dist/{ensure-policies-13mHWjBs.js → ensure-policies-nIITKxud.js} +6 -6
- package/dist/{ensure-policies-13mHWjBs.js.map → ensure-policies-nIITKxud.js.map} +1 -1
- package/dist/{ensure-tables-B3Kh2RwT.js → ensure-tables-Lm-77eM5.js} +6 -6
- package/dist/{ensure-tables-B3Kh2RwT.js.map → ensure-tables-Lm-77eM5.js.map} +1 -1
- package/dist/{ensure-tables-DM1U9AZK.js → ensure-tables-hQ5oAK_j.js} +3 -3
- package/dist/{ensure-tables-DM1U9AZK.js.map → ensure-tables-hQ5oAK_j.js.map} +1 -1
- package/dist/{enum-labels-kept-CJDVtX14.js → enum-labels-kept-mesgEJWH.js} +2 -2
- package/dist/{enum-labels-kept-CJDVtX14.js.map → enum-labels-kept-mesgEJWH.js.map} +1 -1
- package/dist/index.es.js +11 -11
- package/dist/{migrate-baseline-DnMlSDup.js → migrate-baseline-Bzj5gSCM.js} +2 -2
- package/dist/{migrate-baseline-DnMlSDup.js.map → migrate-baseline-Bzj5gSCM.js.map} +1 -1
- package/dist/{migrate-policy-stamps-BpHyEFkk.js → migrate-policy-stamps-C2WaOEsB.js} +4 -4
- package/dist/{migrate-policy-stamps-BpHyEFkk.js.map → migrate-policy-stamps-C2WaOEsB.js.map} +1 -1
- package/dist/{open-rebase-B2mAA7UE.js → open-rebase-OB4hhQuk.js} +391 -33
- package/dist/open-rebase-OB4hhQuk.js.map +1 -0
- package/dist/{pg-error-utils-CpUiBkp-.js → pg-error-utils-CWopxboq.js} +2 -2
- package/dist/{pg-error-utils-CpUiBkp-.js.map → pg-error-utils-CWopxboq.js.map} +1 -1
- package/dist/{policy-drift-C9xRcbsU.js → policy-drift-rVLKS2AG.js} +3 -3
- package/dist/{policy-drift-C9xRcbsU.js.map → policy-drift-rVLKS2AG.js.map} +1 -1
- package/dist/{push-index-adoption-D-ph6kBc.js → push-index-adoption-EcamXfW2.js} +2 -2
- package/dist/{push-index-adoption-D-ph6kBc.js.map → push-index-adoption-EcamXfW2.js.map} +1 -1
- package/dist/{push-index-prebuild-DUKtH87s.js → push-index-prebuild-BPIns6wA.js} +3 -3
- package/dist/{push-index-prebuild-DUKtH87s.js.map → push-index-prebuild-BPIns6wA.js.map} +1 -1
- package/dist/{push-legacy-renames-wLSsAg80.js → push-legacy-renames-lmYkb41I.js} +3 -3
- package/dist/{push-legacy-renames-wLSsAg80.js.map → push-legacy-renames-lmYkb41I.js.map} +1 -1
- package/dist/{push-policy-plan-I9RNoP_-.js → push-policy-plan-Dqu4FKWh.js} +3 -3
- package/dist/{push-policy-plan-I9RNoP_-.js.map → push-policy-plan-Dqu4FKWh.js.map} +1 -1
- package/dist/{request-role-cli-D9yWoeSl.js → request-role-cli-Ay0v9oYZ.js} +8 -8
- package/dist/{request-role-cli-D9yWoeSl.js.map → request-role-cli-Ay0v9oYZ.js.map} +1 -1
- package/dist/{request-role-migration-DQLiYJ4c.js → request-role-migration-DTE3Owsh.js} +2 -2
- package/dist/{request-role-migration-DQLiYJ4c.js.map → request-role-migration-DTE3Owsh.js.map} +1 -1
- package/dist/{rls-enforcement-Cwh5SJRx.js → rls-enforcement-Ck-d8zdJ.js} +2 -2
- package/dist/{rls-enforcement-Cwh5SJRx.js.map → rls-enforcement-Ck-d8zdJ.js.map} +1 -1
- package/dist/schema/doctor-cli.js +5 -5
- package/dist/schema/introspect-db.js +1 -1
- package/dist/services/cdc/CdcListener.d.ts +12 -0
- package/dist/services/cdc/pgoutput.d.ts +6 -0
- package/dist/services/realtime-prefilter.d.ts +90 -0
- package/dist/services/realtimeService.d.ts +39 -1
- package/dist/utils/connection-string.d.ts +9 -1
- package/dist/{websocket-CSVNOYHC.js → websocket-kZixcOXt.js} +3 -3
- package/dist/{websocket-CSVNOYHC.js.map → websocket-kZixcOXt.js.map} +1 -1
- package/package.json +7 -7
- package/dist/cli-schema-dir-DuZIsF2e.js.map +0 -1
- package/dist/open-rebase-B2mAA7UE.js.map +0 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { i as __exportAll } from "./cli-prompt-DXG0yk-h.js";
|
|
4
|
-
import { n as extractPgError } from "./pg-error-utils-
|
|
4
|
+
import { n as extractPgError } from "./pg-error-utils-CWopxboq.js";
|
|
5
5
|
//#region src/schema/boot-ddl.ts
|
|
6
6
|
/**
|
|
7
7
|
* How boot DDL waits for a table lock, and how it applies several statements as
|
|
@@ -102,4 +102,4 @@ var sleep = (ms) => ms > 0 ? new Promise((resolve) => setTimeout(resolve, ms)) :
|
|
|
102
102
|
//#endregion
|
|
103
103
|
export { isLockTimeout as a, resolveBootLockOptions as c, boot_ddl_exports as i, sleep as l, BOOT_LOCK_TIMEOUT_MS as n, isMultiStatementRefusal as o, atomicBatch as r, joinStatements as s, BOOT_LOCK_RETRY_BUDGET_MS as t };
|
|
104
104
|
|
|
105
|
-
//# sourceMappingURL=boot-ddl-
|
|
105
|
+
//# sourceMappingURL=boot-ddl-Bu6gAY-2.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"boot-ddl-
|
|
1
|
+
{"version":3,"file":"boot-ddl-Bu6gAY-2.js","names":[],"sources":["../src/schema/boot-ddl.ts"],"sourcesContent":["/**\n * How boot DDL waits for a table lock, and how it applies several statements as\n * one.\n *\n * ## Why boot DDL has a lock budget at all\n *\n * Every statement that changes a table — `ALTER TABLE`, `CREATE`/`DROP POLICY`,\n * `DROP TRIGGER` — needs a lock that conflicts with readers. While it *waits*\n * for that lock it sits in the table's lock queue, and every query that arrives\n * after it queues behind it, however short. A boot that happened to start while\n * a report, a long transaction or a `pg_dump` held a table stalled every live\n * read of that table for as long as it waited — up to the pool's\n * `statement_timeout` (30 s), per statement, one table after another.\n *\n * `lock_timeout` turns that wait into a short, bounded attempt. Measured on\n * Postgres 18: a reader holding one table for 5 s held a live `SELECT\n * count(*)` behind the boot for 4.4 s; with the budget below it is held for at\n * most {@link BOOT_LOCK_TIMEOUT_MS}, and the queue drains between attempts.\n *\n * ## The budget\n *\n * 1 s per attempt. An uncontended `ACCESS EXCLUSIVE` on a healthy table is\n * granted in well under a millisecond — the wait is for the statements already\n * running on it to finish — so a second is three orders of magnitude of\n * headroom and never fires on a database that is merely busy. It fires only\n * when something holds the table for longer than any interactive query should,\n * and then the cost to live traffic is one second, which sits inside every\n * client timeout this framework ships with. Longer budgets buy nothing a retry\n * does not buy better: the queue behind a waiting lock grows for as long as it\n * waits, and drains as soon as it gives up.\n *\n * ## Applying several statements as one\n *\n * {@link atomicBatch} joins statements into one simple-protocol query string.\n * Postgres runs a multi-statement query as a single implicit transaction: every\n * statement commits or none does, the `SET LOCAL` applies to that transaction\n * only, and a failure rolls it back on its own — the connection goes back to the\n * pool clean, which an explicit `BEGIN` in the string would not guarantee. It is\n * one round trip and one commit instead of one of each per statement.\n *\n * A handle that speaks only the extended protocol (PGlite in-process, used by\n * tests) refuses the string before running any of it; {@link\n * isMultiStatementRefusal} recognises that so the caller can fall back to one\n * statement at a time.\n */\nimport { extractPgError } from \"../utils/pg-error-utils\";\n\n/** `lock_timeout` for each attempt at a boot DDL statement or batch. See the module comment. */\nexport const BOOT_LOCK_TIMEOUT_MS = 1_000;\n\n/** Attempts per table, including the first, before a contended table is given up on. */\nexport const BOOT_LOCK_ATTEMPTS = 3;\n\n/**\n * The most lock waiting one boot step spends on *retries*, in total.\n *\n * Without a cap, a holder that covers the whole database — a `pg_dump` takes\n * `ACCESS SHARE` on every table it dumps, for as long as it runs — costs\n * tables × attempts × timeout: four minutes at 240 tables. Retrying is for the\n * holder that is about to finish (a report, a transaction), and ten seconds is\n * plenty to wait that out; past it, waiting longer only delays the boot.\n */\nexport const BOOT_LOCK_RETRY_BUDGET_MS = 10_000;\n\nexport interface BootLockOptions {\n /** Per-attempt `lock_timeout`, ms. Default {@link BOOT_LOCK_TIMEOUT_MS}. */\n lockTimeoutMs?: number;\n /** Attempts per table, including the first. Default {@link BOOT_LOCK_ATTEMPTS}. */\n attempts?: number;\n /** Total retry waiting per step, ms. Default {@link BOOT_LOCK_RETRY_BUDGET_MS}. */\n retryBudgetMs?: number;\n /** Pause before retry round `round` (1-based), ms. Default: jittered, growing. */\n backoffMs?: (round: number) => number;\n}\n\nexport interface ResolvedBootLockOptions {\n lockTimeoutMs: number;\n attempts: number;\n retryBudgetMs: number;\n backoffMs: (round: number) => number;\n}\n\nexport const resolveBootLockOptions = (options: BootLockOptions = {}): ResolvedBootLockOptions => ({\n lockTimeoutMs: options.lockTimeoutMs ?? BOOT_LOCK_TIMEOUT_MS,\n attempts: Math.max(1, options.attempts ?? BOOT_LOCK_ATTEMPTS),\n retryBudgetMs: options.retryBudgetMs ?? BOOT_LOCK_RETRY_BUDGET_MS,\n // Jittered so two replicas booting together do not retry in lockstep.\n backoffMs: options.backoffMs ?? (round => 500 * round * (1 + Math.random()))\n});\n\n/** `55P03 lock_not_available` — what `lock_timeout` raises. */\nexport const isLockTimeout = (err: unknown): boolean => extractPgError(err)?.code === \"55P03\";\n\n/**\n * `42601` \"cannot insert multiple commands into a prepared statement\": the\n * handle runs every query over the extended protocol, which carries exactly one\n * statement. Raised before anything runs, so nothing needs undoing.\n */\nexport const isMultiStatementRefusal = (err: unknown): boolean => {\n const pg = extractPgError(err);\n return pg?.code === \"42601\" && /multiple commands/i.test(pg.message ?? \"\");\n};\n\n/**\n * `SET LOCAL lock_timeout`, then the statements: one string, one implicit\n * transaction. See the module comment for why this and not `BEGIN … COMMIT`.\n */\nexport const atomicBatch = (statements: readonly string[], lockTimeoutMs: number): string =>\n `SET LOCAL lock_timeout = '${Math.max(1, Math.round(lockTimeoutMs))}ms';\\n${joinStatements(statements)}`;\n\n/** Statements as one multi-statement string — one implicit transaction — each `;`-terminated. */\nexport const joinStatements = (statements: readonly string[]): string =>\n statements\n .map(statement => {\n const trimmed = statement.trim();\n return trimmed.endsWith(\";\") ? trimmed : `${trimmed};`;\n })\n .join(\"\\n\");\n\nexport const sleep = (ms: number): Promise<void> =>\n ms > 0 ? new Promise(resolve => setTimeout(resolve, ms)) : Promise.resolve();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgDA,IAAa,uBAAuB;;;;;;;;;;AAcpC,IAAa,4BAA4B;AAoBzC,IAAa,0BAA0B,UAA2B,CAAC,OAAgC;CAC/F,eAAe,QAAQ,iBAAA;CACvB,UAAU,KAAK,IAAI,GAAG,QAAQ,YAAA,CAA8B;CAC5D,eAAe,QAAQ,iBAAA;CAEvB,WAAW,QAAQ,eAAc,UAAS,MAAM,SAAS,IAAI,KAAK,OAAO;AAC7E;;AAGA,IAAa,iBAAiB,QAA0B,eAAe,GAAG,CAAC,EAAE,SAAS;;;;;;AAOtF,IAAa,2BAA2B,QAA0B;CAC9D,MAAM,KAAK,eAAe,GAAG;CAC7B,OAAO,IAAI,SAAS,WAAW,qBAAqB,KAAK,GAAG,WAAW,EAAE;AAC7E;;;;;AAMA,IAAa,eAAe,YAA+B,kBACvD,6BAA6B,KAAK,IAAI,GAAG,KAAK,MAAM,aAAa,CAAC,EAAE,QAAQ,eAAe,UAAU;;AAGzG,IAAa,kBAAkB,eAC3B,WACK,KAAI,cAAa;CACd,MAAM,UAAU,UAAU,KAAK;CAC/B,OAAO,QAAQ,SAAS,GAAG,IAAI,UAAU,GAAG,QAAQ;AACxD,CAAC,CAAC,CACD,KAAK,IAAI;AAElB,IAAa,SAAS,OAClB,KAAK,IAAI,IAAI,SAAQ,YAAW,WAAW,SAAS,EAAE,CAAC,IAAI,QAAQ,QAAQ"}
|
|
@@ -2,10 +2,10 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { n as require_arg, o as __toESM } from "./cli-prompt-DXG0yk-h.js";
|
|
4
4
|
import { d as poolMaxCeiling } from "./connection-C1zXTPJq.js";
|
|
5
|
-
import { t as openRebase } from "./open-rebase-
|
|
6
|
-
import { c as diagnoseDbError } from "./cli-schema-dir-
|
|
5
|
+
import { t as openRebase } from "./open-rebase-OB4hhQuk.js";
|
|
6
|
+
import { c as diagnoseDbError } from "./cli-schema-dir-CjDH_31U.js";
|
|
7
7
|
import { i as outError, n as describeFailure, r as out } from "./source-VxbrQojV.js";
|
|
8
|
-
import { h as RELAYED_FLAGS } from "./migrate-baseline-
|
|
8
|
+
import { h as RELAYED_FLAGS } from "./migrate-baseline-Bzj5gSCM.js";
|
|
9
9
|
import { setLogOutput } from "@rebasepro/server";
|
|
10
10
|
import path from "path";
|
|
11
11
|
import fs from "fs";
|
|
@@ -317,4 +317,4 @@ async function feedLineByLine(source, server, feed, exited) {
|
|
|
317
317
|
//#endregion
|
|
318
318
|
export { consoleCommand };
|
|
319
319
|
|
|
320
|
-
//# sourceMappingURL=cli-console-
|
|
320
|
+
//# sourceMappingURL=cli-console-DjFiYlSe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli-console-Cu1DzqvR.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's tables (`backend/schema`) the way `rebase db push` does,\n * and the global table hooks `backend/hooks.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `tables` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { TableDescriptor, TableHooks } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { DEFAULT_SCHEMA_DIR } from \"./cli-schema-dir\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--schema-dir\": String,\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n /** The descriptors of the tables the project serves. */\n tables: TableDescriptor[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, tables: TableDescriptor[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `tables` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"tables\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"tables\", code);\n }\n return run(scope.rebase, scope.tables);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n schemaDir: flags[\"--schema-dir\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/** The names a table hook can have; anything else on a `hooks` export is not one. */\nconst TABLE_HOOK_NAMES = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */\nfunction isTableHooks(value: unknown): value is TableHooks {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return Object.entries(value).every(([key, hook]) =>\n (TABLE_HOOK_NAMES as readonly string[]).includes(key) && (hook === undefined || typeof hook === \"function\"));\n}\n\n/**\n * The project's global table hooks: the `hooks` its `backend/hooks.ts`\n * exports, which the server runs for every table ahead of each table's own.\n *\n * `backend/` is the schema directory's parent. No module there means no global\n * hooks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n *\n * They are handed on as declared: the driver calls each with the descriptor\n * of the table it runs for.\n *\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined> {\n const backendDir = path.dirname(schemaDir);\n // `.js` first, as the server's own loader reads a built module.\n const modulePath = [\".js\", \".mjs\", \".ts\", \".mts\"]\n .map(ext => path.join(backendDir, `hooks${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!modulePath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(modulePath).href);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);\n return undefined;\n }\n if (mod.hooks === undefined) return undefined;\n if (!isTableHooks(mod.hooks)) {\n outError(`⚠ Global hooks are off in this session: the \\`hooks\\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(\", \")}).`);\n return undefined;\n }\n return mod.hooks;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; schemaDir?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n // The tables the way every other driver command reads them: a schema that\n // does not compile stops the console too, rather than opening it over a\n // subset of the tables.\n const { loadTableSchema } = await import(\"./schema/load-tables\");\n const schemaDir = path.resolve(options.schemaDir || DEFAULT_SCHEMA_DIR);\n const { tables } = await loadTableSchema(schemaDir);\n // Writes from the console run the same hook tiers as a server write.\n const hooks = await loadProjectHooks(schemaDir);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n tables,\n ...(hooks ? { hooks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, tables: rebase.tables });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, tables: rebase.tables }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.tables = scope.tables;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,gBAAgB;CACzB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAaA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ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AAQ,EAAE;IAC1D,QAAQ;GACZ,CAAC;EACL,CAAC;CACL;CAEA,MAAM,SAAS,IAAI,SAAe,YAAY,OAAO,KAAK,cAAc,QAAQ,CAAC,CAAC;CAClF,OAAO,cAAc;CACrB,IAAI,MAAM,MAAM,eAAe,OAAO,QAAQ,MAAM,MAAM;CAC1D,MAAM;AACV;;;;;;;;;;;;;;;;AAiBA,eAAe,eACX,QACA,QACA,MACA,QACa;CACb,IAAI;CACJ,MAAM,cAAc;EAChB,MAAM,UAAU;EAChB,YAAY,KAAA;EACZ,UAAU;CACd;CAGA,OAAO,gBAAgB,cAAc;EACjC,IAAI,CAAC,OAAO,YAAY,OAAO,MAAM;CACzC,CAAC;CAED,OAAO,GAAG,cAAc;EACpB,IAAI,CAAC,OAAO,YAAY;EACxB,OAAO,OAAO;EACd,MAAM;CACV,CAAC;CACD,OAAO,GAAG,UAAU,KAAK;CAEzB,MAAM,SAAS,OAAO,WAAW,QAAiB;CAClD,MAAM,QAAQ,SAAS,gBAAgB;EAAE,OAAO;EAAQ,WAAW;CAAS,CAAC;CAC7E,WAAW,MAAM,QAAQ,OAAO;EAC5B,MAAM,OAAO,IAAI,SAAiB,YAAY;GAAE,kBAAkB,QAAQ,MAAM;EAAG,CAAC;EACpF,KAAK,MAAM,GAAG,KAAK,GAAG;EAEtB,IAAI,MAAM,QAAQ,KAAK,CAAC,MAAM,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
|
|
1
|
+
{"version":3,"file":"cli-console-DjFiYlSe.js","names":[],"sources":["../src/cli-console.ts"],"sourcesContent":["/**\n * `rebase console` — the driver's half.\n *\n * Loads the project's tables (`backend/schema`) the way `rebase db push` does,\n * and the global table hooks `backend/hooks.ts` exports, opens the database with\n * {@link openRebase}, and either evaluates one piece of code\n * (`--eval`) or starts a Node REPL with `rebase` and `tables` in scope.\n * The `rebase` CLI resolves the database first (the managed one included) and\n * hands this process `DATABASE_URL`, exactly as it does for `db` commands.\n *\n * This is the boot side of `openRebase`: it is where the environment is read\n * — `DATABASE_URL`, and the `REBASE_DB_POOL_MAX` ceiling the managed\n * development database needs — and turned into explicit options.\n */\nimport arg from \"arg\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport readline from \"node:readline\";\nimport repl from \"node:repl\";\nimport { PassThrough } from \"node:stream\";\nimport tty from \"node:tty\";\nimport { pathToFileURL } from \"node:url\";\nimport { inspect } from \"node:util\";\nimport { setLogOutput } from \"@rebasepro/server\";\nimport type { TableDescriptor, TableHooks } from \"@rebasepro/types\";\nimport { RELAYED_FLAGS } from \"./cli-flags\";\nimport { DEFAULT_SCHEMA_DIR } from \"./cli-schema-dir\";\nimport { diagnoseDbError } from \"./cli-errors\";\nimport { out, outError, describeFailure } from \"./cli-output\";\nimport { poolMaxCeiling } from \"./connection\";\nimport { openRebase, type OpenedRebase } from \"./open-rebase\";\n\n/**\n * The flags `rebase console` takes. `--history` is the CLI's own: where it\n * keeps the REPL's history (`.rebase/console_history` in the project).\n */\nexport const CONSOLE_FLAGS = {\n \"--schema-dir\": String,\n \"--eval\": String,\n \"-e\": \"--eval\",\n \"--history\": String\n} satisfies arg.Spec;\n\n/** What the code the console runs can name. */\nexport interface ConsoleScope {\n rebase: OpenedRebase;\n /** The descriptors of the tables the project serves. */\n tables: TableDescriptor[];\n}\n\ntype ScopedFunction = (rebase: OpenedRebase, tables: TableDescriptor[]) => Promise<unknown>;\ntype AsyncFunctionConstructor = new (...parameters: string[]) => ScopedFunction;\n\n/** The constructor of `async function` — what `new Function` is for a body that awaits. */\nconst AsyncFunction: AsyncFunctionConstructor = Object.getPrototypeOf(async () => undefined).constructor;\n\n/**\n * Run `code` with `rebase` and `tables` in scope and resolve with its\n * value.\n *\n * Read as an expression first, so `rebase.dataAsAdmin.posts.find()` is its own\n * result; code that is not one expression runs as a function body, where\n * `await` works everywhere and `return` gives the result.\n */\nexport async function evaluateInConsole(code: string, scope: ConsoleScope): Promise<unknown> {\n let run: ScopedFunction;\n try {\n run = new AsyncFunction(\"rebase\", \"tables\", `return (${code}\\n);`);\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error;\n run = new AsyncFunction(\"rebase\", \"tables\", code);\n }\n return run(scope.rebase, scope.tables);\n}\n\n/** A result as JSON, the way `--eval` prints it: dates as ISO strings, bigints as strings. */\nexport function consoleJson(value: unknown): string {\n return JSON.stringify(value, (_key, item: unknown) => typeof item === \"bigint\" ? item.toString() : item, 2) ?? \"undefined\";\n}\n\n/** The host and database a URL names, for the banner — never its credentials. */\nfunction describeDatabase(databaseUrl: string): string {\n try {\n const url = new URL(databaseUrl);\n return `${url.hostname}${url.port ? `:${url.port}` : \"\"}${url.pathname}`;\n } catch {\n return \"the configured database\";\n }\n}\n\n/** Where the REPL reads and writes; the terminal unless a caller hands it streams. */\nexport interface ConsoleStreams {\n input?: NodeJS.ReadableStream;\n output?: NodeJS.WritableStream;\n}\n\n/**\n * `rebase console [--eval <code>] [--schema-dir <dir>]`, from the driver\n * line `[\"console\", …flags]`. Resolves with the exit code.\n */\nexport async function consoleCommand(args: string[], streams: ConsoleStreams = {}): Promise<number> {\n const flags = arg({ ...RELAYED_FLAGS, ...CONSOLE_FLAGS }, { argv: args.slice(1) });\n if (flags[\"--help\"]) {\n out(\"Run `rebase console --help` for the options — this is the driver's own entry point.\");\n return 0;\n }\n\n const databaseUrl = flags[\"--database-url\"] || process.env.DATABASE_URL;\n if (!databaseUrl) {\n outError(\"✗ No database to open: DATABASE_URL is not set. Set it in .env, or pass --database-url.\");\n return 1;\n }\n\n // The console's own lines are what the reader is here for; the driver's\n // info-level boot notes are not, unless they asked for them.\n if (process.env.LOG_LEVEL === undefined) process.env.LOG_LEVEL = \"warn\";\n\n // And whatever level they asked for, a log line is never part of the\n // answer: stdout holds the `--eval` result a pipe reads (`| jq .`) and the\n // REPL's values. The scaffold's `.env` sets LOG_LEVEL=info, and under\n // NODE_ENV=production warnings go to stdout too.\n setLogOutput(\"stderr\");\n try {\n return await openAndRun({\n databaseUrl,\n schemaDir: flags[\"--schema-dir\"],\n eval: flags[\"--eval\"],\n history: flags[\"--history\"]\n }, streams);\n } finally {\n setLogOutput();\n }\n}\n\n/** Whether a connection was reset or cut off before it answered, anywhere in the error's chain. */\nfunction connectionCutOff(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"ECONNRESET\") return true;\n if (error instanceof Error && /Connection terminated unexpectedly/.test(error.message)) return true;\n if (\"errors\" in error && Array.isArray(error.errors) && error.errors.some(inner => connectionCutOff(inner, depth + 1))) return true;\n return \"cause\" in error && connectionCutOff(error.cause, depth + 1);\n}\n\n/** Whether Postgres refused the connection for want of one: SQLSTATE 53300, anywhere in the error's chain. */\nfunction noFreeConnection(error: unknown, depth = 0): boolean {\n if (!error || typeof error !== \"object\" || depth > 4) return false;\n if (\"code\" in error && error.code === \"53300\") return true;\n return \"cause\" in error && noFreeConnection(error.cause, depth + 1);\n}\n\n/**\n * What the console says when the project's database will not open: the banner\n * every db command prints for a database it cannot reach, or one sentence —\n * never the driver's error serialised onto one line, stack and all.\n *\n * The managed development database accepts only a few connections at a time,\n * and a running `rebase dev` holds some of them. Its proxy refuses one over the\n * limit with SQLSTATE 53300; a database an earlier CLI started resets it\n * instead, and `read ECONNRESET` says nothing about why.\n */\nexport function describeOpenFailure(error: unknown, databaseUrl: string, managed: boolean): string {\n if (managed && (connectionCutOff(error) || noFreeConnection(error))) {\n return \"✗ The managed development database has no free connection: it accepts only a few at a time, \" +\n \"and other clients hold them — a running `rebase dev` holds some.\\n\" +\n \" Close another `rebase console`, psql or database GUI and run this again, \" +\n \"or stop `rebase dev` while you use the console.\";\n }\n return diagnoseDbError(error, databaseUrl) ?? describeFailure(error);\n}\n\n/** The names a table hook can have; anything else on a `hooks` export is not one. */\nconst TABLE_HOOK_NAMES = [\"beforeQuery\", \"afterRead\", \"beforeSave\", \"afterSave\", \"afterSaveError\", \"beforeDelete\", \"afterDelete\"] as const;\n\n/** Whether a module's `hooks` export is table hooks: an object whose every key is a hook name holding a function. */\nfunction isTableHooks(value: unknown): value is TableHooks {\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n return Object.entries(value).every(([key, hook]) =>\n (TABLE_HOOK_NAMES as readonly string[]).includes(key) && (hook === undefined || typeof hook === \"function\"));\n}\n\n/**\n * The project's global table hooks: the `hooks` its `backend/hooks.ts`\n * exports, which the server runs for every table ahead of each table's own.\n *\n * `backend/` is the schema directory's parent. No module there means no global\n * hooks, as it does for the server.\n *\n * One that is there and cannot be imported — an import that needs an\n * environment variable the console was not given, say — does not stop the\n * console, which can still read and write. It says so, once, and runs without\n * them: writes from this session then skip the global tier, and the reader\n * knows it.\n *\n * They are handed on as declared: the driver calls each with the descriptor\n * of the table it runs for.\n *\n * @param schemaDir the schema directory, absolute.\n */\nexport async function loadProjectHooks(schemaDir: string): Promise<TableHooks | undefined> {\n const backendDir = path.dirname(schemaDir);\n // `.js` first, as the server's own loader reads a built module.\n const modulePath = [\".js\", \".mjs\", \".ts\", \".mts\"]\n .map(ext => path.join(backendDir, `hooks${ext}`))\n .find(candidate => fs.existsSync(candidate));\n if (!modulePath) return undefined;\n\n let mod: Record<string, unknown>;\n try {\n mod = await import(pathToFileURL(modulePath).href);\n } catch (error) {\n const reason = (error instanceof Error ? error.message : String(error)).split(\"\\n\")[0];\n outError(`⚠ Global hooks are off in this session: ${modulePath} could not be loaded (${reason}). Each table's own hooks still run.`);\n return undefined;\n }\n if (mod.hooks === undefined) return undefined;\n if (!isTableHooks(mod.hooks)) {\n outError(`⚠ Global hooks are off in this session: the \\`hooks\\` ${modulePath} exports is not an object of table hooks (${TABLE_HOOK_NAMES.join(\", \")}).`);\n return undefined;\n }\n return mod.hooks;\n}\n\n/** Open the project, run `--eval` or the REPL, and close it again. Resolves with the exit code. */\nasync function openAndRun(\n options: { databaseUrl: string; schemaDir?: string; eval?: string; history?: string },\n streams: ConsoleStreams\n): Promise<number> {\n const { databaseUrl } = options;\n // The tables the way every other driver command reads them: a schema that\n // does not compile stops the console too, rather than opening it over a\n // subset of the tables.\n const { loadTableSchema } = await import(\"./schema/load-tables\");\n const schemaDir = path.resolve(options.schemaDir || DEFAULT_SCHEMA_DIR);\n const { tables } = await loadTableSchema(schemaDir);\n // Writes from the console run the same hook tiers as a server write.\n const hooks = await loadProjectHooks(schemaDir);\n\n const ceiling = poolMaxCeiling();\n let rebase: OpenedRebase;\n try {\n rebase = await openRebase({\n databaseUrl,\n tables,\n ...(hooks ? { hooks } : {}),\n ...(ceiling !== null ? { pool: { max: ceiling } } : {})\n });\n } catch (error) {\n outError(describeOpenFailure(error, databaseUrl, process.env.REBASE_DEV_DATABASE_KIND === \"managed\"));\n return 1;\n }\n\n try {\n const code = options.eval;\n if (code !== undefined) {\n try {\n const result = await evaluateInConsole(code, { rebase, tables: rebase.tables });\n if (result !== undefined) out(consoleJson(result));\n return 0;\n } catch (error) {\n outError(describeFailure(error));\n return 1;\n }\n }\n\n await startRepl({ rebase, tables: rebase.tables }, {\n history: options.history,\n database: describeDatabase(databaseUrl),\n ...streams\n });\n return 0;\n } finally {\n await rebase.close();\n }\n}\n\n/** The interactive half: a Node REPL until `.exit`, Ctrl-D or the end of piped input. */\nasync function startRepl(scope: ConsoleScope, options: { history?: string; database: string } & ConsoleStreams): Promise<void> {\n const input = options.input ?? process.stdin;\n const output = options.output ?? process.stdout;\n const typed = input instanceof tty.ReadStream && input.isTTY;\n\n // For a person at a terminal. Piped, stdout is the REPL's answers, which\n // whatever reads the pipe is after, so the banner goes to stderr with the\n // rest of what the console says about itself.\n const say = typed ? out : outError;\n say(\"\");\n say(` rebase console — ${options.database}, ${scope.tables.length} table(s)`);\n say(\" In scope: rebase (dataAsAdmin, sql, withAuth, close) and tables. Top-level await works.\");\n say(\" Try: await rebase.dataAsAdmin.<table>.find({ limit: 5 })\");\n say(\"\");\n\n // Typed at a terminal, the REPL reads it as one. Anything else — a pipe, a\n // file, a stream handed in — reaches it a line at a time through `feed`\n // (see `feedLineByLine`).\n const feed = typed ? undefined : new PassThrough();\n // Colours for a terminal only: piped to a file or another program, the\n // escape codes are noise in the text.\n const colors = output instanceof tty.WriteStream && output.isTTY;\n // Started without a prompt, and given one once the scope is in place: a\n // line that arrives with the first prompt must already see `rebase`.\n const server = repl.start({\n prompt: \"\",\n useGlobal: false,\n ...(feed ? { input: feed, output, terminal: false } : { input, output }),\n writer: (value: unknown) => inspect(value, { colors, depth: 6 })\n });\n server.context.rebase = scope.rebase;\n server.context.tables = scope.tables;\n server.setPrompt(\"rebase> \");\n\n const history = options.history;\n if (history) {\n fs.mkdirSync(path.dirname(history), { recursive: true });\n await new Promise<void>((resolve) => {\n server.setupHistory(history, (error) => {\n if (error) outError(` (history is off: ${error.message})`);\n resolve();\n });\n });\n }\n\n const exited = new Promise<void>((resolve) => server.once(\"exit\", () => resolve()));\n server.displayPrompt();\n if (feed) await feedLineByLine(input, server, feed, exited);\n await exited;\n}\n\n/**\n * Hand input that is not typed at a terminal to the REPL a line at a time,\n * each once the REPL has finished the one before.\n *\n * Typed, the REPL holds keystrokes back while a top-level `await` is pending.\n * Piped, every line arrives at once and each is evaluated as it arrives, so in\n * `const { data } = await …` followed by `data.map(…)` the second line read\n * `data` before the first had assigned it.\n *\n * The REPL is paused as each line reaches it, and it resumes its input when it\n * displays its prompt again: once the line's value has settled, its error has\n * been printed, or it needs the next line to complete it. That resumption is\n * when the next line goes in. Lines are written one per chunk, because a\n * chunk holding several is split and every line of it handed over at once.\n */\nasync function feedLineByLine(\n source: NodeJS.ReadableStream,\n server: repl.REPLServer,\n feed: PassThrough,\n exited: Promise<void>\n): Promise<void> {\n let evaluated: (() => void) | undefined;\n const ready = () => {\n const resolve = evaluated;\n evaluated = undefined;\n resolve?.();\n };\n // Before the REPL's own handler, so a line it evaluates at once resumes\n // after this pause rather than before it.\n server.prependListener(\"line\", () => {\n if (!server.editorMode) server.pause();\n });\n // `.editor` collects lines with no prompt until Ctrl-D: they go straight in.\n server.on(\"line\", () => {\n if (!server.editorMode) return;\n server.resume();\n ready();\n });\n server.on(\"resume\", ready);\n\n const closed = exited.then(() => \"closed\" as const);\n const lines = readline.createInterface({ input: source, crlfDelay: Infinity });\n for await (const line of lines) {\n const done = new Promise<\"done\">((resolve) => { evaluated = () => resolve(\"done\"); });\n feed.write(`${line}\\n`);\n // `.exit`: the rest of the input is not for this REPL.\n if (await Promise.race([done, closed]) === \"closed\") break;\n }\n feed.end();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAoCA,IAAa,gBAAgB;CACzB,gBAAgB;CAChB,UAAU;CACV,MAAM;CACN,aAAa;AACjB;;AAaA,IAAM,gBAA0C,OAAO,eAAe,YAAY,KAAA,CAAS,CAAC,CAAC;;;;;;;;;AAU7F,eAAsB,kBAAkB,MAAc,OAAuC;CACzF,IAAI;CACJ,IAAI;EACA,MAAM,IAAI,cAAc,UAAU,UAAU,WAAW,KAAK,KAAK;CACrE,SAAS,OAAO;EACZ,IAAI,EAAE,iBAAiB,cAAc,MAAM;EAC3C,MAAM,IAAI,cAAc,UAAU,UAAU,IAAI;CACpD;CACA,OAAO,IAAI,MAAM,QAAQ,MAAM,MAAM;AACzC;;AAGA,SAAgB,YAAY,OAAwB;CAChD,OAAO,KAAK,UAAU,QAAQ,MAAM,SAAkB,OAAO,SAAS,WAAW,KAAK,SAAS,IAAI,MAAM,CAAC,KAAK;AACnH;;AAGA,SAAS,iBAAiB,aAA6B;CACnD,IAAI;EACA,MAAM,MAAM,IAAI,IAAI,WAAW;EAC/B,OAAO,GAAG,IAAI,WAAW,IAAI,OAAO,IAAI,IAAI,SAAS,KAAK,IAAI;CAClE,QAAQ;EACJ,OAAO;CACX;AACJ;;;;;AAYA,eAAsB,eAAe,MAAgB,UAA0B,CAAC,GAAoB;CAChG,MAAM,SAAA,GAAA,WAAA,QAAA,CAAY;EAAE,GAAG;EAAe,GAAG;CAAc,GAAG,EAAE,MAAM,KAAK,MAAM,CAAC,EAAE,CAAC;CACjF,IA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OAAO,IAAI,SAAiB,YAAY;GAAE,kBAAkB,QAAQ,MAAM;EAAG,CAAC;EACpF,KAAK,MAAM,GAAG,KAAK,GAAG;EAEtB,IAAI,MAAM,QAAQ,KAAK,CAAC,MAAM,MAAM,CAAC,MAAM,UAAU;CACzD;CACA,KAAK,IAAI;AACb"}
|
package/dist/cli-errors.d.ts
CHANGED
|
@@ -20,6 +20,18 @@ export declare function isAuthFailure(err: unknown): boolean;
|
|
|
20
20
|
* with a plain local dev database). The fix is `?sslmode=disable` on the URL.
|
|
21
21
|
*/
|
|
22
22
|
export declare function isSslNotEnabled(err: unknown): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Whether the connection failed because the server's certificate is not signed
|
|
25
|
+
* by an authority Node trusts.
|
|
26
|
+
*
|
|
27
|
+
* Almost always a managed database whose URL says `sslmode=require`:
|
|
28
|
+
* node-postgres reads `require` as `verify-full`, where libpq — `psql`, Atlas,
|
|
29
|
+
* the provider's own docs — reads it as "encrypted, not verified". The same
|
|
30
|
+
* URL that `psql` accepts then fails here with `self-signed certificate`.
|
|
31
|
+
* Matched on the error code, through Drizzle's `cause` and a dual-stack
|
|
32
|
+
* `AggregateError`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function isUntrustedServerCertificate(err: unknown): boolean;
|
|
23
35
|
/**
|
|
24
36
|
* The database a connection was refused by because it is closed to new
|
|
25
37
|
* connections (`ALLOW_CONNECTIONS false`), or null.
|
package/dist/cli-helpers.d.ts
CHANGED
|
@@ -76,6 +76,26 @@ export declare function workspaceMemberDir(startDir?: string): string | null;
|
|
|
76
76
|
* `ERR_PNPM_ADDING_TO_ROOT`.
|
|
77
77
|
*/
|
|
78
78
|
export declare function describeDevAddCommand(packageName: string, manager?: ProjectPackageManager, workspaceDir?: string | null): string;
|
|
79
|
+
/**
|
|
80
|
+
* The Atlas release Windows readers are sent: the floor of the scaffold's
|
|
81
|
+
* `@ariga/atlas` range. The npm package's version is the Atlas version — its
|
|
82
|
+
* `install.js` passes it to atlasgo.sh as `ATLAS_VERSION` — so Linux and macOS
|
|
83
|
+
* get the newest 1.x the range resolves to (1.3.10 on 2026-11-16) and this is
|
|
84
|
+
* the oldest release that range accepts. A pinned URL keeps the advice
|
|
85
|
+
* reproducible; `tooling/scripts/check-templates.mjs` holds it to the range.
|
|
86
|
+
*/
|
|
87
|
+
export declare const ATLAS_WINDOWS_VERSION = "1.2.3";
|
|
88
|
+
/**
|
|
89
|
+
* How to install Atlas on Windows, as lines for the terminal.
|
|
90
|
+
*
|
|
91
|
+
* `@ariga/atlas` ships Linux and macOS builds only — on Windows its
|
|
92
|
+
* `preinstall` exits "Unsupported platform", so nothing an install command can
|
|
93
|
+
* do will put Atlas in `node_modules/.bin`, and the npm advice below it is a
|
|
94
|
+
* loop. Atlas does publish a Windows binary; `resolveLocalBin` finds it through
|
|
95
|
+
* `where atlas` once it is on PATH. Only x64 is built: Windows on Arm runs it
|
|
96
|
+
* under emulation.
|
|
97
|
+
*/
|
|
98
|
+
export declare function describeAtlasWindowsInstall(version?: string): string[];
|
|
79
99
|
/**
|
|
80
100
|
* Why a dependency's binary is not on `PATH`.
|
|
81
101
|
*
|
|
@@ -45,6 +45,8 @@ var LIBPQ_SSLMODES = /* @__PURE__ */ new Set([
|
|
|
45
45
|
"verify-ca",
|
|
46
46
|
"verify-full"
|
|
47
47
|
]);
|
|
48
|
+
/** Query parameters node-postgres reads and libpq rejects. See {@link forLibpq}. */
|
|
49
|
+
var NODE_PG_ONLY_PARAMS = ["uselibpqcompat"];
|
|
48
50
|
/**
|
|
49
51
|
* Make a connection string safe to hand to a libpq program.
|
|
50
52
|
*
|
|
@@ -63,7 +65,15 @@ var LIBPQ_SSLMODES = /* @__PURE__ */ new Set([
|
|
|
63
65
|
* Nothing is relaxed by the rewrite — `verify-ca` and `verify-full` are left
|
|
64
66
|
* alone, so a connection string that asked for verification still gets it.
|
|
65
67
|
*
|
|
66
|
-
*
|
|
68
|
+
* `uselibpqcompat` is node-postgres's too. It is what node-postgres's own
|
|
69
|
+
* warning tells people to add (`uselibpqcompat=true&sslmode=require`), because
|
|
70
|
+
* node-postgres reads a bare `sslmode=require` as `verify-full`. libpq reports
|
|
71
|
+
* any parameter it does not know as a server setting, so Atlas fails with
|
|
72
|
+
* `unrecognized configuration parameter "uselibpqcompat"`. It only changes how
|
|
73
|
+
* node-postgres reads `sslmode`, and libpq already reads it the standard way,
|
|
74
|
+
* so it is dropped.
|
|
75
|
+
*
|
|
76
|
+
* Only these two are touched, and only when libpq would reject them.
|
|
67
77
|
* Anything unparseable is returned as given: a connection that works
|
|
68
78
|
* unverified beats one this corrupted.
|
|
69
79
|
*/
|
|
@@ -76,8 +86,11 @@ function forLibpq(connectionString) {
|
|
|
76
86
|
}
|
|
77
87
|
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return connectionString;
|
|
78
88
|
const sslmode = url.searchParams.get("sslmode");
|
|
79
|
-
|
|
80
|
-
url.searchParams.
|
|
89
|
+
const rejectedSslmode = sslmode !== null && !LIBPQ_SSLMODES.has(sslmode);
|
|
90
|
+
const nodePgOnly = NODE_PG_ONLY_PARAMS.filter((key) => url.searchParams.has(key));
|
|
91
|
+
if (!rejectedSslmode && nodePgOnly.length === 0) return connectionString;
|
|
92
|
+
if (rejectedSslmode) url.searchParams.set("sslmode", "require");
|
|
93
|
+
for (const key of nodePgOnly) url.searchParams.delete(key);
|
|
81
94
|
url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
|
|
82
95
|
return url.toString();
|
|
83
96
|
}
|
|
@@ -867,6 +880,7 @@ function prepareGeneratedSqlDir(cwd = process.cwd(), options = {}) {
|
|
|
867
880
|
//#region src/cli-helpers.ts
|
|
868
881
|
var cli_helpers_exports = /* @__PURE__ */ __exportAll({
|
|
869
882
|
ATLAS_DEV_URL_ENV: () => ATLAS_DEV_URL_ENV,
|
|
883
|
+
ATLAS_WINDOWS_VERSION: () => ATLAS_WINDOWS_VERSION,
|
|
870
884
|
ExcludeIntrospectionError: () => ExcludeIntrospectionError,
|
|
871
885
|
applySearchDdl: () => applySearchDdl,
|
|
872
886
|
applyTriggersDdl: () => applyTriggersDdl,
|
|
@@ -875,6 +889,7 @@ var cli_helpers_exports = /* @__PURE__ */ __exportAll({
|
|
|
875
889
|
atlasDevDatabaseUrl: () => atlasDevDatabaseUrl,
|
|
876
890
|
closeAppClients: () => closeAppClients,
|
|
877
891
|
declaredBinaries: () => declaredBinaries,
|
|
892
|
+
describeAtlasWindowsInstall: () => describeAtlasWindowsInstall,
|
|
878
893
|
describeBuildScriptRemedy: () => describeBuildScriptRemedy,
|
|
879
894
|
describeDevAddCommand: () => describeDevAddCommand,
|
|
880
895
|
describeDevDatabaseFailure: () => describeDevDatabaseFailure,
|
|
@@ -1041,6 +1056,40 @@ function describeDevAddCommand(packageName, manager = detectProjectPackageManage
|
|
|
1041
1056
|
default: return dir ? `pnpm --dir ${dir} add -D ${packageName}` : `pnpm add -D ${packageName}`;
|
|
1042
1057
|
}
|
|
1043
1058
|
}
|
|
1059
|
+
/**
|
|
1060
|
+
* The Atlas release Windows readers are sent: the floor of the scaffold's
|
|
1061
|
+
* `@ariga/atlas` range. The npm package's version is the Atlas version — its
|
|
1062
|
+
* `install.js` passes it to atlasgo.sh as `ATLAS_VERSION` — so Linux and macOS
|
|
1063
|
+
* get the newest 1.x the range resolves to (1.3.10 on 2026-11-16) and this is
|
|
1064
|
+
* the oldest release that range accepts. A pinned URL keeps the advice
|
|
1065
|
+
* reproducible; `tooling/scripts/check-templates.mjs` holds it to the range.
|
|
1066
|
+
*/
|
|
1067
|
+
var ATLAS_WINDOWS_VERSION = "1.2.3";
|
|
1068
|
+
/**
|
|
1069
|
+
* How to install Atlas on Windows, as lines for the terminal.
|
|
1070
|
+
*
|
|
1071
|
+
* `@ariga/atlas` ships Linux and macOS builds only — on Windows its
|
|
1072
|
+
* `preinstall` exits "Unsupported platform", so nothing an install command can
|
|
1073
|
+
* do will put Atlas in `node_modules/.bin`, and the npm advice below it is a
|
|
1074
|
+
* loop. Atlas does publish a Windows binary; `resolveLocalBin` finds it through
|
|
1075
|
+
* `where atlas` once it is on PATH. Only x64 is built: Windows on Arm runs it
|
|
1076
|
+
* under emulation.
|
|
1077
|
+
*/
|
|
1078
|
+
function describeAtlasWindowsInstall(version = ATLAS_WINDOWS_VERSION) {
|
|
1079
|
+
return [
|
|
1080
|
+
" The @ariga/atlas npm package has no Windows build, so it cannot install here.",
|
|
1081
|
+
" Install Atlas's own Windows binary instead. In PowerShell:",
|
|
1082
|
+
"",
|
|
1083
|
+
" $dir = \"$env:LOCALAPPDATA\\Programs\\atlas\"",
|
|
1084
|
+
" New-Item -ItemType Directory -Force $dir | Out-Null",
|
|
1085
|
+
` Invoke-WebRequest ${`https://release.ariga.io/atlas/atlas-windows-amd64-v${version}.exe`} -OutFile "$dir\\atlas.exe"`,
|
|
1086
|
+
" [Environment]::SetEnvironmentVariable(\"Path\", [Environment]::GetEnvironmentVariable(\"Path\", \"User\") + \";$dir\", \"User\")",
|
|
1087
|
+
"",
|
|
1088
|
+
" Then open a new terminal, check it with `atlas version`, and run the command again.",
|
|
1089
|
+
" Only `db push`, `db generate` and `db migrate` need Atlas; `rebase dev` does not.",
|
|
1090
|
+
" Guide: https://rebase.pro/docs/getting-started/windows/"
|
|
1091
|
+
];
|
|
1092
|
+
}
|
|
1044
1093
|
/** A path as one shell word: as it is when it needs no quoting, single-quoted otherwise. */
|
|
1045
1094
|
var shellWord = (value) => /^[\w./-]+$/.test(value) ? value : `'${value.replace(/'/g, "'\\''")}'`;
|
|
1046
1095
|
/**
|
|
@@ -1745,6 +1794,31 @@ function isSslNotEnabled(err) {
|
|
|
1745
1794
|
if (e.cause && typeof e.cause === "object") return isSslNotEnabled(e.cause);
|
|
1746
1795
|
return false;
|
|
1747
1796
|
}
|
|
1797
|
+
/** Node's codes for a server certificate no trusted authority vouches for. */
|
|
1798
|
+
var UNTRUSTED_CERTIFICATE_CODES = /* @__PURE__ */ new Set([
|
|
1799
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
1800
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
1801
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
1802
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY"
|
|
1803
|
+
]);
|
|
1804
|
+
/**
|
|
1805
|
+
* Whether the connection failed because the server's certificate is not signed
|
|
1806
|
+
* by an authority Node trusts.
|
|
1807
|
+
*
|
|
1808
|
+
* Almost always a managed database whose URL says `sslmode=require`:
|
|
1809
|
+
* node-postgres reads `require` as `verify-full`, where libpq — `psql`, Atlas,
|
|
1810
|
+
* the provider's own docs — reads it as "encrypted, not verified". The same
|
|
1811
|
+
* URL that `psql` accepts then fails here with `self-signed certificate`.
|
|
1812
|
+
* Matched on the error code, through Drizzle's `cause` and a dual-stack
|
|
1813
|
+
* `AggregateError`.
|
|
1814
|
+
*/
|
|
1815
|
+
function isUntrustedServerCertificate(err) {
|
|
1816
|
+
if (!err || typeof err !== "object") return false;
|
|
1817
|
+
if ("code" in err && typeof err.code === "string" && UNTRUSTED_CERTIFICATE_CODES.has(err.code)) return true;
|
|
1818
|
+
if ("cause" in err && isUntrustedServerCertificate(err.cause)) return true;
|
|
1819
|
+
if (err instanceof AggregateError) return err.errors.some(isUntrustedServerCertificate);
|
|
1820
|
+
return false;
|
|
1821
|
+
}
|
|
1748
1822
|
/**
|
|
1749
1823
|
* The database a connection was refused by because it is closed to new
|
|
1750
1824
|
* connections (`ALLOW_CONNECTIONS false`), or null.
|
|
@@ -1899,6 +1973,37 @@ function formatSslNotEnabledBanner(databaseUrl) {
|
|
|
1899
1973
|
❌ SSL is not enabled on the PostgreSQL server at ${hostInfo}\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n The client tried to connect over SSL, but the server does not\n support it. This is normal for a plain local dev database.\n\n Fix: append ${chalk.bold("sslmode=disable")} to DATABASE_URL, e.g.\n\n DATABASE_URL=...${suggestion}\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
|
1900
1974
|
}
|
|
1901
1975
|
/**
|
|
1976
|
+
* `databaseUrl` with `sslmode=no-verify` in place of its own `sslmode`, the
|
|
1977
|
+
* password masked, for a banner to print. Null when it is not a postgres URL.
|
|
1978
|
+
*/
|
|
1979
|
+
function withNoVerify(databaseUrl) {
|
|
1980
|
+
let url;
|
|
1981
|
+
try {
|
|
1982
|
+
url = new URL(databaseUrl);
|
|
1983
|
+
} catch {
|
|
1984
|
+
return null;
|
|
1985
|
+
}
|
|
1986
|
+
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") return null;
|
|
1987
|
+
if (url.password) url.password = "***";
|
|
1988
|
+
url.searchParams.delete("uselibpqcompat");
|
|
1989
|
+
url.searchParams.set("sslmode", "no-verify");
|
|
1990
|
+
url.search = Array.from(url.searchParams.entries()).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`).join("&");
|
|
1991
|
+
return url.toString();
|
|
1992
|
+
}
|
|
1993
|
+
/**
|
|
1994
|
+
* The banner for a server certificate Node does not trust. See
|
|
1995
|
+
* {@link isUntrustedServerCertificate}. Both ways out are named: verify it
|
|
1996
|
+
* against the provider's CA, or encrypt without verifying, which is what
|
|
1997
|
+
* `sslmode=require` already means to every libpq tool.
|
|
1998
|
+
*/
|
|
1999
|
+
function formatUntrustedCertificateBanner(databaseUrl) {
|
|
2000
|
+
const hostInfo = parseHostInfo(databaseUrl);
|
|
2001
|
+
const suggestion = withNoVerify(databaseUrl);
|
|
2002
|
+
return `
|
|
2003
|
+
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
|
|
2004
|
+
❌ The certificate of the PostgreSQL server at ${hostInfo} is not trusted\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n\n The server's certificate is not signed by an authority Node trusts.\n Rebase's Postgres driver reads ${chalk.bold("sslmode=require")} as "encrypt and verify\n the certificate", which is stricter than what ${chalk.bold("require")} means to psql.\n\n To encrypt without verifying, as psql does, use ${chalk.bold("sslmode=no-verify")}:\n\n DATABASE_URL=${suggestion ?? "postgresql://…?sslmode=no-verify"}\n\n Rebase's CLI passes it to Atlas, pg_dump and psql as sslmode=require.\n To verify instead, download the provider's CA certificate and use\n ${chalk.bold("sslmode=verify-full&sslrootcert=/path/to/ca.pem")}.\n\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`;
|
|
2005
|
+
}
|
|
2006
|
+
/**
|
|
1902
2007
|
* Format a diagnostic banner for a database closed to new connections.
|
|
1903
2008
|
*
|
|
1904
2009
|
* Nothing in a development database closes one but `rebase db branch create
|
|
@@ -1978,6 +2083,7 @@ function diagnoseDbError(err, databaseUrl) {
|
|
|
1978
2083
|
if (isEconnrefused(err)) return formatConnectionRefusedBanner(databaseUrl || "", err);
|
|
1979
2084
|
if (isAuthFailure(err)) return formatAuthFailureBanner(databaseUrl || "", err);
|
|
1980
2085
|
if (isSslNotEnabled(err)) return formatSslNotEnabledBanner(databaseUrl || "");
|
|
2086
|
+
if (isUntrustedServerCertificate(err)) return formatUntrustedCertificateBanner(databaseUrl || "");
|
|
1981
2087
|
const closed = closedDatabaseName(err);
|
|
1982
2088
|
if (closed) return formatClosedDatabaseBanner(databaseUrl || "", closed, err);
|
|
1983
2089
|
if (isDependencyDropError(err)) return formatDependencyDropBanner();
|
|
@@ -2612,6 +2718,6 @@ function assertNoCollectionsFlag(args) {
|
|
|
2612
2718
|
if (sentence !== null) throw new Error(sentence);
|
|
2613
2719
|
}
|
|
2614
2720
|
//#endregion
|
|
2615
|
-
export {
|
|
2721
|
+
export { decidePushSafety as $, dropDevDatabase as A, queryGeneratedColumnDependencies as B, closeAppClients as C, describeReinstallCommand as D, describeDevAddCommand as E, getTableExcludes as F, readViewsDdl as G, readSearchDdl as H, getTriggerExcludes as I, workspaceMemberDir as J, resolveLocalBin as K, getUndeclaredConstraintExcludes as L, ensureDevDatabaseExists as M, getForeignIndexExcludes as N, detectProjectPackageManager as O, getSearchExcludes as P, prepareGeneratedSqlDir as Q, getVectorExcludes as R, cli_helpers_exports as S, describeBuildScriptRemedy as T, readTriggersDdl as U, queryUndeclarableConstraints as V, readVectorDdl as W, GENERATED_SQL_DIR as X, DESIRED_STATE_URL as Y, generatedSqlDir as Z, applySearchDdl as _, closedDatabaseName as a, warnIfYesApprovedDestructive as at, applyViewsDdl as b, diagnoseDbError as c, redactConnectionPasswords as ct, isEconnrefused as d, destructiveOptInFlag as et, isSslNotEnabled as f, ExcludeIntrospectionError as g, reportCommandFailure as h, checkDatabaseConnectivity as i, isSyncedPlan as it, dropGeneratedColumns as j, diagnoseMissingBin as k, formatForeignGeneratedColumnBanner as l, splitPassword as lt, parseHostInfo as m, assertNoCollectionsFlag as n, extractPlanStatements as nt, deepestErrorMessage as o, forAtlas as ot, isUntrustedServerCertificate as p, withAppClient as q, assertSchemaDirExists as r, fromAlterTable as rt, diagnoseAtlasFailure as s, forLibpq as st, DEFAULT_SCHEMA_DIR as t, detectDestructiveStatements as tt, isAuthFailure as u, extractCauseMessage as ut, applyTriggersDdl as v, describeAtlasWindowsInstall as w, atlasDevDatabaseUrl as x, applyVectorDdl as y, queryColumnTypes as z };
|
|
2616
2722
|
|
|
2617
|
-
//# sourceMappingURL=cli-schema-dir-
|
|
2723
|
+
//# sourceMappingURL=cli-schema-dir-CjDH_31U.js.map
|