create-backon 0.10.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.
@@ -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
  }
@@ -334,6 +529,11 @@ export function renderPackageJson(
334
529
  project: "bunx create-backon project",
335
530
  "server-config": "bunx create-backon server-config",
336
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}`,
337
537
  };
338
538
  if (language === "typescript") {
339
539
  scripts.typecheck = "tsc --noEmit";