@rebasepro/cli 0.27.0 → 0.28.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/{agent-setup-D9mHRZ5R.js → agent-setup-0uyfC7VX.js} +3 -3
- package/dist/{agent-setup-D9mHRZ5R.js.map → agent-setup-0uyfC7VX.js.map} +1 -1
- package/dist/{api-keys-CyJ26KEJ.js → api-keys-Dfw5-9s1.js} +23 -2
- package/dist/{api-keys-CyJ26KEJ.js.map → api-keys-Dfw5-9s1.js.map} +1 -1
- package/dist/{apps-CdrFm7Y3.js → apps-BpYRGOaM.js} +3 -3
- package/dist/{apps-CdrFm7Y3.js.map → apps-BpYRGOaM.js.map} +1 -1
- package/dist/{auth-dII2jCO1.js → auth-DifFaOyq.js} +2 -2
- package/dist/{auth-dII2jCO1.js.map → auth-DifFaOyq.js.map} +1 -1
- package/dist/{build-D-t5FSg0.js → build-CS-Z75eK.js} +3 -3
- package/dist/{build-D-t5FSg0.js.map → build-CS-Z75eK.js.map} +1 -1
- package/dist/{bundle-CrAWbpbG.js → bundle-C0IBCVpV.js} +5 -4
- package/dist/bundle-C0IBCVpV.js.map +1 -0
- package/dist/{cloud-B2_oJmK7.js → cloud-nwWkzAHu.js} +16 -10
- package/dist/cloud-nwWkzAHu.js.map +1 -0
- package/dist/commands/agent-setup.d.ts +2 -0
- package/dist/commands/cloud/context.d.ts +18 -0
- package/dist/commands/dev.d.ts +12 -0
- package/dist/commands/doctor.d.ts +10 -0
- package/dist/commands/schema-reconcile.d.ts +9 -0
- package/dist/commands/skills.d.ts +3 -0
- package/dist/{context-GUxkZm-S.js → context-DvIUbE-b.js} +39 -5
- package/dist/context-DvIUbE-b.js.map +1 -0
- package/dist/{dev-DTqVMgB3.js → dev-CzOazEHW.js} +17 -3
- package/dist/dev-CzOazEHW.js.map +1 -0
- package/dist/{doctor-BRWOlqeG.js → doctor-BuqSHNrd.js} +45 -26
- package/dist/doctor-BuqSHNrd.js.map +1 -0
- package/dist/doctor-environment.d.ts +7 -19
- package/dist/{fold-static-BGlpi22F.js → fold-static-BMO8LC01.js} +3 -3
- package/dist/fold-static-BMO8LC01.js.map +1 -0
- package/dist/{generate_sdk-BvcWvoUh.js → generate_sdk-_SQuSbJW.js} +2 -2
- package/dist/{generate_sdk-BvcWvoUh.js.map → generate_sdk-_SQuSbJW.js.map} +1 -1
- package/dist/index.es.js +23 -23
- package/dist/index.es.js.map +1 -1
- package/dist/{init-CaU6GhwI.js → init-CHtpYLlh.js} +5 -4
- package/dist/init-CHtpYLlh.js.map +1 -0
- package/dist/{normalize-imports-CK_Mpcej.js → normalize-imports-BN0fzZS8.js} +2 -2
- package/dist/{normalize-imports-CK_Mpcej.js.map → normalize-imports-BN0fzZS8.js.map} +1 -1
- package/dist/schema-2A0dd-Bv.js +321 -0
- package/dist/schema-2A0dd-Bv.js.map +1 -0
- package/dist/schema-reconcile-C3ToVnHr.js +2 -0
- package/dist/{skills-BU2flMOy.js → skills-CbwV6vw_.js} +170 -5
- package/dist/skills-CbwV6vw_.js.map +1 -0
- package/dist/{start-CflvYL60.js → start-21GRsZKc.js} +2 -2
- package/dist/{start-CflvYL60.js.map → start-21GRsZKc.js.map} +1 -1
- package/dist/{storage-DtOXGflp.js → storage-CO9ouK76.js} +2 -2
- package/dist/{storage-DtOXGflp.js.map → storage-CO9ouK76.js.map} +1 -1
- package/dist/utils/libpq-url.d.ts +8 -0
- package/dist/utils/root-pointer.d.ts +43 -0
- package/package.json +8 -8
- package/templates/template/.cursorrules +10 -0
- package/templates/template/.github/copilot-instructions.md +10 -0
- package/templates/template/.windsurfrules +10 -0
- package/templates/template/AGENTS.md +10 -0
- package/templates/template/CLAUDE.md +10 -0
- package/templates/template/ai-instructions.md +1 -1
- package/dist/bundle-CrAWbpbG.js.map +0 -1
- package/dist/cloud-B2_oJmK7.js.map +0 -1
- package/dist/context-GUxkZm-S.js.map +0 -1
- package/dist/dev-DTqVMgB3.js.map +0 -1
- package/dist/doctor-BRWOlqeG.js.map +0 -1
- package/dist/fold-static-BGlpi22F.js.map +0 -1
- package/dist/init-CaU6GhwI.js.map +0 -1
- package/dist/schema-BSXwZSiI.js +0 -152
- package/dist/schema-BSXwZSiI.js.map +0 -1
- package/dist/skills-BU2flMOy.js.map +0 -1
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
import { i as recordEvent } from "./telemetry-CgwJPVMO.js";
|
|
2
|
+
import { E as unknownCommand, b as UsageError, d as readEnvFile, f as requireBackendDir, h as resolvePluginCliScript, l as getActiveBackendPlugin, o as findEnvFile, p as requireProjectRoot, r as exitDependenciesNotInstalled, w as wantsHelp } from "./project-CasK56vN.js";
|
|
3
|
+
import { t as cliUserAgent } from "./version-Buyyo1ut.js";
|
|
4
|
+
import { i as requireBackendUrl, r as describeFailure } from "./api-keys-Dfw5-9s1.js";
|
|
5
|
+
import { i as refuseMissingCollectionsPath, t as COLLECTIONS_FLAG_HELP } from "./path-flags-DNvtEi2-.js";
|
|
6
|
+
import { collectionsDirArgs } from "./collections-dir-DlvDhime.js";
|
|
7
|
+
import { DEV_DATABASE_KIND_ENV, devDatabaseKind, managedNotices, prepareDatabaseEnv } from "./prepare-CTw9NEkh.js";
|
|
8
|
+
import { absolutizeLocalPathArgs, ensureDockerDatabase, n as argsFromCommand, spawnDriverCli, t as reportSpawnFailure } from "./db-KzlqddGD.js";
|
|
9
|
+
import chalk from "chalk";
|
|
10
|
+
import arg from "arg";
|
|
11
|
+
import { RebaseApiError } from "@rebasepro/client";
|
|
12
|
+
import readline from "node:readline/promises";
|
|
13
|
+
//#region src/commands/schema-reconcile.ts
|
|
14
|
+
/**
|
|
15
|
+
* CLI command: rebase schema reconcile
|
|
16
|
+
*
|
|
17
|
+
* The reviewed step for what boot will not do. Boot only ever adds, so a
|
|
18
|
+
* property made optional leaves its column NOT NULL, and a property removed
|
|
19
|
+
* leaves its column behind, with its data, and blocking inserts if it was
|
|
20
|
+
* required. This asks the running backend for the plan that fixes both, prints
|
|
21
|
+
* it, and applies it only once confirmed.
|
|
22
|
+
*
|
|
23
|
+
* Through the backend rather than a database URL, because on Rebase Cloud the
|
|
24
|
+
* backend is the one thing that can reach the database — and because it plans
|
|
25
|
+
* against the collections it actually runs, not the ones in this checkout.
|
|
26
|
+
* Columns are dropped only when named with `--drop`; the confirmation sends
|
|
27
|
+
* the plan's digest, so the server runs exactly the statements printed here.
|
|
28
|
+
*/
|
|
29
|
+
var RECONCILE_USAGE = "rebase schema reconcile [--drop <collection>.<column>]... [--yes]";
|
|
30
|
+
function parseReconcileArgs(rawArgs) {
|
|
31
|
+
const flags = arg({
|
|
32
|
+
"--drop": [String],
|
|
33
|
+
"--yes": Boolean,
|
|
34
|
+
"-y": "--yes"
|
|
35
|
+
}, { argv: rawArgs.slice(2) });
|
|
36
|
+
if (flags._.length > 0) throw new UsageError(`Unexpected argument "${flags._[0]}". Usage: ${RECONCILE_USAGE}`);
|
|
37
|
+
return {
|
|
38
|
+
drop: flags["--drop"] ?? [],
|
|
39
|
+
yes: flags["--yes"] === true
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** The plan, as a person reviews it. Returned as lines so it can be tested. */
|
|
43
|
+
function describeReconcilePlan(plan) {
|
|
44
|
+
const lines = [];
|
|
45
|
+
for (const r of plan.relaxed) lines.push(` ${chalk.cyan("relax")} ${r.table}.${r.column} ${chalk.gray(`optional in "${r.collection}", NOT NULL in the database`)}`);
|
|
46
|
+
for (const d of plan.dropped) {
|
|
47
|
+
const rows = d.rowsWithValue === void 0 ? "" : `${d.rowsWithValue.toLocaleString("en-US")} row(s) hold a value`;
|
|
48
|
+
lines.push(` ${chalk.red("drop")} ${d.table}.${d.column} ${chalk.red(rows)}`);
|
|
49
|
+
}
|
|
50
|
+
const kept = plan.undeclared.filter((u) => !plan.dropped.some((d) => d.table === u.table && d.column === u.column));
|
|
51
|
+
for (const u of kept) {
|
|
52
|
+
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
|
+
lines.push(` ${chalk.gray("keep")} ${u.table}.${u.column} ${note}`);
|
|
54
|
+
}
|
|
55
|
+
return lines;
|
|
56
|
+
}
|
|
57
|
+
/** The project's backend, holding the service key. */
|
|
58
|
+
function connect() {
|
|
59
|
+
const projectRoot = requireProjectRoot();
|
|
60
|
+
const env = readEnvFile(projectRoot);
|
|
61
|
+
const serviceKey = env.SERVICE_KEY || env.REBASE_SERVICE_KEY;
|
|
62
|
+
if (!serviceKey) {
|
|
63
|
+
console.error(chalk.red("✗ REBASE_SERVICE_KEY not found in .env — required to change the database's schema."));
|
|
64
|
+
process.exit(1);
|
|
65
|
+
}
|
|
66
|
+
const baseUrl = requireBackendUrl(env, projectRoot).replace(/\/+$/, "");
|
|
67
|
+
return {
|
|
68
|
+
baseUrl,
|
|
69
|
+
async post(path, body) {
|
|
70
|
+
let response;
|
|
71
|
+
try {
|
|
72
|
+
response = await fetch(`${baseUrl}/api/admin/schema/reconcile${path}`, {
|
|
73
|
+
method: "POST",
|
|
74
|
+
headers: {
|
|
75
|
+
"Authorization": `Bearer ${serviceKey}`,
|
|
76
|
+
"Accept": "application/json",
|
|
77
|
+
"Content-Type": "application/json",
|
|
78
|
+
"User-Agent": cliUserAgent()
|
|
79
|
+
},
|
|
80
|
+
body: JSON.stringify(body)
|
|
81
|
+
});
|
|
82
|
+
} catch (error) {
|
|
83
|
+
throw new RebaseApiError(error instanceof Error ? error.message : String(error), {
|
|
84
|
+
status: 0,
|
|
85
|
+
code: "NETWORK_ERROR"
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
const answer = await response.json().catch(() => void 0);
|
|
89
|
+
if (!response.ok) {
|
|
90
|
+
const error = answer && typeof answer === "object" && "error" in answer && answer.error && typeof answer.error === "object" ? answer.error : void 0;
|
|
91
|
+
throw new RebaseApiError(typeof error?.message === "string" ? error.message : `The server answered ${response.status}.`, {
|
|
92
|
+
status: response.status,
|
|
93
|
+
code: typeof error?.code === "string" ? error.code : void 0,
|
|
94
|
+
details: error?.details
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
return answer;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
function fail(action, error, baseUrl) {
|
|
102
|
+
for (const line of describeFailure(action, error, baseUrl)) console.error(line.startsWith("✗") ? chalk.red(line) : chalk.gray(line));
|
|
103
|
+
if (error instanceof RebaseApiError && error.status === 404) console.error(chalk.gray(" This backend has no reconcile route: it needs a runtime that has `rebase schema reconcile`."));
|
|
104
|
+
process.exit(1);
|
|
105
|
+
}
|
|
106
|
+
async function schemaReconcileCommand(rawArgs) {
|
|
107
|
+
const { drop, yes } = parseReconcileArgs(rawArgs);
|
|
108
|
+
const backend = connect();
|
|
109
|
+
let plan;
|
|
110
|
+
try {
|
|
111
|
+
plan = await backend.post("/plan", { drop });
|
|
112
|
+
} catch (error) {
|
|
113
|
+
fail("Failed to plan the reconcile", error, backend.baseUrl);
|
|
114
|
+
}
|
|
115
|
+
console.log(chalk.bold(`\nSchema reconcile for ${backend.baseUrl}\n`));
|
|
116
|
+
const described = describeReconcilePlan(plan);
|
|
117
|
+
if (described.length > 0) console.log(described.join("\n"));
|
|
118
|
+
if (plan.problems.length > 0) {
|
|
119
|
+
console.error(chalk.red("\n✗ This plan cannot be applied:"));
|
|
120
|
+
for (const problem of plan.problems) console.error(chalk.red(` • ${problem}`));
|
|
121
|
+
process.exit(1);
|
|
122
|
+
}
|
|
123
|
+
if (plan.statements.length === 0) {
|
|
124
|
+
console.log(chalk.green("✓ Nothing to do: the database already matches what the collections declare."));
|
|
125
|
+
if (plan.undeclared.length > 0) console.log(chalk.gray(" To drop a column no property declares, name it: --drop <collection>.<column>"));
|
|
126
|
+
return;
|
|
127
|
+
}
|
|
128
|
+
console.log(chalk.bold("\nStatements"));
|
|
129
|
+
for (const statement of plan.statements) console.log(` ${statement}`);
|
|
130
|
+
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."));
|
|
131
|
+
if (!yes) {
|
|
132
|
+
if (!process.stdin.isTTY) {
|
|
133
|
+
console.error(chalk.red("\n✗ Not applied: confirming needs a terminal. Re-run with --yes once you have read the plan."));
|
|
134
|
+
process.exit(1);
|
|
135
|
+
}
|
|
136
|
+
const rl = readline.createInterface({
|
|
137
|
+
input: process.stdin,
|
|
138
|
+
output: process.stdout
|
|
139
|
+
});
|
|
140
|
+
const answer = (await rl.question(`\nApply ${plan.statements.length} statement(s)? Type "yes" to continue: `)).trim();
|
|
141
|
+
rl.close();
|
|
142
|
+
if (answer !== "yes") {
|
|
143
|
+
console.log(chalk.gray("Aborted. Nothing was changed."));
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
try {
|
|
148
|
+
const result = await backend.post("/apply", {
|
|
149
|
+
drop,
|
|
150
|
+
confirm: plan.digest
|
|
151
|
+
});
|
|
152
|
+
console.log(chalk.green(`✓ Applied ${result.applied.length} statement(s).`));
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (error instanceof RebaseApiError && error.code === "SCHEMA_RECONCILE_STALE") {
|
|
155
|
+
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."));
|
|
156
|
+
process.exit(1);
|
|
157
|
+
}
|
|
158
|
+
fail("Failed to apply the reconcile", error, backend.baseUrl);
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
//#endregion
|
|
162
|
+
//#region src/commands/schema.ts
|
|
163
|
+
/**
|
|
164
|
+
* CLI command: rebase schema <action>
|
|
165
|
+
*/
|
|
166
|
+
/**
|
|
167
|
+
* The line handed to the driver, its paths resolved from where the command was
|
|
168
|
+
* run (the driver runs in `backend/`). `--schema` is left alone: on
|
|
169
|
+
* `introspect` it names a Postgres schema, not a file.
|
|
170
|
+
*/
|
|
171
|
+
function schemaDriverArgs(rawArgs, cwd) {
|
|
172
|
+
return absolutizeLocalPathArgs(argsFromCommand(rawArgs, "schema"), cwd, [
|
|
173
|
+
"--collections",
|
|
174
|
+
"-c",
|
|
175
|
+
"--output",
|
|
176
|
+
"-o",
|
|
177
|
+
"--out"
|
|
178
|
+
]);
|
|
179
|
+
}
|
|
180
|
+
async function schemaCommand(subcommand, rawArgs) {
|
|
181
|
+
if (!subcommand || subcommand === "--help" || wantsHelp(rawArgs)) {
|
|
182
|
+
printSchemaHelp(subcommand === "--help" ? void 0 : subcommand);
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
if (!SCHEMA_ACTION_HELP[subcommand]) unknownCommand(subcommand, Object.keys(SCHEMA_ACTION_HELP), "schema");
|
|
186
|
+
const projectRoot = requireProjectRoot();
|
|
187
|
+
if (subcommand === "reconcile") {
|
|
188
|
+
recordEvent("cli.schema", { subcommand }, { projectRoot });
|
|
189
|
+
const { schemaReconcileCommand } = await import("./schema-reconcile-C3ToVnHr.js");
|
|
190
|
+
await schemaReconcileCommand(rawArgs);
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
recordEvent("cli.schema", { subcommand: subcommand ?? "none" }, { projectRoot });
|
|
194
|
+
const backendDir = requireBackendDir(projectRoot);
|
|
195
|
+
const activePlugin = getActiveBackendPlugin(backendDir);
|
|
196
|
+
if (!activePlugin) {
|
|
197
|
+
console.error(chalk.red("✗ Could not detect an active database plugin."));
|
|
198
|
+
console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgres is installed in backend/package.json."));
|
|
199
|
+
process.exit(1);
|
|
200
|
+
}
|
|
201
|
+
const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
|
|
202
|
+
if (!pluginCli) exitDependenciesNotInstalled(projectRoot);
|
|
203
|
+
const envFile = findEnvFile(projectRoot);
|
|
204
|
+
const env = { ...process.env };
|
|
205
|
+
if (envFile) env.DOTENV_CONFIG_PATH = envFile;
|
|
206
|
+
env[DEV_DATABASE_KIND_ENV] = devDatabaseKind(projectRoot) ?? "";
|
|
207
|
+
refuseMissingCollectionsPath(rawArgs, process.cwd(), backendDir);
|
|
208
|
+
if (subcommand === "introspect") {
|
|
209
|
+
const flags = arg({
|
|
210
|
+
"--database-url": String,
|
|
211
|
+
"--docker": Boolean
|
|
212
|
+
}, {
|
|
213
|
+
argv: rawArgs.slice(2),
|
|
214
|
+
permissive: true
|
|
215
|
+
});
|
|
216
|
+
await ensureDockerDatabase(projectRoot, rawArgs);
|
|
217
|
+
const prepared = await prepareDatabaseEnv(projectRoot, {
|
|
218
|
+
flagUrl: flags["--database-url"] ?? null,
|
|
219
|
+
flagDocker: flags["--docker"] === true,
|
|
220
|
+
onProgress: (message) => console.log(chalk.gray(` ${message}`))
|
|
221
|
+
});
|
|
222
|
+
Object.assign(env, prepared.env);
|
|
223
|
+
env[DEV_DATABASE_KIND_ENV] = prepared.database.kind;
|
|
224
|
+
for (const line of managedNotices(prepared)) console.log(chalk.gray(` ${line}`));
|
|
225
|
+
}
|
|
226
|
+
try {
|
|
227
|
+
const driverArgs = schemaDriverArgs(rawArgs, process.cwd());
|
|
228
|
+
await spawnDriverCli({
|
|
229
|
+
projectRoot,
|
|
230
|
+
backendDir,
|
|
231
|
+
pluginCli,
|
|
232
|
+
env
|
|
233
|
+
}, [...driverArgs, ...collectionsDirArgs(projectRoot, driverArgs)]);
|
|
234
|
+
} catch (error) {
|
|
235
|
+
reportSpawnFailure(error);
|
|
236
|
+
process.exit(1);
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
/** One page per subcommand, so `rebase schema <action> --help` says something. */
|
|
240
|
+
var SCHEMA_ACTION_HELP = {
|
|
241
|
+
generate: {
|
|
242
|
+
usage: "rebase schema generate [--collections <dir>] [--output <file>] [--watch]",
|
|
243
|
+
summary: "Generate the Drizzle schema from the collection definitions.",
|
|
244
|
+
notes: ["--watch regenerates on every change to a collection file."]
|
|
245
|
+
},
|
|
246
|
+
introspect: {
|
|
247
|
+
usage: "rebase schema introspect [--collections <dir>] [--output <dir>] [--schema <name>] [--force] [--data-inference | --no-data-inference]",
|
|
248
|
+
summary: "Read an existing database and write Rebase collection definitions from it.",
|
|
249
|
+
notes: [
|
|
250
|
+
"--force overwrites collection files that are already there.",
|
|
251
|
+
"--data-inference samples up to 100 rows per table to detect formats, constraints and UI settings; --no-data-inference reads the structure only. Without either it asks, and without a terminal it reads the structure only.",
|
|
252
|
+
"Reads this project's database, the one `rebase db url` prints: --database-url <url> names another; --docker uses the compose one, starting it if needed."
|
|
253
|
+
]
|
|
254
|
+
},
|
|
255
|
+
reconcile: {
|
|
256
|
+
usage: RECONCILE_USAGE,
|
|
257
|
+
summary: "Relax and drop what boot will not: NOT NULL on properties made optional, and columns no property declares.",
|
|
258
|
+
notes: [
|
|
259
|
+
"Plans on the running backend (the one `.env` and the cloud link point at), prints the plan, and applies it once you type yes.",
|
|
260
|
+
"A column is dropped only when named: --drop voice_cache.wav. Each drop shows how many rows hold a value.",
|
|
261
|
+
"--yes skips the prompt, for a plan already read. Needs REBASE_SERVICE_KEY in .env."
|
|
262
|
+
]
|
|
263
|
+
},
|
|
264
|
+
stale: {
|
|
265
|
+
usage: "rebase schema stale [--collections <dir>] [--output <file>] [--fix]",
|
|
266
|
+
summary: "Report generated schema files that no longer match the collections.",
|
|
267
|
+
notes: ["--fix regenerates them instead of only reporting."]
|
|
268
|
+
}
|
|
269
|
+
};
|
|
270
|
+
/** Every subcommand the family dispatches — the help table's keys. */
|
|
271
|
+
var SCHEMA_SUBCOMMANDS = Object.keys(SCHEMA_ACTION_HELP);
|
|
272
|
+
function printSchemaHelp(action) {
|
|
273
|
+
const entry = action ? SCHEMA_ACTION_HELP[action] : void 0;
|
|
274
|
+
if (entry) {
|
|
275
|
+
console.log(`
|
|
276
|
+
${chalk.bold(`rebase schema ${action}`)}
|
|
277
|
+
|
|
278
|
+
${entry.summary}
|
|
279
|
+
|
|
280
|
+
${chalk.green.bold("Usage")}
|
|
281
|
+
${chalk.blue(entry.usage)}
|
|
282
|
+
${entry.notes?.length ? `\n${chalk.green.bold("Notes")}\n${entry.notes.map((n) => ` ${chalk.gray(`• ${n}`)}`).join("\n")}\n` : ""}
|
|
283
|
+
${chalk.gray("Run `rebase schema --help` for every subcommand.")}
|
|
284
|
+
`);
|
|
285
|
+
return;
|
|
286
|
+
}
|
|
287
|
+
console.log(`
|
|
288
|
+
${chalk.bold("rebase schema")} — Schema management commands
|
|
289
|
+
|
|
290
|
+
${chalk.green.bold("Usage")}
|
|
291
|
+
rebase schema ${chalk.blue("<command>")} [options]
|
|
292
|
+
|
|
293
|
+
${chalk.green.bold("Commands")}
|
|
294
|
+
${chalk.gray("(Commands are provided by your active database driver plugin)")}
|
|
295
|
+
${chalk.blue.bold("generate")} Generate Schema from collection definitions
|
|
296
|
+
${chalk.blue.bold("introspect")} Introspect an existing database to generate collection definitions
|
|
297
|
+
${chalk.blue.bold("stale")} Report generated schema files that no longer match the collections
|
|
298
|
+
${chalk.blue.bold("reconcile")} Relax NOT NULL and drop columns the collections no longer declare, after review
|
|
299
|
+
|
|
300
|
+
${chalk.green.bold("generate Options")}
|
|
301
|
+
${chalk.blue("--collections, -c")} ${COLLECTIONS_FLAG_HELP}
|
|
302
|
+
${chalk.blue("--output, -o")} Output path for generated schema
|
|
303
|
+
${chalk.blue("--watch, -w")} Watch for changes and regenerate automatically
|
|
304
|
+
|
|
305
|
+
${chalk.green.bold("introspect Options")}
|
|
306
|
+
${chalk.blue("--output, -o")} Output directory for generated collection files
|
|
307
|
+
${chalk.blue("--schema")} Postgres schema to read (default: public)
|
|
308
|
+
${chalk.blue("--force, -f")} Overwrite collection files that already exist
|
|
309
|
+
${chalk.blue("--database-url")} Read this database instead of the project's own
|
|
310
|
+
${chalk.blue("--docker")} Read the compose database, starting it if needed
|
|
311
|
+
${chalk.blue("--data-inference")} Sample rows to detect formats and constraints ${chalk.gray("(asked when omitted)")}
|
|
312
|
+
${chalk.blue("--no-data-inference")} Read the structure only, without asking
|
|
313
|
+
|
|
314
|
+
${chalk.green.bold("stale Options")}
|
|
315
|
+
${chalk.blue("--fix")} Regenerate the stale files instead of only reporting them
|
|
316
|
+
`);
|
|
317
|
+
}
|
|
318
|
+
//#endregion
|
|
319
|
+
export { SCHEMA_SUBCOMMANDS, schemaReconcileCommand as i, describeReconcilePlan as n, parseReconcileArgs as r, schemaCommand, RECONCILE_USAGE as t };
|
|
320
|
+
|
|
321
|
+
//# sourceMappingURL=schema-2A0dd-Bv.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-2A0dd-Bv.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 lines.push(` ${chalk.cyan(\"relax\")} ${r.table}.${r.column} ${chalk.gray(`optional in \"${r.collection}\", NOT NULL in the database`)}`);\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 => !plan.dropped.some(d => d.table === u.table && d.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 if (plan.undeclared.length > 0) {\n console.log(chalk.gray(\" To drop a column no property declares, name it: --drop <collection>.<column>\"));\n }\n return;\n }\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,SACjB,MAAM,KAAK,KAAK,MAAM,KAAK,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,EAAE,OAAO,IAAI,MAAM,KAAK,gBAAgB,EAAE,WAAW,4BAA4B,GAAG;CAE3I,KAAK,MAAM,KAAK,KAAK,SAAS;EAC1B,MAAM,OAAO,EAAE,kBAAkB,KAAA,IAAY,KAAK,GAAG,EAAE,cAAc,eAAe,OAAO,EAAE;EAC7F,MAAM,KAAK,KAAK,MAAM,IAAI,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,EAAE,OAAO,IAAI,MAAM,IAAI,IAAI,GAAG;CACpF;CACA,MAAM,OAAO,KAAK,WAAW,QAAO,MAAK,CAAC,KAAK,QAAQ,MAAK,MAAK,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,CAAC;CAC9G,KAAK,MAAM,KAAK,MAAM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AAM,MAAM,KAAK,UAAU,EAAE;IAC3B,MAAM,KAAK,+DAA+D,EAAE;IAC5E,MAAM,KAAK,KAAK,UAAU,EAAE;IAC5B,MAAM,KAAK,KAAK,YAAY,EAAE;IAC9B,MAAM,KAAK,KAAK,OAAO,EAAE;IACzB,MAAM,KAAK,KAAK,WAAW,EAAE;;EAE/B,MAAM,MAAM,KAAK,kBAAkB,EAAE;IACnC,MAAM,KAAK,mBAAmB,EAAE,IAAI,sBAAsB;IAC1D,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,aAAa,EAAE;;EAE5B,MAAM,MAAM,KAAK,oBAAoB,EAAE;IACrC,MAAM,KAAK,cAAc,EAAE;IAC3B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,aAAa,EAAE;IAC1B,MAAM,KAAK,gBAAgB,EAAE;IAC7B,MAAM,KAAK,UAAU,EAAE;IACvB,MAAM,KAAK,kBAAkB,EAAE,mDAAmD,MAAM,KAAK,sBAAsB,EAAE;IACrH,MAAM,KAAK,qBAAqB,EAAE;;EAEpC,MAAM,MAAM,KAAK,eAAe,EAAE;IAChC,MAAM,KAAK,OAAO,EAAE;CACvB;AACD"}
|
|
@@ -5,7 +5,152 @@ import os from "os";
|
|
|
5
5
|
import path from "path";
|
|
6
6
|
import { createHash } from "crypto";
|
|
7
7
|
import { createRequire } from "module";
|
|
8
|
+
import { spawnSync } from "child_process";
|
|
9
|
+
import { parseEnvBoolean } from "@rebasepro/types";
|
|
8
10
|
import inquirer from "inquirer";
|
|
11
|
+
//#region src/utils/root-pointer.ts
|
|
12
|
+
/**
|
|
13
|
+
* The note a Rebase project leaves at the root of the repository it sits in.
|
|
14
|
+
*
|
|
15
|
+
* A project's `CLAUDE.md`, `AGENTS.md` and the rest are loaded by an assistant
|
|
16
|
+
* started in the project's own directory. One started at the root of a larger
|
|
17
|
+
* repository — `my-app/` holding the site, with the Rebase project in
|
|
18
|
+
* `my-app/cloud/` — loads none of them, and opens none of the files they point
|
|
19
|
+
* to unless something sends it there. That is how an agent building a game on
|
|
20
|
+
* Rebase came to make twelve tables with `CREATE TABLE` in a function: every
|
|
21
|
+
* rule against it was in `cloud/`, and the agent never went there.
|
|
22
|
+
*
|
|
23
|
+
* So `rebase init` and `rebase skills install` write a marked block into the
|
|
24
|
+
* repository root's `CLAUDE.md` and `AGENTS.md`: where the project is, and the
|
|
25
|
+
* scaffold's "Before you write any code" rules, read from the template so there
|
|
26
|
+
* is one copy to keep true. A file that is not there is created; one that is
|
|
27
|
+
* gets the block appended, or replaced between its markers on a later run.
|
|
28
|
+
* `REBASE_ROOT_RULES=0` (any off spelling `parseEnvBoolean` reads) turns it
|
|
29
|
+
* off, for a root whose agent files are kept by hand — and for this package's
|
|
30
|
+
* tests, which scaffold inside this repository.
|
|
31
|
+
*
|
|
32
|
+
* Nothing is written at the home directory or above it: a dotfiles repository
|
|
33
|
+
* at `~` makes `~` the root of every project below it, and an assistant loads
|
|
34
|
+
* `~/CLAUDE.md` in every session it starts under home. Nor where the repository
|
|
35
|
+
* ignores the project, which is then not part of it.
|
|
36
|
+
*/
|
|
37
|
+
var ROOT_POINTER_START = "<!-- rebase:project -->";
|
|
38
|
+
var ROOT_POINTER_END = "<!-- /rebase:project -->";
|
|
39
|
+
var ROOT_POINTER_FILES = ["CLAUDE.md", "AGENTS.md"];
|
|
40
|
+
var RULES_HEADING = "## Before you write any code";
|
|
41
|
+
/**
|
|
42
|
+
* The repository root above a project, or null when the project is the root
|
|
43
|
+
* itself or is in no repository. The project's own directory is not a candidate:
|
|
44
|
+
* there its own files already load.
|
|
45
|
+
*/
|
|
46
|
+
function enclosingRepositoryRoot(projectDir) {
|
|
47
|
+
let dir = path.dirname(path.resolve(projectDir));
|
|
48
|
+
const top = path.parse(dir).root;
|
|
49
|
+
while (true) {
|
|
50
|
+
if (fs.existsSync(path.join(dir, ".git"))) return dir;
|
|
51
|
+
if (dir === top) return null;
|
|
52
|
+
dir = path.dirname(dir);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/** The rules block from the scaffold's `CLAUDE.md`, heading included. */
|
|
56
|
+
function scaffoldRules(templateDir) {
|
|
57
|
+
const text = fs.readFileSync(path.join(templateDir, "CLAUDE.md"), "utf8");
|
|
58
|
+
const at = text.indexOf(RULES_HEADING);
|
|
59
|
+
if (at === -1) throw new Error(`${path.join(templateDir, "CLAUDE.md")} has no "${RULES_HEADING}" block`);
|
|
60
|
+
return text.slice(at).trim();
|
|
61
|
+
}
|
|
62
|
+
/** The marked block for a project at `relativeDir` from the repository root. */
|
|
63
|
+
function rootPointerBlock(relativeDir, rules) {
|
|
64
|
+
const dir = relativeDir.split(path.sep).join("/");
|
|
65
|
+
return [
|
|
66
|
+
ROOT_POINTER_START,
|
|
67
|
+
"<!-- Written by `rebase init` and `rebase skills install`: edits between these markers are overwritten. -->",
|
|
68
|
+
"## Rebase project",
|
|
69
|
+
"",
|
|
70
|
+
`\`${dir}/\` is a Rebase project. Before you change anything in it, read \`${dir}/ai-instructions.md\`; the rules below hold even before you do. Their paths are relative to \`${dir}/\`.`,
|
|
71
|
+
"",
|
|
72
|
+
rules.replace(RULES_HEADING, `### Before you write any code in \`${dir}/\``),
|
|
73
|
+
ROOT_POINTER_END
|
|
74
|
+
].join("\n");
|
|
75
|
+
}
|
|
76
|
+
function occurrences(text, marker) {
|
|
77
|
+
return text.split(marker).length - 1;
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* `text` with the block in it: replaced between its markers, or appended.
|
|
81
|
+
* Null when the markers cannot say where the block is — one of them alone, more
|
|
82
|
+
* than one of either, or the end before the start: replacing from an orphan
|
|
83
|
+
* start to a new end would take whatever the user wrote in between with it.
|
|
84
|
+
* The block takes the file's line ending, so a CRLF file stays CRLF and a
|
|
85
|
+
* second run finds it unchanged.
|
|
86
|
+
*/
|
|
87
|
+
function withRootPointer(text, block) {
|
|
88
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
89
|
+
const lines = block.replace(/\r?\n/g, eol);
|
|
90
|
+
const starts = occurrences(text, ROOT_POINTER_START);
|
|
91
|
+
const ends = occurrences(text, ROOT_POINTER_END);
|
|
92
|
+
if (starts === 0 && ends === 0) {
|
|
93
|
+
if (text.trim() === "") return lines + eol;
|
|
94
|
+
return text.replace(/\s*$/, eol + eol) + lines + eol;
|
|
95
|
+
}
|
|
96
|
+
const start = text.indexOf(ROOT_POINTER_START);
|
|
97
|
+
const end = text.indexOf(ROOT_POINTER_END);
|
|
98
|
+
if (starts !== 1 || ends !== 1 || end < start) return null;
|
|
99
|
+
return text.slice(0, start) + lines + text.slice(end + 24);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Why the block may not go into `root`, or null when it may: `root` is the home
|
|
103
|
+
* directory or above it, or the repository ignores the project.
|
|
104
|
+
*/
|
|
105
|
+
function rootPointerRefusal(root, projectDir) {
|
|
106
|
+
const home = path.resolve(os.homedir());
|
|
107
|
+
const fromRoot = path.relative(root, home);
|
|
108
|
+
if (fromRoot === "" || !fromRoot.startsWith("..") && !path.isAbsolute(fromRoot)) return `${root} is the home directory or above it, and its agent files load in every session there`;
|
|
109
|
+
const relative = path.relative(root, path.resolve(projectDir));
|
|
110
|
+
if (spawnSync("git", [
|
|
111
|
+
"-C",
|
|
112
|
+
root,
|
|
113
|
+
"check-ignore",
|
|
114
|
+
"-q",
|
|
115
|
+
"--",
|
|
116
|
+
relative
|
|
117
|
+
], { stdio: "ignore" }).status === 0) return `${root} ignores ${relative}/, so the project is not part of that repository`;
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Write the block into the repository root's agent files when the project is
|
|
122
|
+
* below that root.
|
|
123
|
+
*/
|
|
124
|
+
function writeRootPointers(projectDir, templateDir) {
|
|
125
|
+
const result = {
|
|
126
|
+
changed: [],
|
|
127
|
+
untouched: [],
|
|
128
|
+
refused: null
|
|
129
|
+
};
|
|
130
|
+
if (parseEnvBoolean(process.env.REBASE_ROOT_RULES) === false) return result;
|
|
131
|
+
const root = enclosingRepositoryRoot(projectDir);
|
|
132
|
+
if (!root) return result;
|
|
133
|
+
result.refused = rootPointerRefusal(root, projectDir);
|
|
134
|
+
if (result.refused !== null) return result;
|
|
135
|
+
const block = rootPointerBlock(path.relative(root, path.resolve(projectDir)), scaffoldRules(templateDir));
|
|
136
|
+
for (const name of ROOT_POINTER_FILES) {
|
|
137
|
+
const file = path.join(root, name);
|
|
138
|
+
const before = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";
|
|
139
|
+
const after = withRootPointer(before, block);
|
|
140
|
+
if (after === null) {
|
|
141
|
+
result.untouched.push({
|
|
142
|
+
file,
|
|
143
|
+
reason: `its ${ROOT_POINTER_START} and ${ROOT_POINTER_END} markers are not one start followed by one end`
|
|
144
|
+
});
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (after === before) continue;
|
|
148
|
+
fs.writeFileSync(file, after);
|
|
149
|
+
result.changed.push(file);
|
|
150
|
+
}
|
|
151
|
+
return result;
|
|
152
|
+
}
|
|
153
|
+
//#endregion
|
|
9
154
|
//#region src/commands/skills.ts
|
|
10
155
|
var require = createRequire(import.meta.url);
|
|
11
156
|
/**
|
|
@@ -354,13 +499,25 @@ var SKILLS_MANIFEST = ".rebase-skills.json";
|
|
|
354
499
|
function sha256(bytes) {
|
|
355
500
|
return createHash("sha256").update(bytes).digest("hex");
|
|
356
501
|
}
|
|
502
|
+
/**
|
|
503
|
+
* Whether a manifest path names a file inside the target directory.
|
|
504
|
+
*
|
|
505
|
+
* The manifest is committed with the project, so whoever wrote the repository
|
|
506
|
+
* wrote it too, and the retired-file sweep below deletes what it lists — with
|
|
507
|
+
* `--force`, whatever it holds. A path that climbs out (`../../.bashrc`) or is
|
|
508
|
+
* absolute was never written by an install, and is not this command's to touch.
|
|
509
|
+
*/
|
|
510
|
+
function insideTarget(targetBase, relPath) {
|
|
511
|
+
const relative = path.relative(targetBase, path.resolve(targetBase, relPath));
|
|
512
|
+
return relative !== "" && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
513
|
+
}
|
|
357
514
|
function readManifest(targetBase) {
|
|
358
515
|
try {
|
|
359
516
|
const parsed = JSON.parse(fs.readFileSync(path.join(targetBase, SKILLS_MANIFEST), "utf-8"));
|
|
360
517
|
if (parsed && typeof parsed === "object" && "files" in parsed) {
|
|
361
518
|
const files = parsed.files;
|
|
362
519
|
if (files && typeof files === "object") {
|
|
363
|
-
const entries = Object.entries(files).filter((e) => typeof e[1] === "string");
|
|
520
|
+
const entries = Object.entries(files).filter((e) => typeof e[1] === "string" && insideTarget(targetBase, e[0]));
|
|
364
521
|
return {
|
|
365
522
|
version: 1,
|
|
366
523
|
files: Object.fromEntries(entries)
|
|
@@ -503,7 +660,7 @@ async function skillsHooks(rawArgs) {
|
|
|
503
660
|
* one line per file.
|
|
504
661
|
*/
|
|
505
662
|
async function installHooksAndReport(projectDir, force) {
|
|
506
|
-
const { installAgentHooks, AGENT_HOOK_SCRIPT } = await import("./agent-setup-
|
|
663
|
+
const { installAgentHooks, AGENT_HOOK_SCRIPT } = await import("./agent-setup-0uyfC7VX.js");
|
|
507
664
|
const shown = (file) => path.relative(process.cwd(), path.join(projectDir, file)) || file;
|
|
508
665
|
for (const { file, status } of installAgentHooks(projectDir, { force })) if (status === "added" || status === "replaced") console.log(` ${chalk.green("✓")} ${status === "added" ? "Wrote" : "Replaced"} ${chalk.gray(shown(file))}`);
|
|
509
666
|
else if (status === "present") console.log(` ${chalk.green("✓")} ${chalk.gray(shown(file))} already in place`);
|
|
@@ -606,7 +763,7 @@ async function skillsInstall(rawArgs = []) {
|
|
|
606
763
|
console.log(chalk.yellow(" Edited files were left as they are. To replace them with the bundle's copy:"));
|
|
607
764
|
console.log(` ${chalk.cyan("rebase skills install --force")}`);
|
|
608
765
|
}
|
|
609
|
-
const { MCP_SERVER_NAME, ensureMcpDependency, mcpDependencyNote, mcpServerRegistered, writeMcpConfig } = await import("./agent-setup-
|
|
766
|
+
const { MCP_SERVER_NAME, ensureMcpDependency, mcpDependencyNote, mcpServerRegistered, writeMcpConfig, cliPackageRoot } = await import("./agent-setup-0uyfC7VX.js");
|
|
610
767
|
const { detectPackageManager } = await import("./package-manager-DSEOwTqM.js").then((n) => n.r);
|
|
611
768
|
const shownFile = (file) => path.relative(process.cwd(), path.join(projectDir, file)) || file;
|
|
612
769
|
if (withMcp) {
|
|
@@ -629,6 +786,7 @@ async function skillsInstall(rawArgs = []) {
|
|
|
629
786
|
console.log("");
|
|
630
787
|
await installHooksAndReport(projectDir, force);
|
|
631
788
|
}
|
|
789
|
+
if (findProjectRoot(projectDir) === projectDir) reportRootPointers(writeRootPointers(projectDir, path.join(cliPackageRoot(), "templates", "template")));
|
|
632
790
|
console.log("");
|
|
633
791
|
console.log(chalk.gray(" Skills are project-local. Commit them to share with your team."));
|
|
634
792
|
console.log(chalk.gray(" Re-run this command to restore them. Upgrade @rebasepro/cli for newer skills."));
|
|
@@ -679,7 +837,14 @@ ${chalk.green.bold("Examples")}
|
|
|
679
837
|
${chalk.cyan("rebase skills --hooks")} ${chalk.gray("# the Claude Code guardrail hook only")}
|
|
680
838
|
`);
|
|
681
839
|
}
|
|
840
|
+
/** One line per repository-root agent file the project's rules were written into, or left alone. */
|
|
841
|
+
function reportRootPointers(result) {
|
|
842
|
+
const shown = (file) => path.relative(process.cwd(), file) || file;
|
|
843
|
+
for (const file of result.changed) console.log(` ${chalk.green("✓")} Rebase rules in ${chalk.gray(shown(file))}, for an assistant started at the repository root`);
|
|
844
|
+
for (const { file, reason } of result.untouched) console.warn(` ${chalk.yellow("!")} Left ${chalk.gray(shown(file))} as it is: ${reason}. Fix or remove them and run ${chalk.cyan("rebase skills install")} again.`);
|
|
845
|
+
if (result.refused !== null) console.log(chalk.gray(` No Rebase rules at the repository root: ${result.refused}.`));
|
|
846
|
+
}
|
|
682
847
|
//#endregion
|
|
683
|
-
export { AGENTS, AGENT_KEYS, SKILLS_SUBCOMMANDS, detectInstalledAgents, installSkills, loadBundledSkills, resolveAgentNames, skillsCommand };
|
|
848
|
+
export { AGENTS, AGENT_KEYS, SKILLS_SUBCOMMANDS, detectInstalledAgents, installSkills, loadBundledSkills, reportRootPointers, resolveAgentNames, skillsCommand, writeRootPointers as t };
|
|
684
849
|
|
|
685
|
-
//# sourceMappingURL=skills-
|
|
850
|
+
//# sourceMappingURL=skills-CbwV6vw_.js.map
|