@rebasepro/cli 0.28.2 → 0.29.0-canary.g0e3a0e7
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/{apps-BpYRGOaM.js → apps-Dg0NnmmJ.js} +3 -3
- package/dist/{apps-BpYRGOaM.js.map → apps-Dg0NnmmJ.js.map} +1 -1
- package/dist/{build-CS-Z75eK.js → build-1Zo35L6a.js} +3 -3
- package/dist/{build-CS-Z75eK.js.map → build-1Zo35L6a.js.map} +1 -1
- package/dist/{bundle-C0IBCVpV.js → bundle-CTkzO2WG.js} +2 -2
- package/dist/{bundle-C0IBCVpV.js.map → bundle-CTkzO2WG.js.map} +1 -1
- package/dist/{cloud-CXyZobBh.js → cloud-CFotGK2-.js} +511 -21
- package/dist/cloud-CFotGK2-.js.map +1 -0
- package/dist/commands/cloud/databases.d.ts +1 -0
- package/dist/commands/cloud/db-access.d.ts +25 -0
- package/dist/commands/cloud/index.d.ts +8 -0
- package/dist/commands/cloud/maintenance.d.ts +44 -0
- package/dist/commands/cloud/resources.d.ts +1 -1
- package/dist/{context-DvIUbE-b.js → context-DN1b9pCR.js} +2 -1
- package/dist/context-DN1b9pCR.js.map +1 -0
- package/dist/{fold-static-BMO8LC01.js → fold-static-vbZJeo37.js} +2 -2
- package/dist/{fold-static-BMO8LC01.js.map → fold-static-vbZJeo37.js.map} +1 -1
- package/dist/{generate_sdk-_SQuSbJW.js → generate_sdk-DCUUogIP.js} +2 -2
- package/dist/{generate_sdk-_SQuSbJW.js.map → generate_sdk-DCUUogIP.js.map} +1 -1
- package/dist/index.es.js +13 -13
- package/dist/{init-CHtpYLlh.js → init-YzfyEffT.js} +2 -2
- package/dist/{init-CHtpYLlh.js.map → init-YzfyEffT.js.map} +1 -1
- package/dist/{normalize-imports-BN0fzZS8.js → normalize-imports-xpSL_GuU.js} +2 -2
- package/dist/{normalize-imports-BN0fzZS8.js.map → normalize-imports-xpSL_GuU.js.map} +1 -1
- package/dist/{schema-2A0dd-Bv.js → schema-CApM25cs.js} +10 -9
- package/dist/schema-CApM25cs.js.map +1 -0
- package/dist/schema-reconcile-CX1_6Xqm.js +2 -0
- package/dist/{start-21GRsZKc.js → start-28EztR4R.js} +2 -2
- package/dist/{start-21GRsZKc.js.map → start-28EztR4R.js.map} +1 -1
- package/package.json +8 -8
- package/templates/template/ai-instructions.md +1 -1
- package/templates/views/AppView.tsx.tmpl +19 -32
- package/templates/views/EntityView.tsx.tmpl +8 -7
- package/dist/cloud-CXyZobBh.js.map +0 -1
- package/dist/context-DvIUbE-b.js.map +0 -1
- package/dist/schema-2A0dd-Bv.js.map +0 -1
- package/dist/schema-reconcile-C3ToVnHr.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { x as parseCommandArgs } from "./project-CasK56vN.js";
|
|
2
|
-
import { b as normalizeEsmSpecifiers } from "./bundle-
|
|
2
|
+
import { b as normalizeEsmSpecifiers } from "./bundle-CTkzO2WG.js";
|
|
3
3
|
import chalk from "chalk";
|
|
4
4
|
import fs from "fs";
|
|
5
5
|
import path from "path";
|
|
@@ -104,4 +104,4 @@ async function normalizeImportsCommand(rawArgs) {
|
|
|
104
104
|
//#endregion
|
|
105
105
|
export { normalizeImportsCommand };
|
|
106
106
|
|
|
107
|
-
//# sourceMappingURL=normalize-imports-
|
|
107
|
+
//# sourceMappingURL=normalize-imports-xpSL_GuU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"normalize-imports-
|
|
1
|
+
{"version":3,"file":"normalize-imports-xpSL_GuU.js","names":[],"sources":["../src/commands/normalize-imports.ts"],"sourcesContent":["import path from \"path\";\nimport fs from \"fs\";\n\nimport chalk from \"chalk\";\n\nimport { normalizeEsmSpecifiers } from \"../bundle\";\nimport { parseCommandArgs } from \"../utils/args\";\n\n/**\n * Give compiled output the relative-import extensions Node's ESM loader needs.\n *\n * ## Why a project needs this at all\n *\n * TypeScript does not rewrite module specifiers, deliberately and by long-stated\n * policy: what you write is what it emits. Node's ESM loader, equally\n * deliberately, resolves no extensions — `./authors` is not a module, only\n * `./authors.js` is. Between those two positions sits every project that writes\n * extensionless relative imports, which is most of them, and which\n * `moduleResolution: \"bundler\"` — what this scaffold ships — is designed for.\n *\n * The usual escape is to write the *output* extension in the *source*:\n * `import x from \"./authors.js\"` in a file called `authors.ts`. It works, and it\n * is a tax on every import in the project to satisfy a step the toolchain could\n * take itself. This is that step.\n *\n * ## Why it is a command\n *\n * `rebase build` has always done this to its own bundle — the specifiers in\n * `dist-bundle` are complete because {@link normalizeEsmSpecifiers} completes\n * them. Nothing did it for the plain `tsc` output that `rebase eject` runs\n * (`node dist/backend/src/index.js`) or that a self-hoster runs after\n * `pnpm build`. So the templates wrote `.js` in source, which is the tax, and\n * removing it silently broke eject at `pnpm start` while `check:eject` — which\n * typechecks with `noEmit` — stayed green.\n *\n * One implementation, on both paths, callable from a package.json script.\n *\n * Mechanical and verifiable: only relative specifiers are touched, and only when\n * the target resolves to a file that exists. Idempotent, so a build that runs it\n * twice is a build that runs it once.\n */\nexport const NORMALIZE_IMPORTS_FLAGS = {\n /** Report what would change without writing anything. */\n \"--check\": Boolean\n} as const;\n\nconst HELP = `\n${chalk.bold(\"rebase normalize-imports\")} — complete the relative imports in compiled output\n\n${chalk.green.bold(\"Usage\")}\n rebase normalize-imports ${chalk.blue(\"<dir>\")} [--check]\n\n${chalk.green.bold(\"What it does\")}\n TypeScript emits your module specifiers verbatim, and Node's ESM loader does\n not guess extensions — so \\`./authors\\` compiles fine and fails at run time.\n This rewrites each relative specifier in the emitted JavaScript to the file it\n actually resolves to, so your source can stay extensionless.\n\n Only relative specifiers, only when the target exists on disk, and idempotent.\n\n${chalk.green.bold(\"Arguments\")}\n ${chalk.blue(\"<dir>\")} The directory tsc emitted into, e.g. ${chalk.cyan(\"dist\")}\n\n${chalk.green.bold(\"Options\")}\n ${chalk.blue(\"--check\")} Report what would change and exit 1 if anything would\n ${chalk.gray(\"(for CI — the build itself should just run the rewrite)\")}\n\n${chalk.green.bold(\"Where it runs\")}\n The scaffold's ${chalk.cyan(\"config\")} and ${chalk.cyan(\"backend\")} build scripts, after ${chalk.cyan(\"tsc\")}.\n ${chalk.cyan(\"rebase build\")} already does the same to the bundle it writes.\n`;\n\nexport async function normalizeImportsCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals, help } = parseCommandArgs({\n spec: NORMALIZE_IMPORTS_FLAGS,\n rawArgs,\n commandWords: 1,\n command: \"normalize-imports\",\n maxPositionals: 1\n });\n\n if (help) {\n console.log(HELP);\n return;\n }\n\n const target = positionals[0] ?? \"dist\";\n const outDir = path.resolve(process.cwd(), target);\n\n // A missing directory is the common shape of \"tsc did not run\", and saying\n // so beats a rewrite that reports zero changes and looks like success.\n if (!fs.existsSync(outDir)) {\n throw new Error(\n `${target} does not exist — run your build first. `\n + \"This step rewrites what the compiler emitted; it does not compile.\"\n );\n }\n\n // `--check` reports and writes nothing: it is what a CI job runs to ask\n // whether the build did this step, and a check that repaired the output\n // would answer \"no\" once and \"yes\" for ever after.\n const check = flags[\"--check\"] === true;\n const { rewritten, unresolved } = normalizeEsmSpecifiers(outDir, { write: !check });\n // A failed check is a verdict, on stderr with exit 1 — not a thrown error,\n // whose handler adds a stack-trace hint to an answer that has no stack.\n const say = check ? console.error : console.log;\n\n if (unresolved.length > 0) {\n say(chalk.yellow(` ⚠ ${unresolved.length} relative import(s) resolve to no file:`));\n for (const specifier of unresolved.slice(0, 10)) {\n say(chalk.dim(` ${specifier}`));\n }\n if (unresolved.length > 10) {\n say(chalk.dim(` …and ${unresolved.length - 10} more`));\n }\n say(chalk.dim(\" These will throw ERR_MODULE_NOT_FOUND at run time. This command cannot complete them:\"));\n say(chalk.dim(\" there is no file to point them at — fix the import, or the build that should emit it.\"));\n }\n\n if (check) {\n if (rewritten > 0) {\n console.error(chalk.red(\n `✗ ${rewritten} relative import(s) in ${target} are incomplete for Node ESM. `\n + `Run \\`rebase normalize-imports ${target}\\` as part of the build.`\n ));\n }\n if (rewritten > 0 || unresolved.length > 0) {\n process.exitCode = 1;\n return;\n }\n console.log(chalk.green(`✓ every relative import in ${target} is complete`));\n return;\n }\n\n console.log(\n rewritten > 0\n ? chalk.dim(` completed ${rewritten} relative import(s) in ${target}/ for Node ESM`)\n : chalk.dim(` ${target}/ — every relative import was already complete`)\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,IAAa,0BAA0B;;AAEnC,WAAW,QACf;AAEA,IAAM,OAAO;EACX,MAAM,KAAK,0BAA0B,EAAE;;EAEvC,MAAM,MAAM,KAAK,OAAO,EAAE;6BACC,MAAM,KAAK,OAAO,EAAE;;EAE/C,MAAM,MAAM,KAAK,cAAc,EAAE;;;;;;;;EAQjC,MAAM,MAAM,KAAK,WAAW,EAAE;IAC5B,MAAM,KAAK,OAAO,EAAE,0DAA0D,MAAM,KAAK,MAAM,EAAE;;EAEnG,MAAM,MAAM,KAAK,SAAS,EAAE;IAC1B,MAAM,KAAK,SAAS,EAAE;4BACE,MAAM,KAAK,yDAAyD,EAAE;;EAEhG,MAAM,MAAM,KAAK,eAAe,EAAE;mBACjB,MAAM,KAAK,QAAQ,EAAE,OAAO,MAAM,KAAK,SAAS,EAAE,wBAAwB,MAAM,KAAK,KAAK,EAAE;IAC3G,MAAM,KAAK,cAAc,EAAE;;AAG/B,eAAsB,wBAAwB,SAAkC;CAC5E,MAAM,EAAE,OAAO,aAAa,SAAS,iBAAiB;EAClD,MAAM;EACN;EACA,cAAc;EACd,SAAS;EACT,gBAAgB;CACpB,CAAC;CAED,IAAI,MAAM;EACN,QAAQ,IAAI,IAAI;EAChB;CACJ;CAEA,MAAM,SAAS,YAAY,MAAM;CACjC,MAAM,SAAS,KAAK,QAAQ,QAAQ,IAAI,GAAG,MAAM;CAIjD,IAAI,CAAC,GAAG,WAAW,MAAM,GACrB,MAAM,IAAI,MACN,GAAG,OAAO,2GAEd;CAMJ,MAAM,QAAQ,MAAM,eAAe;CACnC,MAAM,EAAE,WAAW,eAAe,uBAAuB,QAAQ,EAAE,OAAO,CAAC,MAAM,CAAC;CAGlF,MAAM,MAAM,QAAQ,QAAQ,QAAQ,QAAQ;CAE5C,IAAI,WAAW,SAAS,GAAG;EACvB,IAAI,MAAM,OAAO,OAAO,WAAW,OAAO,wCAAwC,CAAC;EACnF,KAAK,MAAM,aAAa,WAAW,MAAM,GAAG,EAAE,GAC1C,IAAI,MAAM,IAAI,SAAS,WAAW,CAAC;EAEvC,IAAI,WAAW,SAAS,IACpB,IAAI,MAAM,IAAI,cAAc,WAAW,SAAS,GAAG,MAAM,CAAC;EAE9D,IAAI,MAAM,IAAI,2FAA2F,CAAC;EAC1G,IAAI,MAAM,IAAI,2FAA2F,CAAC;CAC9G;CAEA,IAAI,OAAO;EACP,IAAI,YAAY,GACZ,QAAQ,MAAM,MAAM,IAChB,KAAK,UAAU,yBAAyB,OAAO,+DACX,OAAO,yBAC/C,CAAC;EAEL,IAAI,YAAY,KAAK,WAAW,SAAS,GAAG;GACxC,QAAQ,WAAW;GACnB;EACJ;EACA,QAAQ,IAAI,MAAM,MAAM,8BAA8B,OAAO,aAAa,CAAC;EAC3E;CACJ;CAEA,QAAQ,IACJ,YAAY,IACN,MAAM,IAAI,eAAe,UAAU,yBAAyB,OAAO,eAAe,IAClF,MAAM,IAAI,KAAK,OAAO,+CAA+C,CAC/E;AACJ"}
|
|
@@ -42,12 +42,15 @@ function parseReconcileArgs(rawArgs) {
|
|
|
42
42
|
/** The plan, as a person reviews it. Returned as lines so it can be tested. */
|
|
43
43
|
function describeReconcilePlan(plan) {
|
|
44
44
|
const lines = [];
|
|
45
|
-
for (const r of plan.relaxed)
|
|
45
|
+
for (const r of plan.relaxed) {
|
|
46
|
+
const why = r.undeclared ? `no property in "${r.collection}" declares it, and every insert fails on it; its data stays` : `optional in "${r.collection}", NOT NULL in the database`;
|
|
47
|
+
lines.push(` ${chalk.cyan("relax")} ${r.table}.${r.column} ${chalk.gray(why)}`);
|
|
48
|
+
}
|
|
46
49
|
for (const d of plan.dropped) {
|
|
47
50
|
const rows = d.rowsWithValue === void 0 ? "" : `${d.rowsWithValue.toLocaleString("en-US")} row(s) hold a value`;
|
|
48
51
|
lines.push(` ${chalk.red("drop")} ${d.table}.${d.column} ${chalk.red(rows)}`);
|
|
49
52
|
}
|
|
50
|
-
const kept = plan.undeclared.filter((u) => !plan.dropped.some((d) => d.table === u.table && d.column === u.column));
|
|
53
|
+
const kept = plan.undeclared.filter((u) => !plan.dropped.some((d) => d.table === u.table && d.column === u.column) && !plan.relaxed.some((r) => r.undeclared && r.table === u.table && r.column === u.column));
|
|
51
54
|
for (const u of kept) {
|
|
52
55
|
const note = u.blocksInserts ? chalk.yellow("NOT NULL with no default: every insert fails until it is dropped or relaxed") : chalk.gray("no property declares it; kept");
|
|
53
56
|
lines.push(` ${chalk.gray("keep")} ${u.table}.${u.column} ${note}`);
|
|
@@ -120,11 +123,9 @@ async function schemaReconcileCommand(rawArgs) {
|
|
|
120
123
|
for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));
|
|
121
124
|
process.exit(1);
|
|
122
125
|
}
|
|
123
|
-
if (plan.statements.length === 0)
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
return;
|
|
127
|
-
}
|
|
126
|
+
if (plan.statements.length === 0) console.log(chalk.green("✓ Nothing to do: the database already matches what the collections declare."));
|
|
127
|
+
if (plan.undeclared.length > plan.dropped.length) console.log(chalk.gray(" To drop a column no property declares, name it: --drop <collection>.<column>"));
|
|
128
|
+
if (plan.statements.length === 0) return;
|
|
128
129
|
console.log(chalk.bold("\nStatements"));
|
|
129
130
|
for (const statement of plan.statements) console.log(` ${statement}`);
|
|
130
131
|
if (plan.dropped.length > 0) console.log(chalk.red("\n Dropping a column destroys its data. Back the database up first if you may want it back."));
|
|
@@ -186,7 +187,7 @@ async function schemaCommand(subcommand, rawArgs) {
|
|
|
186
187
|
const projectRoot = requireProjectRoot();
|
|
187
188
|
if (subcommand === "reconcile") {
|
|
188
189
|
recordEvent("cli.schema", { subcommand }, { projectRoot });
|
|
189
|
-
const { schemaReconcileCommand } = await import("./schema-reconcile-
|
|
190
|
+
const { schemaReconcileCommand } = await import("./schema-reconcile-CX1_6Xqm.js");
|
|
190
191
|
await schemaReconcileCommand(rawArgs);
|
|
191
192
|
return;
|
|
192
193
|
}
|
|
@@ -318,4 +319,4 @@ ${chalk.green.bold("stale Options")}
|
|
|
318
319
|
//#endregion
|
|
319
320
|
export { SCHEMA_SUBCOMMANDS, schemaReconcileCommand as i, describeReconcilePlan as n, parseReconcileArgs as r, schemaCommand, RECONCILE_USAGE as t };
|
|
320
321
|
|
|
321
|
-
//# sourceMappingURL=schema-
|
|
322
|
+
//# sourceMappingURL=schema-CApM25cs.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-CApM25cs.js","names":[],"sources":["../src/commands/schema-reconcile.ts","../src/commands/schema.ts"],"sourcesContent":["/**\n * CLI command: rebase schema reconcile\n *\n * The reviewed step for what boot will not do. Boot only ever adds, so a\n * property made optional leaves its column NOT NULL, and a property removed\n * leaves its column behind, with its data, and blocking inserts if it was\n * required. This asks the running backend for the plan that fixes both, prints\n * it, and applies it only once confirmed.\n *\n * Through the backend rather than a database URL, because on Rebase Cloud the\n * backend is the one thing that can reach the database — and because it plans\n * against the collections it actually runs, not the ones in this checkout.\n * Columns are dropped only when named with `--drop`; the confirmation sends\n * the plan's digest, so the server runs exactly the statements printed here.\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport readline from \"node:readline/promises\";\nimport { RebaseApiError } from \"@rebasepro/client\";\nimport type { SchemaReconcilePlan } from \"@rebasepro/types\";\nimport { requireProjectRoot, readEnvFile } from \"../utils/project\";\nimport { UsageError } from \"../utils/args\";\nimport { cliUserAgent } from \"../utils/version\";\nimport { describeFailure, requireBackendUrl } from \"./api-keys\";\n\nexport const RECONCILE_USAGE = \"rebase schema reconcile [--drop <collection>.<column>]... [--yes]\";\n\nexport function parseReconcileArgs(rawArgs: string[]): { drop: string[]; yes: boolean } {\n const flags = arg({ \"--drop\": [String], \"--yes\": Boolean, \"-y\": \"--yes\" }, { argv: rawArgs.slice(2) });\n if (flags._.length > 0) throw new UsageError(`Unexpected argument \"${flags._[0]}\". Usage: ${RECONCILE_USAGE}`);\n return { drop: flags[\"--drop\"] ?? [], yes: flags[\"--yes\"] === true };\n}\n\n/** The plan, as a person reviews it. Returned as lines so it can be tested. */\nexport function describeReconcilePlan(plan: SchemaReconcilePlan): string[] {\n const lines: string[] = [];\n for (const r of plan.relaxed) {\n const why = r.undeclared\n ? `no property in \"${r.collection}\" declares it, and every insert fails on it; its data stays`\n : `optional in \"${r.collection}\", NOT NULL in the database`;\n lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(why)}`);\n }\n for (const d of plan.dropped) {\n const rows = d.rowsWithValue === undefined ? \"\" : `${d.rowsWithValue.toLocaleString(\"en-US\")} row(s) hold a value`;\n lines.push(` ${chalk.red(\"drop\")} ${d.table}.${d.column} ${chalk.red(rows)}`);\n }\n const kept = plan.undeclared.filter(u =>\n !plan.dropped.some(d => d.table === u.table && d.column === u.column)\n && !plan.relaxed.some(r => r.undeclared && r.table === u.table && r.column === u.column));\n for (const u of kept) {\n const note = u.blocksInserts\n ? chalk.yellow(\"NOT NULL with no default: every insert fails until it is dropped or relaxed\")\n : chalk.gray(\"no property declares it; kept\");\n lines.push(` ${chalk.gray(\"keep\")} ${u.table}.${u.column} ${note}`);\n }\n return lines;\n}\n\ninterface Backend {\n baseUrl: string;\n post<T>(path: string, body: unknown): Promise<T>;\n}\n\n/** The project's backend, holding the service key. */\nfunction connect(): Backend {\n const projectRoot = requireProjectRoot();\n const env = readEnvFile(projectRoot);\n const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;\n if (!serviceKey) {\n console.error(chalk.red(\"✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema.\"));\n process.exit(1);\n }\n const baseUrl = requireBackendUrl(env, projectRoot).replace(/\\/+$/, \"\");\n return {\n baseUrl,\n async post<T>(path: string, body: unknown): Promise<T> {\n let response: Response;\n try {\n response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {\n method: \"POST\",\n headers: {\n \"Authorization\": `Bearer ${serviceKey}`,\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\",\n \"User-Agent\": cliUserAgent()\n },\n body: JSON.stringify(body)\n });\n } catch (error: unknown) {\n throw new RebaseApiError(error instanceof Error ? error.message : String(error), { status: 0, code: \"NETWORK_ERROR\" });\n }\n const answer: unknown = await response.json().catch(() => undefined);\n if (!response.ok) {\n const error = answer && typeof answer === \"object\" && \"error\" in answer && answer.error && typeof answer.error === \"object\"\n ? answer.error as { message?: unknown; code?: unknown; details?: unknown }\n : undefined;\n throw new RebaseApiError(\n typeof error?.message === \"string\" ? error.message : `The server answered ${response.status}.`,\n { status: response.status, code: typeof error?.code === \"string\" ? error.code : undefined, details: error?.details }\n );\n }\n return answer as T;\n }\n };\n}\n\nfunction fail(action: string, error: unknown, baseUrl: string): never {\n for (const line of describeFailure(action, error, baseUrl)) {\n console.error(line.startsWith(\"✗\") ? chalk.red(line) : chalk.gray(line));\n }\n if (error instanceof RebaseApiError && error.status === 404) {\n console.error(chalk.gray(\" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`.\"));\n }\n process.exit(1);\n}\n\nexport async function schemaReconcileCommand(rawArgs: string[]): Promise<void> {\n const { drop, yes } = parseReconcileArgs(rawArgs);\n const backend = connect();\n\n let plan: SchemaReconcilePlan;\n try {\n plan = await backend.post<SchemaReconcilePlan>(\"/plan\", { drop });\n } catch (error) {\n fail(\"Failed to plan the reconcile\", error, backend.baseUrl);\n }\n\n console.log(chalk.bold(`\\nSchema reconcile for ${backend.baseUrl}\\n`));\n const described = describeReconcilePlan(plan);\n if (described.length > 0) console.log(described.join(\"\\n\"));\n\n if (plan.problems.length > 0) {\n console.error(chalk.red(\"\\n✗ This plan cannot be applied:\"));\n for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));\n process.exit(1);\n }\n if (plan.statements.length === 0) {\n console.log(chalk.green(\"✓ Nothing to do: the database already matches what the collections declare.\"));\n }\n if (plan.undeclared.length > plan.dropped.length) {\n console.log(chalk.gray(\" To drop a column no property declares, name it: --drop <collection>.<column>\"));\n }\n if (plan.statements.length === 0) return;\n\n console.log(chalk.bold(\"\\nStatements\"));\n for (const statement of plan.statements) console.log(` ${statement}`);\n if (plan.dropped.length > 0) {\n console.log(chalk.red(\"\\n Dropping a column destroys its data. Back the database up first if you may want it back.\"));\n }\n\n if (!yes) {\n if (!process.stdin.isTTY) {\n console.error(chalk.red(\"\\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan.\"));\n process.exit(1);\n }\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n const answer = (await rl.question(`\\nApply ${plan.statements.length} statement(s)? Type \"yes\" to continue: `)).trim();\n rl.close();\n if (answer !== \"yes\") {\n console.log(chalk.gray(\"Aborted. Nothing was changed.\"));\n return;\n }\n }\n\n try {\n const result = await backend.post<{ applied: string[] }>(\"/apply\", { drop, confirm: plan.digest });\n console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));\n } catch (error) {\n if (error instanceof RebaseApiError && error.code === \"SCHEMA_RECONCILE_STALE\") {\n console.error(chalk.red(\"✗ Not applied: the database or the collections changed since this plan was made. Run it again to review the new plan.\"));\n process.exit(1);\n }\n fail(\"Failed to apply the reconcile\", error, backend.baseUrl);\n }\n}\n","/**\n * CLI command: rebase schema <action>\n */\nimport arg from \"arg\";\nimport chalk from \"chalk\";\nimport { ensureDockerDatabase, spawnDriverCli } from \"./db\";\nimport {\n requireProjectRoot,\n requireBackendDir,\n getActiveBackendPlugin,\n resolvePluginCliScript,\n resolveTsx,\n findEnvFile,\n exitDependenciesNotInstalled\n} from \"../utils/project\";\nimport { recordEvent } from \"../telemetry\";\nimport { wantsHelp } from \"../utils/args\";\nimport { reportSpawnFailure } from \"../utils/spawn-error\";\nimport { argsFromCommand } from \"../utils/command-words\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from \"../dev-db/prepare\";\nimport { absolutizeLocalPathArgs } from \"./db\";\nimport { COLLECTIONS_FLAG_HELP, refuseMissingCollectionsPath } from \"../utils/path-flags\";\nimport { collectionsDirArgs } from \"../utils/collections-dir\";\nimport { RECONCILE_USAGE } from \"./schema-reconcile\";\n\n/**\n * The line handed to the driver, its paths resolved from where the command was\n * run (the driver runs in `backend/`). `--schema` is left alone: on\n * `introspect` it names a Postgres schema, not a file.\n */\nexport function schemaDriverArgs(rawArgs: string[], cwd: string): string[] {\n return absolutizeLocalPathArgs(argsFromCommand(rawArgs, \"schema\"), cwd, [\"--collections\", \"-c\", \"--output\", \"-o\", \"--out\"]);\n}\n\nexport async function schemaCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n // `--help` is answered here, before `requireProjectRoot` and before the\n // driver is spawned — the same shape `db.ts` already uses, and for the same\n // reason.\n //\n // `cli.ts` rewrites the subcommand to `\"--help\"` only when the user named\n // none, so `rebase schema --help` was covered and `rebase schema generate\n // --help` was not: the flag travelled into `rawArgs.slice(2)` and reached\n // the driver, whose own `schemaCommand` has no `--help` case. It *ran the\n // generator* — overwriting `src/schema.generated.ts` — for a flag whose\n // entire job is to print text. Worse, the first thing it hit outside a\n // project was `requireProjectRoot`, so `rebase schema introspect --help` in\n // an empty directory exited 1 with \"Could not find a Rebase project root\":\n // help you cannot read until you already have a project is help for nobody.\n if (!subcommand || subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printSchemaHelp(subcommand === \"--help\" ? undefined : subcommand);\n return;\n }\n\n // A typo is answered here, in the same words every other family uses.\n //\n // It used to travel to the driver, which said the bare line `Unknown schema\n // command.` — no list, no pointer, no did-you-mean, for a family with three\n // subcommands. The set comes from the help table, so what a typo is measured\n // against and what `--help` prints cannot drift apart.\n if (!SCHEMA_ACTION_HELP[subcommand]) {\n unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), \"schema\");\n }\n\n const projectRoot = requireProjectRoot();\n\n // Talks to the running backend, not the driver: on Rebase Cloud the\n // backend is the only thing that reaches the database.\n if (subcommand === \"reconcile\") {\n void recordEvent(\"cli.schema\", { subcommand }, { projectRoot });\n const { schemaReconcileCommand } = await import(\"./schema-reconcile\");\n await schemaReconcileCommand(rawArgs);\n return;\n }\n\n // Fire-and-forget, and a no-op unless the developer opted in. Never awaited:\n // the command is what the user is waiting for, and a slow collector must not\n // sit in front of it.\n void recordEvent(\"cli.schema\", { subcommand: subcommand ?? \"none\" }, { projectRoot });\n const backendDir = requireBackendDir(projectRoot);\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 // Which database this project is on, so the driver's closing line does not\n // recommend a command that database refuses. A pure decision — nothing is\n // started, which matters here above all: `schema generate` reads collection\n // files and writes one file, and booting a database to run it would be a\n // side effect nobody asked for.\n env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? \"\";\n\n refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir);\n\n // `introspect` is the one schema command that reads a database, and it\n // reads the project's — resolved the way every `db` command resolves it,\n // started if that is what it takes. It used to pass `.env` and nothing\n // else, so on the managed database or after `rebase dev --docker` (with\n // the scaffold's DATABASE_URL commented out, on purpose) it said\n // \"DATABASE_URL is not set\", and `--docker` and `--database-url` passed the\n // flag check only to be ignored.\n if (subcommand === \"introspect\") {\n const flags = arg(\n { \"--database-url\": String, \"--docker\": Boolean },\n { argv: rawArgs.slice(2), permissive: true }\n );\n await ensureDockerDatabase(projectRoot, rawArgs);\n const prepared = await prepareDatabaseEnv(projectRoot, {\n flagUrl: flags[\"--database-url\"] ?? null,\n flagDocker: flags[\"--docker\"] === true,\n onProgress: (message) => console.log(chalk.gray(` ${message}`))\n });\n Object.assign(env, prepared.env);\n env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;\n for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));\n }\n\n try {\n // The one spawn, shared with `db`. This file used to carry its own copy\n // of the tsx-or-node decision; three copies of that rule existed and two\n // were fixed while the third went on spawning plain node.\n const driverArgs = schemaDriverArgs(rawArgs, process.cwd());\n await spawnDriverCli(\n { projectRoot, backendDir, pluginCli, env },\n [...driverArgs, ...collectionsDirArgs(projectRoot, driverArgs)]\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 (ENOENT on tsx,\n // EACCES on the script) printed nothing at all, and this used to exit 1\n // in silence.\n reportSpawnFailure(error);\n process.exit(1);\n }\n}\n\n/** One page per subcommand, so `rebase schema <action> --help` says something. */\nconst SCHEMA_ACTION_HELP: Record<string, { usage: string; summary: string; notes?: string[] }> = {\n generate: {\n usage: \"rebase schema generate [--collections <dir>] [--output <file>] [--watch]\",\n summary: \"Generate the Drizzle schema from the collection definitions.\",\n notes: [\"--watch regenerates on every change to a collection file.\"]\n },\n introspect: {\n usage: \"rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]\",\n summary: \"Read an existing database and write Rebase collection definitions from it.\",\n notes: [\n \"--force overwrites collection files that are already there.\",\n \"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; \"\n + \"--no-data-inference reads the structure only. Without either it asks, and without a terminal \"\n + \"it reads the structure only.\",\n \"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; \"\n + \"--docker uses the compose one, starting it if needed.\"\n ]\n },\n reconcile: {\n usage: RECONCILE_USAGE,\n summary: \"Relax and drop what boot will not: NOT NULL on properties made optional, and columns no property declares.\",\n notes: [\n \"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.\",\n \"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.\",\n \"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env.\"\n ]\n },\n stale: {\n usage: \"rebase schema stale [--collections <dir>] [--output <file>] [--fix]\",\n summary: \"Report generated schema files that no longer match the collections.\",\n notes: [\"--fix regenerates them instead of only reporting.\"]\n }\n};\n\n/** Every subcommand the family dispatches — the help table's keys. */\nexport const SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);\n\nfunction printSchemaHelp(action?: string) {\n const entry = action ? SCHEMA_ACTION_HELP[action] : undefined;\n if (entry) {\n console.log(`\n${chalk.bold(`rebase schema ${action}`)}\n\n ${entry.summary}\n\n${chalk.green.bold(\"Usage\")}\n ${chalk.blue(entry.usage)}\n${entry.notes?.length ? `\\n${chalk.green.bold(\"Notes\")}\\n${entry.notes.map(n => ` ${chalk.gray(`• ${n}`)}`).join(\"\\n\")}\\n` : \"\"}\n${chalk.gray(\"Run `rebase schema --help` for every subcommand.\")}\n`);\n return;\n }\n\n console.log(`\n${chalk.bold(\"rebase schema\")} — Schema management commands\n\n${chalk.green.bold(\"Usage\")}\n rebase schema ${chalk.blue(\"<command>\")} [options]\n\n${chalk.green.bold(\"Commands\")}\n ${chalk.gray(\"(Commands are provided by your active database driver plugin)\")}\n ${chalk.blue.bold(\"generate\")} Generate Schema from collection definitions\n ${chalk.blue.bold(\"introspect\")} Introspect an existing database to generate collection definitions\n ${chalk.blue.bold(\"stale\")} Report generated schema files that no longer match the collections\n ${chalk.blue.bold(\"reconcile\")} Relax NOT NULL and drop columns the collections no longer declare, after review\n\n${chalk.green.bold(\"generate Options\")}\n ${chalk.blue(\"--collections, -c\")} ${COLLECTIONS_FLAG_HELP}\n ${chalk.blue(\"--output, -o\")} Output path for generated schema\n ${chalk.blue(\"--watch, -w\")} Watch for changes and regenerate automatically\n\n${chalk.green.bold(\"introspect Options\")}\n ${chalk.blue(\"--output, -o\")} Output directory for generated collection files\n ${chalk.blue(\"--schema\")} Postgres schema to read (default: public)\n ${chalk.blue(\"--force, -f\")} Overwrite collection files that already exist\n ${chalk.blue(\"--database-url\")} Read this database instead of the project's own\n ${chalk.blue(\"--docker\")} Read the compose database, starting it if needed\n ${chalk.blue(\"--data-inference\")} Sample rows to detect formats and constraints ${chalk.gray(\"(asked when omitted)\")}\n ${chalk.blue(\"--no-data-inference\")} Read the structure only, without asking\n\n${chalk.green.bold(\"stale Options\")}\n ${chalk.blue(\"--fix\")} Regenerate the stale files instead of only reporting them\n`);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAa,kBAAkB;AAE/B,SAAgB,mBAAmB,SAAqD;CACpF,MAAM,QAAQ,IAAI;EAAE,UAAU,CAAC,MAAM;EAAG,SAAS;EAAS,MAAM;CAAQ,GAAG,EAAE,MAAM,QAAQ,MAAM,CAAC,EAAE,CAAC;CACrG,IAAI,MAAM,EAAE,SAAS,GAAG,MAAM,IAAI,WAAW,wBAAwB,MAAM,EAAE,GAAG,YAAY,iBAAiB;CAC7G,OAAO;EAAE,MAAM,MAAM,aAAa,CAAC;EAAG,KAAK,MAAM,aAAa;CAAK;AACvE;;AAGA,SAAgB,sBAAsB,MAAqC;CACvE,MAAM,QAAkB,CAAC;CACzB,KAAK,MAAM,KAAK,KAAK,SAAS;EAC1B,MAAM,MAAM,EAAE,aACR,mBAAmB,EAAE,WAAW,+DAChC,gBAAgB,EAAE,WAAW;EACnC,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,EAAE,O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AEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { n as getPMCommands, t as detectPackageManager } from "./package-manager-DSEOwTqM.js";
|
|
2
2
|
import { c as findProjectRoot, d as readEnvFile, o as findEnvFile, p as requireProjectRoot, w as wantsHelp, x as parseCommandArgs } from "./project-CasK56vN.js";
|
|
3
|
-
import { t as DEFAULT_BUNDLE_DIR } from "./bundle-
|
|
3
|
+
import { t as DEFAULT_BUNDLE_DIR } from "./bundle-CTkzO2WG.js";
|
|
4
4
|
import { t as invokedRebaseCommand } from "./invoked-command-CG_rIa_o.js";
|
|
5
5
|
import chalk from "chalk";
|
|
6
6
|
import fs from "fs";
|
|
@@ -316,4 +316,4 @@ async function startWorkspaceBackend(projectRoot, env) {
|
|
|
316
316
|
//#endregion
|
|
317
317
|
export { startCommand };
|
|
318
318
|
|
|
319
|
-
//# sourceMappingURL=start-
|
|
319
|
+
//# sourceMappingURL=start-28EztR4R.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"start-21GRsZKc.js","names":[],"sources":["../src/commands/start.ts"],"sourcesContent":["/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile, findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { invokedRebaseCommand } from \"../utils/invoked-command\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { detectPackageManager, getPMCommands, type PMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport type { RebaseBundleStatic } from \"@rebasepro/types\";\nimport type { DevDatabase } from \"../dev-db/resolve\";\nimport type { DaemonState } from \"../dev-db/state\";\nimport { MANAGED_POOL_MAX } from \"../dev-db/constraints\";\n\n/**\n * The help's line that runs `start` on the database `rebase dev` uses, spelled\n * as the reader can type it.\n *\n * In a project, the project's package manager: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so a bare `rebase` is \"command not found\" —\n * `pnpm exec rebase …`, as `missingDatabaseUrl` and the CLI's other hints say\n * it. Outside one, the way this CLI was started (`invokedRebaseCommand`).\n */\nexport function startHelpRunLine(projectRoot: string | null = findProjectRoot()): string {\n const rebase = (args: string[]): string => (projectRoot\n ? getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", args)\n : [...invokedRebaseCommand(), ...args]).join(\" \");\n return `DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`;\n}\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --workspace Run the backend workspace's own start script\n -h, --help Show this help\n\nRuns the bundle the way a deployment does, reading PORT and the rest of .env,\nin whatever NODE_ENV the shell or .env sets. A scaffolded .env says\ndevelopment, which keeps development behaviour on — the first account to\nregister becomes the admin. For a production server, run it with\nNODE_ENV=production; it says so at start when it is not one.\n\nIt needs a DATABASE_URL, and starts no database of its own. To run it on the\ndatabase ${chalk.cyan(\"rebase dev\")} uses: ${chalk.cyan(startHelpRunLine())}\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\n/** The NODE_ENV the runtime will see, and where it comes from. */\nexport interface StartNodeEnv {\n value: string | undefined;\n source: \"shell\" | \".env\" | \"unset\";\n}\n\n/**\n * What NODE_ENV the server will boot in. The shell wins — dotenv never\n * overrides a variable that is already set — then `.env`.\n */\nexport function startNodeEnv(projectRoot: string): StartNodeEnv {\n if (process.env.NODE_ENV !== undefined) return { value: process.env.NODE_ENV, source: \"shell\" };\n const fromFile = readEnvFile(projectRoot).NODE_ENV;\n return fromFile !== undefined ? { value: fromFile, source: \".env\" } : { value: undefined, source: \"unset\" };\n}\n\n/**\n * The banner for a `rebase start` that is not a production server, or `null`.\n *\n * Not forced to production: the scaffold's `.env` points at a loopback\n * database, which a production boot refuses, so forcing it would break the\n * documented local run. What must not happen is the silence — a command the\n * help called \"(production)\" booting with the first-registration window open.\n */\nexport function nonProductionWarning(nodeEnv: StartNodeEnv): string[] | null {\n if (nodeEnv.value === \"production\") return null;\n const what = nodeEnv.value === undefined\n ? \"NODE_ENV is not set\"\n : `NODE_ENV=${nodeEnv.value}${nodeEnv.source === \".env\" ? \" (from .env)\" : \"\"}`;\n return [\n chalk.yellow.bold(`⚠ ${what} — this is not a production server.`),\n chalk.yellow(\" Development behaviour is on: the first account to register becomes the admin\"),\n chalk.yellow(\" (REBASE_ADMIN_EMAIL is ignored), and with no SMTP configured, sign-in and\"),\n chalk.yellow(\" password-reset links are printed to this log instead of sent.\"),\n chalk.gray(\" For a production server, run it with NODE_ENV=production (in the shell or .env).\")\n ];\n}\n\n/**\n * What to say about the apps a bundle serves only on their own hostname.\n *\n * The runtime prints \"Server running at http://localhost:<port>\", and an app\n * whose `path` names a hostname answers only requests carrying that `Host` —\n * so opening the printed URL showed a 404 for an app that was running fine,\n * and nothing said why. One line per such app, with a command that reaches it.\n */\nexport function hostRoutedNotice(staticApps: readonly RebaseBundleStatic[], port: string | undefined): string[] {\n const routed = staticApps.filter(app => app.host);\n if (routed.length === 0) return [];\n const origin = `http://localhost:${port || \"<port>\"}`;\n return [\n ...routed.map(app => {\n const name = app.name ?? path.posix.basename(app.dir);\n return chalk.yellow(`⚠ ${name} answers only on ${app.host}, so ${origin}${app.path} will not show it here. Reach it with:`)\n + `\\n ${chalk.cyan(`curl -H \"Host: ${app.host}\" ${origin}${app.path}`)}`;\n }),\n chalk.gray(` (or point ${routed.map(app => app.host).join(\", \")} at 127.0.0.1 in /etc/hosts)`),\n \"\"\n ];\n}\n\n/**\n * What to say when there is no DATABASE_URL for the runtime, or `null`.\n *\n * The runtime requires one, and its refusal — `DATABASE_URL: is required`, and\n * a link to the self-hosting docs — is right for a deployment and says nothing\n * to the reader most likely to see it: someone running the scaffold's own\n * `.env`, which leaves DATABASE_URL commented out because `rebase dev` brings a\n * database of its own. That database is one command away, so this names it.\n *\n * `kind` is what `rebase dev` runs this project on, so the line can say which\n * database `rebase db url` will print. A blank value is unset, as the runtime\n * reads it. `pm` spells the command: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so it is `pnpm exec rebase …` or\n * `npx rebase …`, as in the CLI's other hints.\n */\nexport function missingDatabaseUrl(\n env: Record<string, string | undefined>,\n kind: DevDatabase[\"kind\"] | null,\n pm: PMCommands\n): string[] | null {\n if (env.DATABASE_URL?.trim()) return null;\n\n const rebase = (args: string[]): string => pm.exec(\"rebase\", args).join(\" \");\n\n const which = kind === \"docker\"\n ? \"the Docker database `rebase dev --docker` uses\"\n : kind === \"managed\"\n ? \"the managed development database (PGlite) `rebase dev` uses\"\n : \"this project's development database\";\n return [\n chalk.red(\"✗ DATABASE_URL is not set, so the runtime has no database to start against.\"),\n chalk.gray(\" `rebase start` runs the bundle the way a deployment does, against the database you name;\"),\n chalk.gray(\" `rebase dev` is the command that brings one of its own.\"),\n \"\",\n ` To run it on ${which}:`,\n ` ${chalk.cyan(`DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`)}`,\n \"\",\n chalk.gray(\" For a deployment, set DATABASE_URL in the environment or in .env.\"),\n chalk.gray(\" See https://rebase.pro/docs/deployment/self-hosting/ for the variables a deployment needs.\")\n ];\n}\n\n/**\n * What the runtime needs when DATABASE_URL is this project's managed\n * development database, or nothing.\n *\n * The connection ceiling `rebase dev` sets for it (`MANAGED_POOL_MAX`). PGlite\n * is one session behind a socket server that accepts only a few connections,\n * and a running `rebase dev` holds some. With an ordinary pool, the boot's\n * concurrent probes opened more than were left, the ones over were refused,\n * and a probe that could not connect read as a table that was not there:\n * `❌ rebase.cron_claims is unavailable`, beside tables that existed.\n *\n * Recognised by the running daemon's ports, which is what `rebase db url`\n * prints from. A ceiling set by hand is kept.\n */\nexport function managedDatabaseRuntimeEnv(\n databaseUrl: string | undefined,\n daemon: DaemonState | null,\n env: Record<string, string | undefined>\n): Record<string, string> {\n if (!databaseUrl || !daemon || env.REBASE_DB_POOL_MAX !== undefined) return {};\n let url: URL;\n try {\n url = new URL(databaseUrl);\n } catch {\n return {};\n }\n if (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname)) return {};\n const ports = [daemon.port, ...Object.values(daemon.databases ?? {}).map(database => database.port)];\n if (!ports.includes(Number(url.port))) return {};\n return { REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX) };\n}\n\nfunction readBundleStatic(bundleDir: string): RebaseBundleStatic[] {\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(bundleDir, \"manifest.json\"), \"utf8\")) as { entry?: { static?: RebaseBundleStatic[] } };\n return manifest.entry?.static ?? [];\n } catch {\n return [];\n }\n}\n\nfunction printNonProductionWarning(projectRoot: string): void {\n const warning = nonProductionWarning(startNodeEnv(projectRoot));\n if (!warning) return;\n console.log(warning.join(\"\\n\") + \"\\n\");\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n const { flags: args } = parseCommandArgs({\n spec: {\n \"--bundle\": String,\n \"--workspace\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"start\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\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\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n // Before either path, and before the runtime's own boot logs bury it.\n printNonProductionWarning(projectRoot);\n\n if (args[\"--workspace\"] || !hasBundle) {\n if (!args[\"--workspace\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile, quiet: true });\n }\n\n // Before the runtime, which would refuse with a message written for a\n // deployment. See `missingDatabaseUrl`.\n if (!process.env.DATABASE_URL?.trim()) {\n const { devDatabaseKind } = await import(\"../dev-db/prepare\");\n const missing = missingDatabaseUrl(process.env, devDatabaseKind(projectRoot), getPMCommands(detectPackageManager(projectRoot)));\n if (missing) {\n for (const line of missing) console.error(line);\n process.exit(1);\n }\n }\n\n // See `managedDatabaseRuntimeEnv`.\n const { findRunningDaemon } = await import(\"../dev-db/daemon\");\n const managedEnv = managedDatabaseRuntimeEnv(process.env.DATABASE_URL, await findRunningDaemon(projectRoot), process.env);\n if (managedEnv.REBASE_DB_POOL_MAX) {\n Object.assign(process.env, managedEnv);\n console.log(chalk.dim(\n \"DATABASE_URL is this project's managed development database: the runtime uses one connection,\\n\" +\n \"as `rebase dev` does, so requests are served one at a time.\\n\"\n ));\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n for (const line of hostRoutedNotice(readBundleStatic(bundleDir), process.env.PORT)) console.log(line);\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,iBAAiB,cAA6B,gBAAgB,GAAW;CACrF,MAAM,UAAU,UAA4B,cACtC,cAAc,qBAAqB,WAAW,CAAC,CAAC,CAAC,KAAK,UAAU,IAAI,IACpE,CAAC,GAAG,qBAAqB,GAAG,GAAG,IAAI,EAAA,CAAG,KAAK,GAAG;CACpD,OAAO,mBAAmB,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC;AACzE;AAEA,SAAS,YAAkB;CACvB,QAAQ,IAAI;EACd,MAAM,KAAK,cAAc,EAAE;;EAE3B,MAAM,KAAK,OAAO,EAAE;;;EAGpB,MAAM,KAAK,SAAS,EAAE;kDAC0B,mBAAmB;;;;;;;;;;;WAW1D,MAAM,KAAK,YAAY,EAAE,SAAS,MAAM,KAAK,iBAAiB,CAAC,EAAE;;mBAEzD,MAAM,KAAK,cAAc,EAAE;EAC5C,KAAK,CAAC;AACR;;;;;AAYA,SAAgB,aAAa,aAAmC;CAC5D,IAAA,QAAA,IAAA,aAA6B,KAAA,GAAW,OAAO;EAAE,OAAA,QAAA,IAAA;EA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K,MAAM,SAAS,SAAS;GACzB,IAAI,MAAM,SAAS,UAAU,MAAM,KAAK,WAAW,GAAG,GAAG;GACzD,MAAM,OAAO,KAAK,KAAK,WAAW,MAAM,IAAI;GAC5C,MAAM,KAAK,KAAK,KAAK,WAAW,MAAM,IAAI;GAI1C,IAAI,MAAM,KAAK,WAAW,GAAG,KAAK,MAAM,YAAY,GAAG;IACnD,GAAG,UAAU,IAAI,EAAE,WAAW,KAAK,CAAC;IACpC,SAAS,MAAM,EAAE;IACjB;GACJ;GAEA,IAAI,GAAG,WAAW,EAAE,GAAG;GACvB,IAAI;IACA,GAAG,YAAY,GAAG,aAAa,IAAI,GAAG,IAAI,UAAU;IACpD;GACJ,QAAQ,CAGR;EACJ;CACJ;CAEA,KAAK,MAAM,UAAU,SAAS,SAAS,QAAQ,MAAM;CAErD,IAAI,SAAS,GACT,QAAQ,IAAI,MAAM,IACd,YAAY,OAAO;CAEvB,CAAC;AAET;AAEA,eAAe,sBAAsB,aAAqB,KAA4C;CAGlG,MAAM,WADO,cADF,qBAAqB,WACL,CACV,CAAA,CAAK,aAAa,WAAW,OAAO;CAErD,QAAQ,IAAI,GAAG,MAAM,KAAK,QAAQ,EAAE,gCAAgC;CAEpE,IAAI;EACA,MAAM,MAAM,SAAS,IAAI,SAAS,MAAM,CAAC,GAAG;GACxC,KAAK;GACL,OAAO;GACP;EACJ,CAAC;CACL,QAAQ;EACJ,QAAQ,MAAM,MAAM,IAAI,6BAA6B,CAAC;EACtD,QAAQ,KAAK,CAAC;CAClB;AACJ"}
|
|
1
|
+
{"version":3,"file":"start-28EztR4R.js","names":[],"sources":["../src/commands/start.ts"],"sourcesContent":["/**\n * CLI command: rebase start\n *\n * Runs a built bundle through the Rebase runtime — the same path the official\n * container image takes, so what you test locally is what a deployment runs.\n *\n * When there is no bundle (an ejected backend, or a project that has not adopted\n * `rebase.json`) this falls back to the backend workspace's own `start` script,\n * which is what such a project has always used.\n */\nimport fs from \"fs\";\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport { execa } from \"execa\";\nimport { requireProjectRoot, findEnvFile, findProjectRoot, readEnvFile } from \"../utils/project\";\nimport { invokedRebaseCommand } from \"../utils/invoked-command\";\nimport { parseCommandArgs, wantsHelp } from \"../utils/args\";\nimport { detectPackageManager, getPMCommands, type PMCommands } from \"../utils/package-manager\";\nimport { DEFAULT_BUNDLE_DIR } from \"../bundle\";\nimport type { RebaseBundleStatic } from \"@rebasepro/types\";\nimport type { DevDatabase } from \"../dev-db/resolve\";\nimport type { DaemonState } from \"../dev-db/state\";\nimport { MANAGED_POOL_MAX } from \"../dev-db/constraints\";\n\n/**\n * The help's line that runs `start` on the database `rebase dev` uses, spelled\n * as the reader can type it.\n *\n * In a project, the project's package manager: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so a bare `rebase` is \"command not found\" —\n * `pnpm exec rebase …`, as `missingDatabaseUrl` and the CLI's other hints say\n * it. Outside one, the way this CLI was started (`invokedRebaseCommand`).\n */\nexport function startHelpRunLine(projectRoot: string | null = findProjectRoot()): string {\n const rebase = (args: string[]): string => (projectRoot\n ? getPMCommands(detectPackageManager(projectRoot)).exec(\"rebase\", args)\n : [...invokedRebaseCommand(), ...args]).join(\" \");\n return `DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`;\n}\n\nfunction printHelp(): void {\n console.log(`\n${chalk.bold(\"rebase start\")} — run a built bundle\n\n${chalk.bold(\"Usage\")}\n rebase start [options]\n\n${chalk.bold(\"Options\")}\n --bundle <dir> Bundle directory (default: ${DEFAULT_BUNDLE_DIR})\n --workspace Run the backend workspace's own start script\n -h, --help Show this help\n\nRuns the bundle the way a deployment does, reading PORT and the rest of .env,\nin whatever NODE_ENV the shell or .env sets. A scaffolded .env says\ndevelopment, which keeps development behaviour on — the first account to\nregister becomes the admin. For a production server, run it with\nNODE_ENV=production; it says so at start when it is not one.\n\nIt needs a DATABASE_URL, and starts no database of its own. To run it on the\ndatabase ${chalk.cyan(\"rebase dev\")} uses: ${chalk.cyan(startHelpRunLine())}\n\nBuild first with ${chalk.cyan(\"rebase build\")}.\n`.trim());\n}\n\n/** The NODE_ENV the runtime will see, and where it comes from. */\nexport interface StartNodeEnv {\n value: string | undefined;\n source: \"shell\" | \".env\" | \"unset\";\n}\n\n/**\n * What NODE_ENV the server will boot in. The shell wins — dotenv never\n * overrides a variable that is already set — then `.env`.\n */\nexport function startNodeEnv(projectRoot: string): StartNodeEnv {\n if (process.env.NODE_ENV !== undefined) return { value: process.env.NODE_ENV, source: \"shell\" };\n const fromFile = readEnvFile(projectRoot).NODE_ENV;\n return fromFile !== undefined ? { value: fromFile, source: \".env\" } : { value: undefined, source: \"unset\" };\n}\n\n/**\n * The banner for a `rebase start` that is not a production server, or `null`.\n *\n * Not forced to production: the scaffold's `.env` points at a loopback\n * database, which a production boot refuses, so forcing it would break the\n * documented local run. What must not happen is the silence — a command the\n * help called \"(production)\" booting with the first-registration window open.\n */\nexport function nonProductionWarning(nodeEnv: StartNodeEnv): string[] | null {\n if (nodeEnv.value === \"production\") return null;\n const what = nodeEnv.value === undefined\n ? \"NODE_ENV is not set\"\n : `NODE_ENV=${nodeEnv.value}${nodeEnv.source === \".env\" ? \" (from .env)\" : \"\"}`;\n return [\n chalk.yellow.bold(`⚠ ${what} — this is not a production server.`),\n chalk.yellow(\" Development behaviour is on: the first account to register becomes the admin\"),\n chalk.yellow(\" (REBASE_ADMIN_EMAIL is ignored), and with no SMTP configured, sign-in and\"),\n chalk.yellow(\" password-reset links are printed to this log instead of sent.\"),\n chalk.gray(\" For a production server, run it with NODE_ENV=production (in the shell or .env).\")\n ];\n}\n\n/**\n * What to say about the apps a bundle serves only on their own hostname.\n *\n * The runtime prints \"Server running at http://localhost:<port>\", and an app\n * whose `path` names a hostname answers only requests carrying that `Host` —\n * so opening the printed URL showed a 404 for an app that was running fine,\n * and nothing said why. One line per such app, with a command that reaches it.\n */\nexport function hostRoutedNotice(staticApps: readonly RebaseBundleStatic[], port: string | undefined): string[] {\n const routed = staticApps.filter(app => app.host);\n if (routed.length === 0) return [];\n const origin = `http://localhost:${port || \"<port>\"}`;\n return [\n ...routed.map(app => {\n const name = app.name ?? path.posix.basename(app.dir);\n return chalk.yellow(`⚠ ${name} answers only on ${app.host}, so ${origin}${app.path} will not show it here. Reach it with:`)\n + `\\n ${chalk.cyan(`curl -H \"Host: ${app.host}\" ${origin}${app.path}`)}`;\n }),\n chalk.gray(` (or point ${routed.map(app => app.host).join(\", \")} at 127.0.0.1 in /etc/hosts)`),\n \"\"\n ];\n}\n\n/**\n * What to say when there is no DATABASE_URL for the runtime, or `null`.\n *\n * The runtime requires one, and its refusal — `DATABASE_URL: is required`, and\n * a link to the self-hosting docs — is right for a deployment and says nothing\n * to the reader most likely to see it: someone running the scaffold's own\n * `.env`, which leaves DATABASE_URL commented out because `rebase dev` brings a\n * database of its own. That database is one command away, so this names it.\n *\n * `kind` is what `rebase dev` runs this project on, so the line can say which\n * database `rebase db url` will print. A blank value is unset, as the runtime\n * reads it. `pm` spells the command: a scaffold has `rebase` in\n * `node_modules/.bin`, not on PATH, so it is `pnpm exec rebase …` or\n * `npx rebase …`, as in the CLI's other hints.\n */\nexport function missingDatabaseUrl(\n env: Record<string, string | undefined>,\n kind: DevDatabase[\"kind\"] | null,\n pm: PMCommands\n): string[] | null {\n if (env.DATABASE_URL?.trim()) return null;\n\n const rebase = (args: string[]): string => pm.exec(\"rebase\", args).join(\" \");\n\n const which = kind === \"docker\"\n ? \"the Docker database `rebase dev --docker` uses\"\n : kind === \"managed\"\n ? \"the managed development database (PGlite) `rebase dev` uses\"\n : \"this project's development database\";\n return [\n chalk.red(\"✗ DATABASE_URL is not set, so the runtime has no database to start against.\"),\n chalk.gray(\" `rebase start` runs the bundle the way a deployment does, against the database you name;\"),\n chalk.gray(\" `rebase dev` is the command that brings one of its own.\"),\n \"\",\n ` To run it on ${which}:`,\n ` ${chalk.cyan(`DATABASE_URL=\"$(${rebase([\"db\", \"url\"])})\" ${rebase([\"start\"])}`)}`,\n \"\",\n chalk.gray(\" For a deployment, set DATABASE_URL in the environment or in .env.\"),\n chalk.gray(\" See https://rebase.pro/docs/deployment/self-hosting/ for the variables a deployment needs.\")\n ];\n}\n\n/**\n * What the runtime needs when DATABASE_URL is this project's managed\n * development database, or nothing.\n *\n * The connection ceiling `rebase dev` sets for it (`MANAGED_POOL_MAX`). PGlite\n * is one session behind a socket server that accepts only a few connections,\n * and a running `rebase dev` holds some. With an ordinary pool, the boot's\n * concurrent probes opened more than were left, the ones over were refused,\n * and a probe that could not connect read as a table that was not there:\n * `❌ rebase.cron_claims is unavailable`, beside tables that existed.\n *\n * Recognised by the running daemon's ports, which is what `rebase db url`\n * prints from. A ceiling set by hand is kept.\n */\nexport function managedDatabaseRuntimeEnv(\n databaseUrl: string | undefined,\n daemon: DaemonState | null,\n env: Record<string, string | undefined>\n): Record<string, string> {\n if (!databaseUrl || !daemon || env.REBASE_DB_POOL_MAX !== undefined) return {};\n let url: URL;\n try {\n url = new URL(databaseUrl);\n } catch {\n return {};\n }\n if (![\"127.0.0.1\", \"localhost\", \"[::1]\"].includes(url.hostname)) return {};\n const ports = [daemon.port, ...Object.values(daemon.databases ?? {}).map(database => database.port)];\n if (!ports.includes(Number(url.port))) return {};\n return { REBASE_DB_POOL_MAX: String(MANAGED_POOL_MAX) };\n}\n\nfunction readBundleStatic(bundleDir: string): RebaseBundleStatic[] {\n try {\n const manifest = JSON.parse(fs.readFileSync(path.join(bundleDir, \"manifest.json\"), \"utf8\")) as { entry?: { static?: RebaseBundleStatic[] } };\n return manifest.entry?.static ?? [];\n } catch {\n return [];\n }\n}\n\nfunction printNonProductionWarning(projectRoot: string): void {\n const warning = nonProductionWarning(startNodeEnv(projectRoot));\n if (!warning) return;\n console.log(warning.join(\"\\n\") + \"\\n\");\n}\n\nexport async function startCommand(rawArgs: string[] = []): Promise<void> {\n if (wantsHelp(rawArgs)) {\n printHelp();\n return;\n }\n\n const { flags: args } = parseCommandArgs({\n spec: {\n \"--bundle\": String,\n \"--workspace\": Boolean\n },\n rawArgs,\n commandWords: 1,\n command: \"start\",\n maxPositionals: 0\n });\n\n const projectRoot = requireProjectRoot();\n\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\n const bundleDir = path.resolve(projectRoot, args[\"--bundle\"] ?? DEFAULT_BUNDLE_DIR);\n const hasBundle = fs.existsSync(path.join(bundleDir, \"manifest.json\"));\n\n // Before either path, and before the runtime's own boot logs bury it.\n printNonProductionWarning(projectRoot);\n\n if (args[\"--workspace\"] || !hasBundle) {\n if (!args[\"--workspace\"] && !hasBundle) {\n console.log(chalk.dim(\n `No bundle at ${path.relative(projectRoot, bundleDir)}/ — ` +\n \"starting the backend workspace instead.\\n\"\n ));\n }\n await startWorkspaceBackend(projectRoot, env);\n return;\n }\n\n ensureBundleDependencies(projectRoot, bundleDir);\n\n console.log(`${chalk.bold(\"Rebase\")} — starting runtime from ${chalk.cyan(path.relative(projectRoot, bundleDir))}/\\n`);\n\n // Loaded in-process rather than spawned: the runtime is a library here, so\n // signals, exit codes and stdio need no forwarding, and there is one less\n // process between the developer and a stack trace.\n if (envFile && fs.existsSync(envFile)) {\n const dotenv = await import(\"dotenv\");\n dotenv.config({ path: envFile, quiet: true });\n }\n\n // Before the runtime, which would refuse with a message written for a\n // deployment. See `missingDatabaseUrl`.\n if (!process.env.DATABASE_URL?.trim()) {\n const { devDatabaseKind } = await import(\"../dev-db/prepare\");\n const missing = missingDatabaseUrl(process.env, devDatabaseKind(projectRoot), getPMCommands(detectPackageManager(projectRoot)));\n if (missing) {\n for (const line of missing) console.error(line);\n process.exit(1);\n }\n }\n\n // See `managedDatabaseRuntimeEnv`.\n const { findRunningDaemon } = await import(\"../dev-db/daemon\");\n const managedEnv = managedDatabaseRuntimeEnv(process.env.DATABASE_URL, await findRunningDaemon(projectRoot), process.env);\n if (managedEnv.REBASE_DB_POOL_MAX) {\n Object.assign(process.env, managedEnv);\n console.log(chalk.dim(\n \"DATABASE_URL is this project's managed development database: the runtime uses one connection,\\n\" +\n \"as `rebase dev` does, so requests are served one at a time.\\n\"\n ));\n }\n\n process.env.REBASE_BUNDLE = bundleDir;\n\n for (const line of hostRoutedNotice(readBundleStatic(bundleDir), process.env.PORT)) console.log(line);\n\n try {\n const { runFromBundle } = await import(\"@rebasepro/server\");\n await runFromBundle({ bundleDir });\n } catch (err) {\n console.error(chalk.red(\"\\n✗ Failed to start the runtime.\"));\n console.error(err instanceof Error ? err.message : String(err));\n process.exit(1);\n }\n}\n\n/**\n * Make a bundle's imports resolvable for a local run.\n *\n * Node resolves a module by walking up from the *importing file*, so compiled\n * code sitting in `dist-bundle/` no longer sees the per-package `node_modules`\n * its source could: pnpm and npm both install a workspace package's\n * dependencies inside that package, and the bundle is not inside any of them.\n *\n * A deployment solves this by installing the bundle's own `package.json` beside\n * it — that is what the generated `package.json` is for. Locally, doing a second\n * install to run code whose dependencies are already on disk would be wasteful,\n * so this links what is already there instead.\n *\n * Only ever created when absent, and only under the bundle directory, so a real\n * install always wins and nothing here is ever uploaded (`rebase build` cleans\n * the directory and never writes this).\n */\nfunction ensureBundleDependencies(projectRoot: string, bundleDir: string): void {\n const target = path.join(bundleDir, \"node_modules\");\n if (fs.existsSync(target)) return;\n\n // Later sources fill gaps left by earlier ones; the backend's tree wins\n // because it holds the server and driver the runtime itself needs.\n const sources = [\"backend/node_modules\", \"config/node_modules\", \"node_modules\"]\n .map(relative => path.join(projectRoot, relative))\n .filter(dir => fs.existsSync(dir));\n\n if (sources.length === 0) return;\n\n let linked = 0;\n fs.mkdirSync(target, { recursive: true });\n\n const linkInto = (sourceDir: string, targetDir: string): void => {\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(sourceDir, { withFileTypes: true });\n } catch {\n return;\n }\n\n for (const entry of entries) {\n if (entry.name === \".bin\" || entry.name.startsWith(\".\")) continue;\n const from = path.join(sourceDir, entry.name);\n const to = path.join(targetDir, entry.name);\n\n // A scope is a directory of packages, not a package — merge into it\n // so `@a/one` from one tree and `@a/two` from another both resolve.\n if (entry.name.startsWith(\"@\") && entry.isDirectory()) {\n fs.mkdirSync(to, { recursive: true });\n linkInto(from, to);\n continue;\n }\n\n if (fs.existsSync(to)) continue;\n try {\n fs.symlinkSync(fs.realpathSync(from), to, \"junction\");\n linked++;\n } catch {\n // A package that cannot be linked simply stays unresolved, and\n // the runtime will say so by name if it actually needed it.\n }\n }\n };\n\n for (const source of sources) linkInto(source, target);\n\n if (linked > 0) {\n console.log(chalk.dim(\n ` linked ${linked} package(s) into the bundle for this local run\\n` +\n \" (a deployment installs the bundle's package.json instead)\\n\"\n ));\n }\n}\n\nasync function startWorkspaceBackend(projectRoot: string, env: Record<string, string>): Promise<void> {\n const pm = detectPackageManager(projectRoot);\n const cmds = getPMCommands(pm);\n const startCmd = cmds.runWorkspace(\"backend\", \"start\");\n\n console.log(`${chalk.bold(\"Rebase\")} — Starting backend server...\\n`);\n\n try {\n await execa(startCmd[0], startCmd.slice(1), {\n cwd: projectRoot,\n stdio: \"inherit\",\n env\n });\n } catch {\n console.error(chalk.red(\"\\n✗ Failed to start server.\"));\n process.exit(1);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,SAAgB,iBAAiB,cAA6B,gBAAgB,GAAW;CACrF,MAAM,UAAU,UAA4B,cACtC,cAAc,qBAAqB,WAAW,CAAC,CAAC,CAAC,KAAK,UAAU,IAAI,IACpE,CAAC,GAAG,qBAAqB,GAAG,GAAG,IAAI,EAAA,CAAG,KAAK,GAAG;CACpD,OAAO,mBAAmB,OAAO,CAAC,MAAM,KAAK,CAAC,EAAE,KAAK,OAAO,CAAC,OAAO,CAAC;AACzE;AAEA,SAAS,YAAkB;CACvB,QAAQ,IAAI;EACd,MAAM,KAAK,cAAc,EAAE;;EAE3B,MAAM,KAAK,OAAO,EAAE;;;EAGpB,MAAM,KAAK,SAA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package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@rebasepro/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.29.0-canary.g0e3a0e7",
|
|
4
4
|
"description": "Developer tools for Rebase projects",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -44,13 +44,13 @@
|
|
|
44
44
|
"inquirer": "14.0.2",
|
|
45
45
|
"jiti": "^2.7.0",
|
|
46
46
|
"pg": "^8.22.0",
|
|
47
|
-
"@rebasepro/agent-skills": "0.
|
|
48
|
-
"@rebasepro/client": "0.
|
|
49
|
-
"@rebasepro/rls-check": "0.
|
|
50
|
-
"@rebasepro/
|
|
51
|
-
"@rebasepro/
|
|
52
|
-
"@rebasepro/
|
|
53
|
-
"@rebasepro/
|
|
47
|
+
"@rebasepro/agent-skills": "0.29.0-canary.g0e3a0e7",
|
|
48
|
+
"@rebasepro/client": "0.29.0-canary.g0e3a0e7",
|
|
49
|
+
"@rebasepro/rls-check": "0.29.0-canary.g0e3a0e7",
|
|
50
|
+
"@rebasepro/server": "0.29.0-canary.g0e3a0e7",
|
|
51
|
+
"@rebasepro/types": "0.29.0-canary.g0e3a0e7",
|
|
52
|
+
"@rebasepro/server-postgres": "0.29.0-canary.g0e3a0e7",
|
|
53
|
+
"@rebasepro/codegen": "0.29.0-canary.g0e3a0e7"
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@types/node": "^26.1.2",
|
|
@@ -37,7 +37,7 @@
|
|
|
37
37
|
4. **Guard every custom route**: routes in `backend/functions/` are mounted **without** an auth requirement — webhook receivers need that — so each one is public until you guard it. Import `requireAuth` / `requireAdmin` from `@rebasepro/server/functions` and pass them in the route's own middleware slot (`app.post("/", requireAuth, handler)`), not via `app.use()`, which only covers routes declared below it. Reading `getUser(c)` is not a guard: an anonymous caller gets `undefined` and the handler still runs. See `backend/functions/hello.ts` for all three tiers.
|
|
38
38
|
5. **In `backend/functions/`, always import from `@rebasepro/server/functions`** — never from `@rebasepro/server`. Both work today; the subpath is the portable one, and it also gives you the typed context accessors (`getUser`, `getDriver`, `requireDriver`) instead of casting `c.get("user")`. The package root is for a server entrypoint, not for route handlers.
|
|
39
39
|
6. **Never read `process.env` at the top of a function file.** A module-scope read that comes back undefined throws at import time, and the loader reports that as a *skipped function* — the route simply 404s with no error attached to it. Read configuration inside the handler with `requireEnv(c, "NAME")`, or build a client once with `lazyResource(env => new Client(env.KEY))`.
|
|
40
|
-
7. **Work that outlives the response goes in `waitUntil(c, promise)`**, not a floating promise. A floating promise is dropped when the process shuts down mid-deploy; `waitUntil` is what a graceful shutdown waits for.
|
|
40
|
+
7. **Work that outlives the response goes in `waitUntil(c, promise)`**, not a floating promise; `waitUntil(promise)` where there is no request. A floating promise is dropped when the process shuts down mid-deploy; `waitUntil` is what a graceful shutdown waits for.
|
|
41
41
|
8. **Call your own routes from the browser with the client's `functions.invoke`**, never `fetch` with a token taken from `client.auth.getSession()`. The session is a snapshot that every renewal replaces, about hourly, so a kept token is refused once it expires and the app looks signed out. `invoke` renews before sending and retries once on a 401. For a request that is not to a function, ask for the token each time with `await client.auth.getAccessToken()`.
|
|
42
42
|
|
|
43
43
|
## Backend runtime (`runtime: "managed"` on Rebase Cloud)
|
|
@@ -3,15 +3,15 @@
|
|
|
3
3
|
*
|
|
4
4
|
* Scaffolded by `rebase generate view __SLUG__` and listed in `./index.ts`.
|
|
5
5
|
* It renders inside the admin shell, so the signed-in user, the sidebar, the
|
|
6
|
-
* router and the data layer are already there: read
|
|
7
|
-
* `
|
|
6
|
+
* router and the data layer are already there: read rows with `useRows()`,
|
|
7
|
+
* write them with `useRowWrites()`, and the collection's security rules and
|
|
8
|
+
* callbacks apply.
|
|
8
9
|
*
|
|
9
10
|
* Replace the body with your screen. The `rebase-custom-views` agent skill
|
|
10
11
|
* documents the contract and the design tokens.
|
|
11
12
|
*/
|
|
12
|
-
import {
|
|
13
|
-
import
|
|
14
|
-
import { useAuthController, useData, useSnackbarController } from "@rebasepro/app";
|
|
13
|
+
import { useState } from "react";
|
|
14
|
+
import { useAuthController, useRows, useSnackbarController } from "@rebasepro/app";
|
|
15
15
|
import {
|
|
16
16
|
Button,
|
|
17
17
|
Card,
|
|
@@ -33,30 +33,15 @@ import {
|
|
|
33
33
|
const COLLECTION = "__COLLECTION__";
|
|
34
34
|
|
|
35
35
|
export function __COMPONENT__() {
|
|
36
|
-
const data = useData();
|
|
37
36
|
const { user } = useAuthController();
|
|
38
37
|
const snackbar = useSnackbarController();
|
|
38
|
+
// Rows as the server sends them, kept current after every write.
|
|
39
|
+
const { rows, loading, error, refresh } = useRows(COLLECTION, { limit: 20 });
|
|
39
40
|
|
|
40
|
-
const [rows, setRows] = useState<Entity[] | undefined>();
|
|
41
|
-
const [error, setError] = useState<string | undefined>();
|
|
42
41
|
const [tab, setTab] = useState("rows");
|
|
43
|
-
const [selected, setSelected] = useState<
|
|
42
|
+
const [selected, setSelected] = useState<Record<string, unknown> | undefined>();
|
|
44
43
|
|
|
45
|
-
const
|
|
46
|
-
try {
|
|
47
|
-
const { data: found } = await data.collection(COLLECTION).find({ limit: 20 });
|
|
48
|
-
setRows(found);
|
|
49
|
-
setError(undefined);
|
|
50
|
-
} catch (e: unknown) {
|
|
51
|
-
setError(e instanceof Error ? e.message : String(e));
|
|
52
|
-
}
|
|
53
|
-
}, [data]);
|
|
54
|
-
|
|
55
|
-
useEffect(() => {
|
|
56
|
-
void load();
|
|
57
|
-
}, [load]);
|
|
58
|
-
|
|
59
|
-
const columns = rows?.[0] ? Object.keys(rows[0].values).slice(0, 3) : [];
|
|
44
|
+
const columns = rows[0] ? Object.keys(rows[0]).filter(key => key !== "id").slice(0, 3) : [];
|
|
60
45
|
|
|
61
46
|
return (
|
|
62
47
|
<Container maxWidth="6xl" className="py-8 flex flex-col gap-4">
|
|
@@ -67,7 +52,10 @@ export function __COMPONENT__() {
|
|
|
67
52
|
Signed in as {user?.displayName ?? user?.email ?? "an anonymous user"}
|
|
68
53
|
</Typography>
|
|
69
54
|
</div>
|
|
70
|
-
<Button color="primary" onClick={() =>
|
|
55
|
+
<Button color="primary" onClick={() => {
|
|
56
|
+
refresh();
|
|
57
|
+
snackbar.open({ type: "success", message: "Refreshed" });
|
|
58
|
+
}}>
|
|
71
59
|
Refresh
|
|
72
60
|
</Button>
|
|
73
61
|
</div>
|
|
@@ -78,9 +66,9 @@ export function __COMPONENT__() {
|
|
|
78
66
|
</Tabs>
|
|
79
67
|
|
|
80
68
|
{error && <Typography color="error">{error}</Typography>}
|
|
81
|
-
{!error &&
|
|
69
|
+
{!error && loading && rows.length === 0 && <CircularProgressCenter/>}
|
|
82
70
|
|
|
83
|
-
{
|
|
71
|
+
{!error && tab === "rows" && (
|
|
84
72
|
<Card className="overflow-hidden">
|
|
85
73
|
<Table>
|
|
86
74
|
<TableHeader>
|
|
@@ -91,7 +79,7 @@ export function __COMPONENT__() {
|
|
|
91
79
|
{rows.map(row => (
|
|
92
80
|
<TableRow key={String(row.id)} onClick={() => setSelected(row)}>
|
|
93
81
|
<TableCell>{String(row.id)}</TableCell>
|
|
94
|
-
{columns.map(column => <TableCell key={column}>{display(row
|
|
82
|
+
{columns.map(column => <TableCell key={column}>{display(row[column])}</TableCell>)}
|
|
95
83
|
</TableRow>
|
|
96
84
|
))}
|
|
97
85
|
</TableBody>
|
|
@@ -99,7 +87,7 @@ export function __COMPONENT__() {
|
|
|
99
87
|
</Card>
|
|
100
88
|
)}
|
|
101
89
|
|
|
102
|
-
{
|
|
90
|
+
{!error && tab === "summary" && (
|
|
103
91
|
<div className="grid grid-cols-2 gap-4">
|
|
104
92
|
<Card className="p-4 flex flex-col gap-1">
|
|
105
93
|
<Typography variant="caption" color="secondary">Rows loaded</Typography>
|
|
@@ -115,7 +103,7 @@ export function __COMPONENT__() {
|
|
|
115
103
|
<Sheet open={selected !== undefined} onOpenChange={open => !open && setSelected(undefined)} title="Row">
|
|
116
104
|
<div className="w-[28rem] max-w-full h-full overflow-auto p-6 flex flex-col gap-3">
|
|
117
105
|
<Typography variant="h6">{selected ? String(selected.id) : ""}</Typography>
|
|
118
|
-
{selected && Object.entries(selected
|
|
106
|
+
{selected && Object.entries(selected).map(([key, value]) => (
|
|
119
107
|
<div key={key} className="flex flex-col gap-0.5">
|
|
120
108
|
<Typography variant="caption" color="secondary">{key}</Typography>
|
|
121
109
|
<Typography variant="body2">{display(value)}</Typography>
|
|
@@ -127,10 +115,9 @@ export function __COMPONENT__() {
|
|
|
127
115
|
);
|
|
128
116
|
}
|
|
129
117
|
|
|
130
|
-
/** A cell's text.
|
|
118
|
+
/** A cell's text. A date arrives as its ISO string, a belongsTo as its foreign key. */
|
|
131
119
|
function display(value: unknown): string {
|
|
132
120
|
if (value === null || value === undefined) return "—";
|
|
133
|
-
if (value instanceof Date) return value.toLocaleString();
|
|
134
121
|
if (typeof value === "object") return JSON.stringify(value);
|
|
135
122
|
return String(value);
|
|
136
123
|
}
|
|
@@ -7,19 +7,20 @@
|
|
|
7
7
|
* imports it lazily and renders the default export.
|
|
8
8
|
*
|
|
9
9
|
* The admin hands the component `EntityCustomViewParams`: the collection, the
|
|
10
|
-
* record
|
|
11
|
-
*
|
|
12
|
-
*
|
|
10
|
+
* saved record as the server sends the row (`row`) and its id (`id`), both
|
|
11
|
+
* absent while it is being created, the form's values with unsaved edits
|
|
12
|
+
* (`modifiedValues`) and the form (`formContext`). The `rebase-custom-views` agent skill documents the
|
|
13
|
+
* contract and the design tokens.
|
|
13
14
|
*/
|
|
14
15
|
import type { EntityCustomViewParams } from "@rebasepro/cms-types";
|
|
15
16
|
import { useSnackbarController } from "@rebasepro/app";
|
|
16
17
|
import { Button, Card, Chip, Typography } from "@rebasepro/ui";
|
|
17
18
|
|
|
18
|
-
export function __COMPONENT__({ collection,
|
|
19
|
+
export function __COMPONENT__({ collection, row, modifiedValues, formContext }: EntityCustomViewParams) {
|
|
19
20
|
const snackbar = useSnackbarController();
|
|
20
|
-
const values = modifiedValues ??
|
|
21
|
+
const values = modifiedValues ?? row ?? {};
|
|
21
22
|
|
|
22
|
-
if (!
|
|
23
|
+
if (!row) {
|
|
23
24
|
return (
|
|
24
25
|
<div className="p-6">
|
|
25
26
|
<Typography variant="body2" color="secondary">
|
|
@@ -53,7 +54,7 @@ export function __COMPONENT__({ collection, entity, modifiedValues, formContext
|
|
|
53
54
|
);
|
|
54
55
|
}
|
|
55
56
|
|
|
56
|
-
/** A field's text.
|
|
57
|
+
/** A field's text. In the form's values a date is a `Date`; in the row, ISO text. */
|
|
57
58
|
function display(value: unknown): string {
|
|
58
59
|
if (value === null || value === undefined) return "—";
|
|
59
60
|
if (value instanceof Date) return value.toLocaleString();
|