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.
@@ -0,0 +1,98 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { editSource, removeControllerMethod, removeRouteMount, removeServiceMethod } from "./ast-edit";
4
+ import { detectProject } from "./detect";
5
+ import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
6
+ import { parseRouteMethods } from "./route-methods";
7
+ import { renderBlankController, renderBlankRoutes, renderBlankServices, type HttpVerb } from "./templates/route";
8
+
9
+ export interface RemoveMethodResult {
10
+ route: string;
11
+ root: string;
12
+ removed: { verb: HttpVerb; path: string; name: string };
13
+ }
14
+
15
+ /**
16
+ * The undo for addMethod(): strips one method's mount line from
17
+ * *.routes.<ext>, its defineRoute() export (plus any params/body/query
18
+ * schema consts) from *.controller.<ext>, and its matching function (plus
19
+ * its now-unused schema-type import, if any) from *.services.<ext>.
20
+ * Identified by verb+path, the same pair addMethod() itself refuses to let
21
+ * collide — not by name alone, since two different verb/path pairs could
22
+ * theoretically end up with the same name checked against different
23
+ * endpoints (name uniqueness is only enforced per endpoint, not globally).
24
+ *
25
+ * Every removal goes through ast-edit.ts's ts-morph helpers, which find
26
+ * each method's statements by their actual declared/exported name — the
27
+ * same uniqueness addMethod() enforces — rather than by which \n\n-
28
+ * delimited block of text they happen to sit in. That matters because
29
+ * parseRouteMethods() (used above to confirm the method exists) reads
30
+ * mount lines with a lenient regex that tolerates reformatting; the old
31
+ * text-block removal required an exact line match after that same
32
+ * reformatting and could silently fail to find anything to remove, leaving
33
+ * the controller/services files changed but the route still mounted.
34
+ *
35
+ * Removing the last method on an endpoint resets all three files back to
36
+ * their blank, freshly-scaffolded shape (renderBlank*()) rather than
37
+ * leaving behind an import block with nothing left to import for — the
38
+ * same state addRoute() itself would have written.
39
+ */
40
+ export async function removeMethod(
41
+ route: string,
42
+ verb: HttpVerb,
43
+ path: string,
44
+ cwd: string = process.cwd()
45
+ ): Promise<RemoveMethodResult> {
46
+ const { root, framework, language, ext } = await detectProject(cwd);
47
+
48
+ const { contents: indexContents } = await readEndpointsIndex(root, ext);
49
+ const mounted = parseMountedRoutes(indexContents);
50
+ if (!mounted.includes(route)) {
51
+ throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext}.`);
52
+ }
53
+
54
+ const routeDir = join(root, "src/endpoints", route);
55
+ const controllerPath = join(routeDir, `${route}.controller.${ext}`);
56
+ const routesPath = join(routeDir, `${route}.routes.${ext}`);
57
+ const servicesPath = join(routeDir, `${route}.services.${ext}`);
58
+
59
+ const [controllerContents, routesContents, servicesContents] = await Promise.all([
60
+ readFile(controllerPath, "utf-8"),
61
+ readFile(routesPath, "utf-8"),
62
+ readFile(servicesPath, "utf-8"),
63
+ ]);
64
+
65
+ const existing = parseRouteMethods(routesContents);
66
+ const match = existing.find((m) => m.verb === verb && m.path === path);
67
+ if (!match) {
68
+ throw new Error(`${verb.toUpperCase()} ${path} isn't mounted in ${routesPath}.`);
69
+ }
70
+ const { name } = match;
71
+
72
+ if (existing.length === 1) {
73
+ await Promise.all([
74
+ writeFile(controllerPath, renderBlankController()),
75
+ writeFile(routesPath, renderBlankRoutes(route, framework, language)),
76
+ writeFile(servicesPath, renderBlankServices()),
77
+ ]);
78
+ return { route, root, removed: match };
79
+ }
80
+
81
+ const newController = editSource(controllerPath, controllerContents, (_project, sourceFile) => {
82
+ removeControllerMethod(sourceFile, name);
83
+ });
84
+ const newRoutes = editSource(routesPath, routesContents, (_project, sourceFile) => {
85
+ removeRouteMount(sourceFile, name);
86
+ });
87
+ const newServices = editSource(servicesPath, servicesContents, (_project, sourceFile) => {
88
+ removeServiceMethod(sourceFile, name);
89
+ });
90
+
91
+ await Promise.all([
92
+ writeFile(controllerPath, newController),
93
+ writeFile(routesPath, newRoutes),
94
+ writeFile(servicesPath, newServices),
95
+ ]);
96
+
97
+ return { route, root, removed: match };
98
+ }
@@ -35,6 +35,30 @@ export function parseRouteMethods(routesFileContents: string): EndpointMethod[]
35
35
  return methods;
36
36
  }
37
37
 
38
+ /**
39
+ * Whether a given method actually declared a body/query schema — read off
40
+ * whether *.controller.<ext> exports `<name>BodySchema`/`<name>QuerySchema`,
41
+ * since addMethod() only ever emits those consts when the method's own
42
+ * needsBody/needsQuery was true (see renderControllerMethod in
43
+ * templates/route.ts). Nothing else remembers those two booleans after the
44
+ * fact — this is how the "modify a method" flow prefills its confirm
45
+ * prompts with what the method already has, instead of defaulting both back
46
+ * to false every time.
47
+ */
48
+ export async function detectMethodValidation(
49
+ route: string,
50
+ name: string,
51
+ cwd: string = process.cwd()
52
+ ): Promise<{ needsBody: boolean; needsQuery: boolean }> {
53
+ const { root, ext } = await detectProject(cwd);
54
+ const controllerPath = join(root, "src/endpoints", route, `${route}.controller.${ext}`);
55
+ const contents = await readFile(controllerPath, "utf-8");
56
+ return {
57
+ needsBody: contents.includes(`export const ${name}BodySchema`),
58
+ needsQuery: contents.includes(`export const ${name}QuerySchema`),
59
+ };
60
+ }
61
+
38
62
  /**
39
63
  * Every endpoint currently mounted in src/endpoints/index.<ext>, with the
40
64
  * HTTP methods each one's own *.routes.<ext> file actually wires up right
@@ -226,6 +226,201 @@ console.log("Wrote openapi.json and docs.html");
226
226
  `;
227
227
  }
228
228
 
229
+ // Deliberately NOT built around importing src/app the way
230
+ // renderGenerateDocsScript() is — a client only needs to know verb/path/name
231
+ // per method and which of its body/query schemas exist, and all of that is
232
+ // already sitting in *.routes.<ext>/*.controller.<ext> as plain text (the
233
+ // exact same two facts route-methods.ts's parseRouteMethods()/
234
+ // detectMethodValidation() read off disk inside create-backon itself, just
235
+ // duplicated here in ~20 lines since a generated script can't import
236
+ // create-backon at runtime). No live app instance needed, so this can't fail
237
+ // because app.ts throws on a missing env var the way importing it would.
238
+ //
239
+ // The generated script re-discovers routes fresh every time it runs rather
240
+ // than being regenerated by add-route/add-method/remove-method — it reads
241
+ // src/endpoints/ at *run* time, so it never goes stale on its own; only
242
+ // client/api.<ext> (its output) needs a re-run after routes change, the
243
+ // same way `bun run docs` needs a re-run, not a re-scaffold.
244
+ //
245
+ // The generated output deliberately uses string concatenation (`+`) instead
246
+ // of template literals for building URLs — keeps this template's own
247
+ // authoring simple (no nested-backtick escaping between this file's
248
+ // template literal and the one it's generating) at the cost of slightly
249
+ // less idiomatic output code, a trade worth making for a script nobody is
250
+ // meant to hand-edit anyway (see the "auto-generated" header it writes).
251
+ export function renderGenerateClientScript(language: Language): string {
252
+ const ext = language === "javascript" ? "js" : "ts";
253
+ const typed = language === "javascript" ? "false" : "true";
254
+ // Annotates this script's OWN helper function parameters when it's being
255
+ // written as a .ts file — under the generated tsconfig's `strict: true`,
256
+ // an untyped parameter is a noImplicitAny error, unlike generate-docs.ts
257
+ // (which has no locally-defined functions to trigger it). Distinct from
258
+ // TYPED above, which is about the *output* client's type annotations —
259
+ // both happen to be driven by the same `language`, but conceptually one
260
+ // is "is this script valid strict TS" and the other is "does the file it
261
+ // writes have types".
262
+ const ann = (t: string) => (language === "javascript" ? "" : `: ${t}`);
263
+
264
+ return `// Regenerates client/api.${ext} from src/endpoints/ — reads *.routes.${ext}/*.controller.${ext}
265
+ // directly, the same source add-method/remove-method/server-config write to, so there's
266
+ // nothing to keep in sync by hand. Safe to re-run any time; nothing here needs updating
267
+ // when a route or method is added, removed, or modified — only its output does.
268
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
269
+ import { join } from "node:path";
270
+
271
+ const EXT = "${ext}";
272
+ const TYPED = ${typed};
273
+
274
+ const root = process.cwd();
275
+ const endpointsDir = join(root, "src/endpoints");
276
+
277
+ const MOUNT_PATTERN = /endpoints\\.(?:route|use)\\("\\/([a-z0-9-]+)"/g;
278
+ const METHOD_PATTERN = /\\.(get|post|put|patch|delete)\\(\\s*"([^"]*)"\\s*,\\s*controller\\.(\\w+)\\s*\\)/g;
279
+
280
+ function paramNames(path${ann("string")}) {
281
+ return Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).map((m) => m[1]);
282
+ }
283
+
284
+ function camelCase(name${ann("string")}) {
285
+ const parts = name.split("-");
286
+ return parts[0] + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
287
+ }
288
+
289
+ // Builds a JS expression string for the full request path — literal
290
+ // segments as JSON string literals, :param segments as bare identifiers,
291
+ // joined with "+" — e.g. "/users/:id" becomes the text: "/users/" + id
292
+ function pathExpr(route${ann("string")}, method${ann("any")}) {
293
+ const fullPath = "/" + route + (method.path === "/" ? "" : method.path);
294
+ const pieces = [];
295
+ let lastIndex = 0;
296
+ const paramRe = /:([A-Za-z0-9_]+)/g;
297
+ let match;
298
+ while ((match = paramRe.exec(fullPath))) {
299
+ if (match.index > lastIndex) pieces.push(JSON.stringify(fullPath.slice(lastIndex, match.index)));
300
+ pieces.push(match[1]);
301
+ lastIndex = match.index + match[0].length;
302
+ }
303
+ if (lastIndex < fullPath.length) pieces.push(JSON.stringify(fullPath.slice(lastIndex)));
304
+ return pieces.join(" + ");
305
+ }
306
+
307
+ function funcArgs(method${ann("any")}) {
308
+ const args = paramNames(method.path).slice();
309
+ if (method.needsBody) args.push("body");
310
+ if (method.needsQuery) args.push("query");
311
+ return args;
312
+ }
313
+
314
+ function typedFuncArgs(method${ann("any")}) {
315
+ const parts = paramNames(method.path).map((name) => name + ": string");
316
+ if (method.needsBody) parts.push("body: z.infer<typeof " + method.name + "BodySchema>");
317
+ if (method.needsQuery) parts.push("query: z.infer<typeof " + method.name + "QuerySchema>");
318
+ return parts.join(", ");
319
+ }
320
+
321
+ const indexContents = readFileSync(join(endpointsDir, "index." + EXT), "utf-8");
322
+ const routes = Array.from(indexContents.matchAll(MOUNT_PATTERN)).map((m) => m[1]);
323
+
324
+ const groups = [];
325
+ for (const route of routes) {
326
+ let routesContents, controllerContents;
327
+ try {
328
+ routesContents = readFileSync(join(endpointsDir, route, route + ".routes." + EXT), "utf-8");
329
+ controllerContents = readFileSync(join(endpointsDir, route, route + ".controller." + EXT), "utf-8");
330
+ } catch {
331
+ continue; // mounted but missing a file — \`bun run doctor\` already flags this, skip it here
332
+ }
333
+
334
+ const methods = Array.from(routesContents.matchAll(METHOD_PATTERN)).map((m) => ({
335
+ verb: m[1],
336
+ path: m[2],
337
+ name: m[3],
338
+ needsBody: controllerContents.includes(m[3] + "BodySchema"),
339
+ needsQuery: controllerContents.includes(m[3] + "QuerySchema"),
340
+ }));
341
+ if (methods.length > 0) groups.push({ route, methods });
342
+ }
343
+
344
+ if (groups.length === 0) {
345
+ console.log("No endpoints with methods yet — nothing to generate. Run \`bun run add-method\` first.");
346
+ process.exit(0);
347
+ }
348
+
349
+ const importLines = [];
350
+ if (TYPED) {
351
+ importLines.push('import type { z } from "zod";');
352
+ const namesByModule = new Map();
353
+ for (const group of groups) {
354
+ const names = [];
355
+ for (const m of group.methods) {
356
+ if (m.needsBody) names.push(m.name + "BodySchema");
357
+ if (m.needsQuery) names.push(m.name + "QuerySchema");
358
+ }
359
+ if (names.length > 0) namesByModule.set("../src/endpoints/" + group.route + "/" + group.route + ".controller", names);
360
+ }
361
+ for (const [modulePath, names] of namesByModule) {
362
+ importLines.push('import type { ' + names.join(", ") + ' } from "' + modulePath + '";');
363
+ }
364
+ }
365
+
366
+ const helperLines = [
367
+ 'const BASE_URL = (typeof process !== "undefined" && process.env.API_BASE_URL) || "";',
368
+ "",
369
+ TYPED ? "async function request<T>(path: string, init?: RequestInit): Promise<T> {" : "async function request(path, init) {",
370
+ " const res = await fetch(BASE_URL + path, {",
371
+ " ...init,",
372
+ ' headers: { "Content-Type": "application/json", ...(init && init.headers ? init.headers : {}) },',
373
+ " });",
374
+ " if (!res.ok) {",
375
+ TYPED ? " const errBody: any = await res.json().catch(() => undefined);" : " const errBody = await res.json().catch(() => undefined);",
376
+ ' throw new Error((errBody && errBody.error && errBody.error.message) || ("Request to " + path + " failed with " + res.status));',
377
+ " }",
378
+ TYPED ? " return res.json() as Promise<T>;" : " return res.json();",
379
+ "}",
380
+ ];
381
+
382
+ const groupBlocks = groups.map((group) => {
383
+ const varName = camelCase(group.route) + "Api";
384
+ const methodLines = group.methods.map((m) => {
385
+ const signature = TYPED ? typedFuncArgs(m) : funcArgs(m).join(", ");
386
+ const genericPrefix = TYPED ? "<T = unknown>" : "";
387
+
388
+ let call = "request" + (TYPED ? "<T>" : "") + "(" + pathExpr(group.route, m);
389
+ if (m.needsQuery) call += ' + "?" + new URLSearchParams(query' + (TYPED ? " as any" : "") + ").toString()";
390
+
391
+ const initParts = [];
392
+ if (m.verb !== "get") initParts.push('method: "' + m.verb.toUpperCase() + '"');
393
+ if (m.needsBody) initParts.push("body: JSON.stringify(body)");
394
+ if (initParts.length > 0) call += ", { " + initParts.join(", ") + " }";
395
+ call += ")";
396
+
397
+ return " " + m.name + ": " + genericPrefix + "(" + signature + ") => " + call + ",";
398
+ });
399
+ return "export const " + varName + " = {\\n" + methodLines.join("\\n") + "\\n};";
400
+ });
401
+
402
+ const header =
403
+ "// Auto-generated by \`bun run generate-client\` from src/endpoints/ — re-run after adding, removing,\\n" +
404
+ "// or modifying methods (add-method/remove-method/server-config all count). Hand edits here are\\n" +
405
+ "// overwritten on the next run.\\n\\n";
406
+
407
+ const output =
408
+ header +
409
+ (importLines.length > 0 ? importLines.join("\\n") + "\\n\\n" : "") +
410
+ helperLines.join("\\n") +
411
+ "\\n\\n" +
412
+ groupBlocks.join("\\n\\n") +
413
+ "\\n";
414
+
415
+ mkdirSync(join(root, "client"), { recursive: true });
416
+ const outPath = join(root, "client", "api." + EXT);
417
+ writeFileSync(outPath, output);
418
+ console.log(
419
+ "Wrote " + outPath + " (" + groups.reduce((n, g) => n + g.methods.length, 0) + " method(s) across " + groups.length + " endpoint(s))"
420
+ );
421
+ `;
422
+ }
423
+
229
424
  export function renderEnvExample(db: Answers["db"]): string {
230
425
  return `PORT=3000
231
426
  ALLOWED_ORIGINS=
@@ -249,7 +444,7 @@ export function renderTsconfig(): string {
249
444
  "noEmit": true,
250
445
  "allowJs": false
251
446
  },
252
- "include": ["index.ts", "src", "scripts"]
447
+ "include": ["index.ts", "src", "scripts", "client"]
253
448
  }
254
449
  `;
255
450
  }
@@ -272,7 +467,7 @@ export function renderJsconfig(): string {
272
467
  "checkJs": false,
273
468
  "allowJs": true
274
469
  },
275
- "include": ["index.js", "src", "scripts"]
470
+ "include": ["index.js", "src", "scripts", "client"]
276
471
  }
277
472
  `;
278
473
  }
@@ -327,7 +522,18 @@ export function renderPackageJson(
327
522
  "remove-route": "bunx create-backon remove-route",
328
523
  "list-routes": "bunx create-backon list-routes",
329
524
  doctor: "bunx create-backon doctor",
525
+ // project: read-only overview (db status, endpoints, methods, doctor
526
+ // summary). server-config: the interactive manager for actually
527
+ // changing endpoints/methods — add/remove/modify, without needing to
528
+ // remember which of the individual subcommands above does what.
529
+ project: "bunx create-backon project",
530
+ "server-config": "bunx create-backon server-config",
330
531
  docs: `bun run scripts/generate-docs.${ext}`,
532
+ // Regenerates client/api.<ext> — a typed fetch client, one function per
533
+ // mounted method, read straight off *.routes.<ext>/*.controller.<ext>
534
+ // (the same files add-method/server-config write). client/ is a build
535
+ // artifact like openapi.json/docs.html, not source — see .gitignore.
536
+ "generate-client": `bun run scripts/generate-client.${ext}`,
331
537
  };
332
538
  if (language === "typescript") {
333
539
  scripts.typecheck = "tsc --noEmit";