@rebasepro/cli 0.32.0 → 0.33.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{build-BfdT-AUR.js → build-E5hfEWKj.js} +13 -2
- package/dist/build-E5hfEWKj.js.map +1 -0
- package/dist/{cloud-MqnyPnmX.js → cloud-DNJyUU0T.js} +310 -120
- package/dist/cloud-DNJyUU0T.js.map +1 -0
- package/dist/codemod/collections-to-tables/customization.d.ts +5 -0
- package/dist/{command-D9g46gg9.js → command-Bks5xkrQ.js} +22 -3
- package/dist/command-Bks5xkrQ.js.map +1 -0
- package/dist/commands/cloud/env.d.ts +11 -1
- package/dist/commands/cloud/service-key.d.ts +33 -1
- package/dist/{doctor-2Jlau0Rm.js → doctor-FaBObSlb.js} +21 -3
- package/dist/doctor-FaBObSlb.js.map +1 -0
- package/dist/doctor-environment.d.ts +9 -0
- package/dist/index.es.js +9 -9
- package/dist/legacy-layout-DI2VeQSV.js +36 -0
- package/dist/legacy-layout-DI2VeQSV.js.map +1 -0
- package/dist/{logs-CIgfLBsu.js → logs-DpuMukJe.js} +2 -2
- package/dist/{logs-CIgfLBsu.js.map → logs-DpuMukJe.js.map} +1 -1
- package/dist/{migrate-Cx8-Y4TG.js → migrate-CSY9ZDKy.js} +3 -3
- package/dist/{migrate-Cx8-Y4TG.js.map → migrate-CSY9ZDKy.js.map} +1 -1
- package/dist/{upgrade-DhpUFb6p.js → upgrade-ZASvgxWM.js} +38 -6
- package/dist/{upgrade-DhpUFb6p.js.map → upgrade-ZASvgxWM.js.map} +1 -1
- package/dist/utils/legacy-layout.d.ts +22 -0
- package/package.json +10 -10
- package/templates/overlays/baas/backend/package.json +3 -1
- package/templates/template/backend/package.json +3 -1
- package/dist/build-BfdT-AUR.js.map +0 -1
- package/dist/cloud-MqnyPnmX.js.map +0 -1
- package/dist/command-D9g46gg9.js.map +0 -1
- package/dist/doctor-2Jlau0Rm.js.map +0 -1
|
@@ -76,10 +76,20 @@ export declare function resolveEnvSetArgs(rawArgs: string[]): {
|
|
|
76
76
|
* count of command words is the same for all of them.
|
|
77
77
|
*/
|
|
78
78
|
export declare function resolveEnvKeyArg(rawArgs: string[], action: string): string | undefined;
|
|
79
|
-
/**
|
|
79
|
+
/**
|
|
80
|
+
* {@link resolveEnvKeyArg}, and whether `--preview` was given (`unset` and
|
|
81
|
+
* `reset` take it).
|
|
82
|
+
*
|
|
83
|
+
* `reveal` takes it too, with the preview's name after it, and only for
|
|
84
|
+
* `REBASE_SERVICE_KEY` — the one value a backend preview holds that is neither
|
|
85
|
+
* production's nor an override `env list --preview` already shows. The name
|
|
86
|
+
* is a positional, as in `logs --preview <name>`, so `--preview` stays the
|
|
87
|
+
* switch it is everywhere else.
|
|
88
|
+
*/
|
|
80
89
|
export declare function resolveEnvKeyArgs(rawArgs: string[], action: string): {
|
|
81
90
|
key: string | undefined;
|
|
82
91
|
preview: boolean;
|
|
92
|
+
previewName: string | undefined;
|
|
83
93
|
yes: boolean;
|
|
84
94
|
};
|
|
85
95
|
/**
|
|
@@ -1,4 +1,13 @@
|
|
|
1
|
-
|
|
1
|
+
import { type CloudClient } from "./context.js";
|
|
2
|
+
export declare const SERVICE_KEY_FLAGS: {
|
|
3
|
+
/**
|
|
4
|
+
* A backend preview's own key instead of production's, the preview named by
|
|
5
|
+
* the positional after the action. A switch, as `deploy --preview` and
|
|
6
|
+
* `logs --preview <name>` have it: the dispatcher's list of flags that take
|
|
7
|
+
* a value is one list for the family (`value-flags.test.ts`).
|
|
8
|
+
*/
|
|
9
|
+
readonly "--preview": BooleanConstructor;
|
|
10
|
+
};
|
|
2
11
|
export declare const SERVICE_KEY_ACTIONS: readonly ["rotate"];
|
|
3
12
|
/** What `GET /credentials/:projectId/service-key` answers. Never the key. */
|
|
4
13
|
export interface CliServiceKeyStatus {
|
|
@@ -12,4 +21,27 @@ export interface CliServiceKeyRotation {
|
|
|
12
21
|
generation: number;
|
|
13
22
|
state: "restarting" | "pending";
|
|
14
23
|
}
|
|
24
|
+
/** What `POST /previews/:projectId/:name/service-key/reveal` answers. */
|
|
25
|
+
export interface CliPreviewServiceKey {
|
|
26
|
+
preview: string;
|
|
27
|
+
url: string;
|
|
28
|
+
key: "REBASE_SERVICE_KEY";
|
|
29
|
+
value: string;
|
|
30
|
+
}
|
|
31
|
+
/** What a preview's rotation answers. Never the key. */
|
|
32
|
+
export interface CliPreviewServiceKeyRotation {
|
|
33
|
+
preview: string;
|
|
34
|
+
url: string;
|
|
35
|
+
state: "restarting" | "pending";
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The preview `--preview` names, as the control plane spells it.
|
|
39
|
+
*
|
|
40
|
+
* Only trimmed and lowercased: the control plane decides which names exist,
|
|
41
|
+
* and answers `not_found` for the rest. `deploy`'s stricter name check is for
|
|
42
|
+
* a name about to be created.
|
|
43
|
+
*/
|
|
44
|
+
export declare function previewNameArg(raw: string | undefined, usage: string): string;
|
|
45
|
+
/** Read a backend preview's own key. `env reveal REBASE_SERVICE_KEY --preview <name>` lands here too. */
|
|
46
|
+
export declare function revealPreviewServiceKey(client: CloudClient, projectId: string, name: string): Promise<void>;
|
|
15
47
|
export declare function serviceKeyCommand(rawArgs: string[]): Promise<void>;
|
|
@@ -124,6 +124,13 @@ function scanTextForLibpqUrls(file, text) {
|
|
|
124
124
|
* check has a fixture that fails it without a filesystem, a project or a
|
|
125
125
|
* database.
|
|
126
126
|
*/
|
|
127
|
+
/**
|
|
128
|
+
* The Atlas release Windows readers are sent: the floor of the scaffold's
|
|
129
|
+
* `@ariga/atlas` range, the oldest release it accepts (the npm version is the
|
|
130
|
+
* Atlas version). `tooling/scripts/check-templates.mjs` holds it to that range,
|
|
131
|
+
* beside the same constant in `@rebasepro/server-postgres`.
|
|
132
|
+
*/
|
|
133
|
+
var ATLAS_WINDOWS_VERSION = "1.2.3";
|
|
127
134
|
/** `@ariga/atlas` added as a dev dependency where the project keeps it. */
|
|
128
135
|
function atlasAddCommand(manager, workspaceDir) {
|
|
129
136
|
const pkg = "@ariga/atlas";
|
|
@@ -154,6 +161,12 @@ function atlasAddCommand(manager, workspaceDir) {
|
|
|
154
161
|
*/
|
|
155
162
|
function checkAtlasBinary(state) {
|
|
156
163
|
if (!state || state.onPath) return [];
|
|
164
|
+
if (state.platform === "win32") return [{
|
|
165
|
+
check: "atlas",
|
|
166
|
+
severity: "warning",
|
|
167
|
+
message: "atlas.exe is not on PATH — the @ariga/atlas npm package has no Windows build, so `db push`, `db generate` and `db migrate` will fail. `rebase dev` does not need it.",
|
|
168
|
+
fix: `Download https://release.ariga.io/atlas/atlas-windows-amd64-v${ATLAS_WINDOWS_VERSION}.exe, save it as atlas.exe in a folder on PATH, and open a new terminal. Step by step: https://rebase.pro/docs/getting-started/windows/`
|
|
169
|
+
}];
|
|
157
170
|
if (!state.packageInstalled) return [{
|
|
158
171
|
check: "atlas",
|
|
159
172
|
severity: "warning",
|
|
@@ -534,7 +547,7 @@ function readAtlasBinaryState(projectRoot) {
|
|
|
534
547
|
manifest = resolveFrom(base, "@ariga/atlas/package.json");
|
|
535
548
|
if (manifest) break;
|
|
536
549
|
}
|
|
537
|
-
const onPath = findUpwards([...roots, ...driverManifests.map((file) => path.dirname(file))], path.join(".bin", "atlas")) !== null;
|
|
550
|
+
const onPath = findUpwards([...roots, ...driverManifests.map((file) => path.dirname(file))], path.join(".bin", "atlas")) !== null || process.platform === "win32" && windowsPathHas("atlas.exe");
|
|
538
551
|
let binaryOnDisk = false;
|
|
539
552
|
if (manifest) try {
|
|
540
553
|
const pkg = JSON.parse(fs.readFileSync(manifest, "utf-8"));
|
|
@@ -546,9 +559,14 @@ function readAtlasBinaryState(projectRoot) {
|
|
|
546
559
|
packageInstalled: manifest !== null,
|
|
547
560
|
binaryOnDisk,
|
|
548
561
|
manager: readPackageManagerName(projectRoot),
|
|
549
|
-
workspaceDir: fs.existsSync(path.join(projectRoot, "backend", "package.json")) && isWorkspaceRoot(projectRoot) ? "backend" : null
|
|
562
|
+
workspaceDir: fs.existsSync(path.join(projectRoot, "backend", "package.json")) && isWorkspaceRoot(projectRoot) ? "backend" : null,
|
|
563
|
+
platform: process.platform
|
|
550
564
|
};
|
|
551
565
|
}
|
|
566
|
+
/** Whether a directory on `PATH` holds `file`. `Path` is how Windows spells it. */
|
|
567
|
+
function windowsPathHas(file) {
|
|
568
|
+
return (process.env.PATH ?? process.env.Path ?? "").split(path.delimiter).some((dir) => dir !== "" && fs.existsSync(path.join(dir, file)));
|
|
569
|
+
}
|
|
552
570
|
/** Whether `dir` is a workspace root, where `pnpm add` refuses without `-w`. */
|
|
553
571
|
function isWorkspaceRoot(dir) {
|
|
554
572
|
if (fs.existsSync(path.join(dir, "pnpm-workspace.yaml"))) return true;
|
|
@@ -797,4 +815,4 @@ async function doctorCommand(rawArgs) {
|
|
|
797
815
|
//#endregion
|
|
798
816
|
export { doctorCommand };
|
|
799
817
|
|
|
800
|
-
//# sourceMappingURL=doctor-
|
|
818
|
+
//# sourceMappingURL=doctor-FaBObSlb.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"doctor-FaBObSlb.js","names":[],"sources":["../src/utils/libpq-url.ts","../src/doctor-environment.ts","../src/commands/doctor.ts"],"sourcesContent":["/**\n * Detect Postgres connection strings that libpq refuses to parse.\n *\n * libpq splits a URI query parameter on the FIRST `=` and rejects any further\n * one in the same parameter:\n *\n * extra key/value separator \"=\" in URI query parameter: \"options\"\n *\n * That makes a URL like\n *\n * postgresql://u:p@h:5432/db?options=-c%20search_path=public&sslmode=disable\n *\n * unusable by every libpq caller — `pg_dump`/`pg_restore` behind\n * `rebase db backup|restore`, and a plain `psql \"$DATABASE_URL\"`. It is not a\n * version quirk: Postgres 15 through 18 all refuse it.\n *\n * `rebase init` generated exactly that string until 2026-08-18, and the failure\n * is invisible day to day because node-postgres parses URLs itself and accepts\n * it — so `rebase dev` and `rebase db push` work while backups do not. Fixing\n * the generator does nothing for projects that already exist, which is what\n * these functions are for: `rebase doctor` reads them off disk and reports.\n */\n\n/** A query parameter whose value carries a literal `=`. */\nexport interface UnparseableParam {\n /** The parameter name, e.g. \"options\". */\n name: string;\n /** The raw `name=value` text as it appears in the URL. */\n raw: string;\n}\n\n/** Postgres URI schemes. A key/value DSN (\"host=… dbname=…\") is not one. */\nconst POSTGRES_URI_RE = /^postgres(ql)?:\\/\\//i;\n\n/**\n * Return the query parameters libpq would reject, or an empty array.\n *\n * Deliberately not built on `new URL()`: that parser is happy to accept the\n * broken form (it splits on the first `=` and keeps the rest as the value),\n * so it cannot see the defect at all. The rule being checked is libpq's, and\n * it is about the raw text.\n */\nexport function findUnparseableParams(connectionString: string): UnparseableParam[] {\n if (!POSTGRES_URI_RE.test(connectionString)) return [];\n\n const q = connectionString.indexOf(\"?\");\n if (q === -1) return [];\n\n // A fragment is not part of the query.\n const query = connectionString.slice(q + 1).split(\"#\")[0];\n if (!query) return [];\n\n const found: UnparseableParam[] = [];\n for (const part of query.split(\"&\")) {\n if (!part) continue;\n // One separator is the parameter's own; any further one is the defect.\n if (part.split(\"=\").length > 2) {\n found.push({ name: part.slice(0, part.indexOf(\"=\")), raw: part });\n }\n }\n return found;\n}\n\n/**\n * Percent-encode the offending `=` characters, leaving everything else byte for\n * byte as it was.\n *\n * Only the second and later `=` in a parameter are rewritten — the first is the\n * real separator. Nothing else is touched: re-serialising through `URL` would\n * also reorder parameters and turn spaces into `+`, which libpq does not decode,\n * so a \"tidy up\" would trade one unparseable string for another.\n */\nexport function encodeExtraEquals(connectionString: string): string {\n if (findUnparseableParams(connectionString).length === 0) return connectionString;\n\n const q = connectionString.indexOf(\"?\");\n const head = connectionString.slice(0, q + 1);\n const rest = connectionString.slice(q + 1);\n const hash = rest.indexOf(\"#\");\n const query = hash === -1 ? rest : rest.slice(0, hash);\n const fragment = hash === -1 ? \"\" : rest.slice(hash);\n\n const fixed = query.split(\"&\").map(encodeParamExtraEquals).join(\"&\");\n\n return `${head}${fixed}${fragment}`;\n}\n\n/** One `name=value` query parameter with every `=` after its separator encoded. */\nfunction encodeParamExtraEquals(part: string): string {\n const first = part.indexOf(\"=\");\n if (first === -1) return part;\n return `${part.slice(0, first)}=${part.slice(first + 1).replace(/=/g, \"%3D\")}`;\n}\n\n/** One connection string, found somewhere on disk, that libpq cannot parse. */\nexport interface LibpqUrlFinding {\n /** File it came from, relative to the project root. */\n file: string;\n /** The variable holding it, e.g. \"DATABASE_URL\". */\n variable: string;\n /** Parameter names libpq objects to. */\n params: string[];\n /** The same string with the offending `=` encoded. */\n suggested: string;\n /**\n * Each offending parameter as it is, and as it should be. What a report\n * prints: the whole string carries the database password.\n */\n fixes: Array<{ from: string; to: string }>;\n}\n\n/** Variables whose value is a Postgres connection string. */\nconst CONNECTION_VARIABLES = [\"DATABASE_URL\", \"ADMIN_CONNECTION_STRING\"];\n\n/**\n * Scan one file's text for connection strings libpq would reject.\n *\n * Handles both shapes a scaffolded project uses, because both shipped with the\n * defect and a deployed stack is broken by the compose one alone:\n *\n * .env DATABASE_URL=postgresql://…\n * docker-compose.yml DATABASE_URL: postgresql://…\n */\nexport function scanTextForLibpqUrls(file: string, text: string): LibpqUrlFinding[] {\n const findings: LibpqUrlFinding[] = [];\n\n for (const line of text.split(\"\\n\")) {\n const trimmed = line.trim();\n // Commented-out examples are not what the project runs on.\n if (trimmed.startsWith(\"#\")) continue;\n\n for (const variable of CONNECTION_VARIABLES) {\n // `NAME=value` or `NAME: value`, optionally exported/indented.\n const match = trimmed.match(\n new RegExp(`^(?:export\\\\s+)?${variable}\\\\s*[:=]\\\\s*(.+)$`)\n );\n if (!match) continue;\n\n // Strip surrounding quotes and any trailing comment-free whitespace.\n let value = match[1].trim();\n const quoted = value.match(/^(['\"])(.*)\\1$/);\n if (quoted) value = quoted[2];\n if (!value) continue;\n\n const params = findUnparseableParams(value);\n if (params.length === 0) continue;\n\n findings.push({\n file,\n variable,\n params: params.map((p) => p.name),\n suggested: encodeExtraEquals(value),\n fixes: params.map((p) => ({ from: p.raw, to: encodeParamExtraEquals(p.raw) }))\n });\n }\n }\n\n return findings;\n}\n","/**\n * The checks that need no database, and that catch what breaks a first run.\n *\n * `rebase doctor` compared three descriptions of a schema, which is the right\n * check for a project that is working and the wrong one for a project that has\n * never worked. Everything that stops a first run — the wrong Node, two\n * lockfiles disagreeing, two tables claiming one slug, a `JWT_SECRET`\n * short enough to be guessed, a half-installed workspace with three versions of\n * `@rebasepro/server` in it — happens before a single table is compared, and\n * doctor said nothing about any of it.\n *\n * Every function here is pure: it takes what it read and returns findings. The\n * reading and the printing are at the edges, in `commands/doctor.ts`, so each\n * check has a fixture that fails it without a filesystem, a project or a\n * database.\n */\nimport dotenv from \"dotenv\";\n\n/** One thing that is wrong, and what to do about it. */\nexport interface EnvironmentFinding {\n /** Which check produced it, for grouping in the report. */\n check: \"node\" | \"package-manager\" | \"tables\" | \"env\" | \"versions\" | \"atlas\";\n severity: \"error\" | \"warning\";\n message: string;\n fix: string;\n}\n\n// ── Atlas ────────────────────────────────────────────────────────────────\n\n/** What is on disk for `@ariga/atlas`, read by `commands/doctor.ts`. */\nexport interface AtlasBinaryState {\n /** A `node_modules/.bin/atlas` the project's commands would find. */\n onPath: boolean;\n /** `@ariga/atlas/package.json` resolves from the project. */\n packageInstalled: boolean;\n /** The binary the package's `bin` names exists as a file. */\n binaryOnDisk: boolean;\n /** For the remedy: the reader's own package manager. */\n manager: string;\n /**\n * The workspace member the install goes into (`backend` in a scaffold),\n * or absent at a project that is no workspace. A scaffold's root refuses\n * `pnpm add` without `-w`, and atlas belongs to the backend anyway.\n */\n workspaceDir?: string | null;\n /** `process.platform`, for the one platform where the npm package cannot install. */\n platform?: NodeJS.Platform;\n}\n\n/**\n * The Atlas release Windows readers are sent: the floor of the scaffold's\n * `@ariga/atlas` range, the oldest release it accepts (the npm version is the\n * Atlas version). `tooling/scripts/check-templates.mjs` holds it to that range,\n * beside the same constant in `@rebasepro/server-postgres`.\n */\nexport const ATLAS_WINDOWS_VERSION = \"1.2.3\";\n\n/** `@ariga/atlas` added as a dev dependency where the project keeps it. */\nfunction atlasAddCommand(manager: string, workspaceDir: string | null | undefined): string {\n const pkg = \"@ariga/atlas\";\n if (!workspaceDir) return `${manager} add -D ${pkg}`;\n switch (manager) {\n case \"npm\": return `npm install -D ${pkg} -w ${workspaceDir}`;\n case \"yarn\": return `yarn --cwd ${workspaceDir} add -D ${pkg}`;\n case \"bun\": return `bun add -d ${pkg} --cwd ${workspaceDir}`;\n default: return `${manager} --dir ${workspaceDir} add -D ${pkg}`;\n }\n}\n\n/**\n * Whether `db push`, `db generate` and `db migrate` can run at all.\n *\n * They shell out to `atlas`, and its absence is invisible until one of them is\n * run: `@ariga/atlas` downloads its platform binary in `preinstall`, pnpm 10+\n * and npm 12+ refuse a dependency's lifecycle scripts unless allowlisted, and\n * the install exits 0 either way. The scaffold allowlists it, so this is a\n * problem for the person who added `@rebasepro/server-postgres` to a project\n * they already had — five lines of `ERR_PNPM_IGNORED_BUILDS` and\n * `Failed to create bin … ENOENT`, several screens up, with nothing saying that\n * a schema push will fail later.\n *\n * Three states, because two of them need opposite advice. The package absent is\n * an install; the package present with no binary is an allowlist; the binary\n * present with no `.bin` shim is a re-install, and telling that reader their\n * build scripts are blocked sends them to a command that does nothing.\n */\nexport function checkAtlasBinary(state: AtlasBinaryState | null): EnvironmentFinding[] {\n if (!state || state.onPath) return [];\n\n // `@ariga/atlas` ships Linux and macOS builds only, so on Windows every\n // remedy below — install it, allow its script, re-install — ends where it\n // started. Atlas's own Windows binary on PATH is the way.\n if (state.platform === \"win32\") {\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"atlas.exe is not on PATH — the @ariga/atlas npm package has no Windows build, so \"\n + \"`db push`, `db generate` and `db migrate` will fail. `rebase dev` does not need it.\",\n fix: `Download https://release.ariga.io/atlas/atlas-windows-amd64-v${ATLAS_WINDOWS_VERSION}.exe, `\n + \"save it as atlas.exe in a folder on PATH, and open a new terminal. \"\n + \"Step by step: https://rebase.pro/docs/getting-started/windows/\"\n }];\n }\n\n if (!state.packageInstalled) {\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"The atlas binary is not on PATH and @ariga/atlas is not installed — \"\n + \"`db push`, `db generate` and `db migrate` will fail.\",\n fix: `Install it: ${atlasAddCommand(state.manager, state.workspaceDir)}, and allow its install script.`\n }];\n }\n\n if (!state.binaryOnDisk) {\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"@ariga/atlas is installed and its binary is missing — its `preinstall` \"\n + \"script was blocked, so `db push` and `db migrate` will fail.\",\n fix: \"Allow the build script (pnpm: `allowBuilds` in pnpm-workspace.yaml or \"\n + \"`pnpm approve-builds`; npm: `allowScripts` in package.json), then re-install.\"\n }];\n }\n\n return [{\n check: \"atlas\",\n severity: \"warning\",\n message: \"The atlas binary is on disk but node_modules/.bin/atlas is missing, \"\n + \"so nothing can invoke it.\",\n fix: \"Re-resolve the tree so the link is recreated: `pnpm install --force`, or delete \"\n + \"node_modules and install again.\"\n }];\n}\n\n// ── Node ─────────────────────────────────────────────────────────────────\n\n/**\n * `20.11.0` → `[20, 11, 0]`, ignoring anything after the patch.\n *\n * A bare major is a version: `>=20` is how every `engines.node` in this repo is\n * written, and requiring a minor here made the whole check return nothing —\n * silently, which is the only way a check like this ever fails.\n */\nfunction parseVersion(raw: string): [number, number, number] | null {\n const match = raw.trim().replace(/^v/, \"\").match(/^(\\d+)(?:\\.(\\d+))?(?:\\.(\\d+))?/);\n if (!match) return null;\n return [Number(match[1]), Number(match[2] ?? 0), Number(match[3] ?? 0)];\n}\n\n/** The lowest version a `>=x.y.z` range admits, or null for anything else. */\nexport function minimumFromRange(range: string): [number, number, number] | null {\n const match = range.match(/>=\\s*v?(\\d+(?:\\.\\d+)?(?:\\.\\d+)?)/);\n return match ? parseVersion(match[1]) : null;\n}\n\nfunction isBelow(actual: [number, number, number], minimum: [number, number, number]): boolean {\n for (let i = 0; i < 3; i++) {\n if (actual[i] < minimum[i]) return true;\n if (actual[i] > minimum[i]) return false;\n }\n return false;\n}\n\n/**\n * Is the running Node old enough to break things that will not say so?\n *\n * The symptoms are not \"unsupported Node\". They are a syntax error inside a\n * dependency, a missing global, or — the one that costs the most time — a\n * `node:` builtin that resolves and then behaves differently. Naming the\n * version is the whole check.\n */\nexport function checkNodeVersion(running: string, required: string | undefined): EnvironmentFinding[] {\n if (!required) return [];\n const minimum = minimumFromRange(required);\n const actual = parseVersion(running);\n if (!minimum || !actual) return [];\n if (!isBelow(actual, minimum)) return [];\n\n return [{\n check: \"node\",\n severity: \"error\",\n message: `Node ${running} is running, and Rebase needs ${required}.`,\n fix: `Install Node ${minimum[0]} or newer (nvm install ${minimum[0]}), then reinstall dependencies.`\n }];\n}\n\n// ── Package manager ──────────────────────────────────────────────────────\n\n/** The lockfiles a project may have, and the manager each one belongs to. */\nexport const LOCKFILES: Record<string, string> = {\n \"pnpm-lock.yaml\": \"pnpm\",\n \"package-lock.json\": \"npm\",\n \"yarn.lock\": \"yarn\",\n \"bun.lockb\": \"bun\"\n};\n\n/**\n * Two package managers in one project.\n *\n * A Rebase project is a pnpm workspace, and running `npm install` inside one\n * rewrites `node_modules` into a hoisted layout that pnpm then disagrees with.\n * The result is not an install error: it is `Cannot find module` from inside a\n * dependency, hours later, on a machine where it worked yesterday. The\n * leftover `package-lock.json` is the only durable evidence, and nothing looked\n * at it.\n */\nexport function checkPackageManager(\n lockfilesPresent: string[],\n declared: string | undefined\n): EnvironmentFinding[] {\n const known = lockfilesPresent.filter(file => file in LOCKFILES);\n if (known.length < 2) {\n // One lockfile, or none. A single one that disagrees with\n // `packageManager` is worth saying too.\n const declaredName = declared?.split(\"@\")[0];\n if (known.length === 1 && declaredName && LOCKFILES[known[0]] !== declaredName) {\n return [{\n check: \"package-manager\",\n severity: \"warning\",\n message: `This project declares packageManager \"${declared}\" and has a ${LOCKFILES[known[0]]} lockfile (${known[0]}).`,\n fix: `Delete ${known[0]} and node_modules, then install with ${declaredName}.`\n }];\n }\n return [];\n }\n\n const managers = known.map(file => LOCKFILES[file]);\n return [{\n check: \"package-manager\",\n severity: \"error\",\n message: `Two package managers have installed here: ${known.join(\" and \")}.`,\n fix: `Keep one. Delete the others and node_modules, then reinstall with ${declared?.split(\"@\")[0] ?? managers[0]}.`\n }];\n}\n\n// ── Tables ───────────────────────────────────────────────────────────────\n\n/**\n * Two tables claiming one slug.\n *\n * The slug is the route, the table lookup and the registry key, and the\n * registry keeps the last one registered. So the loser is not reported missing:\n * it is served as the winner, with the winner's columns, under its own name.\n * Every symptom of this points somewhere else.\n */\nexport function checkDuplicateSlugs(\n tables: Array<{ slug?: string; name?: string }>\n): EnvironmentFinding[] {\n const byslug = new Map<string, number>();\n for (const table of tables) {\n if (!table.slug) continue;\n byslug.set(table.slug, (byslug.get(table.slug) ?? 0) + 1);\n }\n\n return [...byslug]\n .filter(([, count]) => count > 1)\n .map(([slug, count]) => ({\n check: \"tables\" as const,\n severity: \"error\" as const,\n message: `${count} tables declare the slug \"${slug}\". Only the last one registered is served.`,\n fix: `Give each table its own slug. The one that loses is not reported missing — it answers as the winner.`\n }));\n}\n\n// ── .env ─────────────────────────────────────────────────────────────────\n\n/** What `loadEnv` requires of a JWT secret. Mirrors `rebaseEnvSchema`. */\nexport const MIN_JWT_SECRET_LENGTH = 32;\n\n/**\n * The two `.env` facts that fail late and confusingly.\n *\n * A short `JWT_SECRET` boots fine and is refused by `loadEnv` only in\n * production, which is the worst place to find out. Missing CORS in production\n * is the opposite shape — it does not fail at all; the API simply accepts\n * requests from anywhere.\n *\n * Values are never echoed. This reads a file that holds every credential the\n * project has, and doctor's output goes wherever a terminal goes.\n */\nexport function checkEnvSanity(values: Record<string, string>): EnvironmentFinding[] {\n const findings: EnvironmentFinding[] = [];\n const production = values.NODE_ENV === \"production\";\n\n const secret = values.JWT_SECRET;\n if (secret !== undefined && secret.length > 0 && secret.length < MIN_JWT_SECRET_LENGTH) {\n findings.push({\n check: \"env\",\n severity: production ? \"error\" : \"warning\",\n message: `JWT_SECRET is ${secret.length} characters. The runtime requires at least ${MIN_JWT_SECRET_LENGTH}, and refuses to boot below it in production.`,\n fix: \"Generate one: openssl rand -hex 32\"\n });\n }\n\n if (production && !values.CORS_ORIGINS && !values.FRONTEND_URL) {\n findings.push({\n check: \"env\",\n severity: \"error\",\n message: \"NODE_ENV=production with neither CORS_ORIGINS nor FRONTEND_URL set — the API will accept requests from any origin.\",\n fix: \"Set CORS_ORIGINS to the origins that may call this API.\"\n });\n }\n\n return findings;\n}\n\n/**\n * Parse a `.env` into a plain object, the way the runtime reads it.\n *\n * `dotenv.parse`, not `dotenv.config`: this must not touch `process.env`, and\n * doctor may be reading a file for a different environment than the one it is\n * running in. And dotenv's grammar, not a line splitter: the server loads this\n * file with dotenv, so `NODE_ENV=production # deploy` is production to it, and\n * a reading that kept the comment in the value judged the file as development\n * and skipped every production check.\n */\nexport function parseEnvFile(text: string): Record<string, string> {\n return dotenv.parse(text);\n}\n\n// ── Version skew ─────────────────────────────────────────────────────────\n\n/** One `@rebasepro/*` dependency, and where it was declared. */\nexport interface DeclaredDependency {\n /** Where it was declared, relative to the project root. */\n file: string;\n name: string;\n /** The range exactly as written. */\n range: string;\n}\n\n/**\n * The same `@rebasepro/*` package pinned to different versions in one project.\n *\n * A Rebase project declares them in several package.json files — the root, the\n * backend, the frontend — and nothing has ever compared\n * them. The failure that produces is not an install error: pnpm installs both,\n * `instanceof` stops working across the two copies, and the symptom is a\n * table definition that fails a type guard written against an identical type.\n *\n * `workspace:` ranges are excluded: inside this repo's own workspaces they all\n * resolve to the same build by construction.\n */\nexport function checkVersionSkew(declared: DeclaredDependency[]): EnvironmentFinding[] {\n const byPackage = new Map<string, Map<string, string[]>>();\n\n for (const dependency of declared) {\n if (!dependency.name.startsWith(\"@rebasepro/\")) continue;\n if (dependency.range.startsWith(\"workspace:\") || dependency.range.startsWith(\"link:\")) continue;\n if (dependency.range === \"*\" || dependency.range === \"latest\") continue;\n\n const ranges = byPackage.get(dependency.name) ?? new Map<string, string[]>();\n ranges.set(dependency.range, [...(ranges.get(dependency.range) ?? []), dependency.file]);\n byPackage.set(dependency.name, ranges);\n }\n\n const findings: EnvironmentFinding[] = [];\n for (const [name, ranges] of byPackage) {\n if (ranges.size < 2) continue;\n const described = [...ranges]\n .map(([range, files]) => `${range} (${files.join(\", \")})`)\n .join(\", \");\n findings.push({\n check: \"versions\",\n severity: \"error\",\n message: `${name} is pinned to different versions in this project: ${described}.`,\n fix: \"Run `rebase upgrade` to pin every @rebasepro package to one release and reinstall. Two copies of a Rebase package break `instanceof` between them, which fails as a type guard rejecting its own type.\"\n });\n }\n return findings;\n}\n","/**\n * CLI command: rebase doctor\n *\n * Detects three-way schema drift between the tables `backend/schema`\n * declares, the generated Drizzle schema, and the live PostgreSQL database.\n */\nimport chalk from \"chalk\";\nimport fs from \"fs\";\nimport path from \"path\";\nimport { execa } from \"execa\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { fileURLToPath, pathToFileURL } from \"url\";\nimport { createRequire } from \"module\";\nimport { scanTextForLibpqUrls, type LibpqUrlFinding } from \"../utils/libpq-url\";\nimport { redactConnectionPasswords } from \"../utils/redact\";\nimport { analyseFunctionsDirectory, summarisePortability } from \"../function-portability\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { SCHEMA_DIR_FLAG_HELP, refuseMissingSchemaDir, refuseRemovedCollectionsFlag } from \"../utils/path-flags\";\nimport { schemaDirArgs, resolveSchemaDir } from \"../utils/schema-dir\";\nimport { declaredTables } from \"../utils/schema-text\";\nimport { absolutizeLocalPathArgs, DATABASE_SOURCE_ENV } from \"./db\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { loadManifest, findBackendApp, resolveBackendPaths } from \"../manifest\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport {\n checkDuplicateSlugs,\n checkEnvSanity,\n checkAtlasBinary,\n checkNodeVersion,\n checkPackageManager,\n checkVersionSkew,\n LOCKFILES,\n parseEnvFile,\n type AtlasBinaryState,\n type DeclaredDependency,\n type EnvironmentFinding\n} from \"../doctor-environment\";\n\n/**\n * Files that can hold a connection string the project actually runs on.\n *\n * `.env` is what local commands read; the compose files are what a self-hosted\n * stack and its scheduled backup cron read. Both shipped with the defect, and a\n * deployed stack is broken by the compose one even when `.env` has been fixed.\n * `.env.example` is deliberately absent: nothing runs on it.\n */\nconst CONNECTION_FILES = [\n \".env\",\n \".env.local\",\n \"docker-compose.yml\",\n \"docker-compose.yaml\",\n \"docker-compose.custom.yml\"\n];\n\n/**\n * Find connection strings libpq cannot parse, anywhere in the project.\n *\n * Exported for the tests; `envFile` is passed separately because a project may\n * keep its `.env` outside the root (see `findEnvFile`).\n */\nexport function findLibpqUrlProblems(projectRoot: string, envFile?: string | null): LibpqUrlFinding[] {\n const candidates = CONNECTION_FILES.map((f) => path.join(projectRoot, f));\n if (envFile) candidates.push(envFile);\n\n const findings: LibpqUrlFinding[] = [];\n const seen = new Set<string>();\n\n for (const file of candidates) {\n if (seen.has(file)) continue;\n seen.add(file);\n let text: string;\n try {\n if (!fs.existsSync(file)) continue;\n text = fs.readFileSync(file, \"utf-8\");\n } catch {\n // Unreadable is not a finding — doctor reports what it can see.\n continue;\n }\n findings.push(...scanTextForLibpqUrls(path.relative(projectRoot, file) || path.basename(file), text));\n }\n\n return findings;\n}\n\n/**\n * Report unparseable connection strings, if any. Returns true when there were,\n * so the finding reaches the exit code like the environment errors do.\n *\n * Runs before the plugin's drift check and never blocks it. The plugin connects\n * through node-postgres, which parses these URLs happily — so it cannot see this\n * defect, and a project with it will otherwise get a clean bill of health while\n * `rebase db backup` fails.\n */\nexport function reportLibpqUrlProblems(findings: LibpqUrlFinding[]): boolean {\n if (findings.length === 0) return false;\n\n console.log(\"\");\n console.log(chalk.red.bold(\" ✗ Connection string that PostgreSQL's own tools cannot parse\"));\n console.log(\"\");\n for (const f of findings) {\n console.log(` ${chalk.bold(f.file)} → ${chalk.bold(f.variable)}`);\n console.log(chalk.gray(` the \"${f.params.join('\", \"')}\" parameter contains an unencoded \"=\". In the value, replace:`));\n // The parameter, not the whole string: the string carries the\n // database password, and this report lands in terminals, CI logs and\n // an assistant's context. A `password=` parameter is masked too.\n for (const fix of f.fixes) {\n console.log(` ${chalk.cyan(redactConnectionPasswords(fix.from))}`);\n console.log(chalk.gray(\" with:\"));\n console.log(` ${chalk.cyan(redactConnectionPasswords(fix.to))}`);\n }\n console.log(\"\");\n }\n console.log(chalk.gray(\" libpq splits a query parameter on the first \\\"=\\\" and rejects any further\"));\n console.log(chalk.gray(\" one, so this fails:\"));\n console.log(chalk.gray(\" extra key/value separator \\\"=\\\" in URI query parameter\"));\n console.log(\"\");\n console.log(chalk.gray(\" Affects rebase db backup / restore, scheduled backups, and psql.\"));\n console.log(chalk.gray(\" NOT rebase dev or db push — those use a driver that accepts it, which\"));\n console.log(chalk.gray(\" is why a project can look healthy and still have no working backups.\"));\n console.log(chalk.gray(\" Projects scaffolded before 2026-08-18 all carry it.\"));\n console.log(\"\");\n return true;\n}\n\n/**\n * `--help` is answered before the project guard, not after.\n *\n * `doctor` declared no `--help` at all, so the flag fell through to the command\n * body and hit `requireProjectRoot()` — and `rebase doctor --help` outside a\n * project answered \"✗ Could not find a Rebase project root.\" Asking a command\n * what it does is the one question that cannot require being somewhere\n * particular to ask.\n */\n/**\n * What each custom function needs from its host.\n *\n * Prints nothing when there is nothing to say — which is the common case, and\n * the reason it can afford to run every time. When it does print, the ordering\n * is deliberate: the one finding that is a bug *today* comes first, and the\n * rest is a single descriptive line about where these functions could run.\n */\nfunction reportFunctionPortability(projectRoot: string): void {\n let results: ReturnType<typeof analyseFunctionsDirectory>;\n try {\n const backend = findBackendApp(loadManifest(projectRoot).manifest);\n if (!backend) return;\n const paths = resolveBackendPaths(backend.app, projectRoot);\n results = analyseFunctionsDirectory(path.join(projectRoot, paths.functions), projectRoot);\n } catch {\n // A project with no manifest, or one shaped differently — doctor has\n // plenty else to report, and this section is advisory.\n return;\n }\n\n const lines = summarisePortability(results);\n if (lines.length === 0) return;\n\n console.log(chalk.bold(\"\\nCustom functions\"));\n for (const line of lines) {\n console.log(line.trimStart().startsWith(\"⚠\") ? chalk.yellow(line) : chalk.gray(line));\n }\n console.log(chalk.gray(\" See https://rebase.pro/docs/backend/custom-functions#runtime-portability\"));\n}\n\n/**\n * Read everything the environment checks need, then run them.\n *\n * The reading is here and the deciding is in `doctor-environment.ts`, so every\n * check has a fixture that fails it without a project on disk.\n */\nexport function collectEnvironmentFindings(\n projectRoot: string,\n envFile: string | null | undefined\n): EnvironmentFinding[] {\n const findings: EnvironmentFinding[] = [];\n\n // Node, against the engines range the installed CLI declares.\n findings.push(...checkNodeVersion(process.versions.node, readCliEngines()));\n\n // Two package managers in one project.\n const rootPackage = readJson(path.join(projectRoot, \"package.json\"));\n findings.push(...checkPackageManager(\n Object.keys(LOCKFILES).filter(file => fs.existsSync(path.join(projectRoot, file))),\n typeof rootPackage?.packageManager === \"string\" ? rootPackage.packageManager : undefined\n ));\n\n // Two tables claiming one slug. Read as text rather than imported: a\n // schema file can import anything, and doctor must not execute a\n // project's code to tell it two slugs collide.\n findings.push(...checkDuplicateSlugs(readDeclaredSlugs(projectRoot)));\n\n // `.env`, values never echoed.\n if (envFile && fs.existsSync(envFile)) {\n try {\n findings.push(...checkEnvSanity(parseEnvFile(fs.readFileSync(envFile, \"utf-8\"))));\n } catch { /* unreadable is not a finding */ }\n }\n\n // One `@rebasepro/*` package, two versions.\n findings.push(...checkVersionSkew(readDeclaredRebaseDeps(projectRoot)));\n\n // The atlas binary, which every schema command shells out to and whose\n // absence is invisible until one of them is run.\n findings.push(...checkAtlasBinary(readAtlasBinaryState(projectRoot)));\n\n return findings;\n}\n\n/**\n * What is actually on disk for `@ariga/atlas`, from the project's point of view.\n *\n * Three separate questions, because the three states they distinguish need\n * three different remedies — see `checkAtlasBinary`. Directories are searched\n * from the project root upwards and through the workspaces a scaffold has,\n * because `db push` runs from `backend/` and the install may be hoisted to the\n * root.\n */\nexport function readAtlasBinaryState(projectRoot: string): AtlasBinaryState | null {\n const roots = [projectRoot, path.join(projectRoot, \"backend\"), path.join(projectRoot, \"config\")];\n\n const findUpwards = (starts: string[], relative: string): string | null => {\n for (const start of starts) {\n let dir = start;\n for (let i = 0; i < 8; i++) {\n const candidate = path.join(dir, \"node_modules\", relative);\n if (fs.existsSync(candidate)) return candidate;\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n }\n return null;\n };\n\n // `@ariga/atlas` is a dependency of `@rebasepro/server-postgres`, not of the\n // project, so under pnpm's isolated layout — the scaffold default — it lives\n // in `.pnpm/` and a directory walk over `node_modules/` never sees it.\n // Resolve through the module graph the way the driver itself does.\n const resolveFrom = (from: string, request: string): string | null => {\n try {\n return createRequire(pathToFileURL(from)).resolve(request);\n } catch {\n return null;\n }\n };\n const bases = roots.map(dir => path.join(dir, \"package.json\")).filter(file => fs.existsSync(file));\n const driverManifests = bases\n .map(base => resolveFrom(base, \"@rebasepro/server-postgres/package.json\"))\n .filter((file): file is string => file !== null);\n\n let manifest: string | null = findUpwards(roots, path.join(\"@ariga\", \"atlas\", \"package.json\"));\n if (!manifest) {\n for (const base of [...bases, ...driverManifests]) {\n manifest = resolveFrom(base, \"@ariga/atlas/package.json\");\n if (manifest) break;\n }\n }\n\n // The `.bin` shim is written beside whichever package declared the\n // dependency, so the driver's own directory is a search root too.\n // On Windows the npm package cannot install at all, so the binary that\n // counts is Atlas's own `atlas.exe` on PATH — the same one the driver\n // finds through `where atlas`.\n const onPath = findUpwards(\n [...roots, ...driverManifests.map(file => path.dirname(file))],\n path.join(\".bin\", \"atlas\")\n ) !== null || (process.platform === \"win32\" && windowsPathHas(\"atlas.exe\"));\n\n let binaryOnDisk = false;\n if (manifest) {\n try {\n const pkg = JSON.parse(fs.readFileSync(manifest, \"utf-8\")) as {\n bin?: string | Record<string, string>;\n };\n const dir = path.dirname(manifest);\n const targets = typeof pkg.bin === \"string\"\n ? [pkg.bin]\n : Object.values(pkg.bin ?? {}).filter((t): t is string => typeof t === \"string\");\n binaryOnDisk = targets.some(target => fs.existsSync(path.resolve(dir, target)));\n } catch { /* unreadable manifest: treat the binary as absent */ }\n }\n\n return {\n onPath,\n packageInstalled: manifest !== null,\n binaryOnDisk,\n manager: readPackageManagerName(projectRoot),\n workspaceDir: fs.existsSync(path.join(projectRoot, \"backend\", \"package.json\")) && isWorkspaceRoot(projectRoot)\n ? \"backend\"\n : null,\n platform: process.platform\n };\n}\n\n/** Whether a directory on `PATH` holds `file`. `Path` is how Windows spells it. */\nfunction windowsPathHas(file: string): boolean {\n const value = process.env.PATH ?? process.env.Path ?? \"\";\n return value.split(path.delimiter).some(dir => dir !== \"\" && fs.existsSync(path.join(dir, file)));\n}\n\n/** Whether `dir` is a workspace root, where `pnpm add` refuses without `-w`. */\nfunction isWorkspaceRoot(dir: string): boolean {\n if (fs.existsSync(path.join(dir, \"pnpm-workspace.yaml\"))) return true;\n try {\n const manifest: unknown = JSON.parse(fs.readFileSync(path.join(dir, \"package.json\"), \"utf8\"));\n return typeof manifest === \"object\" && manifest !== null && \"workspaces\" in manifest;\n } catch {\n return false;\n }\n}\n\n/** The reader's own package manager, from the lockfile beside their project. */\nfunction readPackageManagerName(projectRoot: string): string {\n for (const [file, manager] of Object.entries(LOCKFILES)) {\n if (fs.existsSync(path.join(projectRoot, file))) return manager;\n }\n return \"pnpm\";\n}\n\n/** The `engines.node` range of the CLI actually running. */\nfunction readCliEngines(): string | undefined {\n try {\n const here = path.dirname(fileURLToPath(import.meta.url));\n for (let dir = here, i = 0; i < 5; i++) {\n const candidate = path.join(dir, \"package.json\");\n if (fs.existsSync(candidate)) {\n const parsed = readJson(candidate);\n if (parsed?.name === \"@rebasepro/cli\") {\n const engines = parsed.engines as { node?: string } | undefined;\n return engines?.node;\n }\n }\n const parent = path.dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n } catch { /* the check is advisory */ }\n return undefined;\n}\n\nfunction readJson(file: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(fs.readFileSync(file, \"utf-8\")) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n\n/** Where a project's package.json files live, relative to its root. */\nconst PACKAGE_JSON_LOCATIONS = [\"package.json\", \"backend/package.json\", \"frontend/package.json\", \"config/package.json\"];\n\nfunction readDeclaredRebaseDeps(projectRoot: string): DeclaredDependency[] {\n const declared: DeclaredDependency[] = [];\n for (const relative of PACKAGE_JSON_LOCATIONS) {\n const parsed = readJson(path.join(projectRoot, relative));\n if (!parsed) continue;\n for (const field of [\"dependencies\", \"devDependencies\", \"peerDependencies\"] as const) {\n const block = parsed[field] as Record<string, string> | undefined;\n if (!block) continue;\n for (const [name, range] of Object.entries(block)) {\n if (typeof range === \"string\") declared.push({ file: relative, name, range });\n }\n }\n }\n return declared;\n}\n\n/**\n * Does this project declare its tables in code?\n *\n * `resolveBackendPaths` answers it against the manifest's own `tables` path\n * rather than the convention, because a project may move the directory. A\n * project with no manifest, or one shaped differently, is treated as declaring\n * them: the wrong answer there would silently skip the drift report, which is\n * the reason the command exists.\n */\nexport function hasDeclaredTables(projectRoot: string): boolean {\n try {\n const backend = findBackendApp(loadManifest(projectRoot).manifest);\n if (!backend) return true;\n return resolveBackendPaths(backend.app, projectRoot).hasTables;\n } catch {\n return true;\n }\n}\n\n/** Every table the schema files declare, by slug — read as text, see `utils/schema-text.ts`. */\nfunction readDeclaredSlugs(projectRoot: string): Array<{ slug: string }> {\n return declaredTables(resolveSchemaDir(projectRoot)).map(({ slug }) => ({ slug }));\n}\n\n/** Print what the environment checks found, grouped, or nothing at all. */\nfunction reportEnvironmentFindings(findings: EnvironmentFinding[]): boolean {\n if (findings.length === 0) return false;\n\n console.log(\"\");\n console.log(chalk.bold(\" Environment\"));\n for (const finding of findings) {\n const mark = finding.severity === \"error\" ? chalk.red(\" ✗\") : chalk.yellow(\" ⚠\");\n console.log(`${mark} ${finding.message}`);\n console.log(chalk.gray(` ${finding.fix}`));\n }\n console.log(\"\");\n return findings.some(finding => finding.severity === \"error\");\n}\n\n/**\n * The flags `rebase doctor` takes, and what each is for.\n *\n * One table, read by both the parser and the help page, because they were two\n * things that had to agree and did not: the page listed no flags at all, so\n * `--policies` — the form `cli/index.md` calls \"the form to use as a CI gate\" —\n * was invisible to anyone who ran `rebase doctor --help` to find it. And with\n * nothing parsing the line here, a typo travelled to the driver's permissive\n * parser and was silently dropped, so `rebase doctor --polices` ran the ordinary\n * doctor and reported success on a gate that never ran.\n *\n * The spec mirrors the driver's own (`doctorPluginCommand` in\n * `server-postgres/src/cli.ts`), because the line is relayed to it verbatim.\n */\nexport const DOCTOR_FLAGS = {\n \"--policies\": Boolean,\n \"--database\": Boolean,\n \"--schema-dir\": String,\n \"--schema\": String,\n \"-s\": \"--schema\",\n \"--sdk\": String,\n \"-k\": \"--sdk\"\n} as const;\n\n/** What each long flag above does, for the Options block. */\nconst DOCTOR_FLAG_HELP: Record<string, string> = {\n \"--policies\": \"Also audit the row-level security policies. The form to use as a CI gate.\",\n \"--database\": \"Only check that the database can host the request role(s) under the rls settings: roles, memberships, grants, policies. Read-only; exits 1 on a failure.\",\n \"--schema-dir\": SCHEMA_DIR_FLAG_HELP,\n \"--schema\": \"Path to the generated Drizzle schema (default: backend/src/schema.generated.ts)\",\n \"--sdk\": \"Path to the generated SDK types (default: generated/sdk/database.types.ts)\"\n};\n\n/**\n * The line handed to the driver, every path on it resolved from where the\n * command was run — the driver runs in `backend/`. See `utils/path-flags.ts`.\n */\nexport function doctorDriverArgs(rawArgs: string[], cwd: string, projectRoot?: string): string[] {\n const args = absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"doctor\"), cwd, [\"--schema-dir\", \"--schema\", \"-s\", \"--sdk\", \"-k\"]);\n return projectRoot ? [...args, ...schemaDirArgs(projectRoot, args)] : args;\n}\n\n/** `--schema, -s` — the aliases, resolved from the spec rather than retyped. */\nfunction doctorFlagLabel(flag: string): string {\n const aliases = Object.entries(DOCTOR_FLAGS)\n .filter(([, target]) => target === flag)\n .map(([alias]) => alias);\n return [flag, ...aliases].join(\", \");\n}\n\nfunction printDoctorHelp(): void {\n console.log(`\n${chalk.bold(\"rebase doctor\")} — Check a project for drift and misconfiguration\n\n${chalk.green.bold(\"Usage\")}\n rebase doctor [options]\n\n${chalk.green.bold(\"Options\")}\n${Object.keys(DOCTOR_FLAG_HELP)\n .map(flag => ` ${chalk.blue(doctorFlagLabel(flag).padEnd(22))} ${DOCTOR_FLAG_HELP[flag]}`)\n .join(\"\\n\")}\n\nCompares the tables backend/schema declares, the generated Drizzle schema, and the\ntables that actually exist, then reports what disagrees and how to reconcile it.\n\nWith --database it checks the database itself instead: whether the role\nsigned-in requests run as exists and can be switched to, who else can use it,\nand which tables, grants and policies Rebase would share with other roles. Each\nfinding names the SQL to run as an administrator, the rls setting that adapts\nRebase to the database instead, or both.\n\nAlso checks the connection strings in .env and the compose files for the\nunencoded \"=\" that makes PostgreSQL's own tools refuse to parse them — which\nbreaks backups and psql while leaving the app itself working.\n\nRun from inside a Rebase project — it reads the project's tables and\nconnects to its database.\n`);\n}\n\nexport async function doctorCommand(rawArgs: string[]): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printDoctorHelp();\n return;\n }\n\n // Strictly, before the line is relayed. The driver's own parser is\n // `permissive`, which turns an undeclared flag into a positional rather\n // than an error, so `rebase doctor --polices` ran the ordinary doctor and\n // exited 0 — a CI gate that reported success because the flag asking for it\n // was dropped on the way.\n refuseRemovedCollectionsFlag(rawArgs.slice(2), \"doctor\");\n const { flags } = parseCommandArgs({\n spec: DOCTOR_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"doctor\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n const backendDir = requireBackendDir(projectRoot);\n refuseMissingSchemaDir(rawArgs, process.cwd(), backendDir, \"doctor\");\n\n const activePlugin = getActiveBackendPlugin(backendDir);\n if (!activePlugin) {\n console.error(chalk.red(\"✗ Could not detect an active database plugin.\"));\n console.error(chalk.gray(\" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json.\"));\n process.exit(1);\n }\n\n const pluginCli = resolvePluginCliScript(backendDir, activePlugin);\n if (!pluginCli) {\n exitDependenciesNotInstalled(projectRoot);\n }\n\n // Set up environment with DOTENV_CONFIG_PATH\n const envFile = findEnvFile(projectRoot);\n const env: Record<string, string> = { ...process.env as Record<string, string> };\n if (envFile) {\n env.DOTENV_CONFIG_PATH = envFile;\n }\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n // Reported before the plugin runs: this one needs no database, and if the\n // URL is the problem then anything that tries to connect with it first will\n // fail with a worse message.\n const connectionFailed = reportLibpqUrlProblems(findLibpqUrlProblems(projectRoot, envFile));\n\n // Same reasoning: no database needed, and one of these findings — a\n // `process.env` read at module scope — is a live failure whose only symptom\n // today is a function quietly missing from `GET /api/functions`.\n reportFunctionPortability(projectRoot);\n\n // Everything that breaks a first run happens before a table is compared:\n // the wrong Node, two lockfiles disagreeing, two tables claiming one\n // slug, a JWT_SECRET short enough to be refused in production, three\n // versions of @rebasepro/server in one workspace. Doctor said nothing about\n // any of it. Reported before the plugin runs, and non-blocking — a project\n // with one of these still deserves its drift report.\n const environmentFailed = reportEnvironmentFindings(collectEnvironmentFindings(projectRoot, envFile));\n // Either is an error a CI gate must see: a connection string libpq cannot\n // parse is a project whose backups have never run.\n const failed = connectionFailed || environmentFailed;\n\n // Which database, resolved the way every other command resolves it.\n //\n // Two of doctor's three phases need one, and both used to key on\n // `DATABASE_URL` alone. On the documented first-run path that variable does\n // not exist — `rebase init` leaves it commented out and the managed\n // database fills the vacuum — so a stock scaffold always ended with\n // `⏭ Collections → Database: skipped (DATABASE_URL not set)` and\n // `⚠ No DATABASE_URL — RLS policies were NOT checked`, then told the reader\n // to set the one variable the quickstart tells them to leave alone. For the\n // command `ai-instructions.md` names as the thing to run before guessing.\n //\n // The managed daemon is started here, exactly as `rebase db url` starts it:\n // a doctor that will not start the database it is asked about can only ever\n // answer \"I did not look\".\n //\n // Last, and never fatal. Everything above needs no database, and a doctor\n // that cannot report what it *can* see because a database would not start\n // is the opposite of the job. A failure here is said out loud and the run\n // continues; the driver then reports its two database phases as skipped,\n // which is the truth.\n try {\n const prepared = await prepareDatabaseEnv(projectRoot, {\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n // What named the database, as the `db` commands pass it: the driver's\n // \"Cannot connect\" banner picks its fixes by it. Without it, the\n // remembered Docker database, stopped, got \"Verify DATABASE_URL in\n // your .env file\" — a file that had named nothing.\n env[DATABASE_SOURCE_ENV] = prepared.database.source;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n } catch (error) {\n console.log(\"\");\n console.error(chalk.yellow(` ⚠ Could not resolve this project's database: ${\n error instanceof Error ? error.message : String(error)}`));\n console.error(chalk.gray(\" The checks that need one are reported below as not run.\"));\n }\n\n // A headless project has no `backend/schema` by design — its API is\n // introspected from the live database at boot — and the driver's doctor\n // opens by loading the tables, finds none, and exits 1. So `rebase doctor`\n // failed on the documented headless path while every check above it had\n // just passed. Its three phases all compare *against* declared tables, so\n // there is nothing for them to do here; the environment findings are the\n // whole report.\n // `--database` is the exception: it checks the database a headless project\n // is introspected from, which is exactly the existing database it is for.\n if (!hasDeclaredTables(projectRoot) && flags[\"--database\"] !== true) {\n console.log(\"\");\n console.log(chalk.gray(\n \" ○ Schema drift not checked: this project derives its API from the database — \"\n + \"run `rebase schema introspect` first.\"\n ));\n if (failed) process.exit(1);\n return;\n }\n\n try {\n const isTs = pluginCli.endsWith(\".ts\");\n if (isTs) {\n const tsxBin = resolveTsx(projectRoot);\n if (!tsxBin) {\n exitDependenciesNotInstalled(projectRoot);\n }\n await execa(tsxBin, [pluginCli, ...doctorDriverArgs(rawArgs, process.cwd(), projectRoot)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n } else {\n await execa(\"node\", [pluginCli, ...doctorDriverArgs(rawArgs, process.cwd(), projectRoot)], {\n cwd: backendDir,\n stdio: \"inherit\",\n env\n });\n }\n } catch (error) {\n // A child that ran and exited non-zero already printed its diagnostics\n // through inherited stdio. A child that never started did not — and\n // \"the tsx symlink is broken\" is exactly the state `doctor` exists to\n // report, so exiting 1 in silence was the worst possible answer.\n reportSpawnFailure(error);\n process.exit(1);\n }\n\n // The plugin exited clean, so the schema agrees with itself. That is not\n // the same as the project being able to run: an environment error is still\n // an error, and a doctor that exits 0 over one is a doctor nobody can gate\n // on.\n if (failed) process.exit(1);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAgCA,IAAM,kBAAkB;;;;;;;;;AAUxB,SAAgB,sBAAsB,kBAA8C;CAChF,IAAI,CAAC,gBAAgB,KAAK,gBAAgB,GAAG,OAAO,CAAC;CAErD,MAAM,IAAI,iBAAiB,QAAQ,GAAG;CACtC,IAAI,MAAM,IAAI,OAAO,CAAC;CAGtB,MAAM,QAAQ,iBAAiB,MAAM,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC;CACvD,IAAI,CAAC,OAAO,OAAO,CAAC;CAEpB,MAAM,QAA4B,CAAC;CACnC,KAAK,MAAM,QAAQ,MAAM,MAAM,GAAG,GAAG;EACjC,IAAI,CAAC,MAAM;EAEX,IAAI,KAAK,MAAM,GAAG,CAAC,CAAC,SAAS,GACzB,MAAM,KAAK;GAAE,MAAM,KAAK,MAAM,GAAG,KAAK,QAAQ,GAAG,CAAC;GAAG,KAAK;EAAK,CAAC;CAExE;CACA,OAAO;AACX;;;;;;;;;;AAWA,SAAgB,kBAAkB,kBAAkC;CAChE,IAAI,sBAAsB,gBAAgB,CAAC,CAAC,WAAW,GAAG,OAAO;CAEjE,MAAM,IAAI,iBAAiB,QAAQ,GAAG;CACtC,MAAM,OAAO,iBAAiB,MAAM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 export interface AtlasBinaryState {
|
|
|
22
22
|
* `pnpm add` without `-w`, and atlas belongs to the backend anyway.
|
|
23
23
|
*/
|
|
24
24
|
workspaceDir?: string | null;
|
|
25
|
+
/** `process.platform`, for the one platform where the npm package cannot install. */
|
|
26
|
+
platform?: NodeJS.Platform;
|
|
25
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* The Atlas release Windows readers are sent: the floor of the scaffold's
|
|
30
|
+
* `@ariga/atlas` range, the oldest release it accepts (the npm version is the
|
|
31
|
+
* Atlas version). `tooling/scripts/check-templates.mjs` holds it to that range,
|
|
32
|
+
* beside the same constant in `@rebasepro/server-postgres`.
|
|
33
|
+
*/
|
|
34
|
+
export declare const ATLAS_WINDOWS_VERSION = "1.2.3";
|
|
26
35
|
/**
|
|
27
36
|
* Whether `db push`, `db generate` and `db migrate` can run at all.
|
|
28
37
|
*
|
package/dist/index.es.js
CHANGED
|
@@ -157,11 +157,11 @@ async function commandVocabulary(command) {
|
|
|
157
157
|
aliases: {}
|
|
158
158
|
};
|
|
159
159
|
case "migrate": return {
|
|
160
|
-
subcommands: (await import("./migrate-
|
|
160
|
+
subcommands: (await import("./migrate-CSY9ZDKy.js")).MIGRATE_SUBCOMMANDS,
|
|
161
161
|
aliases: {}
|
|
162
162
|
};
|
|
163
163
|
case "cloud": {
|
|
164
|
-
const cloud = await import("./cloud-
|
|
164
|
+
const cloud = await import("./cloud-DNJyUU0T.js");
|
|
165
165
|
return {
|
|
166
166
|
subcommands: cloud.CLOUD_GROUP_NAMES,
|
|
167
167
|
aliases: cloud.GROUP_ALIASES
|
|
@@ -350,7 +350,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
350
350
|
break;
|
|
351
351
|
}
|
|
352
352
|
case "build": {
|
|
353
|
-
const { buildCommand } = await import("./build-
|
|
353
|
+
const { buildCommand } = await import("./build-E5hfEWKj.js").then((n) => n.n);
|
|
354
354
|
await buildCommand(args);
|
|
355
355
|
break;
|
|
356
356
|
}
|
|
@@ -360,12 +360,12 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
360
360
|
break;
|
|
361
361
|
}
|
|
362
362
|
case "upgrade": {
|
|
363
|
-
const { upgradeCommand } = await import("./upgrade-
|
|
363
|
+
const { upgradeCommand } = await import("./upgrade-ZASvgxWM.js");
|
|
364
364
|
await upgradeCommand(args);
|
|
365
365
|
break;
|
|
366
366
|
}
|
|
367
367
|
case "migrate": {
|
|
368
|
-
const { migrateCommand } = await import("./migrate-
|
|
368
|
+
const { migrateCommand } = await import("./migrate-CSY9ZDKy.js");
|
|
369
369
|
await migrateCommand(effectiveSubcommand, args);
|
|
370
370
|
break;
|
|
371
371
|
}
|
|
@@ -400,7 +400,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
400
400
|
break;
|
|
401
401
|
}
|
|
402
402
|
case "doctor": {
|
|
403
|
-
const { doctorCommand } = await import("./doctor-
|
|
403
|
+
const { doctorCommand } = await import("./doctor-FaBObSlb.js");
|
|
404
404
|
await doctorCommand(args);
|
|
405
405
|
break;
|
|
406
406
|
}
|
|
@@ -425,7 +425,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
425
425
|
break;
|
|
426
426
|
}
|
|
427
427
|
case "cloud": {
|
|
428
|
-
const { cloudCommand } = await import("./cloud-
|
|
428
|
+
const { cloudCommand } = await import("./cloud-DNJyUU0T.js");
|
|
429
429
|
await cloudCommand(effectiveSubcommand, args);
|
|
430
430
|
break;
|
|
431
431
|
}
|
|
@@ -455,7 +455,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
455
455
|
break;
|
|
456
456
|
}
|
|
457
457
|
case "logs": {
|
|
458
|
-
const { logsCommand } = await import("./logs-
|
|
458
|
+
const { logsCommand } = await import("./logs-DpuMukJe.js");
|
|
459
459
|
await logsCommand(args);
|
|
460
460
|
break;
|
|
461
461
|
}
|
|
@@ -469,7 +469,7 @@ async function dispatch(command, effectiveSubcommand, args, parsedArgs, namespac
|
|
|
469
469
|
await rlsCommand(effectiveSubcommand, args);
|
|
470
470
|
break;
|
|
471
471
|
}
|
|
472
|
-
default: unknownCommand(command, namespacedCommands, "", { cloud: (await import("./cloud-
|
|
472
|
+
default: unknownCommand(command, namespacedCommands, "", { cloud: (await import("./cloud-DNJyUU0T.js")).CLOUD_GROUP_NAMES });
|
|
473
473
|
}
|
|
474
474
|
}
|
|
475
475
|
/** The global help. Exported so its Options block can be held against {@link ROOT_FLAGS}. */
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { v as findTablesIndex } from "./manifest-RjqxfCpb.js";
|
|
2
|
+
import path from "path";
|
|
3
|
+
//#region src/utils/legacy-layout.ts
|
|
4
|
+
/** Where the retired layout kept its collections, relative to the project root. */
|
|
5
|
+
var LEGACY_COLLECTIONS_DIR = "config/collections";
|
|
6
|
+
/** The command that moves a project off it, exactly as a person types it. */
|
|
7
|
+
var MIGRATE_COMMAND = "rebase migrate collections-to-tables";
|
|
8
|
+
/**
|
|
9
|
+
* `config/collections` when the project declares its tables there and has no
|
|
10
|
+
* tables directory to replace them; `undefined` otherwise.
|
|
11
|
+
*
|
|
12
|
+
* A project mid-migration has both, and is not legacy: the codemod leaves
|
|
13
|
+
* `config/collections` in place for `--check` until its author deletes it.
|
|
14
|
+
*
|
|
15
|
+
* @param tablesDir The backend's tables directory, relative to the root.
|
|
16
|
+
*/
|
|
17
|
+
function legacyCollectionsDir(projectRoot, tablesDir) {
|
|
18
|
+
const legacy = path.join(projectRoot, LEGACY_COLLECTIONS_DIR);
|
|
19
|
+
if (findTablesIndex(path.join(projectRoot, tablesDir)) !== void 0) return void 0;
|
|
20
|
+
if (findTablesIndex(legacy) === void 0) return void 0;
|
|
21
|
+
return LEGACY_COLLECTIONS_DIR;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* The refusal, as a message and a hint. The command is in the message, not only
|
|
25
|
+
* the hint, so a caller that prints one line still names it.
|
|
26
|
+
*/
|
|
27
|
+
function legacyLayoutRefusal(legacyDir, tablesDir) {
|
|
28
|
+
return {
|
|
29
|
+
message: `This project declares its tables in ${legacyDir}, which Rebase 0.31 and later no longer build or deploy: they read ${tablesDir}. Run \`${MIGRATE_COMMAND}\` to move them.`,
|
|
30
|
+
hint: `\`${MIGRATE_COMMAND} --dry-run\` shows every file it would write. Run it without --dry-run (it checks that the generated SQL is unchanged), commit the result, then build and deploy again.`
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { legacyCollectionsDir as n, legacyLayoutRefusal as r, MIGRATE_COMMAND as t };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=legacy-layout-DI2VeQSV.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"legacy-layout-DI2VeQSV.js","names":[],"sources":["../src/utils/legacy-layout.ts"],"sourcesContent":["/**\n * A project still on the `config/collections` layout, found before anything is\n * built or uploaded.\n *\n * 0.31 moved the schema to `backend/schema` (bundle format 3, runtime contract\n * 2), and both the runtime and Rebase Cloud refuse a bundle built the old way.\n * What they cannot do is refuse it EARLY: the platform sees the manifest only\n * when the deploy is triggered, after the whole bundle has been uploaded. And a\n * project in that state did not reach a useful message on this side either:\n * `rebase build` failed on whatever check came first (SongBuzz, 2026-11-16, was\n * told its admin's Vite config lacked `rebaseBackendGuard()`), because nothing\n * here looks for a layout this CLI no longer reads.\n *\n * Old `rebase.json` fields (`config`, `usersCollection`) are refused by\n * `loadManifest`. This is the case it cannot see: a manifest written after those\n * fields were retired, on a project whose tables are still in\n * `config/collections` — every project scaffolded from 0.25 to 0.30.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport { findTablesIndex } from \"../manifest\";\n\n/** Where the retired layout kept its collections, relative to the project root. */\nexport const LEGACY_COLLECTIONS_DIR = \"config/collections\";\n\n/** The command that moves a project off it, exactly as a person types it. */\nexport const MIGRATE_COMMAND = \"rebase migrate collections-to-tables\";\n\n/**\n * `config/collections` when the project declares its tables there and has no\n * tables directory to replace them; `undefined` otherwise.\n *\n * A project mid-migration has both, and is not legacy: the codemod leaves\n * `config/collections` in place for `--check` until its author deletes it.\n *\n * @param tablesDir The backend's tables directory, relative to the root.\n */\nexport function legacyCollectionsDir(projectRoot: string, tablesDir: string): string | undefined {\n const legacy = path.join(projectRoot, LEGACY_COLLECTIONS_DIR);\n if (findTablesIndex(path.join(projectRoot, tablesDir)) !== undefined) return undefined;\n if (findTablesIndex(legacy) === undefined) return undefined;\n return LEGACY_COLLECTIONS_DIR;\n}\n\n/**\n * The refusal, as a message and a hint. The command is in the message, not only\n * the hint, so a caller that prints one line still names it.\n */\nexport function legacyLayoutRefusal(legacyDir: string, tablesDir: string): { message: string; hint: string } {\n return {\n message:\n `This project declares its tables in ${legacyDir}, which Rebase 0.31 and later no longer build ` +\n `or deploy: they read ${tablesDir}. Run \\`${MIGRATE_COMMAND}\\` to move them.`,\n hint:\n `\\`${MIGRATE_COMMAND} --dry-run\\` shows every file it would write. Run it without --dry-run ` +\n `(it checks that the generated SQL is unchanged), commit the result, then build and deploy again.`\n };\n}\n"],"mappings":";;;;AAuBA,IAAa,yBAAyB;;AAGtC,IAAa,kBAAkB;;;;;;;;;;AAW/B,SAAgB,qBAAqB,aAAqB,WAAuC;CAC7F,MAAM,SAAS,KAAK,KAAK,aAAa,sBAAsB;CAC5D,IAAI,gBAAgB,KAAK,KAAK,aAAa,SAAS,CAAC,MAAM,KAAA,GAAW,OAAO,KAAA;CAC7E,IAAI,gBAAgB,MAAM,MAAM,KAAA,GAAW,OAAO,KAAA;CAClD,OAAO;AACX;;;;;AAMA,SAAgB,oBAAoB,WAAmB,WAAsD;CACzG,OAAO;EACH,SACI,uCAAuC,UAAU,qEACzB,UAAU,UAAU,gBAAgB;EAChE,MACI,KAAK,gBAAgB;CAE7B;AACJ"}
|
|
@@ -163,7 +163,7 @@ async function cloudRuntimeLogs(flags) {
|
|
|
163
163
|
if (typeof flags["--level"] === "string") argv.push("--level", flags["--level"]);
|
|
164
164
|
if (flags["--json"] === true) argv.push("--json");
|
|
165
165
|
if (typeof flags["--source"] === "string") process.stderr.write(chalk.yellow(" ⚠ --source filters one server's own log buffer; the pods' output has no sources, so it is ignored.\n"));
|
|
166
|
-
const { cloudCommand } = await import("./cloud-
|
|
166
|
+
const { cloudCommand } = await import("./cloud-DNJyUU0T.js");
|
|
167
167
|
await cloudCommand("logs", argv);
|
|
168
168
|
}
|
|
169
169
|
function printLogsHelp() {
|
|
@@ -189,4 +189,4 @@ function printLogsHelp() {
|
|
|
189
189
|
//#endregion
|
|
190
190
|
export { logsCommand };
|
|
191
191
|
|
|
192
|
-
//# sourceMappingURL=logs-
|
|
192
|
+
//# sourceMappingURL=logs-DpuMukJe.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"logs-CIgfLBsu.js","names":[],"sources":["../src/commands/logs.ts"],"sourcesContent":["/**\n * CLI command: rebase logs\n *\n * A running server's request and application log — the in-memory ring buffer\n * the Studio Logs Explorer reads, through `/api/admin/logs` — once, or followed\n * live (`-f`, over the route's server-sent events). The buffer is one process's:\n * the `rebase dev` backend, or the one instance `--url` reaches.\n *\n * On a Rebase Cloud project this hands over to `rebase cloud logs --runtime`,\n * which reads every replica's output through the control plane instead of one\n * pod's buffer.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, failureOf } from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n recordsOf,\n reportTargetError,\n requestJson,\n startProjectCommand,\n stringOf\n} from \"../utils/project-command\";\nimport { note } from \"./cloud/context\";\n\nexport const LOGS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--follow\": Boolean,\n \"-f\": \"--follow\",\n \"--level\": String,\n \"--source\": String,\n \"--search\": String,\n \"--grep\": \"--search\",\n \"--since\": String,\n \"--limit\": Number,\n \"-n\": \"--limit\"\n} satisfies arg.Spec;\n\nconst LEVELS = new Set([\"debug\", \"info\", \"warn\", \"error\"]);\nconst SOURCES = new Set([\"api\", \"auth\", \"storage\", \"realtime\", \"system\"]);\n\n/** One line of the log, coloured by level. */\nfunction printEntry(entry: Record<string, unknown>): void {\n if (isJsonMode()) {\n process.stdout.write(`${JSON.stringify(entry)}\\n`);\n return;\n }\n const level = stringOf(entry.level) ?? \"info\";\n const paint = level === \"error\" ? chalk.red : level === \"warn\" ? chalk.yellow : level === \"debug\" ? chalk.gray : (s: string) => s;\n const time = stringOf(entry.timestamp)?.replace(\"T\", \" \").replace(/\\.\\d+Z$/, \"Z\") ?? \"\";\n console.log(`${chalk.gray(time)} ${paint(level.padEnd(5))} ${chalk.cyan((stringOf(entry.source) ?? \"\").padEnd(8))} ${paint(stringOf(entry.message) ?? \"\")}`);\n if (isRecord(entry.metadata) && Object.keys(entry.metadata).length > 0 && level !== \"info\") {\n console.log(chalk.gray(` ${JSON.stringify(entry.metadata)}`));\n }\n}\n\nexport async function logsCommand(rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (wantsHelp(rawArgs)) {\n printLogsHelp();\n return;\n }\n const { flags } = parsedLine(() => {\n const parsed = parseCommandArgs({\n spec: LOGS_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"logs\",\n maxPositionals: 0\n });\n const level = parsed.flags[\"--level\"];\n if (level !== undefined && !LEVELS.has(level)) throw new UsageError(`--level takes debug, info, warn or error (got \"${level}\").`);\n const source = parsed.flags[\"--source\"];\n if (source !== undefined && !SOURCES.has(source)) throw new UsageError(`--source takes api, auth, storage, realtime or system (got \"${source}\").`);\n return parsed;\n });\n\n if (flags[\"--project\"] || flags[\"--cloud\"]) {\n if (flags[\"--token\"] || flags[\"--session\"] || flags[\"--anon\"]) {\n fail(\"On a Rebase Cloud project `rebase logs` reads the pods' output through the control plane; --token, --session and --anon do not apply.\", undefined, \"usage\");\n }\n await cloudRuntimeLogs(flags);\n return;\n }\n\n const target = await projectTarget(flags, { command: \"logs\" });\n const filter = { level: flags[\"--level\"], source: flags[\"--source\"], search: flags[\"--search\"] };\n\n if (!flags[\"--follow\"]) {\n const body = await requestJson(target, \"/api/admin/logs\", \"Failed to read the log\", {\n query: { ...filter, since: flags[\"--since\"], limit: flags[\"--limit\"]?.toString() }\n });\n const entries = recordsOf(isRecord(body) ? body.entries : undefined);\n if (isJsonMode()) {\n emit(() => undefined, body);\n return;\n }\n if (entries.length === 0) note(`No log entries match on ${target.label}.`);\n // The buffer answers newest first; a log reads oldest first.\n for (const entry of [...entries].reverse()) printEntry(entry);\n return;\n }\n\n await followLog(target, { ...filter, limit: flags[\"--limit\"]?.toString() });\n}\n\n/**\n * Tail `/api/admin/logs/stream`: a `snapshot` event with the backlog, then an\n * `append` event per batch. Runs until interrupted or the server closes it.\n */\nasync function followLog(\n target: Awaited<ReturnType<typeof projectTarget>>,\n query: Record<string, string | undefined>\n): Promise<void> {\n let res: Response;\n try {\n res = await target.request(\"/api/admin/logs/stream\", { query, headers: { Accept: \"text/event-stream\" } });\n } catch (e) {\n reportTargetError(e, target);\n }\n if (!res.ok || !res.body) {\n const body: unknown = await res.json().catch(() => null);\n reportTargetError(failureOf(res.status, body, target, \"Failed to follow the log\"), target);\n }\n if (!isJsonMode()) note(`Following the log of ${target.label}. Ctrl-C to stop.`);\n process.once(\"SIGINT\", () => process.exit(0));\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n const reader = res.body.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n handleFrame(frame);\n }\n }\n if (!isJsonMode()) note(\"The server closed the stream.\");\n}\n\n/** One server-sent event: `event:` and `data:` lines. */\nfunction handleFrame(frame: string): void {\n let event = \"message\";\n const data: string[] = [];\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"event:\")) event = line.slice(6).trim();\n else if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (data.length === 0) return;\n let payload: unknown;\n try {\n payload = JSON.parse(data.join(\"\\n\"));\n } catch {\n return;\n }\n if (!isRecord(payload)) return;\n const entries = recordsOf(payload.entries);\n // The snapshot is oldest-first, as are the appends.\n for (const entry of entries) printEntry(entry);\n if (event === \"append\" && typeof payload.dropped === \"number\" && payload.dropped > 0 && !isJsonMode()) {\n console.log(chalk.yellow(` … ${payload.dropped} entries dropped (the stream fell behind)`));\n }\n}\n\n/** The pods' output, through `rebase cloud logs --runtime`, with this command's flags translated. */\nasync function cloudRuntimeLogs(flags: Record<string, unknown>): Promise<void> {\n const argv = [\"node\", \"rebase\", \"cloud\", \"logs\", \"--runtime\"];\n const project = typeof flags[\"--project\"] === \"string\" ? flags[\"--project\"] : undefined;\n if (project) argv.push(\"--project\", project);\n if (flags[\"--follow\"] === true) argv.push(\"--follow\");\n if (typeof flags[\"--since\"] === \"string\") argv.push(\"--since\", flags[\"--since\"]);\n if (typeof flags[\"--limit\"] === \"number\") argv.push(\"--tail\", String(flags[\"--limit\"]));\n if (typeof flags[\"--search\"] === \"string\") argv.push(\"--grep\", flags[\"--search\"]);\n if (typeof flags[\"--level\"] === \"string\") argv.push(\"--level\", flags[\"--level\"]);\n if (flags[\"--json\"] === true) argv.push(\"--json\");\n if (typeof flags[\"--source\"] === \"string\") {\n process.stderr.write(chalk.yellow(\" ⚠ --source filters one server's own log buffer; the pods' output has no sources, so it is ignored.\\n\"));\n }\n const { cloudCommand } = await import(\"./cloud\");\n await cloudCommand(\"logs\", argv);\n}\n\nfunction printLogsHelp(): void {\n printProjectHelp({\n command: \"logs\",\n usage: \"[--follow]\",\n title: \"A running server's log: once, or followed live\",\n actions: [\n {\n action: \"logs\",\n description: \"The newest entries of the server's log buffer, oldest first\",\n flags: [\n [\"--follow, -f\", \"Keep printing entries as they are logged\"],\n [\"--level <level>\", \"debug, info, warn or error\"],\n [\"--source <source>\", \"api, auth, storage, realtime or system\"],\n [\"--search, --grep <text>\", \"Only entries whose message holds this\"],\n [\"--since <iso>\", \"Only entries after this time\"],\n [\"--limit, -n <n>\", \"At most this many entries\"]\n ]\n }\n ],\n notes: [\n \"The buffer is one process's: `rebase dev`'s backend, or the instance --url reaches.\",\n \"With --project or --cloud this is `rebase cloud logs --runtime`: every pod's output, through the control plane.\"\n ]\n });\n}\n"],"mappings":";;;;;AAiCA,IAAa,aAAa;CACtB,GAAG;CACH,YAAY;CACZ,MAAM;CACN,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,WAAW;CACX,WAAW;CACX,MAAM;AACV;AAEA,IAAM,yBAAS,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAQ;AAAO,CAAC;AACzD,IAAM,0BAAU,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAW;CAAY;AAAQ,CAAC;;AAGxE,SAAS,WAAW,OAAsC;CACtD,IAAI,WAAW,GAAG;EACd,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;EACjD;CACJ;CACA,MAAM,QAAQ,SAAS,MAAM,KAAK,KAAK;CACvC,MAAM,QAAQ,UAAU,UAAU,MAAM,MAAM,UAAU,SAAS,MAAM,SAAS,UAAU,UAAU,MAAM,QAAQ,MAAc;CAChI,MAAM,OAAO,SAAS,MAAM,SAAS,CAAC,EAAE,QAAQ,KAAK,GAAG,CAAC,CAAC,QAAQ,WAAW,GAAG,KAAK;CACrF,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE,GAAG,MAAM,MAAM,SAAS,MAAM,MAAM,KAAK,GAAA,CAAI,OAAO,CAAC,CAAC,EAAE,GAAG,MAAM,SAAS,MAAM,OAAO,KAAK,EAAE,GAAG;CAC3J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;CAC/E,IAAI,MAAM,cAAc,MAAM,KAAK,KAAK,QAAQ;CAChD,IAAI,OAAO,MAAM,gBAAgB,UAC7B,QAAQ,OAAO,MAAM,MAAM,OAAO,wGAAwG,CAAC;CAE/I,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,aAAa,QAAQ,IAAI;AACnC;AAEA,SAAS,gBAAsB;CAC3B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,OAAO;EACP,SAAS,CACL;GACI,QAAQ;GACR,aAAa;GACb,OAAO;IACH,CAAC,gBAAgB,0CAA0C;IAC3D,CAAC,mBAAmB,4BAA4B;IAChD,CAAC,qBAAqB,wCAAwC;IAC9D,CAAC,2BAA2B,uCAAuC;IACnE,CAAC,iBAAiB,8BAA8B;IAChD,CAAC,mBAAmB,2BAA2B;GACnD;EACJ,CACJ;EACA,OAAO,CACH,uFACA,iHACJ;CACJ,CAAC;AACL"}
|
|
1
|
+
{"version":3,"file":"logs-DpuMukJe.js","names":[],"sources":["../src/commands/logs.ts"],"sourcesContent":["/**\n * CLI command: rebase logs\n *\n * A running server's request and application log — the in-memory ring buffer\n * the Studio Logs Explorer reads, through `/api/admin/logs` — once, or followed\n * live (`-f`, over the route's server-sent events). The buffer is one process's:\n * the `rebase dev` backend, or the one instance `--url` reaches.\n *\n * On a Rebase Cloud project this hands over to `rebase cloud logs --runtime`,\n * which reads every replica's output through the control plane instead of one\n * pod's buffer.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { PROJECT_TARGET_FLAGS, failureOf } from \"../utils/project-target\";\nimport {\n emit,\n fail,\n isJsonMode,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n recordsOf,\n reportTargetError,\n requestJson,\n startProjectCommand,\n stringOf\n} from \"../utils/project-command\";\nimport { note } from \"./cloud/context\";\n\nexport const LOGS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--follow\": Boolean,\n \"-f\": \"--follow\",\n \"--level\": String,\n \"--source\": String,\n \"--search\": String,\n \"--grep\": \"--search\",\n \"--since\": String,\n \"--limit\": Number,\n \"-n\": \"--limit\"\n} satisfies arg.Spec;\n\nconst LEVELS = new Set([\"debug\", \"info\", \"warn\", \"error\"]);\nconst SOURCES = new Set([\"api\", \"auth\", \"storage\", \"realtime\", \"system\"]);\n\n/** One line of the log, coloured by level. */\nfunction printEntry(entry: Record<string, unknown>): void {\n if (isJsonMode()) {\n process.stdout.write(`${JSON.stringify(entry)}\\n`);\n return;\n }\n const level = stringOf(entry.level) ?? \"info\";\n const paint = level === \"error\" ? chalk.red : level === \"warn\" ? chalk.yellow : level === \"debug\" ? chalk.gray : (s: string) => s;\n const time = stringOf(entry.timestamp)?.replace(\"T\", \" \").replace(/\\.\\d+Z$/, \"Z\") ?? \"\";\n console.log(`${chalk.gray(time)} ${paint(level.padEnd(5))} ${chalk.cyan((stringOf(entry.source) ?? \"\").padEnd(8))} ${paint(stringOf(entry.message) ?? \"\")}`);\n if (isRecord(entry.metadata) && Object.keys(entry.metadata).length > 0 && level !== \"info\") {\n console.log(chalk.gray(` ${JSON.stringify(entry.metadata)}`));\n }\n}\n\nexport async function logsCommand(rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (wantsHelp(rawArgs)) {\n printLogsHelp();\n return;\n }\n const { flags } = parsedLine(() => {\n const parsed = parseCommandArgs({\n spec: LOGS_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"logs\",\n maxPositionals: 0\n });\n const level = parsed.flags[\"--level\"];\n if (level !== undefined && !LEVELS.has(level)) throw new UsageError(`--level takes debug, info, warn or error (got \"${level}\").`);\n const source = parsed.flags[\"--source\"];\n if (source !== undefined && !SOURCES.has(source)) throw new UsageError(`--source takes api, auth, storage, realtime or system (got \"${source}\").`);\n return parsed;\n });\n\n if (flags[\"--project\"] || flags[\"--cloud\"]) {\n if (flags[\"--token\"] || flags[\"--session\"] || flags[\"--anon\"]) {\n fail(\"On a Rebase Cloud project `rebase logs` reads the pods' output through the control plane; --token, --session and --anon do not apply.\", undefined, \"usage\");\n }\n await cloudRuntimeLogs(flags);\n return;\n }\n\n const target = await projectTarget(flags, { command: \"logs\" });\n const filter = { level: flags[\"--level\"], source: flags[\"--source\"], search: flags[\"--search\"] };\n\n if (!flags[\"--follow\"]) {\n const body = await requestJson(target, \"/api/admin/logs\", \"Failed to read the log\", {\n query: { ...filter, since: flags[\"--since\"], limit: flags[\"--limit\"]?.toString() }\n });\n const entries = recordsOf(isRecord(body) ? body.entries : undefined);\n if (isJsonMode()) {\n emit(() => undefined, body);\n return;\n }\n if (entries.length === 0) note(`No log entries match on ${target.label}.`);\n // The buffer answers newest first; a log reads oldest first.\n for (const entry of [...entries].reverse()) printEntry(entry);\n return;\n }\n\n await followLog(target, { ...filter, limit: flags[\"--limit\"]?.toString() });\n}\n\n/**\n * Tail `/api/admin/logs/stream`: a `snapshot` event with the backlog, then an\n * `append` event per batch. Runs until interrupted or the server closes it.\n */\nasync function followLog(\n target: Awaited<ReturnType<typeof projectTarget>>,\n query: Record<string, string | undefined>\n): Promise<void> {\n let res: Response;\n try {\n res = await target.request(\"/api/admin/logs/stream\", { query, headers: { Accept: \"text/event-stream\" } });\n } catch (e) {\n reportTargetError(e, target);\n }\n if (!res.ok || !res.body) {\n const body: unknown = await res.json().catch(() => null);\n reportTargetError(failureOf(res.status, body, target, \"Failed to follow the log\"), target);\n }\n if (!isJsonMode()) note(`Following the log of ${target.label}. Ctrl-C to stop.`);\n process.once(\"SIGINT\", () => process.exit(0));\n\n const decoder = new TextDecoder();\n let buffer = \"\";\n const reader = res.body.getReader();\n for (;;) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value, { stream: true });\n let boundary: number;\n while ((boundary = buffer.indexOf(\"\\n\\n\")) !== -1) {\n const frame = buffer.slice(0, boundary);\n buffer = buffer.slice(boundary + 2);\n handleFrame(frame);\n }\n }\n if (!isJsonMode()) note(\"The server closed the stream.\");\n}\n\n/** One server-sent event: `event:` and `data:` lines. */\nfunction handleFrame(frame: string): void {\n let event = \"message\";\n const data: string[] = [];\n for (const line of frame.split(\"\\n\")) {\n if (line.startsWith(\"event:\")) event = line.slice(6).trim();\n else if (line.startsWith(\"data:\")) data.push(line.slice(5).trimStart());\n }\n if (data.length === 0) return;\n let payload: unknown;\n try {\n payload = JSON.parse(data.join(\"\\n\"));\n } catch {\n return;\n }\n if (!isRecord(payload)) return;\n const entries = recordsOf(payload.entries);\n // The snapshot is oldest-first, as are the appends.\n for (const entry of entries) printEntry(entry);\n if (event === \"append\" && typeof payload.dropped === \"number\" && payload.dropped > 0 && !isJsonMode()) {\n console.log(chalk.yellow(` … ${payload.dropped} entries dropped (the stream fell behind)`));\n }\n}\n\n/** The pods' output, through `rebase cloud logs --runtime`, with this command's flags translated. */\nasync function cloudRuntimeLogs(flags: Record<string, unknown>): Promise<void> {\n const argv = [\"node\", \"rebase\", \"cloud\", \"logs\", \"--runtime\"];\n const project = typeof flags[\"--project\"] === \"string\" ? flags[\"--project\"] : undefined;\n if (project) argv.push(\"--project\", project);\n if (flags[\"--follow\"] === true) argv.push(\"--follow\");\n if (typeof flags[\"--since\"] === \"string\") argv.push(\"--since\", flags[\"--since\"]);\n if (typeof flags[\"--limit\"] === \"number\") argv.push(\"--tail\", String(flags[\"--limit\"]));\n if (typeof flags[\"--search\"] === \"string\") argv.push(\"--grep\", flags[\"--search\"]);\n if (typeof flags[\"--level\"] === \"string\") argv.push(\"--level\", flags[\"--level\"]);\n if (flags[\"--json\"] === true) argv.push(\"--json\");\n if (typeof flags[\"--source\"] === \"string\") {\n process.stderr.write(chalk.yellow(\" ⚠ --source filters one server's own log buffer; the pods' output has no sources, so it is ignored.\\n\"));\n }\n const { cloudCommand } = await import(\"./cloud\");\n await cloudCommand(\"logs\", argv);\n}\n\nfunction printLogsHelp(): void {\n printProjectHelp({\n command: \"logs\",\n usage: \"[--follow]\",\n title: \"A running server's log: once, or followed live\",\n actions: [\n {\n action: \"logs\",\n description: \"The newest entries of the server's log buffer, oldest first\",\n flags: [\n [\"--follow, -f\", \"Keep printing entries as they are logged\"],\n [\"--level <level>\", \"debug, info, warn or error\"],\n [\"--source <source>\", \"api, auth, storage, realtime or system\"],\n [\"--search, --grep <text>\", \"Only entries whose message holds this\"],\n [\"--since <iso>\", \"Only entries after this time\"],\n [\"--limit, -n <n>\", \"At most this many entries\"]\n ]\n }\n ],\n notes: [\n \"The buffer is one process's: `rebase dev`'s backend, or the instance --url reaches.\",\n \"With --project or --cloud this is `rebase cloud logs --runtime`: every pod's output, through the control plane.\"\n ]\n });\n}\n"],"mappings":";;;;;AAiCA,IAAa,aAAa;CACtB,GAAG;CACH,YAAY;CACZ,MAAM;CACN,WAAW;CACX,YAAY;CACZ,YAAY;CACZ,UAAU;CACV,WAAW;CACX,WAAW;CACX,MAAM;AACV;AAEA,IAAM,yBAAS,IAAI,IAAI;CAAC;CAAS;CAAQ;CAAQ;AAAO,CAAC;AACzD,IAAM,0BAAU,IAAI,IAAI;CAAC;CAAO;CAAQ;CAAW;CAAY;AAAQ,CAAC;;AAGxE,SAAS,WAAW,OAAsC;CACtD,IAAI,WAAW,GAAG;EACd,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,KAAK,EAAE,GAAG;EACjD;CACJ;CACA,MAAM,QAAQ,SAAS,MAAM,KAAK,KAAK;CACvC,MAAM,QAAQ,UAAU,UAAU,MAAM,MAAM,UAAU,SAAS,MAAM,SAAS,UAAU,UAAU,MAAM,QAAQ,MAAc;CAChI,MAAM,OAAO,SAAS,MAAM,SAAS,CAAC,EAAE,QAAQ,KAAK,GAAG,CAAC,CAAC,QAAQ,WAAW,GAAG,KAAK;CACrF,QAAQ,IAAI,GAAG,MAAM,KAAK,IAAI,EAAE,GAAG,MAAM,MAAM,OAAO,CAAC,CAAC,EAAE,GAAG,MAAM,MAAM,SAAS,MAAM,MAAM,KAAK,GAAA,CAAI,OAAO,CAAC,CAAC,E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IAAI,OAAO,MAAM,eAAe,UAAU,KAAK,KAAK,WAAW,MAAM,UAAU;CAC/E,IAAI,MAAM,cAAc,MAAM,KAAK,KAAK,QAAQ;CAChD,IAAI,OAAO,MAAM,gBAAgB,UAC7B,QAAQ,OAAO,MAAM,MAAM,OAAO,wGAAwG,CAAC;CAE/I,MAAM,EAAE,iBAAiB,MAAM,OAAO;CACtC,MAAM,aAAa,QAAQ,IAAI;AACnC;AAEA,SAAS,gBAAsB;CAC3B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,OAAO;EACP,SAAS,CACL;GACI,QAAQ;GACR,aAAa;GACb,OAAO;IACH,CAAC,gBAAgB,0CAA0C;IAC3D,CAAC,mBAAmB,4BAA4B;IAChD,CAAC,qBAAqB,wCAAwC;IAC9D,CAAC,2BAA2B,uCAAuC;IACnE,CAAC,iBAAiB,8BAA8B;IAChD,CAAC,mBAAmB,2BAA2B;GACnD;EACJ,CACJ;EACA,OAAO,CACH,uFACA,iHACJ;CACJ,CAAC;AACL"}
|
|
@@ -76,7 +76,7 @@ Run ${chalk.cyan("rebase migrate <subcommand> --help")} for the rest.
|
|
|
76
76
|
async function migrateCommand(subcommand, rawArgs) {
|
|
77
77
|
switch (subcommand) {
|
|
78
78
|
case "collections-to-tables": {
|
|
79
|
-
const { printCollectionsToTablesHelp, runCollectionsToTables } = await import("./command-
|
|
79
|
+
const { printCollectionsToTablesHelp, runCollectionsToTables } = await import("./command-Bks5xkrQ.js");
|
|
80
80
|
if (wantsHelp(rawArgs)) {
|
|
81
81
|
printCollectionsToTablesHelp();
|
|
82
82
|
return;
|
|
@@ -99,7 +99,7 @@ async function migrateCommand(subcommand, rawArgs) {
|
|
|
99
99
|
return;
|
|
100
100
|
}
|
|
101
101
|
case "sdk-calls": {
|
|
102
|
-
const { printSdkCallsHelp, runSdkCalls } = await import("./command-
|
|
102
|
+
const { printSdkCallsHelp, runSdkCalls } = await import("./command-Bks5xkrQ.js");
|
|
103
103
|
if (wantsHelp(rawArgs)) {
|
|
104
104
|
printSdkCallsHelp();
|
|
105
105
|
return;
|
|
@@ -136,4 +136,4 @@ async function migrateCommand(subcommand, rawArgs) {
|
|
|
136
136
|
//#endregion
|
|
137
137
|
export { MIGRATE_SUBCOMMANDS, migrateCommand };
|
|
138
138
|
|
|
139
|
-
//# sourceMappingURL=migrate-
|
|
139
|
+
//# sourceMappingURL=migrate-CSY9ZDKy.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-
|
|
1
|
+
{"version":3,"file":"migrate-CSY9ZDKy.js","names":[],"sources":["../src/commands/migrate.ts"],"sourcesContent":["/**\n * CLI command group: `rebase migrate <subcommand>` — one-way moves of a\n * project from a layout this release no longer reads.\n *\n * - `collections-to-tables [dir]` — `config/collections` → `backend/schema`\n * (+ `frontend/src/cms`), proven by byte-identical generated SQL.\n * - `sdk-calls [dir]` — the project's own code for the renames that came with\n * tables (`data.collection(…)` → `data.table(…)`, rule keys, hooks); part of\n * the first, and on its own for a project already migrated.\n *\n * The work lives in `../codemod/collections-to-tables`, loaded only when the\n * command runs (it brings ts-morph), so `rebase --help` and every other command\n * start as fast as before.\n */\nimport chalk from \"chalk\";\n\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { unknownCommandMessage } from \"../utils/unknown-command\";\n\n/** The subcommands `rebase migrate` dispatches. The CLI's vocabulary and the docs verifier read this. */\nexport const MIGRATE_SUBCOMMANDS = [\"collections-to-tables\", \"sdk-calls\"] as const;\n\n/** Every flag `rebase migrate collections-to-tables` accepts. Its help page and the docs verifier read this. */\nexport const COLLECTIONS_TO_TABLES_FLAGS = {\n \"--check\": Boolean,\n \"--dry-run\": Boolean,\n \"--json\": Boolean,\n \"--force\": Boolean,\n \"--skip-sdk-calls\": Boolean,\n \"--accept-rule-changes\": Boolean\n} as const;\n\n/** Every flag `rebase migrate sdk-calls` accepts. Its help page and the docs verifier read this. */\nexport const SDK_CALLS_FLAGS = {\n \"--dry-run\": Boolean,\n \"--json\": Boolean,\n \"--force\": Boolean\n} as const;\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase migrate\")} — move a project from a layout this release no longer reads\n\n${chalk.bold(\"Usage\")}\n rebase migrate <subcommand> [dir] [options]\n\n${chalk.bold(\"Subcommands\")}\n ${chalk.blue.bold(\"collections-to-tables\")} ${chalk.gray(\"[dir]\")} config/collections → backend/schema + frontend/src/cms, SQL-checked.\n Run it once, on a project the CLI refuses with \"still on the collections layout\".\n It runs sdk-calls too, unless --skip-sdk-calls.\n ${chalk.blue.bold(\"sdk-calls\")} ${chalk.gray(\"[dir]\")} data.collection(\"x\") → data.table(\"x\"), the rule keys (existsIn / membership:\n collection → table) and the other renames, in your own code — including imports\n of names that moved package (@rebasepro/types / common → @rebasepro/cms-types, …),\n adding that package to your package.json. Run it alone on a project already\n migrated, or after a migration run with --skip-sdk-calls.\n\n${chalk.bold(\"Options\")} ${chalk.gray(\"(each subcommand's --help lists its own)\")}\n --dry-run Print the plan and write nothing. Start here.\n --check ${chalk.gray(\"(collections-to-tables)\")} On a project already migrated: prove backend/schema still renders\n the same SQL as config/collections, before you delete config/. Writes nothing.\n --force Run on a git tree with uncommitted changes (the run refuses one, so every change it\n makes is a reviewable diff), and replace output files that hold something else.\n --json One JSON document on stdout, for a script or an agent.\n\n${chalk.bold(\"Manual steps\")}\n What the codemod cannot do safely for you is printed at the end of a run as a numbered list,\n each with the file it is about and the code to paste: mount the customizations, move a module\n it did not read, repoint an import of config/, regenerate the SDK, refresh the agent skills.\n The migration is finished when the list is done and config/ is removed.\n\nRun ${chalk.cyan(\"rebase migrate <subcommand> --help\")} for the rest.\n`);\n}\n\n/**\n * Run `rebase migrate <subcommand>`.\n *\n * @param subcommand the word after `migrate`\n * @param rawArgs the whole command line\n */\nexport async function migrateCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n switch (subcommand) {\n case \"collections-to-tables\": {\n const { printCollectionsToTablesHelp, runCollectionsToTables } = await import(\"../codemod/collections-to-tables/command\");\n if (wantsHelp(rawArgs)) {\n printCollectionsToTablesHelp();\n return;\n }\n const { flags, positionals } = parseCommandArgs({\n spec: COLLECTIONS_TO_TABLES_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"migrate collections-to-tables\",\n maxPositionals: 2\n });\n await runCollectionsToTables({\n check: flags[\"--check\"] === true,\n dryRun: flags[\"--dry-run\"] === true,\n json: flags[\"--json\"] === true,\n force: flags[\"--force\"] === true,\n skipSdkCalls: flags[\"--skip-sdk-calls\"] === true,\n acceptRuleChanges: flags[\"--accept-rule-changes\"] === true\n }, positionals[1]);\n return;\n }\n case \"sdk-calls\": {\n const { printSdkCallsHelp, runSdkCalls } = await import(\"../codemod/collections-to-tables/command\");\n if (wantsHelp(rawArgs)) {\n printSdkCallsHelp();\n return;\n }\n const { flags, positionals } = parseCommandArgs({\n spec: SDK_CALLS_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"migrate sdk-calls\",\n maxPositionals: 2\n });\n await runSdkCalls({\n dryRun: flags[\"--dry-run\"] === true,\n json: flags[\"--json\"] === true,\n force: flags[\"--force\"] === true\n }, positionals[1]);\n return;\n }\n // Bare `rebase migrate`: the CLI hands a group with no subcommand\n // `\"--help\"` as its subcommand, and that printed \"Unknown migrate\n // command\" for the one line most likely to be typed first.\n case undefined:\n case \"--help\":\n case \"-h\":\n case \"help\":\n printHelp();\n return;\n default:\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n // Two subcommands: name both, whatever was typed.\n console.error(chalk.red(`✗ ${unknownCommandMessage(subcommand, MIGRATE_SUBCOMMANDS, \"migrate\")} ` +\n `The subcommands are ${MIGRATE_SUBCOMMANDS.join(\" and \")}.`));\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,IAAa,sBAAsB,CAAC,yBAAyB,WAAW;;AAGxE,IAAa,8BAA8B;CACvC,WAAW;CACX,aAAa;CACb,UAAU;CACV,WAAW;CACX,oBAAoB;CACpB,yB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