@rebasepro/cli 0.0.1-canary.2 → 0.0.1-canary.4f204c2

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.
Files changed (48) hide show
  1. package/dist/commands/auth.d.ts +1 -0
  2. package/dist/commands/cli.test.d.ts +1 -0
  3. package/dist/commands/db.d.ts +1 -0
  4. package/dist/commands/dev.d.ts +1 -0
  5. package/dist/commands/dev.test.d.ts +1 -0
  6. package/dist/commands/doctor.d.ts +1 -0
  7. package/dist/commands/generate_sdk.d.ts +18 -0
  8. package/dist/commands/init.d.ts +1 -0
  9. package/dist/commands/init.test.d.ts +1 -0
  10. package/dist/commands/schema.d.ts +1 -0
  11. package/dist/index.cjs +986 -27
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.ts +5 -0
  14. package/dist/index.es.js +987 -26
  15. package/dist/index.es.js.map +1 -1
  16. package/dist/utils/project.d.ts +45 -0
  17. package/dist/utils/project.test.d.ts +1 -0
  18. package/package.json +20 -11
  19. package/templates/template/.dockerignore +28 -0
  20. package/templates/template/.env.template +42 -11
  21. package/templates/template/README.md +74 -17
  22. package/templates/template/backend/Dockerfile +55 -10
  23. package/templates/template/backend/functions/hello.ts +52 -0
  24. package/templates/template/backend/package.json +30 -34
  25. package/templates/template/backend/src/env.ts +52 -0
  26. package/templates/template/backend/src/index.ts +113 -99
  27. package/templates/template/backend/tsconfig.json +1 -1
  28. package/templates/template/config/collections/authors.ts +45 -0
  29. package/templates/template/config/collections/index.ts +5 -0
  30. package/templates/template/{shared → config}/collections/posts.ts +40 -2
  31. package/templates/template/config/collections/tags.ts +27 -0
  32. package/templates/template/config/package.json +28 -0
  33. package/templates/template/docker-compose.yml +77 -16
  34. package/templates/template/frontend/Dockerfile +36 -14
  35. package/templates/template/frontend/nginx.conf +40 -0
  36. package/templates/template/frontend/package.json +9 -10
  37. package/templates/template/frontend/src/App.tsx +26 -33
  38. package/templates/template/frontend/src/index.css +15 -1
  39. package/templates/template/frontend/src/main.tsx +2 -2
  40. package/templates/template/frontend/vite.config.ts +1 -1
  41. package/templates/template/package.json +11 -16
  42. package/templates/template/pnpm-workspace.yaml +4 -0
  43. package/templates/template/scripts/example.ts +91 -0
  44. package/templates/template/backend/scripts/db-generate.ts +0 -60
  45. package/templates/template/shared/collections/index.ts +0 -3
  46. package/templates/template/shared/package.json +0 -28
  47. /package/templates/template/{shared → config}/index.ts +0 -0
  48. /package/templates/template/{shared → config}/tsconfig.json +0 -0
package/dist/index.cjs CHANGED
@@ -1,6 +1,6 @@
1
1
  (function(global, factory) {
2
- typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("chalk"), require("arg"), require("inquirer"), require("path"), require("fs"), require("util"), require("execa"), require("ncp"), require("url"), require("crypto"), require("os")) : typeof define === "function" && define.amd ? define(["exports", "chalk", "arg", "inquirer", "path", "fs", "util", "execa", "ncp", "url", "crypto", "os"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase CLI"] = {}, global.chalk, global.arg, global.inquirer, global.path, global.fs, global.util, global.execa, global.ncp, global.url, global.crypto, global.os));
3
- })(this, (function(exports2, chalk, arg, inquirer, path, fs, util, execa, ncp, url, crypto, os) {
2
+ typeof exports === "object" && typeof module !== "undefined" ? factory(exports, require("chalk"), require("arg"), require("inquirer"), require("path"), require("fs"), require("util"), require("execa"), require("ncp"), require("url"), require("crypto"), require("@rebasepro/sdk-generator"), require("child_process"), require("os")) : typeof define === "function" && define.amd ? define(["exports", "chalk", "arg", "inquirer", "path", "fs", "util", "execa", "ncp", "url", "crypto", "@rebasepro/sdk-generator", "child_process", "os"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global["Rebase CLI"] = {}, global.chalk, global.arg, global.inquirer, global.path, global.fs, global.util, global.execa, global.ncp, global.url, global.crypto, global.sdkGenerator, global.child_process, global.os));
3
+ })(this, (function(exports2, chalk, arg, inquirer, path, fs, util, execa, ncp, url, crypto, sdkGenerator, child_process, os) {
4
4
  "use strict";
5
5
  var _documentCurrentScript = typeof document !== "undefined" ? document.currentScript : null;
6
6
  function _interopNamespaceDefault(e) {
@@ -46,7 +46,9 @@ ${chalk.bold("Rebase")} — Create a new project 🚀
46
46
  const args = arg(
47
47
  {
48
48
  "--git": Boolean,
49
- "-g": "--git"
49
+ "--install": Boolean,
50
+ "-g": "--git",
51
+ "-i": "--install"
50
52
  },
51
53
  {
52
54
  argv: rawArgs.slice(3),
@@ -79,13 +81,22 @@ ${chalk.bold("Rebase")} — Create a new project 🚀
79
81
  default: true
80
82
  });
81
83
  }
84
+ if (!args["--install"]) {
85
+ questions.push({
86
+ type: "confirm",
87
+ name: "installDeps",
88
+ message: "Install dependencies with pnpm?",
89
+ default: true
90
+ });
91
+ }
82
92
  const answers = await inquirer.prompt(questions);
83
- const projectName = nameArg || answers.projectName;
84
- const targetDirectory = path.resolve(process.cwd(), projectName);
93
+ const targetDirectory = path.resolve(process.cwd(), nameArg || answers.projectName);
94
+ const projectName = path.basename(targetDirectory);
85
95
  const templateDirectory = path.resolve(cliRoot, "templates", "template");
86
96
  return {
87
97
  projectName,
88
98
  git: args["--git"] || answers.git || false,
99
+ installDeps: args["--install"] || answers.installDeps || false,
89
100
  targetDirectory,
90
101
  templateDirectory
91
102
  };
@@ -106,14 +117,19 @@ ${chalk.bold("Rebase")} — Create a new project 🚀
106
117
  process.exit(1);
107
118
  }
108
119
  console.log(chalk.gray(" Copying project files..."));
109
- await copy(options.templateDirectory, options.targetDirectory, {
110
- clobber: false,
111
- dot: true,
112
- filter: (source) => {
113
- const basename = path.basename(source);
114
- return basename !== "node_modules" && basename !== ".DS_Store";
115
- }
116
- });
120
+ try {
121
+ await copy(options.templateDirectory, options.targetDirectory, {
122
+ clobber: false,
123
+ dot: true,
124
+ filter: (source) => {
125
+ const basename = path.basename(source);
126
+ return basename !== "node_modules" && basename !== ".DS_Store";
127
+ }
128
+ });
129
+ } catch (err) {
130
+ console.error(`${chalk.red.bold("ERROR")} Failed to copy template files: ${err instanceof Error ? err.message : String(err)}`);
131
+ process.exit(1);
132
+ }
117
133
  await replacePlaceholders(options);
118
134
  const envTemplatePath = path.join(options.targetDirectory, ".env.template");
119
135
  const envPath = path.join(options.targetDirectory, ".env");
@@ -144,23 +160,38 @@ POSTGRES_PASSWORD=${dbPassword}
144
160
  console.warn(chalk.yellow(" Warning: Failed to initialize git repository"));
145
161
  }
146
162
  }
163
+ if (options.installDeps) {
164
+ console.log("");
165
+ console.log(chalk.gray(" Installing dependencies with pnpm..."));
166
+ console.log("");
167
+ try {
168
+ await execa("pnpm", ["install"], {
169
+ cwd: options.targetDirectory,
170
+ stdio: "inherit"
171
+ });
172
+ } catch {
173
+ console.warn(chalk.yellow(" Warning: Failed to install dependencies. You may need to run `pnpm install` manually."));
174
+ }
175
+ }
147
176
  console.log("");
148
177
  console.log(`${chalk.green.bold("✓")} Project ${chalk.bold(options.projectName)} created successfully!`);
149
178
  console.log("");
150
179
  console.log(chalk.bold("Next steps:"));
151
180
  console.log("");
152
181
  console.log(` ${chalk.cyan("cd")} ${options.projectName}`);
153
- console.log(` ${chalk.cyan("pnpm install")}`);
182
+ if (!options.installDeps) {
183
+ console.log(` ${chalk.cyan("pnpm install")}`);
184
+ }
154
185
  console.log("");
155
186
  console.log(chalk.gray(" # Set up your database connection in .env"));
156
187
  console.log(chalk.gray(" # Then run:"));
157
188
  console.log("");
158
189
  console.log(` ${chalk.cyan("pnpm dev")}`);
159
190
  console.log("");
160
- console.log(chalk.gray("This starts both the backend (Express + PostgreSQL)") + chalk.gray(" and the frontend (Vite + React) concurrently."));
191
+ console.log(chalk.gray("This starts both the backend (Hono + PostgreSQL)") + chalk.gray(" and the frontend (Vite + React) concurrently."));
161
192
  console.log("");
162
193
  console.log(chalk.gray("Docs: https://rebase.pro/docs"));
163
- console.log(chalk.gray("GitHub: https://github.com/rebaseco/rebase"));
194
+ console.log(chalk.gray("GitHub: https://github.com/rebasepro/rebase"));
164
195
  console.log("");
165
196
  }
166
197
  async function replacePlaceholders(options) {
@@ -168,17 +199,868 @@ POSTGRES_PASSWORD=${dbPassword}
168
199
  "package.json",
169
200
  "frontend/package.json",
170
201
  "backend/package.json",
171
- "shared/package.json",
202
+ "config/package.json",
172
203
  "frontend/index.html"
173
204
  ];
205
+ const packageJsonPath = path.resolve(cliRoot, "package.json");
206
+ let cliVersion = "latest";
207
+ if (fs.existsSync(packageJsonPath)) {
208
+ const pkg = JSON.parse(fs.readFileSync(packageJsonPath, "utf-8"));
209
+ cliVersion = pkg.version || "latest";
210
+ }
211
+ const versionCache = /* @__PURE__ */ new Map();
212
+ const getPackageVersion = async (pkgName) => {
213
+ if (versionCache.has(pkgName)) return versionCache.get(pkgName);
214
+ let versionToUse = cliVersion;
215
+ try {
216
+ const { stdout } = await execa("npm", ["--loglevel", "error", "info", `${pkgName}@${cliVersion}`, "version"]);
217
+ if (!stdout.trim()) throw new Error("Not found");
218
+ versionToUse = stdout.trim();
219
+ } catch {
220
+ try {
221
+ const tag = cliVersion.includes("canary") ? "canary" : "latest";
222
+ const { stdout } = await execa("npm", ["--loglevel", "error", "info", `${pkgName}@${tag}`, "version"]);
223
+ if (!stdout.trim()) throw new Error("Not found");
224
+ versionToUse = stdout.trim();
225
+ } catch {
226
+ try {
227
+ const { stdout } = await execa("npm", ["--loglevel", "error", "info", pkgName, "version"]);
228
+ versionToUse = stdout.trim() || "latest";
229
+ } catch {
230
+ versionToUse = "latest";
231
+ }
232
+ }
233
+ }
234
+ versionCache.set(pkgName, versionToUse);
235
+ return versionToUse;
236
+ };
237
+ const allPackages = /* @__PURE__ */ new Set();
238
+ const fileContents = /* @__PURE__ */ new Map();
174
239
  for (const file of filesToProcess) {
175
240
  const fullPath = path.resolve(options.targetDirectory, file);
176
241
  if (!fs.existsSync(fullPath)) continue;
177
- let content = fs.readFileSync(fullPath, "utf-8");
178
- content = content.replace(/\{\{PROJECT_NAME\}\}/g, options.projectName);
242
+ const content = fs.readFileSync(fullPath, "utf-8");
243
+ fileContents.set(fullPath, content);
244
+ const matches = [...content.matchAll(/"(@rebasepro\/[^"]+)":\s*"workspace:\*"/g)];
245
+ for (const match of matches) {
246
+ allPackages.add(match[1]);
247
+ }
248
+ }
249
+ console.log(chalk.gray(" Resolving package versions..."));
250
+ await Promise.all(Array.from(allPackages).map(getPackageVersion));
251
+ for (const [fullPath, originalContent] of fileContents.entries()) {
252
+ let content = originalContent.replace(/\{\{PROJECT_NAME\}\}/g, options.projectName);
253
+ const matches = [...content.matchAll(/"(@rebasepro\/[^"]+)":\s*"workspace:\*"/g)];
254
+ for (const match of matches) {
255
+ const pkgName = match[1];
256
+ const resolvedVersion = versionCache.get(pkgName) || "latest";
257
+ content = content.replace(new RegExp(`"${pkgName}":\\s*"workspace:\\*"`, "g"), `"${pkgName}": "${resolvedVersion}"`);
258
+ }
179
259
  fs.writeFileSync(fullPath, content, "utf-8");
180
260
  }
181
261
  }
262
+ async function loadCollections(collectionsDir) {
263
+ const absDir = path.resolve(collectionsDir);
264
+ if (!fs.existsSync(absDir)) {
265
+ throw new Error(`Collections directory not found: ${absDir}`);
266
+ }
267
+ let jiti;
268
+ try {
269
+ const jitiModule = await import("jiti");
270
+ jiti = jitiModule.default || jitiModule;
271
+ } catch {
272
+ throw new Error(
273
+ "Could not load 'jiti'. Install it with: pnpm add -D jiti\njiti is required to dynamically import TypeScript collection definitions."
274
+ );
275
+ }
276
+ const jitiInstance = jiti(absDir, {
277
+ interopDefault: true,
278
+ esmResolve: true
279
+ });
280
+ const indexCandidates = ["index.ts", "index.js", "index.mjs"];
281
+ let indexPath = null;
282
+ for (const candidate of indexCandidates) {
283
+ const p = path.join(absDir, candidate);
284
+ if (fs.existsSync(p)) {
285
+ indexPath = p;
286
+ break;
287
+ }
288
+ }
289
+ if (!indexPath) {
290
+ console.log(chalk.yellow(" No index file found, scanning individual collection files..."));
291
+ const collections = [];
292
+ const files = fs.readdirSync(absDir).filter(
293
+ (f) => (f.endsWith(".ts") || f.endsWith(".js")) && !f.startsWith(".")
294
+ );
295
+ for (const file of files) {
296
+ try {
297
+ const mod2 = jitiInstance(path.join(absDir, file));
298
+ const exported2 = mod2.default || mod2;
299
+ if (exported2 && typeof exported2 === "object" && "slug" in exported2) {
300
+ collections.push(exported2);
301
+ } else if (Array.isArray(exported2)) {
302
+ collections.push(...exported2);
303
+ }
304
+ } catch (err) {
305
+ console.warn(chalk.yellow(` ⚠ Skipping ${file}: ${err.message}`));
306
+ }
307
+ }
308
+ return collections;
309
+ }
310
+ const mod = jitiInstance(indexPath);
311
+ const exported = mod.default || mod;
312
+ if (Array.isArray(exported)) {
313
+ return exported;
314
+ } else if (typeof exported === "object" && exported !== null) {
315
+ if ("collections" in exported && Array.isArray(exported.collections)) {
316
+ return exported.collections;
317
+ }
318
+ const collections = [];
319
+ for (const value of Object.values(exported)) {
320
+ if (value && typeof value === "object" && "slug" in value) {
321
+ collections.push(value);
322
+ }
323
+ }
324
+ if (collections.length > 0) return collections;
325
+ }
326
+ throw new Error(
327
+ `Could not extract collections from ${indexPath}.
328
+ Expected a default export of EntityCollection[] or an object with named collection exports.`
329
+ );
330
+ }
331
+ function writeFiles(outputDir, files) {
332
+ const absOutput = path.resolve(outputDir);
333
+ fs.mkdirSync(absOutput, { recursive: true });
334
+ for (const file of files) {
335
+ const filePath = path.join(absOutput, file.path);
336
+ const dir = path.dirname(filePath);
337
+ if (!fs.existsSync(dir)) {
338
+ fs.mkdirSync(dir, { recursive: true });
339
+ }
340
+ fs.writeFileSync(filePath, file.content, "utf-8");
341
+ }
342
+ }
343
+ async function generateSdkCommand(args) {
344
+ const { collectionsDir, output, cwd } = args;
345
+ const resolvedCollectionsDir = path.isAbsolute(collectionsDir) ? collectionsDir : path.join(cwd, collectionsDir);
346
+ const resolvedOutput = path.isAbsolute(output) ? output : path.join(cwd, output);
347
+ console.log("");
348
+ console.log(chalk.bold(" 🔧 Rebase SDK Generator"));
349
+ console.log("");
350
+ console.log(` ${chalk.gray("Collections:")} ${resolvedCollectionsDir}`);
351
+ console.log(` ${chalk.gray("Output:")} ${resolvedOutput}`);
352
+ console.log("");
353
+ console.log(chalk.cyan(" → Loading collection definitions..."));
354
+ const collections = await loadCollections(resolvedCollectionsDir);
355
+ if (collections.length === 0) {
356
+ console.log(chalk.red(" ✗ No collections found. Nothing to generate."));
357
+ process.exit(1);
358
+ }
359
+ console.log(chalk.green(` ✓ Found ${collections.length} collection(s): ${collections.map((c) => c.slug).join(", ")}`));
360
+ console.log("");
361
+ console.log(chalk.cyan(" → Generating SDK files..."));
362
+ const files = sdkGenerator.generateSDK(collections);
363
+ console.log(chalk.green(` ✓ Generated ${files.length} file(s)`));
364
+ console.log(chalk.cyan(` → Writing to ${resolvedOutput}...`));
365
+ writeFiles(resolvedOutput, files);
366
+ console.log("");
367
+ console.log(chalk.green.bold(" ✓ SDK generated successfully!"));
368
+ console.log("");
369
+ console.log(chalk.gray(" Usage:"));
370
+ console.log(chalk.gray(" import { createRebaseClient } from '@rebasepro/client';"));
371
+ console.log(chalk.gray(` import type { Database } from './${path.relative(cwd, path.join(resolvedOutput, "database.types"))}';`));
372
+ console.log("");
373
+ console.log(chalk.gray(" const rebase = createRebaseClient<Database>({"));
374
+ console.log(chalk.gray(" baseUrl: 'http://localhost:3001',"));
375
+ console.log(chalk.gray(" // token: 'your-jwt-token',"));
376
+ console.log(chalk.gray(" });"));
377
+ console.log("");
378
+ console.log(chalk.gray(` const { data } = await rebase.collection('${collections[0]?.slug || "my_collection"}').find();`));
379
+ console.log("");
380
+ }
381
+ function findProjectRoot(startDir = process.cwd()) {
382
+ let dir = path.resolve(startDir);
383
+ const root = path.parse(dir).root;
384
+ while (dir !== root) {
385
+ const pkgPath = path.join(dir, "package.json");
386
+ if (fs.existsSync(pkgPath)) {
387
+ try {
388
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
389
+ if (pkg.workspaces && Array.isArray(pkg.workspaces)) {
390
+ const hasBackend = pkg.workspaces.some(
391
+ (w) => w === "backend" || w.includes("backend")
392
+ );
393
+ if (hasBackend) return dir;
394
+ }
395
+ } catch {
396
+ }
397
+ if (fs.existsSync(path.join(dir, "backend")) && fs.existsSync(path.join(dir, "config"))) {
398
+ return dir;
399
+ }
400
+ }
401
+ dir = path.dirname(dir);
402
+ }
403
+ return null;
404
+ }
405
+ function findBackendDir(projectRoot) {
406
+ const backendDir = path.join(projectRoot, "backend");
407
+ return fs.existsSync(backendDir) ? backendDir : null;
408
+ }
409
+ function getActiveBackendPlugin(backendDir) {
410
+ const pkgPath = path.join(backendDir, "package.json");
411
+ if (!fs.existsSync(pkgPath)) return null;
412
+ try {
413
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
414
+ const deps = {
415
+ ...pkg.dependencies,
416
+ ...pkg.devDependencies
417
+ };
418
+ for (const dep of Object.keys(deps)) {
419
+ if (dep.startsWith("@rebasepro/server-") && dep !== "@rebasepro/server-core") {
420
+ return dep;
421
+ }
422
+ }
423
+ } catch {
424
+ }
425
+ return null;
426
+ }
427
+ function resolvePluginCliScript(backendDir, pluginName) {
428
+ const candidates = [
429
+ path.join(backendDir, "node_modules", pluginName, "src", "cli.ts"),
430
+ path.join(backendDir, "node_modules", pluginName, "dist", "cli.js"),
431
+ // For monorepo dev mode:
432
+ path.resolve(backendDir, "..", "..", "packages", pluginName.replace("@rebasepro/", ""), "src", "cli.ts"),
433
+ path.resolve(backendDir, "..", "packages", pluginName.replace("@rebasepro/", ""), "src", "cli.ts")
434
+ ];
435
+ for (const candidate of candidates) {
436
+ if (fs.existsSync(candidate)) return candidate;
437
+ }
438
+ return null;
439
+ }
440
+ function findFrontendDir(projectRoot) {
441
+ const frontendDir = path.join(projectRoot, "frontend");
442
+ return fs.existsSync(frontendDir) ? frontendDir : null;
443
+ }
444
+ function findEnvFile(projectRoot) {
445
+ const candidates = [
446
+ path.join(projectRoot, ".env"),
447
+ path.join(projectRoot, "backend", ".env")
448
+ ];
449
+ for (const candidate of candidates) {
450
+ if (fs.existsSync(candidate)) return candidate;
451
+ }
452
+ return null;
453
+ }
454
+ function resolveLocalBin(projectRoot, binName) {
455
+ const candidates = [
456
+ path.join(projectRoot, "backend", "node_modules", ".bin", binName),
457
+ path.join(projectRoot, "node_modules", ".bin", binName)
458
+ ];
459
+ let parent = path.dirname(projectRoot);
460
+ const rootDir = path.parse(parent).root;
461
+ while (parent !== rootDir) {
462
+ candidates.push(path.join(parent, "node_modules", ".bin", binName));
463
+ parent = path.dirname(parent);
464
+ }
465
+ for (const candidate of candidates) {
466
+ if (fs.existsSync(candidate)) return candidate;
467
+ }
468
+ try {
469
+ const globalPath = child_process.execSync(`which ${binName}`, { encoding: "utf-8" }).trim();
470
+ if (globalPath && fs.existsSync(globalPath)) return globalPath;
471
+ } catch {
472
+ }
473
+ return null;
474
+ }
475
+ function resolveTsx(projectRoot) {
476
+ return resolveLocalBin(projectRoot, "tsx");
477
+ }
478
+ function requireProjectRoot() {
479
+ const root = findProjectRoot();
480
+ if (!root) {
481
+ console.error(chalk.red("✗ Could not find a Rebase project root."));
482
+ console.error(chalk.gray(" Make sure you are inside a Rebase project directory"));
483
+ console.error(chalk.gray(" (one with backend/, frontend/, and shared/ directories)."));
484
+ process.exit(1);
485
+ }
486
+ return root;
487
+ }
488
+ function requireBackendDir(projectRoot) {
489
+ const backendDir = findBackendDir(projectRoot);
490
+ if (!backendDir) {
491
+ console.error(chalk.red("✗ Could not find a backend/ directory."));
492
+ console.error(chalk.gray(` Expected at: ${path.join(projectRoot, "backend")}`));
493
+ process.exit(1);
494
+ }
495
+ return backendDir;
496
+ }
497
+ async function schemaCommand(subcommand, rawArgs) {
498
+ if (!subcommand || subcommand === "--help") {
499
+ printSchemaHelp();
500
+ return;
501
+ }
502
+ const projectRoot = requireProjectRoot();
503
+ const backendDir = requireBackendDir(projectRoot);
504
+ const activePlugin = getActiveBackendPlugin(backendDir);
505
+ if (!activePlugin) {
506
+ console.error(chalk.red("✗ Could not detect an active database plugin."));
507
+ console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgresql is installed in backend/package.json."));
508
+ process.exit(1);
509
+ }
510
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
511
+ if (!pluginCli) {
512
+ console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));
513
+ process.exit(1);
514
+ }
515
+ const envFile = findEnvFile(projectRoot);
516
+ const env = { ...process.env };
517
+ if (envFile) {
518
+ env.DOTENV_CONFIG_PATH = envFile;
519
+ }
520
+ try {
521
+ const isTs = pluginCli.endsWith(".ts");
522
+ if (isTs) {
523
+ const tsxBin = resolveTsx(projectRoot);
524
+ if (!tsxBin) {
525
+ console.error(chalk.red("✗ Could not find tsx binary."));
526
+ process.exit(1);
527
+ }
528
+ await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {
529
+ cwd: backendDir,
530
+ stdio: "inherit",
531
+ env
532
+ });
533
+ } else {
534
+ await execa("node", [pluginCli, ...rawArgs.slice(2)], {
535
+ cwd: backendDir,
536
+ stdio: "inherit",
537
+ env
538
+ });
539
+ }
540
+ } catch (err) {
541
+ process.exit(1);
542
+ }
543
+ }
544
+ function printSchemaHelp() {
545
+ console.log(`
546
+ ${chalk.bold("rebase schema")} — Schema management commands
547
+
548
+ ${chalk.green.bold("Usage")}
549
+ rebase schema ${chalk.blue("<command>")} [options]
550
+
551
+ ${chalk.green.bold("Commands")}
552
+ ${chalk.gray("(Commands are provided by your active database driver plugin)")}
553
+ ${chalk.blue.bold("generate")} Generate Schema from collection definitions
554
+
555
+ ${chalk.green.bold("generate Options")}
556
+ ${chalk.blue("--collections, -c")} Path to collections directory
557
+ ${chalk.blue("--output, -o")} Output path for generated schema
558
+ ${chalk.blue("--watch, -w")} Watch for changes and regenerate automatically
559
+ `);
560
+ }
561
+ async function dbCommand(subcommand, rawArgs) {
562
+ if (!subcommand || subcommand === "--help") {
563
+ printDbHelp();
564
+ return;
565
+ }
566
+ const projectRoot = requireProjectRoot();
567
+ const backendDir = requireBackendDir(projectRoot);
568
+ const activePlugin = getActiveBackendPlugin(backendDir);
569
+ if (!activePlugin) {
570
+ console.error(chalk.red("✗ Could not detect an active database plugin."));
571
+ console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgresql is installed in backend/package.json."));
572
+ process.exit(1);
573
+ }
574
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
575
+ if (!pluginCli) {
576
+ console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));
577
+ process.exit(1);
578
+ }
579
+ const envFile = findEnvFile(projectRoot);
580
+ const env = { ...process.env };
581
+ if (envFile) {
582
+ env.DOTENV_CONFIG_PATH = envFile;
583
+ }
584
+ try {
585
+ const isTs = pluginCli.endsWith(".ts");
586
+ if (isTs) {
587
+ const tsxBin = resolveTsx(projectRoot);
588
+ if (!tsxBin) {
589
+ console.error(chalk.red("✗ Could not find tsx binary."));
590
+ process.exit(1);
591
+ }
592
+ await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {
593
+ cwd: backendDir,
594
+ stdio: "inherit",
595
+ env
596
+ });
597
+ } else {
598
+ await execa("node", [pluginCli, ...rawArgs.slice(2)], {
599
+ cwd: backendDir,
600
+ stdio: "inherit",
601
+ env
602
+ });
603
+ }
604
+ } catch (err) {
605
+ process.exit(1);
606
+ }
607
+ }
608
+ function printDbHelp() {
609
+ console.log(`
610
+ ${chalk.bold("rebase db")} — Database management commands
611
+
612
+ ${chalk.green.bold("Usage")}
613
+ rebase db ${chalk.blue("<command>")} [options]
614
+
615
+ ${chalk.green.bold("Commands")}
616
+ ${chalk.gray("(Commands are provided by your active database driver plugin)")}
617
+ ${chalk.blue.bold("push")} Apply schema directly to database (development)
618
+ ${chalk.blue.bold("pull")} Introspect database → Schema
619
+ ${chalk.blue.bold("generate")} Generate migration files
620
+ ${chalk.blue.bold("migrate")} Run pending migrations
621
+ ${chalk.blue.bold("studio")} Open Studio viewer
622
+ ${chalk.blue.bold("branch")} Database branching (create, list, delete, info)
623
+
624
+ ${chalk.green.bold("Examples")}
625
+ ${chalk.gray("# Quick development workflow")}
626
+ rebase schema generate && rebase db push
627
+
628
+ ${chalk.gray("# Production migration workflow")}
629
+ rebase db generate
630
+ rebase db migrate
631
+
632
+ ${chalk.gray("# Create a database branch")}
633
+ rebase db branch create feature_auth
634
+ `);
635
+ }
636
+ const DEV_PORT_FILENAME = ".rebase-dev-port";
637
+ function getProjectPort(projectRoot) {
638
+ let hash = 0;
639
+ for (let i = 0; i < projectRoot.length; i++) {
640
+ hash = (hash << 5) - hash + projectRoot.charCodeAt(i) | 0;
641
+ }
642
+ return 3001 + Math.abs(hash) % 999;
643
+ }
644
+ function resolveStartPort(projectRoot, explicitPort) {
645
+ if (explicitPort) return explicitPort;
646
+ if (process.env.PORT) return parseInt(process.env.PORT, 10);
647
+ try {
648
+ const portFile = path.join(projectRoot, DEV_PORT_FILENAME);
649
+ if (fs.existsSync(portFile)) {
650
+ const saved = parseInt(fs.readFileSync(portFile, "utf-8").trim(), 10);
651
+ if (saved > 0 && saved < 65536) return saved;
652
+ }
653
+ } catch {
654
+ }
655
+ return getProjectPort(projectRoot);
656
+ }
657
+ async function devCommand(rawArgs) {
658
+ const args = arg(
659
+ {
660
+ "--backend-only": Boolean,
661
+ "--frontend-only": Boolean,
662
+ "--port": Number,
663
+ "--help": Boolean,
664
+ "-b": "--backend-only",
665
+ "-f": "--frontend-only",
666
+ "-p": "--port",
667
+ "-h": "--help"
668
+ },
669
+ {
670
+ argv: rawArgs.slice(3),
671
+ // skip "node rebase dev"
672
+ permissive: true
673
+ }
674
+ );
675
+ if (args["--help"]) {
676
+ printDevHelp();
677
+ return;
678
+ }
679
+ const projectRoot = requireProjectRoot();
680
+ const backendDir = findBackendDir(projectRoot);
681
+ const frontendDir = findFrontendDir(projectRoot);
682
+ const backendOnly = args["--backend-only"] || false;
683
+ const frontendOnly = args["--frontend-only"] || false;
684
+ const startPort = resolveStartPort(projectRoot, args["--port"]);
685
+ console.log("");
686
+ console.log(chalk.bold(" 🚀 Rebase Dev Server"));
687
+ console.log("");
688
+ const children = [];
689
+ let frontendUrl = "";
690
+ let backendUrl = "";
691
+ let debounceSummary = null;
692
+ let bannerPrinted = false;
693
+ let resolvedBackendPort = null;
694
+ const stripAnsi = (str) => str.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
695
+ function printSummary() {
696
+ if (!frontendUrl || !backendUrl) return;
697
+ if (debounceSummary) clearTimeout(debounceSummary);
698
+ debounceSummary = setTimeout(() => {
699
+ if (bannerPrinted) return;
700
+ console.log("");
701
+ console.log(chalk.cyan("┌────────────────────────────────────────────────────────────┐"));
702
+ console.log(chalk.cyan("│ │"));
703
+ console.log(chalk.cyan("│ ✨ Rebase Admin App is ready! │"));
704
+ const cleanUrl = stripAnsi(frontendUrl);
705
+ const paddedUrl = cleanUrl.padEnd(40);
706
+ console.log(chalk.cyan("│ 👉 Frontend URL: ") + chalk.white(paddedUrl) + chalk.cyan("│"));
707
+ console.log(chalk.cyan("│ │"));
708
+ console.log(chalk.cyan("└────────────────────────────────────────────────────────────┘"));
709
+ console.log("");
710
+ bannerPrinted = true;
711
+ }, 500);
712
+ }
713
+ const cleanup = () => {
714
+ try {
715
+ const portFile = path.join(projectRoot, DEV_PORT_FILENAME);
716
+ if (fs.existsSync(portFile)) fs.unlinkSync(portFile);
717
+ const urlFile = path.join(projectRoot, ".rebase-dev-url");
718
+ if (fs.existsSync(urlFile)) fs.unlinkSync(urlFile);
719
+ } catch {
720
+ }
721
+ children.forEach((child) => {
722
+ if (child.pid && !child.killed) {
723
+ try {
724
+ if (process.platform === "win32") {
725
+ execa.commandSync(`taskkill /pid ${child.pid} /T /F`);
726
+ } else {
727
+ process.kill(-child.pid, "SIGKILL");
728
+ }
729
+ } catch (e) {
730
+ try {
731
+ child.kill("SIGKILL");
732
+ } catch (err) {
733
+ }
734
+ }
735
+ }
736
+ });
737
+ process.exit(0);
738
+ };
739
+ process.on("SIGINT", cleanup);
740
+ process.on("SIGTERM", cleanup);
741
+ function startFrontend(backendPort) {
742
+ if (!frontendDir) return;
743
+ console.log(` ${chalk.magenta("▶")} Frontend: ${chalk.gray(frontendDir)}`);
744
+ const frontendEnv = { ...process.env };
745
+ if (backendPort) {
746
+ frontendEnv.VITE_API_URL = `http://localhost:${backendPort}`;
747
+ console.log(` ${chalk.gray("↳ VITE_API_URL")} = ${chalk.white(`http://localhost:${backendPort}`)}`);
748
+ }
749
+ const frontendChild = execa(
750
+ "pnpm",
751
+ ["run", "dev"],
752
+ {
753
+ cwd: frontendDir,
754
+ stdio: ["inherit", "pipe", "pipe"],
755
+ env: frontendEnv,
756
+ shell: true,
757
+ detached: process.platform !== "win32"
758
+ }
759
+ );
760
+ frontendChild.catch(() => {
761
+ });
762
+ frontendChild.stdout?.on("data", (data) => {
763
+ const lines = data.toString().split("\n").filter(Boolean);
764
+ lines.forEach((line) => {
765
+ console.log(`${chalk.magenta.bold("[admin]")} ${line}`);
766
+ const cleanLine = stripAnsi(line);
767
+ const urlMatch = cleanLine.match(/(http:\/\/(?:localhost|127\.0\.0\.1):\d+)/);
768
+ if (cleanLine.includes("Local:") && urlMatch) {
769
+ frontendUrl = urlMatch[1];
770
+ printSummary();
771
+ }
772
+ });
773
+ });
774
+ frontendChild.stderr?.on("data", (data) => {
775
+ const lines = data.toString().split("\n").filter(Boolean);
776
+ lines.forEach((line) => {
777
+ console.log(`${chalk.magenta.bold("[admin]")} ${line}`);
778
+ });
779
+ });
780
+ children.push(frontendChild);
781
+ }
782
+ if (!frontendOnly && backendDir) {
783
+ const tsxBin = resolveTsx(projectRoot);
784
+ if (!tsxBin) {
785
+ console.error(chalk.red(" ✗ Could not find tsx binary for backend."));
786
+ console.error(chalk.gray(" Install it with: pnpm add -D tsx"));
787
+ process.exit(1);
788
+ }
789
+ const envFile = findEnvFile(projectRoot);
790
+ const env = { ...process.env };
791
+ if (envFile) {
792
+ env.DOTENV_CONFIG_PATH = envFile;
793
+ }
794
+ env.PORT = String(startPort);
795
+ console.log(` ${chalk.cyan("▶")} Backend: ${chalk.gray(backendDir)}`);
796
+ console.log(` ${chalk.gray("↳ PORT")} = ${chalk.white(String(startPort))}`);
797
+ let frontendLaunched = false;
798
+ const backendChild = execa(
799
+ tsxBin,
800
+ ["watch", `--watch="${path.join("..", "config", "**", "*")}"`, "--conditions", "development", "src/index.ts"],
801
+ {
802
+ cwd: backendDir,
803
+ stdio: ["inherit", "pipe", "pipe"],
804
+ env,
805
+ shell: true,
806
+ detached: process.platform !== "win32"
807
+ }
808
+ );
809
+ backendChild.catch(() => {
810
+ });
811
+ backendChild.stdout?.on("data", (data) => {
812
+ const lines = data.toString().split("\n").filter(Boolean);
813
+ lines.forEach((line) => {
814
+ console.log(`${chalk.cyan.bold("[backend]")} ${line}`);
815
+ const cleanLine = stripAnsi(line);
816
+ const serverMatch = cleanLine.match(/Server running at http:\/\/(?:localhost|127\.0\.0\.1):(\d+)/);
817
+ if (serverMatch) {
818
+ resolvedBackendPort = parseInt(serverMatch[1], 10);
819
+ backendUrl = "started";
820
+ printSummary();
821
+ const urlFile = path.join(projectRoot, ".rebase-dev-url");
822
+ fs.writeFileSync(urlFile, `http://localhost:${resolvedBackendPort}`, "utf-8");
823
+ const portFile = path.join(projectRoot, DEV_PORT_FILENAME);
824
+ fs.writeFileSync(portFile, String(resolvedBackendPort), "utf-8");
825
+ if (!backendOnly && frontendDir && !frontendLaunched) {
826
+ frontendLaunched = true;
827
+ startFrontend(resolvedBackendPort);
828
+ }
829
+ }
830
+ });
831
+ });
832
+ backendChild.stderr?.on("data", (data) => {
833
+ const lines = data.toString().split("\n").filter(Boolean);
834
+ lines.forEach((line) => {
835
+ console.log(`${chalk.cyan.bold("[backend]")} ${line}`);
836
+ });
837
+ });
838
+ children.push(backendChild);
839
+ } else if (!frontendOnly && !backendDir) {
840
+ console.warn(chalk.yellow(" ⚠ No backend/ directory found, skipping backend."));
841
+ }
842
+ if (!backendOnly && frontendDir && (frontendOnly || !backendDir)) {
843
+ startFrontend(null);
844
+ } else if (!backendOnly && !frontendDir) {
845
+ console.warn(chalk.yellow(" ⚠ No frontend/ directory found, skipping frontend."));
846
+ }
847
+ if (children.length === 0) {
848
+ console.error(chalk.red(" ✗ Nothing to start. Check your project structure."));
849
+ process.exit(1);
850
+ }
851
+ console.log("");
852
+ console.log(chalk.gray(" Press Ctrl+C to stop all servers."));
853
+ console.log("");
854
+ await Promise.all(
855
+ children.map(
856
+ (child) => new Promise((resolve) => {
857
+ child.finally(() => resolve());
858
+ })
859
+ )
860
+ );
861
+ }
862
+ function printDevHelp() {
863
+ console.log(`
864
+ ${chalk.bold("rebase dev")} — Start the development server
865
+
866
+ ${chalk.green.bold("Usage")}
867
+ rebase dev [options]
868
+
869
+ ${chalk.green.bold("Options")}
870
+ ${chalk.blue("--backend-only, -b")} Only start the backend server
871
+ ${chalk.blue("--frontend-only, -f")} Only start the frontend server
872
+ ${chalk.blue("--port, -p")} Backend port (default: auto-detected per project)
873
+
874
+ ${chalk.green.bold("Description")}
875
+ Starts both the backend (tsx watch + Hono) and frontend (Vite)
876
+ dev servers concurrently with color-coded output prefixes.
877
+
878
+ Each project automatically receives a unique default port derived
879
+ from its directory path, preventing collisions when running multiple
880
+ Rebase instances simultaneously.
881
+
882
+ If the assigned port is already in use, the server will automatically
883
+ try the next available port. The frontend is started only after the
884
+ backend is ready, and VITE_API_URL is injected automatically.
885
+ `);
886
+ }
887
+ async function authCommand(subcommand, rawArgs) {
888
+ if (!subcommand || subcommand === "--help") {
889
+ printAuthHelp();
890
+ return;
891
+ }
892
+ switch (subcommand) {
893
+ case "reset-password":
894
+ await resetPassword(rawArgs);
895
+ break;
896
+ default:
897
+ console.error(chalk.red(`Unknown auth command: ${subcommand}`));
898
+ console.log("");
899
+ printAuthHelp();
900
+ process.exit(1);
901
+ }
902
+ }
903
+ async function resetPassword(rawArgs) {
904
+ const args = arg(
905
+ {
906
+ "--email": String,
907
+ "--password": String,
908
+ "-e": "--email",
909
+ "-p": "--password"
910
+ },
911
+ {
912
+ argv: rawArgs.slice(4),
913
+ // skip "node rebase auth reset-password"
914
+ permissive: true
915
+ }
916
+ );
917
+ const email = args["--email"] || args._[0];
918
+ const newPassword = args["--password"] || args._[1];
919
+ if (!email) {
920
+ console.error(chalk.red("✗ Email is required."));
921
+ console.log("");
922
+ console.log(chalk.gray(" Usage: rebase auth reset-password <email> [new-password]"));
923
+ console.log(chalk.gray(" rebase auth reset-password --email user@example.com --password NewPass123!"));
924
+ process.exit(1);
925
+ }
926
+ const projectRoot = requireProjectRoot();
927
+ const backendDir = requireBackendDir(projectRoot);
928
+ const tsxBin = resolveTsx(projectRoot);
929
+ if (!tsxBin) {
930
+ console.error(chalk.red("✗ Could not find tsx binary."));
931
+ process.exit(1);
932
+ }
933
+ const envFile = findEnvFile(projectRoot);
934
+ const env = { ...process.env };
935
+ if (envFile) {
936
+ env.DOTENV_CONFIG_PATH = envFile;
937
+ }
938
+ const scriptContent = `
939
+ import { createPostgresDatabaseConnection } from "@rebasepro/server-core";
940
+ import { hashPassword } from "@rebasepro/server-core/src/auth/password";
941
+ import { eq } from "drizzle-orm";
942
+ import { users } from "@rebasepro/server-core/src/db/auth-schema";
943
+ import * as dotenv from "dotenv";
944
+ import path from "path";
945
+
946
+ dotenv.config({ path: "${envFile || path.join(projectRoot, ".env")}" });
947
+
948
+ const email = "${email}";
949
+ const newPassword = "${newPassword || "NewPassword123!"}";
950
+
951
+ async function resetPassword() {
952
+ const { db } = createPostgresDatabaseConnection(process.env.DATABASE_URL!);
953
+ const hash = await hashPassword(newPassword);
954
+
955
+ const result = await db.update(users)
956
+ .set({ passwordHash: hash })
957
+ .where(eq(users.email, email))
958
+ .returning({
959
+ id: users.id,
960
+ email: users.email
961
+ });
962
+
963
+ if (result.length > 0) {
964
+ console.log("✅ Password reset for: " + result[0].email);
965
+ ${!newPassword ? 'console.log(" New password: " + newPassword);' : ""}
966
+ } else {
967
+ console.log("✗ User not found: " + email);
968
+ }
969
+ process.exit(0);
970
+ }
971
+
972
+ resetPassword().catch(console.error);
973
+ `;
974
+ const tmpScriptPath = path.join(backendDir, ".tmp-reset-password.ts");
975
+ fs.writeFileSync(tmpScriptPath, scriptContent, "utf-8");
976
+ console.log("");
977
+ console.log(chalk.bold(" 🔑 Rebase Auth — Reset Password"));
978
+ console.log("");
979
+ console.log(` ${chalk.gray("Email:")} ${email}`);
980
+ if (newPassword) {
981
+ console.log(` ${chalk.gray("Password:")} ${"*".repeat(newPassword.length)}`);
982
+ }
983
+ console.log("");
984
+ const child = child_process.spawn(tsxBin, [tmpScriptPath], {
985
+ cwd: backendDir,
986
+ stdio: "inherit",
987
+ env
988
+ });
989
+ return new Promise((resolve) => {
990
+ child.on("close", (code) => {
991
+ try {
992
+ fs.unlinkSync(tmpScriptPath);
993
+ } catch {
994
+ }
995
+ if (code !== 0) {
996
+ process.exit(code ?? 1);
997
+ }
998
+ resolve();
999
+ });
1000
+ });
1001
+ }
1002
+ function printAuthHelp() {
1003
+ console.log(`
1004
+ ${chalk.bold("rebase auth")} — Authentication management commands
1005
+
1006
+ ${chalk.green.bold("Usage")}
1007
+ rebase auth ${chalk.blue("<command>")} [options]
1008
+
1009
+ ${chalk.green.bold("Commands")}
1010
+ ${chalk.blue.bold("reset-password")} Reset a user's password
1011
+
1012
+ ${chalk.green.bold("reset-password Options")}
1013
+ ${chalk.blue("--email, -e")} User's email address
1014
+ ${chalk.blue("--password, -p")} New password (default: NewPassword123!)
1015
+
1016
+ ${chalk.green.bold("Examples")}
1017
+ rebase auth reset-password user@example.com
1018
+ rebase auth reset-password --email user@example.com --password MyNewPass!
1019
+ `);
1020
+ }
1021
+ async function doctorCommand(rawArgs) {
1022
+ const projectRoot = requireProjectRoot();
1023
+ const backendDir = requireBackendDir(projectRoot);
1024
+ const activePlugin = getActiveBackendPlugin(backendDir);
1025
+ if (!activePlugin) {
1026
+ console.error(chalk.red("✗ Could not detect an active database plugin."));
1027
+ console.error(chalk.gray(" Make sure a package like @rebasepro/server-postgresql is installed in backend/package.json."));
1028
+ process.exit(1);
1029
+ }
1030
+ const pluginCli = resolvePluginCliScript(backendDir, activePlugin);
1031
+ if (!pluginCli) {
1032
+ console.error(chalk.red(`✗ Could not find CLI entry point for ${activePlugin}.`));
1033
+ process.exit(1);
1034
+ }
1035
+ const envFile = findEnvFile(projectRoot);
1036
+ const env = { ...process.env };
1037
+ if (envFile) {
1038
+ env.DOTENV_CONFIG_PATH = envFile;
1039
+ }
1040
+ try {
1041
+ const isTs = pluginCli.endsWith(".ts");
1042
+ if (isTs) {
1043
+ const tsxBin = resolveTsx(projectRoot);
1044
+ if (!tsxBin) {
1045
+ console.error(chalk.red("✗ Could not find tsx binary."));
1046
+ process.exit(1);
1047
+ }
1048
+ await execa(tsxBin, [pluginCli, ...rawArgs.slice(2)], {
1049
+ cwd: backendDir,
1050
+ stdio: "inherit",
1051
+ env
1052
+ });
1053
+ } else {
1054
+ await execa("node", [pluginCli, ...rawArgs.slice(2)], {
1055
+ cwd: backendDir,
1056
+ stdio: "inherit",
1057
+ env
1058
+ });
1059
+ }
1060
+ } catch {
1061
+ process.exit(1);
1062
+ }
1063
+ }
182
1064
  const __filename$1 = url.fileURLToPath(typeof document === "undefined" && typeof location === "undefined" ? require("url").pathToFileURL(__filename).href : typeof document === "undefined" ? location.href : _documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === "SCRIPT" && _documentCurrentScript.src || new URL("index.cjs", document.baseURI).href);
183
1065
  const __dirname$1 = path.dirname(__filename$1);
184
1066
  function getVersion() {
@@ -209,16 +1091,56 @@ POSTGRES_PASSWORD=${dbPassword}
209
1091
  return;
210
1092
  }
211
1093
  const command = parsedArgs._[0];
212
- if (!command || parsedArgs["--help"]) {
1094
+ const subcommand = parsedArgs._[1];
1095
+ const namespacedCommands = ["schema", "db", "dev", "auth", "doctor"];
1096
+ if (!command || parsedArgs["--help"] && !namespacedCommands.includes(command)) {
213
1097
  printHelp();
214
1098
  return;
215
1099
  }
216
- if (command === "init") {
217
- await createRebaseApp(args);
218
- } else {
219
- console.log(chalk.red(`Unknown command: ${command}`));
220
- console.log("");
221
- printHelp();
1100
+ const effectiveSubcommand = parsedArgs["--help"] ? "--help" : subcommand;
1101
+ switch (command) {
1102
+ case "init":
1103
+ await createRebaseApp(args);
1104
+ break;
1105
+ case "generate-sdk": {
1106
+ const sdkArgs = arg(
1107
+ {
1108
+ "--collections-dir": String,
1109
+ "--output": String,
1110
+ "-c": "--collections-dir",
1111
+ "-o": "--output"
1112
+ },
1113
+ {
1114
+ argv: args.slice(3),
1115
+ permissive: true
1116
+ }
1117
+ );
1118
+ await generateSdkCommand({
1119
+ collectionsDir: sdkArgs["--collections-dir"] || "./config/collections",
1120
+ output: sdkArgs["--output"] || "./generated/sdk",
1121
+ cwd: process.cwd()
1122
+ });
1123
+ break;
1124
+ }
1125
+ case "schema":
1126
+ await schemaCommand(effectiveSubcommand, args);
1127
+ break;
1128
+ case "db":
1129
+ await dbCommand(effectiveSubcommand, args);
1130
+ break;
1131
+ case "dev":
1132
+ await devCommand(args);
1133
+ break;
1134
+ case "auth":
1135
+ await authCommand(effectiveSubcommand, args);
1136
+ break;
1137
+ case "doctor":
1138
+ await doctorCommand(args);
1139
+ break;
1140
+ default:
1141
+ console.log(chalk.red(`Unknown command: ${command}`));
1142
+ console.log("");
1143
+ printHelp();
222
1144
  }
223
1145
  }
224
1146
  function printHelp() {
@@ -229,7 +1151,30 @@ ${chalk.green.bold("Usage")}
229
1151
  rebase ${chalk.blue("<command>")} [options]
230
1152
 
231
1153
  ${chalk.green.bold("Commands")}
232
- ${chalk.blue.bold("init")} Create a new Rebase project
1154
+ ${chalk.blue.bold("init")} Create a new Rebase project
1155
+ ${chalk.blue.bold("dev")} Start the development server
1156
+
1157
+ ${chalk.green.bold("Schema")}
1158
+ ${chalk.blue.bold("schema generate")} Generate Drizzle schema from collections
1159
+ ${chalk.blue.bold("schema")} ${chalk.gray("--help")} Show schema command help
1160
+
1161
+ ${chalk.green.bold("Database")}
1162
+ ${chalk.blue.bold("db push")} Apply schema directly to database ${chalk.gray("(dev)")}
1163
+ ${chalk.blue.bold("db pull")} Introspect database → Drizzle schema
1164
+ ${chalk.blue.bold("db generate")} Generate SQL migration files
1165
+ ${chalk.blue.bold("db migrate")} Run pending migrations
1166
+ ${chalk.blue.bold("db studio")} Open Drizzle Studio
1167
+ ${chalk.blue.bold("db")} ${chalk.gray("--help")} Show database command help
1168
+
1169
+ ${chalk.green.bold("SDK")}
1170
+ ${chalk.blue.bold("generate-sdk")} Generate a typed JS SDK from collections
1171
+
1172
+ ${chalk.green.bold("Auth")}
1173
+ ${chalk.blue.bold("auth reset-password")} Reset a user's password
1174
+ ${chalk.blue.bold("auth")} ${chalk.gray("--help")} Show auth command help
1175
+
1176
+ ${chalk.green.bold("Diagnostics")}
1177
+ ${chalk.blue.bold("doctor")} Detect schema drift between collections, schema, and DB
233
1178
 
234
1179
  ${chalk.green.bold("Options")}
235
1180
  ${chalk.blue("--version, -v")} Show version number
@@ -281,13 +1226,27 @@ ${chalk.gray("Documentation: https://rebase.pro/docs")}
281
1226
  console.log("You are not logged in.");
282
1227
  }
283
1228
  }
1229
+ exports2.authCommand = authCommand;
284
1230
  exports2.createRebaseApp = createRebaseApp;
1231
+ exports2.dbCommand = dbCommand;
1232
+ exports2.devCommand = devCommand;
285
1233
  exports2.entry = entry;
1234
+ exports2.findBackendDir = findBackendDir;
1235
+ exports2.findEnvFile = findEnvFile;
1236
+ exports2.findFrontendDir = findFrontendDir;
1237
+ exports2.findProjectRoot = findProjectRoot;
1238
+ exports2.getActiveBackendPlugin = getActiveBackendPlugin;
286
1239
  exports2.getTokens = getTokens;
287
1240
  exports2.login = login;
288
1241
  exports2.logout = logout;
289
1242
  exports2.parseJwt = parseJwt;
290
1243
  exports2.refreshCredentials = refreshCredentials;
1244
+ exports2.requireBackendDir = requireBackendDir;
1245
+ exports2.requireProjectRoot = requireProjectRoot;
1246
+ exports2.resolveLocalBin = resolveLocalBin;
1247
+ exports2.resolvePluginCliScript = resolvePluginCliScript;
1248
+ exports2.resolveTsx = resolveTsx;
1249
+ exports2.schemaCommand = schemaCommand;
291
1250
  Object.defineProperty(exports2, Symbol.toStringTag, { value: "Module" });
292
1251
  }));
293
1252
  //# sourceMappingURL=index.cjs.map