create-backon 0.11.0 → 0.13.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.
@@ -1,6 +1,6 @@
1
1
  import type { Answers, DeployTarget, Framework, Language } from "../prompts";
2
2
  import { camelCase } from "./route";
3
- import { dbDependencies, dbEnvVars, dbReadmeNote } from "./db";
3
+ import { dbDependencies, dbDevDependencies, dbEnvVars, dbHasSchemaSupport, dbReadmeNote } from "./db";
4
4
 
5
5
  // renderIndexTs/renderAppTs/renderEndpointsIndex are intentionally NOT
6
6
  // language-aware: none of them contain TypeScript-only syntax (no type
@@ -500,13 +500,15 @@ export function renderPackageJson(
500
500
 
501
501
  // JavaScript mode intentionally has zero TypeScript-related devDependencies
502
502
  // (no `typescript`, no `@types/*`) — there's nothing being compiled or
503
- // typechecked, so pulling those in would just be dead weight.
503
+ // typechecked, so pulling those in would just be dead weight. drizzle-kit
504
+ // is a CLI tool driven by schema.ts's shape, not by language, so it's
505
+ // merged in either way via dbDevDependencies(db).
504
506
  const devDependencies: Record<string, string> =
505
507
  language === "javascript"
506
- ? {}
508
+ ? { ...dbDevDependencies(db) }
507
509
  : framework === "express"
508
- ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" }
509
- : { "@types/bun": "latest", typescript: "^5.7.2" };
510
+ ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2", ...dbDevDependencies(db) }
511
+ : { "@types/bun": "latest", typescript: "^5.7.2", ...dbDevDependencies(db) };
510
512
 
511
513
  const scripts: Record<string, string> = {
512
514
  dev: `bun run --watch index.${ext}`,
@@ -538,12 +540,33 @@ export function renderPackageJson(
538
540
  if (language === "typescript") {
539
541
  scripts.typecheck = "tsc --noEmit";
540
542
  }
543
+ if (dbHasSchemaSupport(db)) {
544
+ // add-table/remove-table: thin aliases matching the add-route/add-method
545
+ // pattern above. db:generate/db:migrate/db:push call drizzle-kit
546
+ // directly (not create-backon) — schema.ts is a real drizzle-kit
547
+ // config target, no wrapper needed.
548
+ scripts["add-table"] = "bunx create-backon add-table";
549
+ scripts["remove-table"] = "bunx create-backon remove-table";
550
+ scripts["db:generate"] = "drizzle-kit generate";
551
+ scripts["db:migrate"] = "drizzle-kit migrate";
552
+ scripts["db:push"] = "drizzle-kit push";
553
+ }
541
554
 
542
555
  const pkg = {
543
556
  name: projectName,
544
557
  version: "0.1.0",
545
558
  private: true,
546
559
  type: "module",
560
+ // Node's package.json subpath imports (Bun resolves these too, both
561
+ // locally and on Vercel's Bun runtime — no bundler-specific config
562
+ // needed, unlike a tsconfig "paths" alias). Lets any file import the db
563
+ // client as `import { db } from "#config/db"` regardless of how deep
564
+ // it's nested under src/endpoints/, instead of a depth-counted
565
+ // `../../config/db`. Verified against a real `bun run` and a real
566
+ // `tsc --noEmit` (moduleResolution: "bundler" already resolves it).
567
+ imports: {
568
+ "#config/*": `./src/config/*.${ext}`,
569
+ },
547
570
  scripts,
548
571
  dependencies,
549
572
  devDependencies,
@@ -594,6 +617,29 @@ both for free.
594
617
  }
595
618
  }
596
619
 
620
+ function renderSchemaReadmeSection(ext: string): string {
621
+ return `
622
+ ### Table schema
623
+
624
+ \`src/config/schema.${ext}\` holds every table (empty until you add one — see below). \`bun run
625
+ add-table\`/\`bun run remove-table\` (also reachable from \`server-config\`'s menu) edit it for you —
626
+ picking a column type, nullability, uniqueness, a default, and whether it references another
627
+ table's \`id\`. This only ever edits \`schema.${ext}\` on disk; it never touches the actual database.
628
+
629
+ To apply a schema change for real:
630
+
631
+ \`\`\`
632
+ bun run db:generate # writes a reviewable .sql migration under drizzle/ — no DB connection needed
633
+ bun run db:migrate # applies pending migrations to DATABASE_URL
634
+ \`\`\`
635
+
636
+ \`bun run db:push\` applies \`schema.${ext}\` straight to the database with no migration file — faster
637
+ to iterate with early on (empty/throwaway dev database), but skips the reviewable, versioned trail
638
+ \`generate\`/\`migrate\` gives you. Switch to \`generate\`/\`migrate\` once there's real data, or before
639
+ deploying anywhere with staging/prod.
640
+ `;
641
+ }
642
+
597
643
  export function renderReadme(answers: Answers): string {
598
644
  const routeList = answers.routes.length
599
645
  ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n")
@@ -623,6 +669,11 @@ document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
623
669
 
624
670
  ${dbReadmeNote(answers.db)}
625
671
 
672
+ Import the client from anywhere as \`import { db } from "#config/db";\` — a package.json subpath
673
+ import (\`imports\`), not a relative path, so it stays \`#config/db\` no matter how deeply nested the
674
+ importing file is under \`src/endpoints/\`. Bun resolves it the same way locally and on Vercel;
675
+ \`tsc --noEmit\` resolves it too, no extra tsconfig needed.
676
+ ${dbHasSchemaSupport(answers.db) ? renderSchemaReadmeSection(ext) : ""}
626
677
  ## Routes
627
678
 
628
679
  ${routeList}
@@ -5,16 +5,27 @@ export interface DbTemplate {
5
5
  file: string;
6
6
  /** Extra runtime dependencies the generated package.json needs. */
7
7
  dependencies: Record<string, string>;
8
+ /** Extra dev-only dependencies the generated package.json needs (drizzle-kit — a CLI tool, not runtime code). */
9
+ devDependencies: Record<string, string>;
8
10
  /** Line(s) appended to .env.example. */
9
11
  envVars: string;
10
12
  /** One-line note surfaced in the generated README so the caveats aren't silently lost. */
11
13
  readmeNote: string;
14
+ /** Whether this driver gets src/config/schema.ts + drizzle.config.ts + db:generate/db:migrate/db:push scripts — true for neon/postgres (same pg-core dialect), false for sqlite/none (see schema-edit.ts's requireNeonOrPostgres()). */
15
+ hasSchemaSupport: boolean;
12
16
  }
13
17
 
18
+ // drizzle-kit is genuinely the same for "neon" and "postgres" — both speak
19
+ // dialect: "postgresql", both point at the same schema.ts, both use the
20
+ // same DATABASE_URL-shaped dbCredentials.url (see templates/schema.ts's
21
+ // renderDrizzleConfig()) — only db.ts's client construction differs.
22
+ const DRIZZLE_KIT_DEV_DEPENDENCY = { "drizzle-kit": "^0.31.0" };
23
+
14
24
  const TEMPLATES: Record<DbChoice, DbTemplate> = {
15
25
  neon: {
16
26
  file: `import { drizzle } from "drizzle-orm/neon-http";
17
27
  import { neon } from "@neondatabase/serverless";
28
+ import * as schema from "./schema";
18
29
 
19
30
  if (!process.env.DATABASE_URL) {
20
31
  throw new Error("DATABASE_URL is required (Neon connection string)");
@@ -22,19 +33,22 @@ if (!process.env.DATABASE_URL) {
22
33
 
23
34
  const sql = neon(process.env.DATABASE_URL);
24
35
 
25
- export const db = drizzle(sql);
36
+ export const db = drizzle(sql, { schema });
26
37
  `,
27
38
  dependencies: {
28
39
  "drizzle-orm": "^0.38.2",
29
40
  "@neondatabase/serverless": "^0.10.4",
30
41
  },
42
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
31
43
  envVars: "DATABASE_URL=postgres://user:password@ep-example-123456.us-east-2.aws.neon.tech/dbname?sslmode=require\n",
32
44
  readmeNote:
33
45
  "Uses Neon's HTTP driver — no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel).",
46
+ hasSchemaSupport: true,
34
47
  },
35
48
  postgres: {
36
49
  file: `import { drizzle } from "drizzle-orm/node-postgres";
37
50
  import { Pool } from "pg";
51
+ import * as schema from "./schema";
38
52
 
39
53
  // NOTE: this pooled connection is for local dev or a long-running server
40
54
  // (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
@@ -48,15 +62,17 @@ if (!process.env.DATABASE_URL) {
48
62
 
49
63
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
50
64
 
51
- export const db = drizzle(pool);
65
+ export const db = drizzle(pool, { schema });
52
66
  `,
53
67
  dependencies: {
54
68
  "drizzle-orm": "^0.38.2",
55
69
  pg: "^8.13.1",
56
70
  },
71
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
57
72
  envVars: "DATABASE_URL=postgres://user:password@localhost:5432/dbname\n",
58
73
  readmeNote:
59
74
  "Pooled Postgres connection — fine for local dev or a long-running server, NOT safe as-is on Vercel serverless functions (connection pool exhaustion on cold starts). Use Neon for serverless deploys.",
75
+ hasSchemaSupport: true,
60
76
  },
61
77
  sqlite: {
62
78
  file: `import { drizzle } from "drizzle-orm/bun-sqlite";
@@ -72,19 +88,26 @@ export const db = drizzle(sqlite);
72
88
  dependencies: {
73
89
  "drizzle-orm": "^0.38.2",
74
90
  },
91
+ devDependencies: {},
75
92
  envVars: "DATABASE_URL=./dev.db\n",
76
- readmeNote: "Local file-based SQLite — for local dev only, not for a serverless deploy target.",
93
+ readmeNote:
94
+ "Local file-based SQLite — for local dev only, not for a serverless deploy target. No schema.ts/add-table support yet — SQLite uses a different set of drizzle-orm column builders (sqlite-core, not pg-core), hand-write a schema with drizzle-orm/sqlite-core if you need one.",
95
+ hasSchemaSupport: false,
77
96
  },
78
97
  none: {
79
98
  file: `// No database configured yet. Wire up a real client here — e.g. one of
80
99
  // the neon/postgres/sqlite variants this CLI can also generate — and
81
- // export it as \`db\` so src/endpoints/*/*.services.ts can import it.
100
+ // export it as \`db\`. Any service file can then do
101
+ // \`import { db } from "#config/db";\` (see package.json's "imports" field
102
+ // and the README's Database section) regardless of how deep it's nested.
82
103
 
83
104
  export const db = undefined;
84
105
  `,
85
106
  dependencies: {},
107
+ devDependencies: {},
86
108
  envVars: "",
87
109
  readmeNote: "No database configured. src/config/db.ts is an empty stub.",
110
+ hasSchemaSupport: false,
88
111
  },
89
112
  };
90
113
 
@@ -96,6 +119,10 @@ export function dbDependencies(db: DbChoice): Record<string, string> {
96
119
  return TEMPLATES[db].dependencies;
97
120
  }
98
121
 
122
+ export function dbDevDependencies(db: DbChoice): Record<string, string> {
123
+ return TEMPLATES[db].devDependencies;
124
+ }
125
+
99
126
  export function dbEnvVars(db: DbChoice): string {
100
127
  return TEMPLATES[db].envVars;
101
128
  }
@@ -103,3 +130,7 @@ export function dbEnvVars(db: DbChoice): string {
103
130
  export function dbReadmeNote(db: DbChoice): string {
104
131
  return TEMPLATES[db].readmeNote;
105
132
  }
133
+
134
+ export function dbHasSchemaSupport(db: DbChoice): boolean {
135
+ return TEMPLATES[db].hasSchemaSupport;
136
+ }
@@ -177,9 +177,12 @@ export function serviceImports(route: string, spec: MethodSpec, language: Langua
177
177
  }
178
178
 
179
179
  export function renderServiceMethod(spec: MethodSpec, language: Language): string {
180
- const ext = language === "javascript" ? "js" : "ts";
181
180
  const argList = language === "javascript" ? serviceCallArgs(spec).join(", ") : serviceParamList(spec);
182
- return `// TODO: replace with real data access (see src/config/db.${ext})
181
+ // "#config/db" is a package.json subpath import (Node's `imports` field,
182
+ // which Bun also resolves) — points at src/config/db.<ext> regardless of
183
+ // how deep the importing file is, so this never turns into `../../config/db`
184
+ // as routes get nested. See the "Database" section of the generated README.
185
+ return `// TODO: replace with real data access — e.g. import { db } from "#config/db";
183
186
  export async function ${spec.name}(${argList}) {
184
187
  ${defaultServiceReturn(spec)}
185
188
  }`;
@@ -0,0 +1,160 @@
1
+ import { toKebabCase } from "../prompts";
2
+ import { camelCase } from "./route";
3
+
4
+ /**
5
+ * The column types offered by `add-table`/`server-config`'s table editor.
6
+ * Deliberately a curated subset of what drizzle-orm/pg-core actually
7
+ * offers, not the full set (no jsonb, arrays, enums, numeric/decimal,
8
+ * varchar-with-length, etc. — those still work fine, they just have to be
9
+ * hand-added to schema.ts, same "escape hatch, not a lock-in" approach
10
+ * obfuscateTailwind()/frontonCompression() use elsewhere in this monorepo).
11
+ * Every one of these, plus the modifier chains below, was checked against a
12
+ * real `tsc --noEmit` run against real drizzle-orm/pg-core types before
13
+ * this went in, not assumed from docs.
14
+ */
15
+ export const COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"] as const;
16
+ export type ColumnType = (typeof COLUMN_TYPES)[number];
17
+
18
+ export interface ColumnSpec {
19
+ /** Raw name as typed, e.g. "Login Count" — sqlName/jsKey are both derived from this. */
20
+ name: string;
21
+ type: ColumnType;
22
+ notNull: boolean;
23
+ unique: boolean;
24
+ /**
25
+ * Pre-rendered modifier chain fragment for a default value, e.g.
26
+ * `.default(true)`, `.defaultNow()`, `.defaultRandom()` — empty string
27
+ * means no default. Kept pre-rendered (rather than a structured value)
28
+ * because each column type's default looks nothing like the others
29
+ * (timestamp/uuid use a no-arg method, text/integer/boolean take a
30
+ * literal), so there's no shared shape worth modeling.
31
+ */
32
+ defaultExpr: string;
33
+ /**
34
+ * A referenced table's JS identifier, e.g. "users" — when set, this
35
+ * column is always rendered as `integer(...).references(() => X.id)`
36
+ * regardless of `type`, matching the idiomatic Drizzle FK pattern (an
37
+ * `integer` column referencing another table's `serial` primary key).
38
+ * Verified against a real `tsc --noEmit`.
39
+ */
40
+ references?: string;
41
+ }
42
+
43
+ export interface TableSpec {
44
+ /** Raw name as typed, e.g. "Blog Posts" — identifier/sqlName are both derived from this. */
45
+ name: string;
46
+ /** Whether to prepend `id: serial("id").primaryKey()` — on by default, matches near-universal convention. */
47
+ includeId: boolean;
48
+ columns: ColumnSpec[];
49
+ }
50
+
51
+ export function tableIdentifier(name: string): string {
52
+ return camelCase(toKebabCase(name));
53
+ }
54
+
55
+ export function tableSqlName(name: string): string {
56
+ return toKebabCase(name).replace(/-/g, "_");
57
+ }
58
+
59
+ export function columnIdentifier(name: string): string {
60
+ return camelCase(toKebabCase(name));
61
+ }
62
+
63
+ function columnSqlName(name: string): string {
64
+ return toKebabCase(name).replace(/-/g, "_");
65
+ }
66
+
67
+ /** Which drizzle-orm/pg-core builder functions a table actually needs — used to keep the shared import declaration minimal and merge-friendly across repeated add-table calls. */
68
+ export function requiredBuilders(table: TableSpec): Set<string> {
69
+ const builders = new Set<string>(["pgTable"]);
70
+ if (table.includeId) builders.add("serial");
71
+ for (const col of table.columns) {
72
+ builders.add(col.references ? "integer" : col.type);
73
+ }
74
+ return builders;
75
+ }
76
+
77
+ function renderColumnLine(col: ColumnSpec): string {
78
+ const key = columnIdentifier(col.name);
79
+ const sqlName = columnSqlName(col.name);
80
+
81
+ let expr: string;
82
+ if (col.references) {
83
+ expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
84
+ } else {
85
+ expr = `${col.type}("${sqlName}")`;
86
+ }
87
+
88
+ if (col.notNull) expr += ".notNull()";
89
+ if (col.unique) expr += ".unique()";
90
+ if (col.defaultExpr) expr += col.defaultExpr;
91
+
92
+ return ` ${key}: ${expr},`;
93
+ }
94
+
95
+ /**
96
+ * Renders one `export const <identifier> = pgTable(...)` block — appended
97
+ * as-is to schema.ts by schema-edit.ts's ts-morph layer, the same
98
+ * append-real-statements approach templates/route.ts's method codegen
99
+ * uses.
100
+ */
101
+ export function renderTableBlock(table: TableSpec): string {
102
+ const identifier = tableIdentifier(table.name);
103
+ const sqlName = tableSqlName(table.name);
104
+ const lines: string[] = [];
105
+ if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
106
+ for (const col of table.columns) lines.push(renderColumnLine(col));
107
+
108
+ return `export const ${identifier} = pgTable("${sqlName}", {
109
+ ${lines.join("\n")}
110
+ });`;
111
+ }
112
+
113
+ export function renderBlankSchema(): string {
114
+ // The trailing `export {};` matters: a .ts file with zero import/export
115
+ // statements is a *script* to TypeScript, not a module, and db.ts's
116
+ // `import * as schema from "./schema"` fails to compile against a script
117
+ // file (`error TS2306: File '...' is not a module`) — caught against a
118
+ // real `tsc --noEmit` on a freshly scaffolded project, not assumed.
119
+ return `// No tables yet — add one via \`bun run add-table\` (or server-config's
120
+ // "Add a database table"). Each table becomes a real pgTable(...) export
121
+ // here, picked up automatically by both db.ts's schema import and
122
+ // drizzle-kit (see drizzle.config.ts) — nothing else needs to be told
123
+ // about a new table by hand.
124
+
125
+ export {};
126
+ `;
127
+ }
128
+
129
+ /**
130
+ * drizzle-kit's own config file, not one of backon's generated project
131
+ * files in the usual sense — drizzle-kit reads this directly, by
132
+ * convention, from the project root. `dialect: "postgresql"` is correct
133
+ * for both the "neon" and "postgres" db choices: neon-http still speaks
134
+ * the Postgres wire dialect over HTTP, so schema.ts, migrations, and this
135
+ * config are identical between the two — only db.ts's client construction
136
+ * differs (see templates/db.ts).
137
+ */
138
+ export function renderDrizzleConfig(ext: "ts" | "js"): string {
139
+ // The guard-then-use shape (rather than a TS-only `!` non-null assertion)
140
+ // matches templates/db.ts's neon/postgres templates exactly, and for the
141
+ // same reason: this file is generated for JavaScript projects too, where
142
+ // `!` isn't valid syntax at all. TypeScript's control-flow narrowing
143
+ // still applies to `process.env.DATABASE_URL` across the two statements
144
+ // below, same as it already does in db.ts.
145
+ return `import { defineConfig } from "drizzle-kit";
146
+
147
+ if (!process.env.DATABASE_URL) {
148
+ throw new Error("DATABASE_URL is required (see src/config/db.${ext})");
149
+ }
150
+
151
+ export default defineConfig({
152
+ schema: "./src/config/schema.${ext}",
153
+ out: "./drizzle",
154
+ dialect: "postgresql",
155
+ dbCredentials: {
156
+ url: process.env.DATABASE_URL,
157
+ },
158
+ });
159
+ `;
160
+ }