create-backon 0.13.3 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
+ import { spawnSync } from "node:child_process";
4
5
  import { readFile as readFile8 } from "node:fs/promises";
5
6
  import { join as join12 } from "node:path";
6
7
  import * as p2 from "@clack/prompts";
@@ -726,27 +727,27 @@ function renderPackageJson(projectName, framework, language, db) {
726
727
  const ext = language === "javascript" ? "js" : "ts";
727
728
  const dependencies = framework === "express" ? {
728
729
  "@mednours/backon": "latest",
729
- express: "^4.21.0",
730
+ express: "^5.3.0",
730
731
  cors: "^2.8.5",
731
732
  helmet: "^8.0.0",
732
733
  compression: "^1.7.5",
733
- zod: "^3.24.1",
734
+ zod: "^4.6.7",
734
735
  ...dbDependencies(db)
735
736
  } : {
736
737
  "@mednours/backon": "latest",
737
- hono: "^4.6.14",
738
- zod: "^3.24.1",
738
+ hono: "^4.13.23",
739
+ zod: "^4.6.7",
739
740
  ...dbDependencies(db)
740
741
  };
741
742
  const devDependencies = language === "javascript" ? { ...dbDevDependencies(db) } : framework === "express" ? {
742
743
  "@types/bun": "latest",
743
- "@types/express": "^4.17.21",
744
- typescript: "^5.7.2",
744
+ "@types/express": "^5.0.6",
745
+ typescript: "^7.0.2",
745
746
  ...dbDevDependencies(db),
746
747
  ...dbTypeOnlyDevDependencies(db)
747
748
  } : {
748
749
  "@types/bun": "latest",
749
- typescript: "^5.7.2",
750
+ typescript: "^7.0.2",
750
751
  ...dbDevDependencies(db),
751
752
  ...dbTypeOnlyDevDependencies(db)
752
753
  };
@@ -782,6 +783,7 @@ function renderPackageJson(projectName, framework, language, db) {
782
783
  }
783
784
  if (dbHasSchemaSupport(db)) {
784
785
  scripts["add-table"] = "bunx create-backon add-table";
786
+ scripts["add-column"] = "bunx create-backon add-column";
785
787
  scripts["remove-table"] = "bunx create-backon remove-table";
786
788
  scripts["db:generate"] = "drizzle-kit generate";
787
789
  scripts["db:migrate"] = "drizzle-kit migrate";
@@ -921,7 +923,20 @@ ${renderDeploySection(answers.deployTarget, ext)}`;
921
923
  }
922
924
 
923
925
  // src/templates/schema.ts
924
- var COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"];
926
+ var COLUMN_TYPES = [
927
+ "text",
928
+ "varchar",
929
+ "integer",
930
+ "serial",
931
+ "numeric",
932
+ "real",
933
+ "boolean",
934
+ "timestamp",
935
+ "date",
936
+ "uuid",
937
+ "jsonb"
938
+ ];
939
+ var ON_DELETE_ACTIONS = ["cascade", "set null", "restrict"];
925
940
  function tableIdentifier(name) {
926
941
  return camelCase(toKebabCase(name));
927
942
  }
@@ -934,27 +949,61 @@ function columnIdentifier(name) {
934
949
  function columnSqlName(name) {
935
950
  return toKebabCase(name).replace(/-/g, "_");
936
951
  }
952
+ function singularizeIdentifier(name) {
953
+ if (name.endsWith("ies") && name.length > 3) return `${name.slice(0, -3)}y`;
954
+ if (/(?:ss|x|ch|sh)es$/i.test(name) && name.length > 4) return name.slice(0, -2);
955
+ if (name.endsWith("s") && !name.endsWith("ss") && name.length > 1) return name.slice(0, -1);
956
+ return name;
957
+ }
958
+ function buildJunctionTableSpec(options) {
959
+ const { leftTable, rightTable, extraColumns = [], includeTimestamps = false, onDelete = "cascade" } = options;
960
+ const selfJoin = leftTable === rightTable;
961
+ const leftBase = singularizeIdentifier(leftTable);
962
+ const rightBase = singularizeIdentifier(rightTable);
963
+ const leftColName = selfJoin ? `${leftBase} a id` : `${leftBase} id`;
964
+ const rightColName = selfJoin ? `${rightBase} b id` : `${rightBase} id`;
965
+ const columns = [
966
+ { name: leftColName, type: "integer", notNull: true, unique: false, defaultExpr: "", references: leftTable, onDelete },
967
+ { name: rightColName, type: "integer", notNull: true, unique: false, defaultExpr: "", references: rightTable, onDelete },
968
+ ...extraColumns
969
+ ];
970
+ return {
971
+ name: options.name?.trim() || `${leftTable}_${rightTable}`,
972
+ includeId: false,
973
+ includeTimestamps,
974
+ compositePrimaryKey: [columnIdentifier(leftColName), columnIdentifier(rightColName)],
975
+ columns
976
+ };
977
+ }
937
978
  function requiredBuilders(table) {
938
979
  const builders = /* @__PURE__ */ new Set(["pgTable"]);
939
980
  if (table.includeId) builders.add("serial");
981
+ if (table.includeTimestamps) builders.add("timestamp");
982
+ if (table.compositePrimaryKey?.length) builders.add("primaryKey");
940
983
  for (const col of table.columns) {
941
984
  builders.add(col.references ? "integer" : col.type);
942
985
  }
943
986
  return builders;
944
987
  }
945
- function renderColumnLine(col) {
946
- const key = columnIdentifier(col.name);
988
+ function renderColumnExpression(col) {
947
989
  const sqlName = columnSqlName(col.name);
948
990
  let expr;
949
991
  if (col.references) {
950
- expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
992
+ const refOpts = col.onDelete ? `, { onDelete: "${col.onDelete}" }` : "";
993
+ expr = `integer("${sqlName}").references(() => ${col.references}.id${refOpts})`;
994
+ } else if (col.type === "varchar") {
995
+ const length = col.varcharLength ?? 255;
996
+ expr = `varchar("${sqlName}", { length: ${length} })`;
951
997
  } else {
952
998
  expr = `${col.type}("${sqlName}")`;
953
999
  }
954
1000
  if (col.notNull) expr += ".notNull()";
955
1001
  if (col.unique) expr += ".unique()";
956
1002
  if (col.defaultExpr) expr += col.defaultExpr;
957
- return ` ${key}: ${expr},`;
1003
+ return expr;
1004
+ }
1005
+ function renderColumnLine(col) {
1006
+ return ` ${columnIdentifier(col.name)}: ${renderColumnExpression(col)},`;
958
1007
  }
959
1008
  function renderTableBlock(table) {
960
1009
  const identifier = tableIdentifier(table.name);
@@ -962,6 +1011,20 @@ function renderTableBlock(table) {
962
1011
  const lines = [];
963
1012
  if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
964
1013
  for (const col of table.columns) lines.push(renderColumnLine(col));
1014
+ if (table.includeTimestamps) {
1015
+ lines.push(` createdAt: timestamp("created_at").notNull().defaultNow(),`);
1016
+ lines.push(` updatedAt: timestamp("updated_at").notNull().defaultNow(),`);
1017
+ }
1018
+ if (table.compositePrimaryKey?.length) {
1019
+ const pkCols = table.compositePrimaryKey.map((key) => `table.${key}`).join(", ");
1020
+ return `export const ${identifier} = pgTable(
1021
+ "${sqlName}",
1022
+ {
1023
+ ${lines.map((line) => ` ${line}`).join("\n")}
1024
+ },
1025
+ (table) => [primaryKey({ columns: [${pkCols}] })]
1026
+ );`;
1027
+ }
965
1028
  return `export const ${identifier} = pgTable("${sqlName}", {
966
1029
  ${lines.join("\n")}
967
1030
  });`;
@@ -1686,19 +1749,39 @@ function parseSchemaTables(contents) {
1686
1749
  if (!init || !Node2.isCallExpression(init)) continue;
1687
1750
  const callee = init.getExpression();
1688
1751
  if (!Node2.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
1689
- const [sqlNameArg, columnsArg] = init.getArguments();
1752
+ const [sqlNameArg, columnsArg, extraArg] = init.getArguments();
1690
1753
  const sqlName = sqlNameArg && Node2.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
1754
+ const isJunction = Boolean(extraArg && extraArg.getText().includes("primaryKey"));
1691
1755
  const columns = [];
1692
1756
  if (columnsArg && Node2.isObjectLiteralExpression(columnsArg)) {
1693
1757
  for (const prop of columnsArg.getProperties()) {
1694
1758
  if (!Node2.isPropertyAssignment(prop)) continue;
1695
- columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
1759
+ columns.push({
1760
+ key: prop.getName(),
1761
+ type: findColumnBuilderType(prop),
1762
+ references: findReferencedTable(prop)
1763
+ });
1696
1764
  }
1697
1765
  }
1698
- tables.push({ identifier: decl.getName(), sqlName, columns });
1766
+ tables.push({ identifier: decl.getName(), sqlName, isJunction, columns });
1699
1767
  }
1700
1768
  return tables;
1701
1769
  }
1770
+ function findColumnBuilderType(propAssignment) {
1771
+ const init = Node2.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : void 0;
1772
+ if (!init) return void 0;
1773
+ let deepest = init;
1774
+ while (Node2.isCallExpression(deepest)) {
1775
+ const expr = deepest.getExpression();
1776
+ if (Node2.isIdentifier(expr)) return expr.getText();
1777
+ if (Node2.isPropertyAccessExpression(expr)) {
1778
+ deepest = expr.getExpression();
1779
+ } else {
1780
+ break;
1781
+ }
1782
+ }
1783
+ return void 0;
1784
+ }
1702
1785
  function findReferencedTable(propAssignment) {
1703
1786
  const init = Node2.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : void 0;
1704
1787
  if (!init) return void 0;
@@ -1745,6 +1828,20 @@ function prunePgCoreImport(sourceFile) {
1745
1828
  }
1746
1829
  if (decl.getNamedImports().length === 0) decl.remove();
1747
1830
  }
1831
+ function findTableColumnsObject(sourceFile, identifier) {
1832
+ for (const stmt of sourceFile.getVariableStatements()) {
1833
+ if (!stmt.isExported()) continue;
1834
+ const decl = stmt.getDeclarations()[0];
1835
+ if (!decl || decl.getName() !== identifier) continue;
1836
+ const init = decl.getInitializer();
1837
+ if (!init || !Node2.isCallExpression(init)) continue;
1838
+ const callee = init.getExpression();
1839
+ if (!Node2.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
1840
+ const columnsArg = init.getArguments()[1];
1841
+ if (columnsArg && Node2.isObjectLiteralExpression(columnsArg)) return columnsArg;
1842
+ }
1843
+ return void 0;
1844
+ }
1748
1845
  function removeTableStatement(sourceFile, identifier) {
1749
1846
  for (const stmt of sourceFile.getVariableStatements()) {
1750
1847
  const decls = stmt.getDeclarations();
@@ -1797,13 +1894,48 @@ async function addTable(spec, cwd = process.cwd()) {
1797
1894
  await writeFile6(path, updated);
1798
1895
  return { root, identifier, filePath: path };
1799
1896
  }
1897
+ async function addColumn(table, col, cwd = process.cwd()) {
1898
+ await requireNeonOrPostgres(cwd);
1899
+ const { root, ext } = await detectProject(cwd);
1900
+ const { path, contents } = await readSchemaFile(root, ext);
1901
+ const tableId = tableIdentifier(table);
1902
+ const existingTables = parseSchemaTables(contents);
1903
+ const target = existingTables.find((t) => t.identifier === tableId || t.identifier === table);
1904
+ if (!target) {
1905
+ throw new Error(`No table "${table}" found in ${path}.`);
1906
+ }
1907
+ const columnKey = columnIdentifier(col.name);
1908
+ if (target.columns.some((c) => c.key === columnKey)) {
1909
+ throw new Error(`Column "${columnKey}" already exists on table "${target.identifier}".`);
1910
+ }
1911
+ if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
1912
+ throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
1913
+ }
1914
+ const builder = col.references ? "integer" : col.type;
1915
+ const initializer = renderColumnExpression(col);
1916
+ const updated = editSource(path, contents, (_project, sourceFile) => {
1917
+ ensurePgCoreImport(sourceFile, /* @__PURE__ */ new Set([builder]));
1918
+ const columnsObj = findTableColumnsObject(sourceFile, target.identifier);
1919
+ if (!columnsObj) {
1920
+ throw new Error(`Could not locate columns object for table "${target.identifier}".`);
1921
+ }
1922
+ columnsObj.addPropertyAssignment({ name: columnKey, initializer });
1923
+ });
1924
+ await writeFile6(path, updated);
1925
+ return { root, table: target.identifier, columnKey, filePath: path };
1926
+ }
1800
1927
  function formatTablesDashboard(tables) {
1801
1928
  if (tables.length === 0) return dim("No tables yet.");
1802
1929
  return tables.map((t) => {
1803
- if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})
1930
+ const badge = t.isJunction ? dim(" [junction]") : "";
1931
+ if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})${badge}
1804
1932
  ${dim("(no columns)")}`;
1805
- const lines = t.columns.map((c) => ` ${c.key}${c.references ? dim(` \u2192 references ${c.references}.id`) : ""}`);
1806
- return `${t.identifier} (${t.sqlName})
1933
+ const lines = t.columns.map((c) => {
1934
+ const typeLabel = c.type ? dim(` : ${c.type}`) : "";
1935
+ const refLabel = c.references ? dim(` \u2192 references ${c.references}.id`) : "";
1936
+ return ` ${c.key}${typeLabel}${refLabel}`;
1937
+ });
1938
+ return `${t.identifier} (${t.sqlName})${badge}
1807
1939
  ${lines.join("\n")}`;
1808
1940
  }).join("\n\n");
1809
1941
  }
@@ -1834,6 +1966,268 @@ async function removeTable(identifier, cwd = process.cwd()) {
1834
1966
  return { root, identifier, filePath: path };
1835
1967
  }
1836
1968
 
1969
+ // src/tui.ts
1970
+ import { emitKeypressEvents } from "node:readline";
1971
+ var ANSI_RESET = "\x1B[0m";
1972
+ var ANSI_BOLD = "\x1B[1m";
1973
+ var ANSI_DIM = "\x1B[2m";
1974
+ var ANSI_CYAN = "\x1B[36m";
1975
+ var ANSI_GREEN = "\x1B[32m";
1976
+ var ANSI_YELLOW = "\x1B[33m";
1977
+ var ANSI_RED = "\x1B[31m";
1978
+ var ANSI_INVERSE = "\x1B[7m";
1979
+ var ANSI_REGEX = /\x1b\[[0-9;]*m/g;
1980
+ function visibleLength(text3) {
1981
+ return text3.replace(ANSI_REGEX, "").length;
1982
+ }
1983
+ function padOrTruncate(text3, width) {
1984
+ const len = visibleLength(text3);
1985
+ if (len === width) return text3;
1986
+ if (len < width) return text3 + " ".repeat(width - len);
1987
+ const plain = text3.replace(ANSI_REGEX, "");
1988
+ return width <= 1 ? plain.slice(0, width) : plain.slice(0, width - 1) + "\u2026";
1989
+ }
1990
+ function verbBadge(verb) {
1991
+ const upper = verb.toUpperCase().padEnd(6);
1992
+ if (verb === "get") return `${ANSI_GREEN}${upper}${ANSI_RESET}`;
1993
+ if (verb === "post") return `${ANSI_CYAN}${upper}${ANSI_RESET}`;
1994
+ if (verb === "put" || verb === "patch") return `${ANSI_YELLOW}${upper}${ANSI_RESET}`;
1995
+ if (verb === "delete") return `${ANSI_RED}${upper}${ANSI_RESET}`;
1996
+ return upper;
1997
+ }
1998
+ function itemCountForTab(snapshot, tab) {
1999
+ if (tab === "endpoints") return snapshot.endpoints.length;
2000
+ if (tab === "tables") return snapshot.tables.length;
2001
+ return Math.max(1, snapshot.issues.length);
2002
+ }
2003
+ function clampSelection(snapshot, state) {
2004
+ const count = itemCountForTab(snapshot, state.tab);
2005
+ const maxIndex = Math.max(0, count - 1);
2006
+ const selectedIndex = Math.min(Math.max(0, state.selectedIndex), maxIndex);
2007
+ return selectedIndex === state.selectedIndex ? state : { ...state, selectedIndex };
2008
+ }
2009
+ var TABS = ["endpoints", "tables", "doctor"];
2010
+ function nextTab(current, delta) {
2011
+ const idx = TABS.indexOf(current);
2012
+ return TABS[(idx + delta + TABS.length) % TABS.length];
2013
+ }
2014
+ function renderTuiFrame(snapshot, rawState, width = 96, height = 26) {
2015
+ const state = clampSelection(snapshot, rawState);
2016
+ const cols = Math.max(60, width);
2017
+ const rows = Math.max(16, height);
2018
+ const leftWidth = Math.max(24, Math.min(36, Math.floor(cols * 0.36)));
2019
+ const rightWidth = cols - leftWidth - 3;
2020
+ const tabPill = (tab, label) => state.tab === tab ? `${ANSI_INVERSE}${ANSI_BOLD} ${label} ${ANSI_RESET}` : `${ANSI_DIM} ${label} ${ANSI_RESET}`;
2021
+ const header = `${ANSI_BOLD}${ANSI_CYAN}backon server-config${ANSI_RESET} ${ANSI_DIM}${snapshot.framework} \xB7 ${snapshot.dbStatus.driver} \xB7 ${snapshot.root}${ANSI_RESET}`;
2022
+ const tabBar = [
2023
+ tabPill("endpoints", `1 Endpoints (${snapshot.endpoints.length})`),
2024
+ tabPill("tables", `2 Tables (${snapshot.tables.length})`),
2025
+ tabPill("doctor", `3 Doctor (${snapshot.issues.length})`)
2026
+ ].join(" ");
2027
+ const rule = `${ANSI_DIM}${"\u2500".repeat(cols)}${ANSI_RESET}`;
2028
+ const leftLines = [];
2029
+ const rightLines = [];
2030
+ if (state.tab === "endpoints") {
2031
+ if (snapshot.endpoints.length === 0) {
2032
+ leftLines.push(`${ANSI_DIM}(no endpoints yet)${ANSI_RESET}`);
2033
+ rightLines.push(`${ANSI_BOLD}No endpoints mounted${ANSI_RESET}`, "", "Press [a] to add your first endpoint.");
2034
+ } else {
2035
+ snapshot.endpoints.forEach((ep, i) => {
2036
+ const selected = i === state.selectedIndex;
2037
+ const prefix = selected ? `${ANSI_CYAN}\u25B8${ANSI_RESET} ` : " ";
2038
+ const label = `${prefix}/${ep.route} ${ANSI_DIM}(${ep.methods.length})${ANSI_RESET}`;
2039
+ leftLines.push(selected ? `${ANSI_BOLD}${label}${ANSI_RESET}` : label);
2040
+ });
2041
+ const active = snapshot.endpoints[state.selectedIndex];
2042
+ if (active) {
2043
+ rightLines.push(`${ANSI_BOLD}Endpoint: /${active.route}${ANSI_RESET}`, "");
2044
+ if (active.methods.length === 0) {
2045
+ rightLines.push(`${ANSI_DIM}No methods yet. Press [n] to add one or [c] for CRUD.${ANSI_RESET}`);
2046
+ } else {
2047
+ for (const m of active.methods) {
2048
+ rightLines.push(`${verbBadge(m.verb)} ${m.path.padEnd(18)} ${ANSI_DIM}\u2192 ${m.name}()${ANSI_RESET}`);
2049
+ }
2050
+ }
2051
+ }
2052
+ }
2053
+ } else if (state.tab === "tables") {
2054
+ if (!snapshot.schemaCapable) {
2055
+ leftLines.push(`${ANSI_DIM}(schema disabled)${ANSI_RESET}`);
2056
+ rightLines.push(
2057
+ `${ANSI_YELLOW}Schema editor requires Neon or Postgres${ANSI_RESET}`,
2058
+ "",
2059
+ `Current db driver: ${snapshot.dbStatus.driver}`
2060
+ );
2061
+ } else if (snapshot.tables.length === 0) {
2062
+ leftLines.push(`${ANSI_DIM}(no tables yet)${ANSI_RESET}`);
2063
+ rightLines.push(
2064
+ `${ANSI_BOLD}No tables in schema${ANSI_RESET}`,
2065
+ "",
2066
+ "Press [a] to create a table, or [m] for a junction table once 2+ tables exist."
2067
+ );
2068
+ } else {
2069
+ snapshot.tables.forEach((tbl, i) => {
2070
+ const selected = i === state.selectedIndex;
2071
+ const prefix = selected ? `${ANSI_CYAN}\u25B8${ANSI_RESET} ` : " ";
2072
+ const tag = tbl.isJunction ? " [M:N]" : ` (${tbl.columns.length})`;
2073
+ const label = `${prefix}${tbl.identifier}${ANSI_DIM}${tag}${ANSI_RESET}`;
2074
+ leftLines.push(selected ? `${ANSI_BOLD}${label}${ANSI_RESET}` : label);
2075
+ });
2076
+ const active = snapshot.tables[state.selectedIndex];
2077
+ if (active) {
2078
+ const kind = active.isJunction ? ` ${ANSI_CYAN}[junction table]${ANSI_RESET}` : "";
2079
+ rightLines.push(`${ANSI_BOLD}${active.identifier}${ANSI_RESET} ${ANSI_DIM}(${active.sqlName})${ANSI_RESET}${kind}`, "");
2080
+ for (const c of active.columns) {
2081
+ const typeText = c.type ? ` : ${c.type}` : "";
2082
+ const refText = c.references ? ` ${ANSI_CYAN}\u2192 ${c.references}.id${ANSI_RESET}` : "";
2083
+ rightLines.push(` \u2022 ${c.key}${ANSI_DIM}${typeText}${ANSI_RESET}${refText}`);
2084
+ }
2085
+ }
2086
+ }
2087
+ } else {
2088
+ if (snapshot.issues.length === 0) {
2089
+ leftLines.push(`${ANSI_GREEN}\u2713 Healthy${ANSI_RESET}`);
2090
+ rightLines.push(
2091
+ `${ANSI_GREEN}${ANSI_BOLD}All endpoint & schema checks passed${ANSI_RESET}`,
2092
+ "",
2093
+ `Database: ${snapshot.dbStatus.summary}`,
2094
+ "",
2095
+ "Quick tools:",
2096
+ " [g] Run bun run generate-client",
2097
+ " [o] Run bun run docs (OpenAPI + Scalar)"
2098
+ );
2099
+ } else {
2100
+ snapshot.issues.forEach((issue, i) => {
2101
+ const selected = i === state.selectedIndex;
2102
+ const prefix = selected ? `${ANSI_YELLOW}\u25B8${ANSI_RESET} ` : " ";
2103
+ leftLines.push(`${prefix}${ANSI_YELLOW}!${ANSI_RESET} ${issue.detail}`);
2104
+ });
2105
+ const active = snapshot.issues[state.selectedIndex];
2106
+ if (active) {
2107
+ rightLines.push(`${ANSI_YELLOW}${ANSI_BOLD}Doctor Issue${ANSI_RESET}`, "", active.detail);
2108
+ }
2109
+ }
2110
+ }
2111
+ const bodyRows = Math.max(6, rows - 6);
2112
+ const body = [];
2113
+ for (let r = 0; r < bodyRows; r++) {
2114
+ const l = padOrTruncate(leftLines[r] ?? "", leftWidth);
2115
+ const rt = padOrTruncate(rightLines[r] ?? "", rightWidth);
2116
+ body.push(`${l} ${ANSI_DIM}\u2502${ANSI_RESET} ${rt}`);
2117
+ }
2118
+ const shortcuts = state.tab === "endpoints" ? "[a] Add endpoint [c] Add CRUD [n] Add method [m] Modify [x] Rm method [d] Rm endpoint" : state.tab === "tables" ? "[a] Add table [m] Junction (M:N) [c] Add column [d] Remove table" : "[g] Generate client [o] Generate docs [r] Re-run doctor";
2119
+ const statusLine = state.statusMessage ? `${ANSI_CYAN}${state.statusMessage}${ANSI_RESET}` : `${ANSI_DIM}\u2191/\u2193 Move Tab/1-3 Switch r Refresh q Quit${ANSI_RESET}`;
2120
+ const footer = `${ANSI_DIM}${shortcuts}${ANSI_RESET}
2121
+ ${statusLine}`;
2122
+ return [padOrTruncate(header, cols), padOrTruncate(tabBar, cols), rule, ...body, rule, footer].join("\n");
2123
+ }
2124
+ function enterAltScreen() {
2125
+ process.stdout.write("\x1B[?1049h\x1B[?25l");
2126
+ }
2127
+ function exitAltScreen() {
2128
+ process.stdout.write("\x1B[?25h\x1B[?1049l");
2129
+ }
2130
+ async function waitForAnyKey() {
2131
+ process.stdout.write(`
2132
+ ${ANSI_DIM}Press any key to return to server-config...${ANSI_RESET}`);
2133
+ await new Promise((resolve) => {
2134
+ const wasRaw = process.stdin.isRaw;
2135
+ process.stdin.setRawMode(true);
2136
+ process.stdin.resume();
2137
+ const onData = () => {
2138
+ process.stdin.removeListener("data", onData);
2139
+ if (!wasRaw) process.stdin.setRawMode(false);
2140
+ resolve();
2141
+ };
2142
+ process.stdin.once("data", onData);
2143
+ });
2144
+ }
2145
+ async function runServerConfigTui(actions) {
2146
+ let snapshot = await actions.loadSnapshot();
2147
+ let state = { tab: "endpoints", selectedIndex: 0 };
2148
+ emitKeypressEvents(process.stdin);
2149
+ enterAltScreen();
2150
+ const draw = () => {
2151
+ const width = process.stdout.columns || 96;
2152
+ const height = process.stdout.rows || 26;
2153
+ process.stdout.write("\x1B[H\x1B[2J" + renderTuiFrame(snapshot, state, width, height));
2154
+ };
2155
+ const runInteractive = async (fn) => {
2156
+ process.stdin.setRawMode(false);
2157
+ exitAltScreen();
2158
+ try {
2159
+ const msg = await fn();
2160
+ snapshot = await actions.loadSnapshot();
2161
+ state = clampSelection(snapshot, { ...state, statusMessage: msg || void 0 });
2162
+ } catch (err) {
2163
+ state = { ...state, statusMessage: `Error: ${err instanceof Error ? err.message : String(err)}` };
2164
+ await waitForAnyKey();
2165
+ }
2166
+ enterAltScreen();
2167
+ process.stdin.setRawMode(true);
2168
+ process.stdin.resume();
2169
+ draw();
2170
+ };
2171
+ try {
2172
+ process.stdin.setRawMode(true);
2173
+ process.stdin.resume();
2174
+ draw();
2175
+ await new Promise((resolve) => {
2176
+ const onResize = () => draw();
2177
+ const cleanup = () => {
2178
+ process.stdin.removeListener("keypress", onKeypress);
2179
+ process.stdout.removeListener("resize", onResize);
2180
+ };
2181
+ const onKeypress = async (str, key) => {
2182
+ if (key.ctrl && key.name === "c" || key.name === "escape" || str === "q") {
2183
+ cleanup();
2184
+ resolve();
2185
+ return;
2186
+ }
2187
+ if (str === "1") state = clampSelection(snapshot, { tab: "endpoints", selectedIndex: 0 });
2188
+ else if (str === "2") state = clampSelection(snapshot, { tab: "tables", selectedIndex: 0 });
2189
+ else if (str === "3") state = clampSelection(snapshot, { tab: "doctor", selectedIndex: 0 });
2190
+ else if (key.name === "tab" || key.name === "right") {
2191
+ state = clampSelection(snapshot, { tab: nextTab(state.tab, 1), selectedIndex: 0 });
2192
+ } else if (key.name === "left") {
2193
+ state = clampSelection(snapshot, { tab: nextTab(state.tab, -1), selectedIndex: 0 });
2194
+ } else if (key.name === "up" || str === "k") {
2195
+ state = clampSelection(snapshot, { ...state, selectedIndex: state.selectedIndex - 1 });
2196
+ } else if (key.name === "down" || str === "j") {
2197
+ state = clampSelection(snapshot, { ...state, selectedIndex: state.selectedIndex + 1 });
2198
+ } else if (str === "r") {
2199
+ snapshot = await actions.loadSnapshot();
2200
+ state = clampSelection(snapshot, { ...state, statusMessage: "Refreshed." });
2201
+ } else if (state.tab === "endpoints") {
2202
+ const current = snapshot.endpoints[state.selectedIndex];
2203
+ if (str === "a") await runInteractive(() => actions.addEndpoint());
2204
+ else if (str === "d") await runInteractive(() => actions.removeEndpoint(current));
2205
+ else if (str === "c") await runInteractive(() => actions.addCrud(current));
2206
+ else if (str === "n") await runInteractive(() => actions.addMethod(current));
2207
+ else if (str === "m") await runInteractive(() => actions.modifyMethod(current));
2208
+ else if (str === "x") await runInteractive(() => actions.removeMethod(current));
2209
+ } else if (state.tab === "tables") {
2210
+ const current = snapshot.tables[state.selectedIndex];
2211
+ if (str === "a") await runInteractive(() => actions.addTable(snapshot.tables));
2212
+ else if (str === "m") await runInteractive(() => actions.addJunctionTable(snapshot.tables));
2213
+ else if (str === "c") await runInteractive(() => actions.addColumn(current, snapshot.tables));
2214
+ else if (str === "d") await runInteractive(() => actions.removeTable(current, snapshot.tables));
2215
+ } else if (state.tab === "doctor") {
2216
+ if (str === "g") await runInteractive(() => actions.generateClient());
2217
+ else if (str === "o") await runInteractive(() => actions.generateDocs());
2218
+ }
2219
+ draw();
2220
+ };
2221
+ process.stdin.on("keypress", onKeypress);
2222
+ process.stdout.on("resize", onResize);
2223
+ });
2224
+ } finally {
2225
+ if (process.stdin.isTTY) process.stdin.setRawMode(false);
2226
+ process.stdin.pause();
2227
+ exitAltScreen();
2228
+ }
2229
+ }
2230
+
1837
2231
  // src/cli.ts
1838
2232
  var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
1839
2233
  var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
@@ -1843,6 +2237,7 @@ var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
1843
2237
  var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
1844
2238
  var SERVER_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set(["server-config"]);
1845
2239
  var ADD_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-table", "table"]);
2240
+ var ADD_COLUMN_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-column", "column"]);
1846
2241
  var REMOVE_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-table", "rm-table"]);
1847
2242
  async function promptForRouteName(introText) {
1848
2243
  p2.intro(introText);
@@ -1956,7 +2351,8 @@ async function readSchemaTables() {
1956
2351
  }
1957
2352
  }
1958
2353
  async function promptDefaultExpr(type) {
1959
- if (type === "timestamp") {
2354
+ if (type === "serial") return "";
2355
+ if (type === "timestamp" || type === "date") {
1960
2356
  const v2 = await p2.confirm({ message: "Default to now()?", initialValue: false });
1961
2357
  if (p2.isCancel(v2)) return null;
1962
2358
  return v2 ? ".defaultNow()" : "";
@@ -1979,13 +2375,27 @@ async function promptDefaultExpr(type) {
1979
2375
  if (p2.isCancel(v2)) return null;
1980
2376
  return v2 === "none" ? "" : `.default(${v2})`;
1981
2377
  }
2378
+ if (type === "jsonb") {
2379
+ const v2 = await p2.select({
2380
+ message: "Default JSON value",
2381
+ options: [
2382
+ { value: "none", label: "None" },
2383
+ { value: "{}", label: "{} (empty object)" },
2384
+ { value: "[]", label: "[] (empty array)" }
2385
+ ],
2386
+ initialValue: "none"
2387
+ });
2388
+ if (p2.isCancel(v2)) return null;
2389
+ return v2 === "none" ? "" : `.default(${v2})`;
2390
+ }
2391
+ const isNumber = type === "integer" || type === "real";
1982
2392
  const v = await p2.text({
1983
2393
  message: "Default value (blank for none)",
1984
- placeholder: type === "integer" ? "e.g. 0" : "e.g. pending"
2394
+ placeholder: isNumber ? "e.g. 0" : type === "numeric" ? "e.g. 0.00" : "e.g. pending"
1985
2395
  });
1986
2396
  if (p2.isCancel(v)) return null;
1987
2397
  if (!v) return "";
1988
- if (type === "integer") {
2398
+ if (isNumber) {
1989
2399
  const n = Number(v);
1990
2400
  if (Number.isNaN(n)) {
1991
2401
  p2.log.warn(`"${v}" isn't a number \u2014 skipping the default.`);
@@ -1995,7 +2405,66 @@ async function promptDefaultExpr(type) {
1995
2405
  }
1996
2406
  return `.default(${JSON.stringify(v)})`;
1997
2407
  }
1998
- async function promptForColumns(existingTables) {
2408
+ async function promptSingleColumn(name, existingTables, defaultRequired = true) {
2409
+ let references;
2410
+ let onDelete;
2411
+ if (existingTables.length > 0) {
2412
+ const refChoice = await p2.select({
2413
+ message: `Does "${name}" reference another table's id?`,
2414
+ options: [
2415
+ { value: "__none__", label: "No" },
2416
+ ...existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
2417
+ ],
2418
+ initialValue: "__none__"
2419
+ });
2420
+ if (p2.isCancel(refChoice)) return null;
2421
+ if (refChoice !== "__none__") {
2422
+ references = refChoice;
2423
+ const deleteChoice = await p2.select({
2424
+ message: "On referenced row delete",
2425
+ options: [
2426
+ { value: "__none__", label: "Default (no action)" },
2427
+ ...ON_DELETE_ACTIONS.map((a) => ({ value: a, label: a }))
2428
+ ],
2429
+ initialValue: "cascade"
2430
+ });
2431
+ if (p2.isCancel(deleteChoice)) return null;
2432
+ if (deleteChoice !== "__none__") onDelete = deleteChoice;
2433
+ }
2434
+ }
2435
+ let type = "integer";
2436
+ let varcharLength;
2437
+ let defaultExpr = "";
2438
+ if (!references) {
2439
+ const typeChoice = await p2.select({
2440
+ message: "Column type",
2441
+ options: COLUMN_TYPES.map((t) => ({ value: t, label: t }))
2442
+ });
2443
+ if (p2.isCancel(typeChoice)) return null;
2444
+ type = typeChoice;
2445
+ if (type === "varchar") {
2446
+ const lenInput = await p2.text({
2447
+ message: "Max varchar length",
2448
+ initialValue: "255",
2449
+ validate: (value) => {
2450
+ const n = Number(value);
2451
+ return !value || !Number.isInteger(n) || n <= 0 ? "Enter a positive integer." : void 0;
2452
+ }
2453
+ });
2454
+ if (p2.isCancel(lenInput)) return null;
2455
+ varcharLength = Number(lenInput);
2456
+ }
2457
+ const expr = await promptDefaultExpr(type);
2458
+ if (expr === null) return null;
2459
+ defaultExpr = expr;
2460
+ }
2461
+ const notNull = await p2.confirm({ message: "Required (NOT NULL)?", initialValue: defaultRequired });
2462
+ if (p2.isCancel(notNull)) return null;
2463
+ const unique = await p2.confirm({ message: "Unique?", initialValue: false });
2464
+ if (p2.isCancel(unique)) return null;
2465
+ return { name, type, notNull, unique, defaultExpr, varcharLength, references, onDelete };
2466
+ }
2467
+ async function promptForColumns(existingTables, existingKeys = []) {
1999
2468
  const columns = [];
2000
2469
  p2.log.step("Add columns one at a time. Leave the name blank to finish.");
2001
2470
  while (true) {
@@ -2006,41 +2475,13 @@ async function promptForColumns(existingTables) {
2006
2475
  if (p2.isCancel(nameProbe)) return null;
2007
2476
  if (!nameProbe) break;
2008
2477
  const key = columnIdentifier(nameProbe);
2009
- if (columns.some((c) => columnIdentifier(c.name) === key)) {
2478
+ if (existingKeys.includes(key) || columns.some((c) => columnIdentifier(c.name) === key)) {
2010
2479
  p2.log.error(`"${key}" is already a column on this table.`);
2011
2480
  continue;
2012
2481
  }
2013
- let references;
2014
- if (existingTables.length > 0) {
2015
- const refChoice = await p2.select({
2016
- message: `Does "${nameProbe}" reference another table's id?`,
2017
- options: [
2018
- { value: "__none__", label: "No" },
2019
- ...existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
2020
- ],
2021
- initialValue: "__none__"
2022
- });
2023
- if (p2.isCancel(refChoice)) return null;
2024
- if (refChoice !== "__none__") references = refChoice;
2025
- }
2026
- let type = "integer";
2027
- let defaultExpr = "";
2028
- if (!references) {
2029
- const typeChoice = await p2.select({
2030
- message: "Column type",
2031
- options: COLUMN_TYPES.map((t) => ({ value: t, label: t }))
2032
- });
2033
- if (p2.isCancel(typeChoice)) return null;
2034
- type = typeChoice;
2035
- const expr = await promptDefaultExpr(type);
2036
- if (expr === null) return null;
2037
- defaultExpr = expr;
2038
- }
2039
- const notNull = await p2.confirm({ message: "Required (NOT NULL)?", initialValue: true });
2040
- if (p2.isCancel(notNull)) return null;
2041
- const unique = await p2.confirm({ message: "Unique?", initialValue: false });
2042
- if (p2.isCancel(unique)) return null;
2043
- columns.push({ name: nameProbe, type, notNull, unique, defaultExpr, references });
2482
+ const spec = await promptSingleColumn(nameProbe, existingTables);
2483
+ if (spec === null) return null;
2484
+ columns.push(spec);
2044
2485
  }
2045
2486
  return columns;
2046
2487
  }
@@ -2072,18 +2513,81 @@ async function collectTableSpec(existingTables, forcedName) {
2072
2513
  initialValue: true
2073
2514
  });
2074
2515
  if (p2.isCancel(includeId)) return null;
2075
- const columns = await promptForColumns(existingTables);
2516
+ const includeTimestamps = await p2.confirm({
2517
+ message: "Add createdAt / updatedAt timestamp columns?",
2518
+ initialValue: true
2519
+ });
2520
+ if (p2.isCancel(includeTimestamps)) return null;
2521
+ const columns = await promptForColumns(existingTables, includeId ? ["id"] : []);
2076
2522
  if (columns === null) return null;
2077
- return { name, includeId, columns };
2523
+ return { name, includeId, includeTimestamps, columns };
2524
+ }
2525
+ async function collectJunctionTableSpec(existingTables) {
2526
+ if (existingTables.length < 2) {
2527
+ p2.log.warn("Need at least 2 existing tables to create a many-to-many junction table.");
2528
+ return null;
2529
+ }
2530
+ const leftTable = await p2.select({
2531
+ message: "First table",
2532
+ options: existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
2533
+ });
2534
+ if (p2.isCancel(leftTable)) return null;
2535
+ const rightTable = await p2.select({
2536
+ message: "Second table",
2537
+ options: existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
2538
+ });
2539
+ if (p2.isCancel(rightTable)) return null;
2540
+ const defaultName = `${leftTable}_${rightTable}`;
2541
+ const name = await p2.text({
2542
+ message: "Junction table name",
2543
+ initialValue: defaultName,
2544
+ validate: (value) => {
2545
+ if (!value) return "Required.";
2546
+ if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
2547
+ return `"${tableIdentifier(value)}" already exists.`;
2548
+ }
2549
+ return void 0;
2550
+ }
2551
+ });
2552
+ if (p2.isCancel(name)) return null;
2553
+ const onDelete = await p2.select({
2554
+ message: "Cascade behavior when either referenced row is deleted",
2555
+ options: ON_DELETE_ACTIONS.map((a) => ({ value: a, label: a })),
2556
+ initialValue: "cascade"
2557
+ });
2558
+ if (p2.isCancel(onDelete)) return null;
2559
+ const includeTimestamps = await p2.confirm({
2560
+ message: "Add createdAt / updatedAt timestamp columns?",
2561
+ initialValue: true
2562
+ });
2563
+ if (p2.isCancel(includeTimestamps)) return null;
2564
+ const addExtra = await p2.confirm({
2565
+ message: "Add extra attributes to the junction table (e.g. role, quantity)?",
2566
+ initialValue: false
2567
+ });
2568
+ if (p2.isCancel(addExtra)) return null;
2569
+ const baseSpec = buildJunctionTableSpec({ leftTable, rightTable, name, includeTimestamps, onDelete });
2570
+ let extraColumns = [];
2571
+ if (addExtra) {
2572
+ const cols = await promptForColumns(
2573
+ existingTables,
2574
+ baseSpec.columns.map((c) => columnIdentifier(c.name))
2575
+ );
2576
+ if (cols === null) return null;
2577
+ extraColumns = cols;
2578
+ }
2579
+ return buildJunctionTableSpec({ leftTable, rightTable, name, includeTimestamps, onDelete, extraColumns });
2078
2580
  }
2079
2581
  async function runAddTable(args) {
2080
2582
  p2.intro("create-backon add-table");
2081
2583
  if (!await ensureSchemaSupport()) return;
2082
- const [forcedName] = args;
2584
+ const junctionFlag = args.includes("--junction");
2585
+ const positional = args.filter((a) => a !== "--junction");
2586
+ const [forcedName] = positional;
2083
2587
  let existingTables = await readSchemaTables();
2084
2588
  let first = true;
2085
2589
  while (true) {
2086
- const spec = await collectTableSpec(existingTables, first ? forcedName : void 0);
2590
+ const spec = first && junctionFlag ? await collectJunctionTableSpec(existingTables) : await collectTableSpec(existingTables, first ? forcedName : void 0);
2087
2591
  first = false;
2088
2592
  if (!spec) {
2089
2593
  p2.cancel("Cancelled.");
@@ -2101,6 +2605,63 @@ async function runAddTable(args) {
2101
2605
  }
2102
2606
  p2.outro("Done.");
2103
2607
  }
2608
+ async function runAddColumn(args) {
2609
+ p2.intro("create-backon add-column");
2610
+ if (!await ensureSchemaSupport()) return;
2611
+ const existingTables = await readSchemaTables();
2612
+ if (existingTables.length === 0) {
2613
+ p2.log.info("No tables yet \u2014 run `bun run add-table` first.");
2614
+ return;
2615
+ }
2616
+ const [forcedTable, forcedCol] = args;
2617
+ let tableId;
2618
+ if (forcedTable) {
2619
+ const candidate = tableIdentifier(forcedTable);
2620
+ const match = existingTables.find((t) => t.identifier === candidate || t.identifier === forcedTable);
2621
+ if (!match) {
2622
+ p2.log.error(`No table "${forcedTable}" found.`);
2623
+ return;
2624
+ }
2625
+ tableId = match.identifier;
2626
+ } else {
2627
+ const choice = await p2.select({
2628
+ message: "Add a column to which table?",
2629
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2630
+ });
2631
+ if (p2.isCancel(choice)) {
2632
+ p2.cancel("Cancelled.");
2633
+ return;
2634
+ }
2635
+ tableId = choice;
2636
+ }
2637
+ const target = existingTables.find((t) => t.identifier === tableId);
2638
+ let colName = forcedCol;
2639
+ if (!colName) {
2640
+ const answer = await p2.text({
2641
+ message: "Column name",
2642
+ placeholder: "e.g. avatarUrl",
2643
+ validate: (value) => {
2644
+ if (!value) return "Required.";
2645
+ const key = columnIdentifier(value);
2646
+ if (target.columns.some((c) => c.key === key)) return `"${key}" already exists on ${tableId}.`;
2647
+ return void 0;
2648
+ }
2649
+ });
2650
+ if (p2.isCancel(answer)) {
2651
+ p2.cancel("Cancelled.");
2652
+ return;
2653
+ }
2654
+ colName = answer;
2655
+ }
2656
+ const spec = await promptSingleColumn(colName, existingTables);
2657
+ if (!spec) {
2658
+ p2.cancel("Cancelled.");
2659
+ return;
2660
+ }
2661
+ const { columnKey, filePath } = await addColumn(tableId, spec);
2662
+ p2.log.success(`Added column "${columnKey}" to "${tableId}" in ${filePath}.`);
2663
+ p2.outro("Run `bun run db:generate` to create a migration.");
2664
+ }
2104
2665
  async function runRemoveTable(args) {
2105
2666
  p2.intro("create-backon remove-table");
2106
2667
  if (!await ensureSchemaSupport()) return;
@@ -2152,20 +2713,76 @@ async function serverConfigAddTable(existingTables) {
2152
2713
  }
2153
2714
  const { filePath, identifier } = await addTable(spec);
2154
2715
  p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
2716
+ return `Added table "${identifier}"`;
2155
2717
  }
2156
- async function serverConfigRemoveTable(existingTables) {
2718
+ async function serverConfigAddJunctionTable(existingTables) {
2719
+ const spec = await collectJunctionTableSpec(existingTables);
2720
+ if (!spec) {
2721
+ p2.cancel("Cancelled.");
2722
+ return;
2723
+ }
2724
+ const { filePath, identifier } = await addTable(spec);
2725
+ p2.log.success(`Added junction table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
2726
+ return `Added junction table "${identifier}"`;
2727
+ }
2728
+ async function serverConfigAddColumn(existingTables, forcedTable) {
2157
2729
  if (existingTables.length === 0) {
2158
- p2.log.info("No tables yet.");
2730
+ p2.log.info("No tables yet \u2014 add a table first.");
2159
2731
  return;
2160
2732
  }
2161
- const choice = await p2.select({
2162
- message: "Remove which table?",
2163
- options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2733
+ let target = forcedTable;
2734
+ if (!target) {
2735
+ const choice = await p2.select({
2736
+ message: "Add a column to which table?",
2737
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2738
+ });
2739
+ if (p2.isCancel(choice)) {
2740
+ p2.cancel("Cancelled.");
2741
+ return;
2742
+ }
2743
+ target = existingTables.find((t) => t.identifier === choice);
2744
+ }
2745
+ if (!target) return;
2746
+ const colName = await p2.text({
2747
+ message: `New column name on "${target.identifier}"`,
2748
+ placeholder: "e.g. avatarUrl",
2749
+ validate: (value) => {
2750
+ if (!value) return "Required.";
2751
+ const key = columnIdentifier(value);
2752
+ if (target.columns.some((c) => c.key === key)) return `"${key}" already exists on ${target.identifier}.`;
2753
+ return void 0;
2754
+ }
2164
2755
  });
2165
- if (p2.isCancel(choice)) {
2756
+ if (p2.isCancel(colName)) {
2166
2757
  p2.cancel("Cancelled.");
2167
2758
  return;
2168
2759
  }
2760
+ const spec = await promptSingleColumn(colName, existingTables);
2761
+ if (!spec) {
2762
+ p2.cancel("Cancelled.");
2763
+ return;
2764
+ }
2765
+ const { columnKey, filePath } = await addColumn(target.identifier, spec);
2766
+ p2.log.success(`Added column "${columnKey}" to "${target.identifier}" in ${filePath}.`);
2767
+ return `Added column "${target.identifier}.${columnKey}"`;
2768
+ }
2769
+ async function serverConfigRemoveTable(existingTables, forcedTable) {
2770
+ if (existingTables.length === 0) {
2771
+ p2.log.info("No tables yet.");
2772
+ return;
2773
+ }
2774
+ let choice = forcedTable?.identifier;
2775
+ if (!choice) {
2776
+ const picked = await p2.select({
2777
+ message: "Remove which table?",
2778
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2779
+ });
2780
+ if (p2.isCancel(picked)) {
2781
+ p2.cancel("Cancelled.");
2782
+ return;
2783
+ }
2784
+ choice = picked;
2785
+ }
2169
2786
  const confirmed = await p2.confirm({
2170
2787
  message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
2171
2788
  initialValue: false
@@ -2176,6 +2793,7 @@ async function serverConfigRemoveTable(existingTables) {
2176
2793
  }
2177
2794
  const { filePath } = await removeTable(choice);
2178
2795
  p2.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
2796
+ return `Removed table "${choice}"`;
2179
2797
  }
2180
2798
  function suggestMethodName(verb, path) {
2181
2799
  const params = paramNamesFromPath(path);
@@ -2231,7 +2849,7 @@ async function runAddMethod() {
2231
2849
  message: "Path (relative to this endpoint's mount)",
2232
2850
  placeholder: defaultPath,
2233
2851
  initialValue: defaultPath,
2234
- validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
2852
+ validate: (value) => !value?.startsWith("/") ? 'Must start with "/".' : void 0
2235
2853
  });
2236
2854
  if (p2.isCancel(path)) {
2237
2855
  p2.cancel("Cancelled.");
@@ -2244,7 +2862,7 @@ async function runAddMethod() {
2244
2862
  placeholder: defaultName,
2245
2863
  initialValue: defaultName,
2246
2864
  validate: (value) => {
2247
- if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
2865
+ if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
2248
2866
  if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
2249
2867
  return void 0;
2250
2868
  }
@@ -2365,7 +2983,7 @@ async function serverConfigAddMethod(summaries) {
2365
2983
  message: "Path (relative to this endpoint's mount)",
2366
2984
  placeholder: defaultPath,
2367
2985
  initialValue: defaultPath,
2368
- validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
2986
+ validate: (value) => !value?.startsWith("/") ? 'Must start with "/".' : void 0
2369
2987
  });
2370
2988
  if (p2.isCancel(path)) {
2371
2989
  p2.cancel("Cancelled.");
@@ -2377,7 +2995,7 @@ async function serverConfigAddMethod(summaries) {
2377
2995
  placeholder: defaultName,
2378
2996
  initialValue: defaultName,
2379
2997
  validate: (value) => {
2380
- if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
2998
+ if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
2381
2999
  if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
2382
3000
  return void 0;
2383
3001
  }
@@ -2470,7 +3088,7 @@ async function serverConfigModifyMethod(summaries) {
2470
3088
  const path = await p2.text({
2471
3089
  message: "Path (relative to this endpoint's mount)",
2472
3090
  initialValue: old.path,
2473
- validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
3091
+ validate: (value) => !value?.startsWith("/") ? 'Must start with "/".' : void 0
2474
3092
  });
2475
3093
  if (p2.isCancel(path)) {
2476
3094
  p2.cancel("Cancelled.");
@@ -2480,7 +3098,7 @@ async function serverConfigModifyMethod(summaries) {
2480
3098
  message: "Name (controller export + service function)",
2481
3099
  initialValue: old.name,
2482
3100
  validate: (value) => {
2483
- if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
3101
+ if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
2484
3102
  if (others.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
2485
3103
  return void 0;
2486
3104
  }
@@ -2514,6 +3132,86 @@ async function serverConfigModifyMethod(summaries) {
2514
3132
  );
2515
3133
  }
2516
3134
  async function runServerConfig() {
3135
+ if (process.stdin.isTTY && process.stdout.isTTY) {
3136
+ await runServerConfigTui({
3137
+ loadSnapshot: async () => {
3138
+ const project = await detectProject();
3139
+ const dbStatus = await detectDbStatus();
3140
+ const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
3141
+ const [endpoints, tables, doctor] = await Promise.all([
3142
+ listEndpointsWithMethods(),
3143
+ schemaCapable ? readSchemaTables() : Promise.resolve([]),
3144
+ runDoctor()
3145
+ ]);
3146
+ return {
3147
+ root: project.root,
3148
+ framework: project.framework,
3149
+ language: project.ext === "ts" ? "TypeScript" : "JavaScript",
3150
+ dbStatus,
3151
+ schemaCapable,
3152
+ endpoints,
3153
+ tables,
3154
+ issues: doctor.issues
3155
+ };
3156
+ },
3157
+ addEndpoint: async () => {
3158
+ await serverConfigAddEndpoint();
3159
+ },
3160
+ removeEndpoint: async (ep) => {
3161
+ const summaries = await listEndpointsWithMethods();
3162
+ if (ep) {
3163
+ const confirmed = await p2.confirm({
3164
+ message: `Remove src/endpoints/${ep.route} and unmount it? This deletes the folder.`,
3165
+ initialValue: false
3166
+ });
3167
+ if (!p2.isCancel(confirmed) && confirmed) await removeRoute(ep.route);
3168
+ } else {
3169
+ await serverConfigRemoveEndpoint(summaries);
3170
+ }
3171
+ },
3172
+ addCrud: async (ep) => {
3173
+ if (!ep) {
3174
+ await serverConfigAddEndpoint();
3175
+ return;
3176
+ }
3177
+ logCrudResult(await addCrudMethods(ep.route));
3178
+ },
3179
+ addMethod: async () => {
3180
+ await serverConfigAddMethod(await listEndpointsWithMethods());
3181
+ },
3182
+ modifyMethod: async () => {
3183
+ await serverConfigModifyMethod(await listEndpointsWithMethods());
3184
+ },
3185
+ removeMethod: async () => {
3186
+ await serverConfigRemoveMethod(await listEndpointsWithMethods());
3187
+ },
3188
+ addTable: async (tables) => {
3189
+ if (await ensureSchemaSupport()) await serverConfigAddTable(tables);
3190
+ },
3191
+ addJunctionTable: async (tables) => {
3192
+ if (await ensureSchemaSupport()) await serverConfigAddJunctionTable(tables);
3193
+ },
3194
+ addColumn: async (tbl, tables) => {
3195
+ if (await ensureSchemaSupport()) await serverConfigAddColumn(tables, tbl);
3196
+ },
3197
+ removeTable: async (tbl, tables) => {
3198
+ if (await ensureSchemaSupport()) await serverConfigRemoveTable(tables, tbl);
3199
+ },
3200
+ generateClient: async () => {
3201
+ const { root, ext } = await detectProject();
3202
+ const res = spawnSync("bun", ["run", `scripts/generate-client.${ext}`], { cwd: root, encoding: "utf-8" });
3203
+ if (res.status !== 0) throw new Error((res.stderr || res.stdout || "generate-client failed").trim());
3204
+ return "Generated client/api." + ext;
3205
+ },
3206
+ generateDocs: async () => {
3207
+ const { root, ext } = await detectProject();
3208
+ const res = spawnSync("bun", ["run", `scripts/generate-docs.${ext}`], { cwd: root, encoding: "utf-8" });
3209
+ if (res.status !== 0) throw new Error((res.stderr || res.stdout || "generate-docs failed").trim());
3210
+ return "Generated openapi.json + docs.html";
3211
+ }
3212
+ });
3213
+ return;
3214
+ }
2517
3215
  p2.intro("create-backon server-config");
2518
3216
  while (true) {
2519
3217
  const { root } = await detectProject();
@@ -2533,6 +3231,8 @@ async function runServerConfig() {
2533
3231
  { value: "remove-method", label: "Remove a method" },
2534
3232
  { value: "modify-method", label: "Modify a method" },
2535
3233
  { value: "add-table", label: "Add a database table" },
3234
+ { value: "add-junction", label: "Add a junction table (M:N)" },
3235
+ { value: "add-column", label: "Add a column to a table" },
2536
3236
  { value: "remove-table", label: "Remove a database table" },
2537
3237
  { value: "exit", label: "Exit" }
2538
3238
  ]
@@ -2558,6 +3258,12 @@ async function runServerConfig() {
2558
3258
  case "add-table":
2559
3259
  if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
2560
3260
  break;
3261
+ case "add-junction":
3262
+ if (await ensureSchemaSupport()) await serverConfigAddJunctionTable(await readSchemaTables());
3263
+ break;
3264
+ case "add-column":
3265
+ if (await ensureSchemaSupport()) await serverConfigAddColumn(await readSchemaTables());
3266
+ break;
2561
3267
  case "remove-table":
2562
3268
  if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
2563
3269
  break;
@@ -2611,6 +3317,10 @@ async function main() {
2611
3317
  await runAddTable(rest);
2612
3318
  return;
2613
3319
  }
3320
+ if (subcommand && ADD_COLUMN_SUBCOMMANDS.has(subcommand)) {
3321
+ await runAddColumn(rest);
3322
+ return;
3323
+ }
2614
3324
  if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
2615
3325
  await runRemoveTable(rest);
2616
3326
  return;