create-backon 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.ts CHANGED
@@ -15,7 +15,17 @@ import { removeRoute } from "./remove-route";
15
15
  import { listRoutes } from "./list-routes";
16
16
  import { runDoctor } from "./doctor";
17
17
  import { addMethod } from "./add-method";
18
- import { formatEndpointsDashboard, listEndpointsWithMethods } from "./route-methods";
18
+ import { removeMethod } from "./remove-method";
19
+ import { detectDbStatus } from "./db-status";
20
+ import { detectProject } from "./detect";
21
+ import { addCrudMethods } from "./crud-scaffold";
22
+ import {
23
+ detectMethodValidation,
24
+ formatEndpointsDashboard,
25
+ listEndpointsWithMethods,
26
+ type EndpointMethod,
27
+ type EndpointSummary,
28
+ } from "./route-methods";
19
29
  import { HTTP_VERBS, paramNamesFromPath, pascalCase, type HttpVerb, type MethodSpec } from "./templates/route";
20
30
 
21
31
  const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
@@ -23,6 +33,17 @@ const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
23
33
  const LIST_ROUTES_SUBCOMMANDS = new Set(["list-routes", "routes"]);
24
34
  const DOCTOR_SUBCOMMANDS = new Set(["doctor"]);
25
35
  const ADD_METHOD_SUBCOMMANDS = new Set(["add-method", "method"]);
36
+ // project: a read-only overview (db status, endpoints, methods, doctor
37
+ // summary) — nothing here writes to disk. server-config: the interactive
38
+ // wrapper around add-route/remove-route/add-method/remove-method (plus
39
+ // modify, which neither standalone command offers) for managing endpoints
40
+ // without remembering individual subcommand names. Deliberately two
41
+ // separate commands rather than one combined dashboard — "just show me
42
+ // what's here" and "let me start changing things" are different intents,
43
+ // and collapsing them risks an accidental edit from someone who only
44
+ // wanted to look.
45
+ const PROJECT_SUBCOMMANDS = new Set(["project"]);
46
+ const SERVER_CONFIG_SUBCOMMANDS = new Set(["server-config"]);
26
47
 
27
48
  async function promptForRouteName(introText: string): Promise<string> {
28
49
  p.intro(introText);
@@ -38,17 +59,42 @@ async function promptForRouteName(introText: string): Promise<string> {
38
59
  return answer;
39
60
  }
40
61
 
62
+ /** Shared by every "just added a CRUD set" log line, interactive or scripted. */
63
+ function logCrudResult(result: Awaited<ReturnType<typeof addCrudMethods>>): void {
64
+ const skippedNote = result.skipped.length ? ` (skipped, already there: ${result.skipped.join(", ")})` : "";
65
+ p.log.success(`Added CRUD methods to ${result.route}: ${result.added.join(", ") || "none"}${skippedNote}`);
66
+ }
67
+
41
68
  async function runAddRoute(args: string[]): Promise<void> {
42
- let [name] = args;
69
+ const crudFlagIndex = args.indexOf("--crud");
70
+ const withCrud = crudFlagIndex !== -1;
71
+ const positional = withCrud ? args.filter((_, i) => i !== crudFlagIndex) : args;
72
+ let [name] = positional;
43
73
 
74
+ let interactive = false;
44
75
  if (!name) {
76
+ interactive = true;
45
77
  name = await promptForRouteName("create-backon add-route");
46
78
  p.outro(`Adding ${name}...`);
47
79
  }
48
80
 
49
81
  const { route, root, filesWritten } = await addRoute(name);
50
82
  p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
51
- p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
83
+
84
+ let scaffoldCrud = withCrud;
85
+ if (!withCrud && interactive) {
86
+ const answer = await p.confirm({
87
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
88
+ initialValue: false,
89
+ });
90
+ scaffoldCrud = !p.isCancel(answer) && answer;
91
+ }
92
+
93
+ if (scaffoldCrud) {
94
+ logCrudResult(await addCrudMethods(route, root));
95
+ } else {
96
+ p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
97
+ }
52
98
  }
53
99
 
54
100
  async function runRemoveRoute(args: string[]): Promise<void> {
@@ -91,6 +137,31 @@ async function runDoctorCommand(): Promise<void> {
91
137
  process.exitCode = 1;
92
138
  }
93
139
 
140
+ /**
141
+ * Read-only: db status, every endpoint and its methods, and a doctor
142
+ * summary, in one shot. No prompts, no writes — `bun run server-config` is
143
+ * where anything actually changes.
144
+ */
145
+ async function runProjectOverview(): Promise<void> {
146
+ p.intro("create-backon project");
147
+
148
+ const { root } = await detectProject();
149
+ const dbStatus = await detectDbStatus();
150
+ const summaries = await listEndpointsWithMethods();
151
+ const { issues } = await runDoctor();
152
+
153
+ p.note(dbStatus.summary, "Database");
154
+ p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
155
+
156
+ if (issues.length > 0) {
157
+ p.log.warn(`${issues.length} issue(s) between src/endpoints/ and index — run \`bun run doctor\` for details.`);
158
+ } else {
159
+ p.log.success("No drift between src/endpoints/ and index.");
160
+ }
161
+
162
+ p.outro("Manage endpoints and methods with `bun run server-config`.");
163
+ }
164
+
94
165
  function suggestMethodName(verb: HttpVerb, path: string): string {
95
166
  const params = paramNamesFromPath(path);
96
167
  if (verb === "get" && params.length === 0) return "list";
@@ -215,6 +286,328 @@ async function runAddMethod(): Promise<void> {
215
286
  p.outro("Done.");
216
287
  }
217
288
 
289
+ // ---------------------------------------------------------------------------
290
+ // server-config: the interactive endpoint/method manager. Each of these is
291
+ // a single, self-contained step (no intro/outro of its own, no "add
292
+ // another?" loop of its own) — runServerConfig()'s own while loop is what
293
+ // repeats, and it re-reads the endpoint list fresh every iteration so any
294
+ // step's changes are immediately visible to the next one.
295
+ // ---------------------------------------------------------------------------
296
+
297
+ async function serverConfigAddEndpoint(): Promise<void> {
298
+ const name = await p.text({
299
+ message: "New endpoint name",
300
+ placeholder: "e.g. users",
301
+ validate: (value) => (!value ? "Required." : undefined),
302
+ });
303
+ if (p.isCancel(name)) {
304
+ p.cancel("Cancelled.");
305
+ return;
306
+ }
307
+ const { route, filesWritten } = await addRoute(name);
308
+ p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
309
+
310
+ const scaffoldCrud = await p.confirm({
311
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
312
+ initialValue: false,
313
+ });
314
+ if (!p.isCancel(scaffoldCrud) && scaffoldCrud) {
315
+ logCrudResult(await addCrudMethods(route));
316
+ }
317
+ }
318
+
319
+ async function serverConfigRemoveEndpoint(summaries: EndpointSummary[]): Promise<void> {
320
+ if (summaries.length === 0) {
321
+ p.log.info("No endpoints yet.");
322
+ return;
323
+ }
324
+ const route = await p.select({
325
+ message: "Remove which endpoint?",
326
+ options: summaries.map((s) => ({ value: s.route, label: s.route })),
327
+ });
328
+ if (p.isCancel(route)) {
329
+ p.cancel("Cancelled.");
330
+ return;
331
+ }
332
+ const confirmed = await p.confirm({
333
+ message: `Remove src/endpoints/${route} and unmount it? This deletes the folder.`,
334
+ initialValue: false,
335
+ });
336
+ if (p.isCancel(confirmed) || !confirmed) {
337
+ p.cancel("Cancelled.");
338
+ return;
339
+ }
340
+ const { removedDir } = await removeRoute(route);
341
+ p.log.success(`Removed ${removedDir}.`);
342
+ }
343
+
344
+ async function serverConfigAddMethod(summaries: EndpointSummary[]): Promise<void> {
345
+ const routeChoice = await p.select({
346
+ message: "Add a method to which endpoint?",
347
+ options: [
348
+ ...summaries.map((s) => ({ value: s.route, label: s.route })),
349
+ { value: "__new__", label: "+ New blank endpoint" },
350
+ ],
351
+ });
352
+ if (p.isCancel(routeChoice)) {
353
+ p.cancel("Cancelled.");
354
+ return;
355
+ }
356
+
357
+ let route = routeChoice;
358
+ let existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
359
+ if (route === "__new__") {
360
+ const name = await p.text({
361
+ message: "New endpoint name",
362
+ placeholder: "e.g. users",
363
+ validate: (value) => (!value ? "Required." : undefined),
364
+ });
365
+ if (p.isCancel(name)) {
366
+ p.cancel("Cancelled.");
367
+ return;
368
+ }
369
+ const added = await addRoute(name);
370
+ route = added.route;
371
+ existingMethods = [];
372
+ p.log.success(`Added blank endpoint src/endpoints/${route}`);
373
+ }
374
+
375
+ const verb = await p.select({
376
+ message: "HTTP method",
377
+ options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() })),
378
+ });
379
+ if (p.isCancel(verb)) {
380
+ p.cancel("Cancelled.");
381
+ return;
382
+ }
383
+
384
+ const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
385
+ const path = await p.text({
386
+ message: "Path (relative to this endpoint's mount)",
387
+ placeholder: defaultPath,
388
+ initialValue: defaultPath,
389
+ validate: (value) => (!value.startsWith("/") ? 'Must start with "/".' : undefined),
390
+ });
391
+ if (p.isCancel(path)) {
392
+ p.cancel("Cancelled.");
393
+ return;
394
+ }
395
+
396
+ const defaultName = suggestMethodName(verb, path);
397
+ const name = await p.text({
398
+ message: "Name (controller export + service function)",
399
+ placeholder: defaultName,
400
+ initialValue: defaultName,
401
+ validate: (value) => {
402
+ if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
403
+ if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
404
+ return undefined;
405
+ },
406
+ });
407
+ if (p.isCancel(name)) {
408
+ p.cancel("Cancelled.");
409
+ return;
410
+ }
411
+
412
+ let needsBody = false;
413
+ if (verb === "post" || verb === "put" || verb === "patch") {
414
+ const answer = await p.confirm({ message: "Validate a request body?", initialValue: true });
415
+ if (p.isCancel(answer)) {
416
+ p.cancel("Cancelled.");
417
+ return;
418
+ }
419
+ needsBody = answer;
420
+ }
421
+
422
+ const needsQuery = await p.confirm({ message: "Validate query params?", initialValue: false });
423
+ if (p.isCancel(needsQuery)) {
424
+ p.cancel("Cancelled.");
425
+ return;
426
+ }
427
+
428
+ const spec: MethodSpec = { verb, path, name, needsBody, needsQuery };
429
+ const { filesWritten } = await addMethod(route, spec);
430
+ p.log.success(`Added ${verb.toUpperCase()} ${path} → ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
431
+ }
432
+
433
+ /** Endpoints with at least one method — remove/modify both operate on an existing method, so an endpoint with none isn't a valid choice for either. */
434
+ async function selectEndpointWithMethods(summaries: EndpointSummary[], message: string): Promise<EndpointSummary | null> {
435
+ const withMethods = summaries.filter((s) => s.methods.length > 0);
436
+ if (withMethods.length === 0) {
437
+ p.log.info("No methods yet — add one first.");
438
+ return null;
439
+ }
440
+ const route = await p.select({
441
+ message,
442
+ options: withMethods.map((s) => ({ value: s.route, label: s.route })),
443
+ });
444
+ if (p.isCancel(route)) {
445
+ p.cancel("Cancelled.");
446
+ return null;
447
+ }
448
+ return withMethods.find((s) => s.route === route) ?? null;
449
+ }
450
+
451
+ async function selectMethod(endpoint: EndpointSummary, message: string): Promise<EndpointMethod | null> {
452
+ const choice = await p.select({
453
+ message,
454
+ options: endpoint.methods.map((m) => ({
455
+ value: `${m.verb}:${m.path}`,
456
+ label: `${m.verb.toUpperCase()} ${m.path} → ${m.name}`,
457
+ })),
458
+ });
459
+ if (p.isCancel(choice)) {
460
+ p.cancel("Cancelled.");
461
+ return null;
462
+ }
463
+ // Split on the FIRST colon only — a path itself can contain no colons
464
+ // outside of :param segments, but this keeps the parse correct even if
465
+ // that ever changes, since verb never contains one.
466
+ const [verb, path] = choice.split(/:(.*)/s) as [HttpVerb, string];
467
+ return endpoint.methods.find((m) => m.verb === verb && m.path === path) ?? null;
468
+ }
469
+
470
+ async function serverConfigRemoveMethod(summaries: EndpointSummary[]): Promise<void> {
471
+ const endpoint = await selectEndpointWithMethods(summaries, "Remove a method from which endpoint?");
472
+ if (!endpoint) return;
473
+ const method = await selectMethod(endpoint, "Remove which method?");
474
+ if (!method) return;
475
+
476
+ const confirmed = await p.confirm({
477
+ message: `Remove ${method.verb.toUpperCase()} ${method.path} (${method.name}) from ${endpoint.route}?`,
478
+ initialValue: false,
479
+ });
480
+ if (p.isCancel(confirmed) || !confirmed) {
481
+ p.cancel("Cancelled.");
482
+ return;
483
+ }
484
+
485
+ const { removed } = await removeMethod(endpoint.route, method.verb, method.path);
486
+ p.log.success(`Removed ${removed.verb.toUpperCase()} ${removed.path} (${removed.name}) from src/endpoints/${endpoint.route}.`);
487
+ }
488
+
489
+ /** Edits a method's verb/path/name/validation in place: a checked removeMethod() + addMethod() pair, not a separate codegen path. */
490
+ async function serverConfigModifyMethod(summaries: EndpointSummary[]): Promise<void> {
491
+ const endpoint = await selectEndpointWithMethods(summaries, "Modify a method on which endpoint?");
492
+ if (!endpoint) return;
493
+ const old = await selectMethod(endpoint, "Modify which method?");
494
+ if (!old) return;
495
+
496
+ const { needsBody: oldNeedsBody, needsQuery: oldNeedsQuery } = await detectMethodValidation(endpoint.route, old.name);
497
+ const others = endpoint.methods.filter((m) => m !== old);
498
+
499
+ const verb = await p.select({
500
+ message: "HTTP method",
501
+ initialValue: old.verb,
502
+ options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() })),
503
+ });
504
+ if (p.isCancel(verb)) {
505
+ p.cancel("Cancelled.");
506
+ return;
507
+ }
508
+
509
+ const path = await p.text({
510
+ message: "Path (relative to this endpoint's mount)",
511
+ initialValue: old.path,
512
+ validate: (value) => (!value.startsWith("/") ? 'Must start with "/".' : undefined),
513
+ });
514
+ if (p.isCancel(path)) {
515
+ p.cancel("Cancelled.");
516
+ return;
517
+ }
518
+
519
+ const name = await p.text({
520
+ message: "Name (controller export + service function)",
521
+ initialValue: old.name,
522
+ validate: (value) => {
523
+ if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
524
+ if (others.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
525
+ return undefined;
526
+ },
527
+ });
528
+ if (p.isCancel(name)) {
529
+ p.cancel("Cancelled.");
530
+ return;
531
+ }
532
+
533
+ // Checked before anything on disk changes — removeMethod() below is only
534
+ // safe to run once we know addMethod() won't then fail on a collision.
535
+ if (others.some((m) => m.verb === verb && m.path === path)) {
536
+ p.log.error(`${verb.toUpperCase()} ${path} is already used by another method on this endpoint.`);
537
+ return;
538
+ }
539
+
540
+ let needsBody = false;
541
+ if (verb === "post" || verb === "put" || verb === "patch") {
542
+ const answer = await p.confirm({ message: "Validate a request body?", initialValue: oldNeedsBody });
543
+ if (p.isCancel(answer)) {
544
+ p.cancel("Cancelled.");
545
+ return;
546
+ }
547
+ needsBody = answer;
548
+ }
549
+
550
+ const needsQuery = await p.confirm({ message: "Validate query params?", initialValue: oldNeedsQuery });
551
+ if (p.isCancel(needsQuery)) {
552
+ p.cancel("Cancelled.");
553
+ return;
554
+ }
555
+
556
+ await removeMethod(endpoint.route, old.verb, old.path);
557
+ const { filesWritten } = await addMethod(endpoint.route, { verb, path, name, needsBody, needsQuery });
558
+ p.log.success(
559
+ `Updated src/endpoints/${endpoint.route}: ${old.verb.toUpperCase()} ${old.path} → ${verb.toUpperCase()} ${path} (${name}), ${filesWritten.length} files touched.`
560
+ );
561
+ }
562
+
563
+ async function runServerConfig(): Promise<void> {
564
+ p.intro("create-backon server-config");
565
+
566
+ // eslint-disable-next-line no-constant-condition
567
+ while (true) {
568
+ const { root } = await detectProject();
569
+ const summaries = await listEndpointsWithMethods();
570
+ p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
571
+
572
+ const action = await p.select({
573
+ message: "What do you want to do?",
574
+ options: [
575
+ { value: "add-endpoint", label: "Add a new endpoint" },
576
+ { value: "remove-endpoint", label: "Remove an endpoint" },
577
+ { value: "add-method", label: "Add a method" },
578
+ { value: "remove-method", label: "Remove a method" },
579
+ { value: "modify-method", label: "Modify a method" },
580
+ { value: "exit", label: "Exit" },
581
+ ],
582
+ });
583
+ if (p.isCancel(action) || action === "exit") break;
584
+
585
+ try {
586
+ switch (action) {
587
+ case "add-endpoint":
588
+ await serverConfigAddEndpoint();
589
+ break;
590
+ case "remove-endpoint":
591
+ await serverConfigRemoveEndpoint(summaries);
592
+ break;
593
+ case "add-method":
594
+ await serverConfigAddMethod(summaries);
595
+ break;
596
+ case "remove-method":
597
+ await serverConfigRemoveMethod(summaries);
598
+ break;
599
+ case "modify-method":
600
+ await serverConfigModifyMethod(summaries);
601
+ break;
602
+ }
603
+ } catch (err) {
604
+ p.log.error(err instanceof Error ? err.message : String(err));
605
+ }
606
+ }
607
+
608
+ p.outro("Done.");
609
+ }
610
+
218
611
  async function runScaffold(): Promise<void> {
219
612
  const answers = await runPrompts();
220
613
  const { root, filesWritten } = await generateProject(answers);
@@ -248,6 +641,14 @@ async function main() {
248
641
  await runAddMethod();
249
642
  return;
250
643
  }
644
+ if (subcommand && PROJECT_SUBCOMMANDS.has(subcommand)) {
645
+ await runProjectOverview();
646
+ return;
647
+ }
648
+ if (subcommand && SERVER_CONFIG_SUBCOMMANDS.has(subcommand)) {
649
+ await runServerConfig();
650
+ return;
651
+ }
251
652
 
252
653
  await runScaffold();
253
654
  }
package/src/colors.ts CHANGED
@@ -23,3 +23,13 @@ export function colorVerb(verb: HttpVerb): string {
23
23
  export function dim(text: string): string {
24
24
  return `\x1b[2m${text}${RESET}`;
25
25
  }
26
+
27
+ /** Green — a status line that's actually fine (a DB driver with everything it needs, a clean doctor run). */
28
+ export function ok(text: string): string {
29
+ return `\x1b[32m${text}${RESET}`;
30
+ }
31
+
32
+ /** Amber — a status line that needs attention, but isn't a hard failure. */
33
+ export function warn(text: string): string {
34
+ return `\x1b[33m${text}${RESET}`;
35
+ }
@@ -0,0 +1,62 @@
1
+ import { addMethod } from "./add-method";
2
+ import { listEndpointsWithMethods } from "./route-methods";
3
+ import type { MethodSpec } from "./templates/route";
4
+
5
+ /**
6
+ * The standard REST five — list/create/getById/update/remove — named to
7
+ * match exactly what `add-method`'s own name-suggestion logic
8
+ * (suggestMethodName in cli.ts) already produces for GET /, POST /,
9
+ * GET /:id, PUT /:id, DELETE /:id. Not a new convention, just all five of
10
+ * an existing one applied at once instead of one at a time.
11
+ */
12
+ export const CRUD_METHOD_SPECS: readonly MethodSpec[] = [
13
+ { verb: "get", path: "/", name: "list", needsBody: false, needsQuery: false },
14
+ { verb: "post", path: "/", name: "create", needsBody: true, needsQuery: false },
15
+ { verb: "get", path: "/:id", name: "getById", needsBody: false, needsQuery: false },
16
+ { verb: "put", path: "/:id", name: "update", needsBody: true, needsQuery: false },
17
+ { verb: "delete", path: "/:id", name: "remove", needsBody: false, needsQuery: false },
18
+ ];
19
+
20
+ export interface AddCrudMethodsResult {
21
+ route: string;
22
+ /** Method names actually written. */
23
+ added: string[];
24
+ /** Method names skipped because the endpoint already had a same-name method, or something already mounted at that verb+path. */
25
+ skipped: string[];
26
+ }
27
+
28
+ /**
29
+ * Adds the standard CRUD_METHOD_SPECS set to an already-mounted endpoint,
30
+ * via addMethod() — the exact same codegen a manual `add-method` run
31
+ * produces, just five calls run in sequence instead of one at a time.
32
+ * Sequential on purpose: addMethod() reads all three of an endpoint's files
33
+ * fresh off disk on every call, so firing five in parallel at the same
34
+ * endpoint would have them race on stale reads and clobber each other.
35
+ *
36
+ * Any of the five that would collide with a method the endpoint already has
37
+ * (same name, or the same verb+path already mounted) is skipped rather than
38
+ * failing the whole batch — this makes it safe to run on an endpoint that
39
+ * already has some hand-added methods, e.g. re-running it after removing
40
+ * just "remove" to get the other four without erroring on the four that are
41
+ * already there.
42
+ */
43
+ export async function addCrudMethods(route: string, cwd: string = process.cwd()): Promise<AddCrudMethodsResult> {
44
+ const summaries = await listEndpointsWithMethods(cwd);
45
+ const existing = [...(summaries.find((s) => s.route === route)?.methods ?? [])];
46
+
47
+ const added: string[] = [];
48
+ const skipped: string[] = [];
49
+
50
+ for (const spec of CRUD_METHOD_SPECS) {
51
+ const collides = existing.some((m) => m.name === spec.name || (m.verb === spec.verb && m.path === spec.path));
52
+ if (collides) {
53
+ skipped.push(spec.name);
54
+ continue;
55
+ }
56
+ await addMethod(route, spec, cwd);
57
+ added.push(spec.name);
58
+ existing.push({ verb: spec.verb, path: spec.path, name: spec.name });
59
+ }
60
+
61
+ return { route, added, skipped };
62
+ }
@@ -0,0 +1,117 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { dim, ok, warn } from "./colors";
4
+ import { detectProject } from "./detect";
5
+ import type { DbChoice } from "./prompts";
6
+
7
+ export interface DbStatus {
8
+ /**
9
+ * Which driver's actually wired up in src/config/db.<ext> — read from the
10
+ * file's own imports rather than remembered from scaffold time, since
11
+ * there's nowhere the original `bun create backon` db choice is
12
+ * persisted. "custom" means the file doesn't match any of the four
13
+ * generated shapes (hand-edited past recognition); "missing" means
14
+ * src/config/db.<ext> doesn't exist at all.
15
+ */
16
+ driver: DbChoice | "custom" | "missing";
17
+ /** Whether .env exists in the project root at all. */
18
+ envFileExists: boolean;
19
+ /**
20
+ * Whether this driver has what it needs to run right now, best guess.
21
+ * "none" and "sqlite" (DATABASE_URL optional there — defaults to
22
+ * ./dev.db) are always ready; "neon"/"postgres" need a non-empty
23
+ * DATABASE_URL in .env; "custom"/"missing" can't be assessed at all.
24
+ */
25
+ ready: boolean | "unknown";
26
+ /** One-line, human-readable, pre-colored summary — this is what actually gets rendered. */
27
+ summary: string;
28
+ }
29
+
30
+ // Matches exactly the driver-identifying import each db.ts template in
31
+ // templates/db.ts actually has — read off the file's real imports rather
32
+ // than anything remembered from scaffold time, since the original choice
33
+ // isn't persisted anywhere.
34
+ const DRIVER_SIGNATURES: Array<[string, DbChoice]> = [
35
+ ["drizzle-orm/neon-http", "neon"],
36
+ ["drizzle-orm/node-postgres", "postgres"],
37
+ ["drizzle-orm/bun-sqlite", "sqlite"],
38
+ ];
39
+
40
+ function detectDriver(dbFileContents: string): DbChoice | "custom" {
41
+ for (const [signature, driver] of DRIVER_SIGNATURES) {
42
+ if (dbFileContents.includes(signature)) return driver;
43
+ }
44
+ if (dbFileContents.includes("No database configured yet")) return "none";
45
+ return "custom";
46
+ }
47
+
48
+ function parseEnvValue(envContents: string, key: string): string | undefined {
49
+ const match = envContents.match(new RegExp(`^${key}=(.*)$`, "m"));
50
+ const value = match?.[1]?.trim();
51
+ return value ? value : undefined;
52
+ }
53
+
54
+ /**
55
+ * Config-check only, on purpose — no network call or file-existence probe
56
+ * against the actual database is attempted. Reports the driver wired up in
57
+ * src/config/db.<ext> and whether the env var it needs is set in .env.
58
+ * Fast, and behaves the same for every provider; a live connectivity test
59
+ * would need separate driver-specific logic (TCP for Postgres, HTTPS for
60
+ * Neon, a file stat for SQLite) for comparatively little extra signal, and
61
+ * would turn every `bun run project` into a network call.
62
+ */
63
+ export async function detectDbStatus(cwd: string = process.cwd()): Promise<DbStatus> {
64
+ const { root, ext } = await detectProject(cwd);
65
+
66
+ let dbFileContents: string | undefined;
67
+ try {
68
+ dbFileContents = await readFile(join(root, "src/config", `db.${ext}`), "utf-8");
69
+ } catch {
70
+ dbFileContents = undefined;
71
+ }
72
+
73
+ const driver = dbFileContents === undefined ? "missing" : detectDriver(dbFileContents);
74
+
75
+ let envContents = "";
76
+ let envFileExists = true;
77
+ try {
78
+ envContents = await readFile(join(root, ".env"), "utf-8");
79
+ } catch {
80
+ envFileExists = false;
81
+ }
82
+
83
+ const databaseUrl = parseEnvValue(envContents, "DATABASE_URL");
84
+
85
+ if (driver === "missing") {
86
+ return { driver, envFileExists, ready: "unknown", summary: warn("src/config/db file not found.") };
87
+ }
88
+ if (driver === "custom") {
89
+ return {
90
+ driver,
91
+ envFileExists,
92
+ ready: "unknown",
93
+ summary: `${dim("custom")} — src/config/db has been hand-edited, can't tell you its status here.`,
94
+ };
95
+ }
96
+ if (driver === "none") {
97
+ return { driver, envFileExists, ready: true, summary: dim("none — no database configured.") };
98
+ }
99
+ if (driver === "sqlite") {
100
+ const path = databaseUrl ?? "./dev.db";
101
+ return { driver, envFileExists, ready: true, summary: `${ok("sqlite")} — using ${path}.` };
102
+ }
103
+
104
+ // neon / postgres both hard-require DATABASE_URL — db.ts itself throws at
105
+ // import time without one, so "missing-env" here means the app won't boot.
106
+ if (databaseUrl) {
107
+ return { driver, envFileExists, ready: true, summary: `${ok(driver)} — DATABASE_URL is set in .env.` };
108
+ }
109
+ return {
110
+ driver,
111
+ envFileExists,
112
+ ready: false,
113
+ summary: `${warn(driver)} — DATABASE_URL missing from .env${
114
+ envFileExists ? "" : " (no .env file)"
115
+ }; src/config/db.ts will throw at startup until it's set.`,
116
+ };
117
+ }
package/src/generate.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  renderEndpointsIndex,
7
7
  renderEnvExample,
8
8
  renderExampleMiddleware,
9
+ renderGenerateClientScript,
9
10
  renderGenerateDocsScript,
10
11
  renderIndexTs,
11
12
  renderJsconfig,
@@ -94,7 +95,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
94
95
  [join(root, "README.md"), renderReadme(readmeAnswers)],
95
96
  [
96
97
  join(root, ".gitignore"),
97
- `node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n${
98
+ `node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\nclient/\n${
98
99
  answers.deployTarget === "vercel" ? ".vercel\n" : ""
99
100
  }`,
100
101
  ],
@@ -106,6 +107,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
106
107
  ],
107
108
  [join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
108
109
  [join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
110
+ [join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
109
111
  ...(answers.deployTarget === "vercel"
110
112
  ? ([[join(root, "vercel.json"), renderVercelJson()]] as Array<[string, string]>)
111
113
  : []),