create-backon 0.6.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +102 -12
- package/dist/cli.js +1240 -0
- package/package.json +10 -6
- package/src/add-method.ts +101 -0
- package/src/add-route.ts +11 -9
- package/src/cli.ts +145 -3
- package/src/colors.ts +25 -0
- package/src/generate.ts +17 -6
- package/src/prompts.ts +26 -0
- package/src/route-methods.ts +76 -0
- package/src/templates/base.ts +103 -7
- package/src/templates/route.ts +143 -64
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1240 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import * as p2 from "@clack/prompts";
|
|
5
|
+
|
|
6
|
+
// src/prompts.ts
|
|
7
|
+
import * as p from "@clack/prompts";
|
|
8
|
+
function bail() {
|
|
9
|
+
p.cancel("Cancelled.");
|
|
10
|
+
process.exit(0);
|
|
11
|
+
}
|
|
12
|
+
function toKebabCase(input) {
|
|
13
|
+
return input.trim().replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
async function runPrompts() {
|
|
16
|
+
p.intro("create-backon");
|
|
17
|
+
const projectName = await p.text({
|
|
18
|
+
message: 'Project name (or "." to scaffold into the current directory)',
|
|
19
|
+
placeholder: "my-api",
|
|
20
|
+
validate: (value) => {
|
|
21
|
+
if (!value) return "Required.";
|
|
22
|
+
if (value === ".") return void 0;
|
|
23
|
+
if (!/^[a-z0-9-]+$/.test(value)) {
|
|
24
|
+
return 'Lowercase letters, numbers, and hyphens only (or "." for the current directory).';
|
|
25
|
+
}
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
if (p.isCancel(projectName)) bail();
|
|
30
|
+
const framework = await p.select({
|
|
31
|
+
message: "Framework",
|
|
32
|
+
options: [
|
|
33
|
+
{ value: "hono", label: "Hono", hint: "faster, runs anywhere \u2014 Bun, edge, serverless" },
|
|
34
|
+
{ value: "express", label: "Express" }
|
|
35
|
+
]
|
|
36
|
+
});
|
|
37
|
+
if (p.isCancel(framework)) bail();
|
|
38
|
+
const language = await p.select({
|
|
39
|
+
message: "Language",
|
|
40
|
+
options: [
|
|
41
|
+
{ value: "typescript", label: "TypeScript" },
|
|
42
|
+
{ value: "javascript", label: "JavaScript" }
|
|
43
|
+
]
|
|
44
|
+
});
|
|
45
|
+
if (p.isCancel(language)) bail();
|
|
46
|
+
const db = await p.select({
|
|
47
|
+
message: "Database",
|
|
48
|
+
options: [
|
|
49
|
+
{ value: "neon", label: "Neon", hint: "serverless Postgres \u2014 matches a Vercel deploy" },
|
|
50
|
+
{ value: "postgres", label: "Postgres", hint: "local/self-hosted \u2014 dev or a long-running server only" },
|
|
51
|
+
{ value: "sqlite", label: "SQLite", hint: "local dev only" },
|
|
52
|
+
{ value: "none", label: "None", hint: "empty db.ts stub, wire it up later" }
|
|
53
|
+
]
|
|
54
|
+
});
|
|
55
|
+
if (p.isCancel(db)) bail();
|
|
56
|
+
const deployTarget = await p.select({
|
|
57
|
+
message: "Where's this headed?",
|
|
58
|
+
options: [
|
|
59
|
+
{
|
|
60
|
+
value: "vercel",
|
|
61
|
+
label: "Vercel",
|
|
62
|
+
hint: "adds vercel.json + a default export so it deploys with zero config"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
value: "node",
|
|
66
|
+
label: "Another Node/Bun host",
|
|
67
|
+
hint: "Render, Railway, Fly, a VPS \u2014 index.ts's serve() already listens on PORT, nothing extra needed"
|
|
68
|
+
},
|
|
69
|
+
{ value: "local", label: "Local / self-hosted only", hint: "no deploy scaffolding added" },
|
|
70
|
+
{ value: "undecided", label: "Not sure yet", hint: "same as local for now \u2014 figure it out later" }
|
|
71
|
+
]
|
|
72
|
+
});
|
|
73
|
+
if (p.isCancel(deployTarget)) bail();
|
|
74
|
+
const copyEnv = await p.confirm({
|
|
75
|
+
message: "Create .env from .env.example now?",
|
|
76
|
+
initialValue: true
|
|
77
|
+
});
|
|
78
|
+
if (p.isCancel(copyEnv)) bail();
|
|
79
|
+
const routes = [];
|
|
80
|
+
p.log.step("Add routes one at a time. Leave the name blank to finish.");
|
|
81
|
+
while (true) {
|
|
82
|
+
const name = await p.text({
|
|
83
|
+
message: routes.length === 0 ? "Route name" : "Another route? (blank to finish)",
|
|
84
|
+
placeholder: routes.length === 0 ? "e.g. users" : ""
|
|
85
|
+
});
|
|
86
|
+
if (p.isCancel(name)) bail();
|
|
87
|
+
if (!name) break;
|
|
88
|
+
routes.push(toKebabCase(name));
|
|
89
|
+
}
|
|
90
|
+
p.outro(`Scaffolding ${projectName}...`);
|
|
91
|
+
return {
|
|
92
|
+
projectName,
|
|
93
|
+
framework,
|
|
94
|
+
language,
|
|
95
|
+
db,
|
|
96
|
+
routes,
|
|
97
|
+
copyEnv,
|
|
98
|
+
deployTarget
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/generate.ts
|
|
103
|
+
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
104
|
+
import { basename, dirname, join } from "node:path";
|
|
105
|
+
|
|
106
|
+
// src/templates/route.ts
|
|
107
|
+
function pascalCase(name) {
|
|
108
|
+
return name.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
109
|
+
}
|
|
110
|
+
function camelCase(name) {
|
|
111
|
+
const [first, ...rest] = name.split("-");
|
|
112
|
+
return [first, ...rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1))].join("");
|
|
113
|
+
}
|
|
114
|
+
var HTTP_VERBS = ["get", "post", "put", "patch", "delete"];
|
|
115
|
+
function paramNamesFromPath(path) {
|
|
116
|
+
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
|
|
117
|
+
}
|
|
118
|
+
var PLACEHOLDER_COMMENT = "// No methods yet \u2014 run `bun run add-method` to add one.";
|
|
119
|
+
function renderBlankController() {
|
|
120
|
+
return `${PLACEHOLDER_COMMENT}
|
|
121
|
+
`;
|
|
122
|
+
}
|
|
123
|
+
function renderBlankRoutes(route, framework, language) {
|
|
124
|
+
const varName = `${camelCase(route)}Routes`;
|
|
125
|
+
if (framework === "express") {
|
|
126
|
+
return `import { Router } from "@mednours/backon/express";
|
|
127
|
+
|
|
128
|
+
export const ${varName} = Router();
|
|
129
|
+
|
|
130
|
+
${PLACEHOLDER_COMMENT}
|
|
131
|
+
`;
|
|
132
|
+
}
|
|
133
|
+
if (language === "javascript") {
|
|
134
|
+
return `import { Hono } from "@mednours/backon";
|
|
135
|
+
|
|
136
|
+
export const ${varName} = new Hono();
|
|
137
|
+
|
|
138
|
+
${PLACEHOLDER_COMMENT}
|
|
139
|
+
`;
|
|
140
|
+
}
|
|
141
|
+
return `import { Hono, type Env } from "@mednours/backon";
|
|
142
|
+
|
|
143
|
+
export const ${varName} = new Hono<Env>();
|
|
144
|
+
|
|
145
|
+
${PLACEHOLDER_COMMENT}
|
|
146
|
+
`;
|
|
147
|
+
}
|
|
148
|
+
function renderBlankServices() {
|
|
149
|
+
return `// No routes yet \u2014 service functions land here as methods are added via \`bun run add-method\`.
|
|
150
|
+
`;
|
|
151
|
+
}
|
|
152
|
+
function defaultServiceReturn(spec) {
|
|
153
|
+
const { verb, needsBody } = spec;
|
|
154
|
+
const hasParams = paramNamesFromPath(spec.path).length > 0;
|
|
155
|
+
if (verb === "get" && !hasParams) return "return [];";
|
|
156
|
+
if (verb === "get") return "return null; // TODO: fetch the real record";
|
|
157
|
+
if (verb === "post") return needsBody ? "return { id: crypto.randomUUID(), ...body };" : "return { id: crypto.randomUUID() };";
|
|
158
|
+
if (verb === "put" || verb === "patch") return needsBody ? "return { ...params, ...body };" : "return { ...params };";
|
|
159
|
+
return "return { success: true };";
|
|
160
|
+
}
|
|
161
|
+
function serviceCallArgs(spec) {
|
|
162
|
+
const args = [];
|
|
163
|
+
if (paramNamesFromPath(spec.path).length > 0) args.push("params");
|
|
164
|
+
if (spec.needsBody) args.push("body");
|
|
165
|
+
if (spec.needsQuery) args.push("query");
|
|
166
|
+
return args;
|
|
167
|
+
}
|
|
168
|
+
function serviceParamList(spec) {
|
|
169
|
+
const parts = [];
|
|
170
|
+
if (paramNamesFromPath(spec.path).length > 0) parts.push(`params: z.infer<typeof ${spec.name}ParamsSchema>`);
|
|
171
|
+
if (spec.needsBody) parts.push(`body: z.infer<typeof ${spec.name}BodySchema>`);
|
|
172
|
+
if (spec.needsQuery) parts.push(`query: z.infer<typeof ${spec.name}QuerySchema>`);
|
|
173
|
+
return parts.join(", ");
|
|
174
|
+
}
|
|
175
|
+
function controllerImports(route, framework) {
|
|
176
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
177
|
+
return [`import { z } from "zod";`, `import { defineRoute } from "${backonImport}";`, `import * as service from "./${route}.services";`];
|
|
178
|
+
}
|
|
179
|
+
function renderControllerMethod(spec) {
|
|
180
|
+
const paramNames = paramNamesFromPath(spec.path);
|
|
181
|
+
const lines = [];
|
|
182
|
+
if (paramNames.length > 0) {
|
|
183
|
+
const shape = paramNames.map((name) => `${name}: z.string()`).join(", ");
|
|
184
|
+
lines.push(`export const ${spec.name}ParamsSchema = z.object({ ${shape} });`);
|
|
185
|
+
}
|
|
186
|
+
if (spec.needsBody) {
|
|
187
|
+
lines.push(`// TODO: replace with the real shape of "${spec.name}"'s request body`);
|
|
188
|
+
lines.push(`export const ${spec.name}BodySchema = z.object({});`);
|
|
189
|
+
}
|
|
190
|
+
if (spec.needsQuery) {
|
|
191
|
+
lines.push(`// TODO: replace with the real shape of "${spec.name}"'s query params`);
|
|
192
|
+
lines.push(`export const ${spec.name}QuerySchema = z.object({});`);
|
|
193
|
+
}
|
|
194
|
+
const schemaEntries = [];
|
|
195
|
+
if (paramNames.length > 0) schemaEntries.push(`params: ${spec.name}ParamsSchema`);
|
|
196
|
+
if (spec.needsBody) schemaEntries.push(`body: ${spec.name}BodySchema`);
|
|
197
|
+
if (spec.needsQuery) schemaEntries.push(`query: ${spec.name}QuerySchema`);
|
|
198
|
+
const schemaObject = schemaEntries.length > 0 ? `{ ${schemaEntries.join(", ")} }` : "{}";
|
|
199
|
+
const callArgs = serviceCallArgs(spec).join(", ");
|
|
200
|
+
const status = spec.verb === "post" ? ", 201" : "";
|
|
201
|
+
lines.push(
|
|
202
|
+
`export const ${spec.name} = defineRoute(${schemaObject}, async (c, { body, query, params }) => {`,
|
|
203
|
+
` const result = await service.${spec.name}(${callArgs});`,
|
|
204
|
+
` return c.json(result${status});`,
|
|
205
|
+
`});`
|
|
206
|
+
);
|
|
207
|
+
return lines.join("\n");
|
|
208
|
+
}
|
|
209
|
+
function routeMountLine(route, spec) {
|
|
210
|
+
return `${camelCase(route)}Routes.${spec.verb}("${spec.path}", controller.${spec.name});`;
|
|
211
|
+
}
|
|
212
|
+
function serviceImports(route, spec, language) {
|
|
213
|
+
if (language === "javascript") return [];
|
|
214
|
+
const imports = [`import type { z } from "zod";`];
|
|
215
|
+
const named = [];
|
|
216
|
+
if (paramNamesFromPath(spec.path).length > 0) named.push(`${spec.name}ParamsSchema`);
|
|
217
|
+
if (spec.needsBody) named.push(`${spec.name}BodySchema`);
|
|
218
|
+
if (spec.needsQuery) named.push(`${spec.name}QuerySchema`);
|
|
219
|
+
if (named.length > 0) imports.push(`import type { ${named.join(", ")} } from "./${route}.controller";`);
|
|
220
|
+
return imports;
|
|
221
|
+
}
|
|
222
|
+
function renderServiceMethod(spec, language) {
|
|
223
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
224
|
+
const argList = language === "javascript" ? serviceCallArgs(spec).join(", ") : serviceParamList(spec);
|
|
225
|
+
return `// TODO: replace with real data access (see src/config/db.${ext})
|
|
226
|
+
export async function ${spec.name}(${argList}) {
|
|
227
|
+
${defaultServiceReturn(spec)}
|
|
228
|
+
}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/templates/db.ts
|
|
232
|
+
var TEMPLATES = {
|
|
233
|
+
neon: {
|
|
234
|
+
file: `import { drizzle } from "drizzle-orm/neon-http";
|
|
235
|
+
import { neon } from "@neondatabase/serverless";
|
|
236
|
+
|
|
237
|
+
if (!process.env.DATABASE_URL) {
|
|
238
|
+
throw new Error("DATABASE_URL is required (Neon connection string)");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const sql = neon(process.env.DATABASE_URL);
|
|
242
|
+
|
|
243
|
+
export const db = drizzle(sql);
|
|
244
|
+
`,
|
|
245
|
+
dependencies: {
|
|
246
|
+
"drizzle-orm": "^0.38.2",
|
|
247
|
+
"@neondatabase/serverless": "^0.10.4"
|
|
248
|
+
},
|
|
249
|
+
envVars: "DATABASE_URL=postgres://user:password@ep-example-123456.us-east-2.aws.neon.tech/dbname?sslmode=require\n",
|
|
250
|
+
readmeNote: "Uses Neon's HTTP driver \u2014 no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel)."
|
|
251
|
+
},
|
|
252
|
+
postgres: {
|
|
253
|
+
file: `import { drizzle } from "drizzle-orm/node-postgres";
|
|
254
|
+
import { Pool } from "pg";
|
|
255
|
+
|
|
256
|
+
// NOTE: this pooled connection is for local dev or a long-running server
|
|
257
|
+
// (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
|
|
258
|
+
// serverless functions \u2014 each cold start can open a new connection until
|
|
259
|
+
// the database's connection limit is exhausted. Use the "neon" db option
|
|
260
|
+
// instead for serverless deploys.
|
|
261
|
+
|
|
262
|
+
if (!process.env.DATABASE_URL) {
|
|
263
|
+
throw new Error("DATABASE_URL is required");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
267
|
+
|
|
268
|
+
export const db = drizzle(pool);
|
|
269
|
+
`,
|
|
270
|
+
dependencies: {
|
|
271
|
+
"drizzle-orm": "^0.38.2",
|
|
272
|
+
pg: "^8.13.1"
|
|
273
|
+
},
|
|
274
|
+
envVars: "DATABASE_URL=postgres://user:password@localhost:5432/dbname\n",
|
|
275
|
+
readmeNote: "Pooled Postgres connection \u2014 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."
|
|
276
|
+
},
|
|
277
|
+
sqlite: {
|
|
278
|
+
file: `import { drizzle } from "drizzle-orm/bun-sqlite";
|
|
279
|
+
import { Database } from "bun:sqlite";
|
|
280
|
+
|
|
281
|
+
// NOTE: local dev only. A serverless function's filesystem is ephemeral \u2014
|
|
282
|
+
// this file won't persist between invocations if deployed as-is.
|
|
283
|
+
|
|
284
|
+
const sqlite = new Database(process.env.DATABASE_URL ?? "./dev.db");
|
|
285
|
+
|
|
286
|
+
export const db = drizzle(sqlite);
|
|
287
|
+
`,
|
|
288
|
+
dependencies: {
|
|
289
|
+
"drizzle-orm": "^0.38.2"
|
|
290
|
+
},
|
|
291
|
+
envVars: "DATABASE_URL=./dev.db\n",
|
|
292
|
+
readmeNote: "Local file-based SQLite \u2014 for local dev only, not for a serverless deploy target."
|
|
293
|
+
},
|
|
294
|
+
none: {
|
|
295
|
+
file: `// No database configured yet. Wire up a real client here \u2014 e.g. one of
|
|
296
|
+
// the neon/postgres/sqlite variants this CLI can also generate \u2014 and
|
|
297
|
+
// export it as \`db\` so src/endpoints/*/*.services.ts can import it.
|
|
298
|
+
|
|
299
|
+
export const db = undefined;
|
|
300
|
+
`,
|
|
301
|
+
dependencies: {},
|
|
302
|
+
envVars: "",
|
|
303
|
+
readmeNote: "No database configured. src/config/db.ts is an empty stub."
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
function renderDbFile(db) {
|
|
307
|
+
return TEMPLATES[db].file;
|
|
308
|
+
}
|
|
309
|
+
function dbDependencies(db) {
|
|
310
|
+
return TEMPLATES[db].dependencies;
|
|
311
|
+
}
|
|
312
|
+
function dbEnvVars(db) {
|
|
313
|
+
return TEMPLATES[db].envVars;
|
|
314
|
+
}
|
|
315
|
+
function dbReadmeNote(db) {
|
|
316
|
+
return TEMPLATES[db].readmeNote;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/templates/base.ts
|
|
320
|
+
function renderIndexTs(framework) {
|
|
321
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
322
|
+
const call = framework === "express" ? "serve(app);" : "await serve(app);";
|
|
323
|
+
return `import { serve } from "${backonImport}";
|
|
324
|
+
import { app } from "./src/app";
|
|
325
|
+
|
|
326
|
+
${call}
|
|
327
|
+
`;
|
|
328
|
+
}
|
|
329
|
+
function renderAppTs(projectName, framework, deployTarget) {
|
|
330
|
+
const defaultExport = deployTarget === "vercel" ? `
|
|
331
|
+
// Vercel deploys straight from this export \u2014 see vercel.json.
|
|
332
|
+
export default app;
|
|
333
|
+
` : "";
|
|
334
|
+
if (framework === "express") {
|
|
335
|
+
return `import { createApp, serveApiDocs } from "@mednours/backon/express";
|
|
336
|
+
import { endpoints } from "./endpoints";
|
|
337
|
+
import { exampleMiddleware } from "./middleware/example.middleware";
|
|
338
|
+
|
|
339
|
+
export const app = createApp();
|
|
340
|
+
|
|
341
|
+
app.use(exampleMiddleware);
|
|
342
|
+
app.use("/", endpoints);
|
|
343
|
+
|
|
344
|
+
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
345
|
+
${defaultExport}`;
|
|
346
|
+
}
|
|
347
|
+
return `import { createApp, serveApiDocs } from "@mednours/backon";
|
|
348
|
+
import { endpoints } from "./endpoints";
|
|
349
|
+
import { exampleMiddleware } from "./middleware/example.middleware";
|
|
350
|
+
|
|
351
|
+
export const app = createApp();
|
|
352
|
+
|
|
353
|
+
app.use("*", exampleMiddleware);
|
|
354
|
+
app.route("/", endpoints);
|
|
355
|
+
|
|
356
|
+
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
357
|
+
${defaultExport}`;
|
|
358
|
+
}
|
|
359
|
+
function renderVercelJson() {
|
|
360
|
+
return `{
|
|
361
|
+
"$schema": "https://openapi.vercel.sh/vercel.json",
|
|
362
|
+
"bunVersion": "1.x"
|
|
363
|
+
}
|
|
364
|
+
`;
|
|
365
|
+
}
|
|
366
|
+
function renderExampleMiddleware(framework, language) {
|
|
367
|
+
if (framework === "express") {
|
|
368
|
+
if (language === "javascript") {
|
|
369
|
+
return `/**
|
|
370
|
+
* Example middleware, just to show the pattern \u2014 stamps a request-start
|
|
371
|
+
* timestamp onto res.locals. Error handling, request logging, secure
|
|
372
|
+
* headers, CORS, and the request body size limit are already wired into
|
|
373
|
+
* createApp() by backon itself; a separate
|
|
374
|
+
* error.middleware.js is only needed to override that default behavior.
|
|
375
|
+
*
|
|
376
|
+
* This is plain Express middleware (req, res, next), not backon's
|
|
377
|
+
* BackonContext \u2014 that wrapper only exists inside defineRoute() handlers.
|
|
378
|
+
* Middleware always operates at the framework's own layer. (Also: Express
|
|
379
|
+
* middleware can't safely set a response header after calling next() \u2014 by
|
|
380
|
+
* then the response may already be sent \u2014 which is why this demonstrates
|
|
381
|
+
* res.locals instead of a header.)
|
|
382
|
+
*
|
|
383
|
+
* @param {import("@mednours/backon/express").Request} req
|
|
384
|
+
* @param {import("@mednours/backon/express").Response} res
|
|
385
|
+
* @param {import("@mednours/backon/express").NextFunction} next
|
|
386
|
+
*/
|
|
387
|
+
export function exampleMiddleware(req, res, next) {
|
|
388
|
+
res.locals.requestStartedAt = Date.now();
|
|
389
|
+
next();
|
|
390
|
+
}
|
|
391
|
+
`;
|
|
392
|
+
}
|
|
393
|
+
return `import type { Request, Response, NextFunction } from "@mednours/backon/express";
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Example middleware, just to show the pattern \u2014 stamps a request-start
|
|
397
|
+
* timestamp onto res.locals. Error handling, request logging, secure
|
|
398
|
+
* headers, CORS, and the request body size limit are already wired into
|
|
399
|
+
* createApp() by backon itself; a separate
|
|
400
|
+
* error.middleware.ts is only needed to override that default behavior.
|
|
401
|
+
*
|
|
402
|
+
* This is plain Express middleware (req, res, next), not backon's
|
|
403
|
+
* BackonContext \u2014 that wrapper only exists inside defineRoute() handlers.
|
|
404
|
+
* Middleware always operates at the framework's own layer. (Also: Express
|
|
405
|
+
* middleware can't safely set a response header after calling next() \u2014 by
|
|
406
|
+
* then the response may already be sent \u2014 which is why this demonstrates
|
|
407
|
+
* res.locals instead of a header.)
|
|
408
|
+
*/
|
|
409
|
+
export function exampleMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
410
|
+
res.locals.requestStartedAt = Date.now();
|
|
411
|
+
next();
|
|
412
|
+
}
|
|
413
|
+
`;
|
|
414
|
+
}
|
|
415
|
+
if (language === "javascript") {
|
|
416
|
+
return `/**
|
|
417
|
+
* Example middleware, just to show the pattern \u2014 adds a response-time
|
|
418
|
+
* header. Error handling, request logging, secure headers, CORS, and the
|
|
419
|
+
* request body size limit are already wired into createApp() by backon
|
|
420
|
+
* itself; a separate error.middleware.js is only needed to override that
|
|
421
|
+
* default behavior.
|
|
422
|
+
*
|
|
423
|
+
* @param {import("@mednours/backon").BackonContext} c
|
|
424
|
+
* @param {import("@mednours/backon").Next} next
|
|
425
|
+
*/
|
|
426
|
+
export async function exampleMiddleware(c, next) {
|
|
427
|
+
const start = performance.now();
|
|
428
|
+
await next();
|
|
429
|
+
c.header("x-response-time-ms", String(Math.round(performance.now() - start)));
|
|
430
|
+
}
|
|
431
|
+
`;
|
|
432
|
+
}
|
|
433
|
+
return `import type { Next } from "@mednours/backon";
|
|
434
|
+
import type { BackonContext } from "@mednours/backon";
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Example middleware, just to show the pattern \u2014 adds a response-time
|
|
438
|
+
* header. Error handling, request logging, secure headers, CORS, and the
|
|
439
|
+
* request body size limit are already wired into createApp() by backon
|
|
440
|
+
* itself; a separate error.middleware.ts is only needed to override that
|
|
441
|
+
* default behavior.
|
|
442
|
+
*/
|
|
443
|
+
export async function exampleMiddleware(c: BackonContext, next: Next) {
|
|
444
|
+
const start = performance.now();
|
|
445
|
+
await next();
|
|
446
|
+
c.header("x-response-time-ms", String(Math.round(performance.now() - start)));
|
|
447
|
+
}
|
|
448
|
+
`;
|
|
449
|
+
}
|
|
450
|
+
function renderEndpointsIndex(framework, routes) {
|
|
451
|
+
const imports = routes.map((route) => `import { ${camelCase(route)}Routes } from "./${route}/${route}.routes";`).join("\n");
|
|
452
|
+
if (framework === "express") {
|
|
453
|
+
const mounts2 = routes.map((route) => `endpoints.use("/${route}", ${camelCase(route)}Routes);`).join("\n");
|
|
454
|
+
return `import { Router } from "@mednours/backon/express";
|
|
455
|
+
${imports}
|
|
456
|
+
|
|
457
|
+
export const endpoints = Router();
|
|
458
|
+
|
|
459
|
+
${mounts2}
|
|
460
|
+
`;
|
|
461
|
+
}
|
|
462
|
+
const mounts = routes.map((route) => `endpoints.route("/${route}", ${camelCase(route)}Routes);`).join("\n");
|
|
463
|
+
return `import { Hono } from "@mednours/backon";
|
|
464
|
+
${imports}
|
|
465
|
+
|
|
466
|
+
export const endpoints = new Hono();
|
|
467
|
+
|
|
468
|
+
${mounts}
|
|
469
|
+
`;
|
|
470
|
+
}
|
|
471
|
+
function renderGenerateDocsScript(projectName, framework) {
|
|
472
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
473
|
+
return `import { writeFileSync } from "node:fs";
|
|
474
|
+
import { generateOpenApiSpec, apiReferenceHtmlInline } from "${backonImport}";
|
|
475
|
+
import { app } from "../src/app";
|
|
476
|
+
|
|
477
|
+
const spec = generateOpenApiSpec(app, { title: "${projectName}", version: "0.1.0" });
|
|
478
|
+
writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
479
|
+
writeFileSync("docs.html", apiReferenceHtmlInline(spec, "${projectName}"));
|
|
480
|
+
|
|
481
|
+
console.log("Wrote openapi.json and docs.html");
|
|
482
|
+
`;
|
|
483
|
+
}
|
|
484
|
+
function renderEnvExample(db) {
|
|
485
|
+
return `PORT=3000
|
|
486
|
+
ALLOWED_ORIGINS=
|
|
487
|
+
${dbEnvVars(db)}`;
|
|
488
|
+
}
|
|
489
|
+
function renderTsconfig() {
|
|
490
|
+
return `{
|
|
491
|
+
"compilerOptions": {
|
|
492
|
+
"target": "ESNext",
|
|
493
|
+
"module": "ESNext",
|
|
494
|
+
"moduleResolution": "bundler",
|
|
495
|
+
"lib": ["ESNext"],
|
|
496
|
+
"types": ["bun"],
|
|
497
|
+
"strict": true,
|
|
498
|
+
"esModuleInterop": true,
|
|
499
|
+
"skipLibCheck": true,
|
|
500
|
+
"forceConsistentCasingInFileNames": true,
|
|
501
|
+
"resolveJsonModule": true,
|
|
502
|
+
"isolatedModules": true,
|
|
503
|
+
"noEmit": true,
|
|
504
|
+
"allowJs": false
|
|
505
|
+
},
|
|
506
|
+
"include": ["index.ts", "src", "scripts"]
|
|
507
|
+
}
|
|
508
|
+
`;
|
|
509
|
+
}
|
|
510
|
+
function renderJsconfig() {
|
|
511
|
+
return `{
|
|
512
|
+
"compilerOptions": {
|
|
513
|
+
"target": "ESNext",
|
|
514
|
+
"module": "ESNext",
|
|
515
|
+
"moduleResolution": "bundler",
|
|
516
|
+
"lib": ["ESNext"],
|
|
517
|
+
"checkJs": false,
|
|
518
|
+
"allowJs": true
|
|
519
|
+
},
|
|
520
|
+
"include": ["index.js", "src", "scripts"]
|
|
521
|
+
}
|
|
522
|
+
`;
|
|
523
|
+
}
|
|
524
|
+
function renderPackageJson(projectName, framework, language, db) {
|
|
525
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
526
|
+
const dependencies = framework === "express" ? {
|
|
527
|
+
"@mednours/backon": "latest",
|
|
528
|
+
express: "^4.21.0",
|
|
529
|
+
cors: "^2.8.5",
|
|
530
|
+
helmet: "^8.0.0",
|
|
531
|
+
compression: "^1.7.5",
|
|
532
|
+
zod: "^3.24.1",
|
|
533
|
+
...dbDependencies(db)
|
|
534
|
+
} : {
|
|
535
|
+
"@mednours/backon": "latest",
|
|
536
|
+
hono: "^4.6.14",
|
|
537
|
+
zod: "^3.24.1",
|
|
538
|
+
...dbDependencies(db)
|
|
539
|
+
};
|
|
540
|
+
const devDependencies = language === "javascript" ? {} : framework === "express" ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" } : { "@types/bun": "latest", typescript: "^5.7.2" };
|
|
541
|
+
const scripts = {
|
|
542
|
+
dev: `bun run --watch index.${ext}`,
|
|
543
|
+
start: `bun run index.${ext}`,
|
|
544
|
+
test: "bun test",
|
|
545
|
+
// Thin aliases over `bunx create-backon <subcommand>` — running
|
|
546
|
+
// `bun run add-route users` from inside the project is shorter than
|
|
547
|
+
// remembering the create-backon invocation, and bun forwards extra
|
|
548
|
+
// arguments (like the route name) straight through without needing
|
|
549
|
+
// a `--` separator.
|
|
550
|
+
"add-route": "bunx create-backon add-route",
|
|
551
|
+
"add-method": "bunx create-backon add-method",
|
|
552
|
+
"remove-route": "bunx create-backon remove-route",
|
|
553
|
+
"list-routes": "bunx create-backon list-routes",
|
|
554
|
+
doctor: "bunx create-backon doctor",
|
|
555
|
+
docs: `bun run scripts/generate-docs.${ext}`
|
|
556
|
+
};
|
|
557
|
+
if (language === "typescript") {
|
|
558
|
+
scripts.typecheck = "tsc --noEmit";
|
|
559
|
+
}
|
|
560
|
+
const pkg = {
|
|
561
|
+
name: projectName,
|
|
562
|
+
version: "0.1.0",
|
|
563
|
+
private: true,
|
|
564
|
+
type: "module",
|
|
565
|
+
scripts,
|
|
566
|
+
dependencies,
|
|
567
|
+
devDependencies
|
|
568
|
+
};
|
|
569
|
+
return `${JSON.stringify(pkg, null, 2)}
|
|
570
|
+
`;
|
|
571
|
+
}
|
|
572
|
+
function renderDeploySection(deployTarget, ext) {
|
|
573
|
+
switch (deployTarget) {
|
|
574
|
+
case "vercel":
|
|
575
|
+
return `## Deploying
|
|
576
|
+
|
|
577
|
+
Set up for [Vercel](https://vercel.com)'s zero-config Hono/Express support:
|
|
578
|
+
\`src/app.${ext}\` has a default export (Vercel deploys straight from it,
|
|
579
|
+
bypassing \`index.${ext}\`/\`serve()\` \u2014 those keep working locally exactly as
|
|
580
|
+
before), and \`vercel.json\` pins the Bun runtime so the deployed function
|
|
581
|
+
matches local dev. Connect the repo on [vercel.com/new](https://vercel.com/new)
|
|
582
|
+
or run \`vercel deploy\` \u2014 no other configuration needed. \`vercel dev\` runs it
|
|
583
|
+
locally the same way it'll run once deployed.
|
|
584
|
+
`;
|
|
585
|
+
case "node":
|
|
586
|
+
return `## Deploying
|
|
587
|
+
|
|
588
|
+
No deploy-specific files here \u2014 \`index.${ext}\` calls \`serve(app)\`, which
|
|
589
|
+
listens on \`PORT\` (see \`.env.example\`) wherever it's run. That's what
|
|
590
|
+
Render, Railway, Fly, a plain VPS, or any other Node/Bun host expects: point
|
|
591
|
+
the platform's start command at \`bun run start\` (or \`bun run index.${ext}\`)
|
|
592
|
+
and set \`PORT\`/your database env vars in its dashboard.
|
|
593
|
+
`;
|
|
594
|
+
case "local":
|
|
595
|
+
return `## Deploying
|
|
596
|
+
|
|
597
|
+
Not set up for a specific host \u2014 \`bun run start\` runs \`index.${ext}\`, which
|
|
598
|
+
listens on \`PORT\` (see \`.env.example\`). Point any Node/Bun-capable host's
|
|
599
|
+
start command at that when you're ready.
|
|
600
|
+
`;
|
|
601
|
+
default:
|
|
602
|
+
return `## Deploying
|
|
603
|
+
|
|
604
|
+
Not decided yet \u2014 \`index.${ext}\` already calls \`serve(app)\`, listening on
|
|
605
|
+
\`PORT\` (see \`.env.example\`), which is all most Node/Bun hosts need. For
|
|
606
|
+
[Vercel](https://vercel.com) specifically, add a default export to
|
|
607
|
+
\`src/app.${ext}\` (\`export default app;\`) and a \`vercel.json\` with
|
|
608
|
+
\`{ "bunVersion": "1.x" }\` \u2014 or re-run \`create-backon\` and pick Vercel to get
|
|
609
|
+
both for free.
|
|
610
|
+
`;
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
function renderReadme(answers) {
|
|
614
|
+
const routeList = answers.routes.length ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n") : "- (none yet \u2014 add one under src/endpoints/)";
|
|
615
|
+
const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
616
|
+
const languageLabel = answers.language === "javascript" ? "JavaScript" : "TypeScript";
|
|
617
|
+
const ext = answers.language === "javascript" ? "js" : "ts";
|
|
618
|
+
return `# ${answers.projectName}
|
|
619
|
+
|
|
620
|
+
Generated by \`create-backon\` (${answers.framework}, ${languageLabel}).
|
|
621
|
+
|
|
622
|
+
## Getting started
|
|
623
|
+
|
|
624
|
+
\`\`\`
|
|
625
|
+
bun install
|
|
626
|
+
cp .env.example .env # fill in real values
|
|
627
|
+
bun run dev
|
|
628
|
+
\`\`\`
|
|
629
|
+
|
|
630
|
+
Once running, \`http://localhost:3000/docs\` has a live API reference for
|
|
631
|
+
every route added via \`defineRoute\` \u2014 \`bun run docs\` also writes the same
|
|
632
|
+
document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
|
|
633
|
+
|
|
634
|
+
## Database: ${answers.db}
|
|
635
|
+
|
|
636
|
+
${dbReadmeNote(answers.db)}
|
|
637
|
+
|
|
638
|
+
## Routes
|
|
639
|
+
|
|
640
|
+
${routeList}
|
|
641
|
+
|
|
642
|
+
Each route folder follows the same shape: \`*.routes.${answers.language === "javascript" ? "js" : "ts"}\` wires HTTP
|
|
643
|
+
methods to controller functions, \`*.controller.${answers.language === "javascript" ? "js" : "ts"}\` validates the
|
|
644
|
+
request (via \`defineRoute\` from \`${backonImport}\`) and calls into
|
|
645
|
+
\`*.services.${answers.language === "javascript" ? "js" : "ts"}\`, which is where real data access belongs.
|
|
646
|
+
|
|
647
|
+
${renderDeploySection(answers.deployTarget, ext)}`;
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/generate.ts
|
|
651
|
+
async function write(path, contents) {
|
|
652
|
+
await mkdir(dirname(path), { recursive: true });
|
|
653
|
+
await writeFile(path, contents);
|
|
654
|
+
}
|
|
655
|
+
var IGNORABLE_ENTRIES = /* @__PURE__ */ new Set([
|
|
656
|
+
".git",
|
|
657
|
+
".gitignore",
|
|
658
|
+
".github",
|
|
659
|
+
".idea",
|
|
660
|
+
".vscode",
|
|
661
|
+
".DS_Store",
|
|
662
|
+
"LICENSE",
|
|
663
|
+
"LICENSE.md",
|
|
664
|
+
"README.md"
|
|
665
|
+
]);
|
|
666
|
+
async function ensureSafeToWrite(root) {
|
|
667
|
+
let entries;
|
|
668
|
+
try {
|
|
669
|
+
entries = await readdir(root);
|
|
670
|
+
} catch (err) {
|
|
671
|
+
if (err.code === "ENOENT") return;
|
|
672
|
+
throw err;
|
|
673
|
+
}
|
|
674
|
+
const meaningful = entries.filter((name) => !IGNORABLE_ENTRIES.has(name));
|
|
675
|
+
if (meaningful.length > 0) {
|
|
676
|
+
const shown = meaningful.slice(0, 5).join(", ") + (meaningful.length > 5 ? ", ..." : "");
|
|
677
|
+
throw new Error(
|
|
678
|
+
`Refusing to scaffold into ${root} \u2014 it already has files in it (${shown}). Clear it out first, or pick an empty/new directory.`
|
|
679
|
+
);
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
async function generateProject(answers, cwd = process.cwd()) {
|
|
683
|
+
const root = answers.projectName === "." ? cwd : join(cwd, answers.projectName);
|
|
684
|
+
const packageName = answers.projectName === "." ? basename(root) || "app" : answers.projectName;
|
|
685
|
+
const readmeAnswers = { ...answers, projectName: packageName };
|
|
686
|
+
const ext = answers.language === "javascript" ? "js" : "ts";
|
|
687
|
+
await ensureSafeToWrite(root);
|
|
688
|
+
const filesWritten = [];
|
|
689
|
+
const files = [
|
|
690
|
+
[join(root, `index.${ext}`), renderIndexTs(answers.framework)],
|
|
691
|
+
[join(root, ".env.example"), renderEnvExample(answers.db)],
|
|
692
|
+
...answers.copyEnv ? [[join(root, ".env"), renderEnvExample(answers.db)]] : [],
|
|
693
|
+
[join(root, "package.json"), renderPackageJson(packageName, answers.framework, answers.language, answers.db)],
|
|
694
|
+
answers.language === "javascript" ? [join(root, "jsconfig.json"), renderJsconfig()] : [join(root, "tsconfig.json"), renderTsconfig()],
|
|
695
|
+
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
696
|
+
[
|
|
697
|
+
join(root, ".gitignore"),
|
|
698
|
+
`node_modules/
|
|
699
|
+
dist/
|
|
700
|
+
*.log
|
|
701
|
+
.env
|
|
702
|
+
.env.local
|
|
703
|
+
openapi.json
|
|
704
|
+
docs.html
|
|
705
|
+
${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
|
|
706
|
+
],
|
|
707
|
+
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
708
|
+
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
709
|
+
[
|
|
710
|
+
join(root, `src/middleware/example.middleware.${ext}`),
|
|
711
|
+
renderExampleMiddleware(answers.framework, answers.language)
|
|
712
|
+
],
|
|
713
|
+
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
714
|
+
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
715
|
+
...answers.deployTarget === "vercel" ? [[join(root, "vercel.json"), renderVercelJson()]] : []
|
|
716
|
+
];
|
|
717
|
+
for (const route of answers.routes) {
|
|
718
|
+
const dir = join(root, "src/endpoints", route);
|
|
719
|
+
files.push(
|
|
720
|
+
[join(dir, `${route}.controller.${ext}`), renderBlankController()],
|
|
721
|
+
[join(dir, `${route}.routes.${ext}`), renderBlankRoutes(route, answers.framework, answers.language)],
|
|
722
|
+
[join(dir, `${route}.services.${ext}`), renderBlankServices()]
|
|
723
|
+
);
|
|
724
|
+
}
|
|
725
|
+
for (const [path, contents] of files) {
|
|
726
|
+
await write(path, contents);
|
|
727
|
+
filesWritten.push(path);
|
|
728
|
+
}
|
|
729
|
+
return { root, filesWritten };
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// src/add-route.ts
|
|
733
|
+
import { mkdir as mkdir2, readdir as readdir2, writeFile as writeFile2 } from "node:fs/promises";
|
|
734
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
735
|
+
|
|
736
|
+
// src/detect.ts
|
|
737
|
+
import { readFile } from "node:fs/promises";
|
|
738
|
+
import { join as join2 } from "node:path";
|
|
739
|
+
async function detectProject(cwd = process.cwd()) {
|
|
740
|
+
const pkgPath = join2(cwd, "package.json");
|
|
741
|
+
let raw;
|
|
742
|
+
try {
|
|
743
|
+
raw = await readFile(pkgPath, "utf-8");
|
|
744
|
+
} catch (err) {
|
|
745
|
+
if (err.code === "ENOENT") {
|
|
746
|
+
throw new Error(`No package.json found in ${cwd} \u2014 run this from a project created by \`bun create backon\`.`);
|
|
747
|
+
}
|
|
748
|
+
throw err;
|
|
749
|
+
}
|
|
750
|
+
let pkg;
|
|
751
|
+
try {
|
|
752
|
+
pkg = JSON.parse(raw);
|
|
753
|
+
} catch {
|
|
754
|
+
throw new Error(`Couldn't parse ${pkgPath} as JSON.`);
|
|
755
|
+
}
|
|
756
|
+
const dependencies = pkg.dependencies ?? {};
|
|
757
|
+
const devDependencies = pkg.devDependencies ?? {};
|
|
758
|
+
if (!dependencies["@mednours/backon"]) {
|
|
759
|
+
throw new Error(`${cwd} doesn't look like a backon project \u2014 package.json has no "@mednours/backon" dependency.`);
|
|
760
|
+
}
|
|
761
|
+
const framework = dependencies.express ? "express" : "hono";
|
|
762
|
+
const language = devDependencies.typescript ? "typescript" : "javascript";
|
|
763
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
764
|
+
return { root: cwd, framework, language, ext };
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// src/endpoints-index.ts
|
|
768
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
769
|
+
import { join as join3 } from "node:path";
|
|
770
|
+
var MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
|
|
771
|
+
function parseMountedRoutes(indexContents) {
|
|
772
|
+
const routes = [];
|
|
773
|
+
for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
|
|
774
|
+
routes.push(match[1]);
|
|
775
|
+
}
|
|
776
|
+
return routes;
|
|
777
|
+
}
|
|
778
|
+
async function readEndpointsIndex(root, ext) {
|
|
779
|
+
const path = join3(root, "src/endpoints", `index.${ext}`);
|
|
780
|
+
let contents;
|
|
781
|
+
try {
|
|
782
|
+
contents = await readFile2(path, "utf-8");
|
|
783
|
+
} catch (err) {
|
|
784
|
+
if (err.code === "ENOENT") {
|
|
785
|
+
throw new Error(`${path} doesn't exist \u2014 is this a backon project?`);
|
|
786
|
+
}
|
|
787
|
+
throw err;
|
|
788
|
+
}
|
|
789
|
+
return { path, contents };
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// src/add-route.ts
|
|
793
|
+
async function write2(path, contents) {
|
|
794
|
+
await mkdir2(dirname2(path), { recursive: true });
|
|
795
|
+
await writeFile2(path, contents);
|
|
796
|
+
}
|
|
797
|
+
async function addRoute(rawName, cwd = process.cwd()) {
|
|
798
|
+
const route = toKebabCase(rawName);
|
|
799
|
+
if (!route) {
|
|
800
|
+
throw new Error("Route name can't be empty.");
|
|
801
|
+
}
|
|
802
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
803
|
+
const endpointsDir = join4(root, "src/endpoints");
|
|
804
|
+
let dirEntries;
|
|
805
|
+
try {
|
|
806
|
+
dirEntries = await readdir2(endpointsDir);
|
|
807
|
+
} catch (err) {
|
|
808
|
+
if (err.code === "ENOENT") {
|
|
809
|
+
throw new Error(`${endpointsDir} doesn't exist \u2014 is this a backon project?`);
|
|
810
|
+
}
|
|
811
|
+
throw err;
|
|
812
|
+
}
|
|
813
|
+
if (dirEntries.includes(route)) {
|
|
814
|
+
throw new Error(`src/endpoints/${route} already exists.`);
|
|
815
|
+
}
|
|
816
|
+
const { path: indexPath, contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
817
|
+
const existingRoutes = parseMountedRoutes(indexContents);
|
|
818
|
+
if (existingRoutes.includes(route)) {
|
|
819
|
+
throw new Error(`"${route}" is already mounted in ${indexPath}.`);
|
|
820
|
+
}
|
|
821
|
+
const routeDir = join4(endpointsDir, route);
|
|
822
|
+
const filesWritten = [];
|
|
823
|
+
const files = [
|
|
824
|
+
[join4(routeDir, `${route}.controller.${ext}`), renderBlankController()],
|
|
825
|
+
[join4(routeDir, `${route}.routes.${ext}`), renderBlankRoutes(route, framework, language)],
|
|
826
|
+
[join4(routeDir, `${route}.services.${ext}`), renderBlankServices()]
|
|
827
|
+
];
|
|
828
|
+
for (const [path, contents] of files) {
|
|
829
|
+
await write2(path, contents);
|
|
830
|
+
filesWritten.push(path);
|
|
831
|
+
}
|
|
832
|
+
const allRoutes = [...existingRoutes, route];
|
|
833
|
+
await writeFile2(indexPath, renderEndpointsIndex(framework, allRoutes));
|
|
834
|
+
filesWritten.push(indexPath);
|
|
835
|
+
return { route, root, filesWritten };
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// src/remove-route.ts
|
|
839
|
+
import { rm, writeFile as writeFile3 } from "node:fs/promises";
|
|
840
|
+
import { join as join5 } from "node:path";
|
|
841
|
+
async function removeRoute(rawName, cwd = process.cwd()) {
|
|
842
|
+
const route = toKebabCase(rawName);
|
|
843
|
+
if (!route) {
|
|
844
|
+
throw new Error("Route name can't be empty.");
|
|
845
|
+
}
|
|
846
|
+
const { root, framework, ext } = await detectProject(cwd);
|
|
847
|
+
const { path: indexPath, contents } = await readEndpointsIndex(root, ext);
|
|
848
|
+
const mounted = parseMountedRoutes(contents);
|
|
849
|
+
if (!mounted.includes(route)) {
|
|
850
|
+
throw new Error(`"${route}" isn't mounted in ${indexPath} \u2014 nothing to remove.`);
|
|
851
|
+
}
|
|
852
|
+
const remaining = mounted.filter((name) => name !== route);
|
|
853
|
+
await writeFile3(indexPath, renderEndpointsIndex(framework, remaining));
|
|
854
|
+
const removedDir = join5(root, "src/endpoints", route);
|
|
855
|
+
await rm(removedDir, { recursive: true, force: true });
|
|
856
|
+
return { route, root, removedDir };
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
// src/list-routes.ts
|
|
860
|
+
async function listRoutes(cwd = process.cwd()) {
|
|
861
|
+
const { root, ext } = await detectProject(cwd);
|
|
862
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
863
|
+
return { root, routes: parseMountedRoutes(contents) };
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
// src/doctor.ts
|
|
867
|
+
import { access, readdir as readdir3 } from "node:fs/promises";
|
|
868
|
+
import { join as join6 } from "node:path";
|
|
869
|
+
var ROUTE_FILE_SUFFIXES = ["controller", "routes", "services"];
|
|
870
|
+
async function runDoctor(cwd = process.cwd()) {
|
|
871
|
+
const { root, ext } = await detectProject(cwd);
|
|
872
|
+
const endpointsDir = join6(root, "src/endpoints");
|
|
873
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
874
|
+
const mounted = new Set(parseMountedRoutes(contents));
|
|
875
|
+
const dirents = await readdir3(endpointsDir, { withFileTypes: true }).catch((err) => {
|
|
876
|
+
if (err.code === "ENOENT") return [];
|
|
877
|
+
throw err;
|
|
878
|
+
});
|
|
879
|
+
const folders = dirents.filter((d) => d.isDirectory()).map((d) => d.name);
|
|
880
|
+
const folderSet = new Set(folders);
|
|
881
|
+
const issues = [];
|
|
882
|
+
for (const route of mounted) {
|
|
883
|
+
if (!folderSet.has(route)) {
|
|
884
|
+
issues.push({
|
|
885
|
+
kind: "dangling-mount",
|
|
886
|
+
route,
|
|
887
|
+
detail: `index.${ext} mounts "/${route}" but src/endpoints/${route}/ doesn't exist.`
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
for (const route of folders) {
|
|
892
|
+
if (!mounted.has(route)) {
|
|
893
|
+
issues.push({
|
|
894
|
+
kind: "orphaned-folder",
|
|
895
|
+
route,
|
|
896
|
+
detail: `src/endpoints/${route}/ exists but isn't mounted in index.${ext}.`
|
|
897
|
+
});
|
|
898
|
+
}
|
|
899
|
+
for (const suffix of ROUTE_FILE_SUFFIXES) {
|
|
900
|
+
const filePath = join6(endpointsDir, route, `${route}.${suffix}.${ext}`);
|
|
901
|
+
try {
|
|
902
|
+
await access(filePath);
|
|
903
|
+
} catch {
|
|
904
|
+
issues.push({ kind: "missing-file", route, detail: `${filePath} is missing.` });
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
}
|
|
908
|
+
return { root, issues };
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// src/add-method.ts
|
|
912
|
+
import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
|
|
913
|
+
import { join as join8 } from "node:path";
|
|
914
|
+
|
|
915
|
+
// src/route-methods.ts
|
|
916
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
917
|
+
import { join as join7 } from "node:path";
|
|
918
|
+
|
|
919
|
+
// src/colors.ts
|
|
920
|
+
var VERB_CODES = {
|
|
921
|
+
get: "36",
|
|
922
|
+
post: "32",
|
|
923
|
+
put: "33",
|
|
924
|
+
patch: "35",
|
|
925
|
+
delete: "31"
|
|
926
|
+
};
|
|
927
|
+
var RESET = "\x1B[0m";
|
|
928
|
+
function colorVerb(verb) {
|
|
929
|
+
const label = verb.toUpperCase().padEnd(6);
|
|
930
|
+
const code = VERB_CODES[verb];
|
|
931
|
+
return code ? `\x1B[${code}m${label}${RESET}` : label;
|
|
932
|
+
}
|
|
933
|
+
function dim(text3) {
|
|
934
|
+
return `\x1B[2m${text3}${RESET}`;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// src/route-methods.ts
|
|
938
|
+
var METHOD_MOUNT_PATTERN = /\.(get|post|put|patch|delete)\(\s*"([^"]*)"\s*,\s*controller\.(\w+)\s*\)/g;
|
|
939
|
+
function parseRouteMethods(routesFileContents) {
|
|
940
|
+
const methods = [];
|
|
941
|
+
for (const match of routesFileContents.matchAll(METHOD_MOUNT_PATTERN)) {
|
|
942
|
+
const [, verb, path, name] = match;
|
|
943
|
+
if (verb && path !== void 0 && name) {
|
|
944
|
+
methods.push({ verb, path, name });
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
return methods;
|
|
948
|
+
}
|
|
949
|
+
async function listEndpointsWithMethods(cwd = process.cwd()) {
|
|
950
|
+
const { root, ext } = await detectProject(cwd);
|
|
951
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
952
|
+
const routes = parseMountedRoutes(contents);
|
|
953
|
+
const summaries = [];
|
|
954
|
+
for (const route of routes) {
|
|
955
|
+
const routesFilePath = join7(root, "src/endpoints", route, `${route}.routes.${ext}`);
|
|
956
|
+
let routesFileContents;
|
|
957
|
+
try {
|
|
958
|
+
routesFileContents = await readFile3(routesFilePath, "utf-8");
|
|
959
|
+
} catch {
|
|
960
|
+
summaries.push({ route, methods: [] });
|
|
961
|
+
continue;
|
|
962
|
+
}
|
|
963
|
+
summaries.push({ route, methods: parseRouteMethods(routesFileContents) });
|
|
964
|
+
}
|
|
965
|
+
return summaries;
|
|
966
|
+
}
|
|
967
|
+
function formatEndpointsDashboard(summaries) {
|
|
968
|
+
if (summaries.length === 0) return dim("No endpoints yet.");
|
|
969
|
+
return summaries.map(({ route, methods }) => {
|
|
970
|
+
if (methods.length === 0) return `${route}
|
|
971
|
+
${dim("(no methods yet)")}`;
|
|
972
|
+
const lines = methods.map((m) => ` ${colorVerb(m.verb)} ${m.path} ${dim(`\u2192 ${m.name}`)}`);
|
|
973
|
+
return `${route}
|
|
974
|
+
${lines.join("\n")}`;
|
|
975
|
+
}).join("\n\n");
|
|
976
|
+
}
|
|
977
|
+
|
|
978
|
+
// src/add-method.ts
|
|
979
|
+
var PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
|
|
980
|
+
function stripPlaceholder(content) {
|
|
981
|
+
return content.replace(PLACEHOLDER_PATTERN, "");
|
|
982
|
+
}
|
|
983
|
+
function ensureImports(content, importLines) {
|
|
984
|
+
const stripped = stripPlaceholder(content);
|
|
985
|
+
const missing = importLines.filter((line) => !stripped.includes(line));
|
|
986
|
+
if (missing.length === 0) return stripped;
|
|
987
|
+
const lines = stripped.split("\n");
|
|
988
|
+
let insertAt = 0;
|
|
989
|
+
while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
|
|
990
|
+
lines.splice(insertAt, 0, ...missing);
|
|
991
|
+
return lines.join("\n");
|
|
992
|
+
}
|
|
993
|
+
function appendBlock(content, block) {
|
|
994
|
+
const trimmed = content.replace(/\n+$/, "");
|
|
995
|
+
return trimmed ? `${trimmed}
|
|
996
|
+
|
|
997
|
+
${block}
|
|
998
|
+
` : `${block}
|
|
999
|
+
`;
|
|
1000
|
+
}
|
|
1001
|
+
async function addMethod(route, spec, cwd = process.cwd()) {
|
|
1002
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
1003
|
+
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
1004
|
+
const mounted = parseMountedRoutes(indexContents);
|
|
1005
|
+
if (!mounted.includes(route)) {
|
|
1006
|
+
throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext} \u2014 add it first with \`bun run add-route\`.`);
|
|
1007
|
+
}
|
|
1008
|
+
const routeDir = join8(root, "src/endpoints", route);
|
|
1009
|
+
const controllerPath = join8(routeDir, `${route}.controller.${ext}`);
|
|
1010
|
+
const routesPath = join8(routeDir, `${route}.routes.${ext}`);
|
|
1011
|
+
const servicesPath = join8(routeDir, `${route}.services.${ext}`);
|
|
1012
|
+
const [controllerContents, routesContents, servicesContents] = await Promise.all([
|
|
1013
|
+
readFile4(controllerPath, "utf-8"),
|
|
1014
|
+
readFile4(routesPath, "utf-8"),
|
|
1015
|
+
readFile4(servicesPath, "utf-8")
|
|
1016
|
+
]);
|
|
1017
|
+
const existing = parseRouteMethods(routesContents);
|
|
1018
|
+
if (existing.some((m) => m.name === spec.name)) {
|
|
1019
|
+
throw new Error(`"${spec.name}" is already used in ${controllerPath} \u2014 pick a different name.`);
|
|
1020
|
+
}
|
|
1021
|
+
if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
|
|
1022
|
+
throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
|
|
1023
|
+
}
|
|
1024
|
+
const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
|
|
1025
|
+
const newRoutes = appendBlock(
|
|
1026
|
+
ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
|
|
1027
|
+
routeMountLine(route, spec)
|
|
1028
|
+
);
|
|
1029
|
+
const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
|
|
1030
|
+
await Promise.all([
|
|
1031
|
+
writeFile4(controllerPath, newController),
|
|
1032
|
+
writeFile4(routesPath, newRoutes),
|
|
1033
|
+
writeFile4(servicesPath, newServices)
|
|
1034
|
+
]);
|
|
1035
|
+
return { route, root, filesWritten: [controllerPath, routesPath, servicesPath] };
|
|
1036
|
+
}
|
|
1037
|
+
|
|
1038
|
+
// src/cli.ts
|
|
1039
|
+
var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
|
|
1040
|
+
var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
|
|
1041
|
+
var LIST_ROUTES_SUBCOMMANDS = /* @__PURE__ */ new Set(["list-routes", "routes"]);
|
|
1042
|
+
var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
|
|
1043
|
+
var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
|
|
1044
|
+
async function promptForRouteName(introText) {
|
|
1045
|
+
p2.intro(introText);
|
|
1046
|
+
const answer = await p2.text({
|
|
1047
|
+
message: "Route name",
|
|
1048
|
+
placeholder: "e.g. users",
|
|
1049
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1050
|
+
});
|
|
1051
|
+
if (p2.isCancel(answer)) {
|
|
1052
|
+
p2.cancel("Cancelled.");
|
|
1053
|
+
process.exit(0);
|
|
1054
|
+
}
|
|
1055
|
+
return answer;
|
|
1056
|
+
}
|
|
1057
|
+
async function runAddRoute(args) {
|
|
1058
|
+
let [name] = args;
|
|
1059
|
+
if (!name) {
|
|
1060
|
+
name = await promptForRouteName("create-backon add-route");
|
|
1061
|
+
p2.outro(`Adding ${name}...`);
|
|
1062
|
+
}
|
|
1063
|
+
const { route, root, filesWritten } = await addRoute(name);
|
|
1064
|
+
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
|
|
1065
|
+
p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
|
|
1066
|
+
}
|
|
1067
|
+
async function runRemoveRoute(args) {
|
|
1068
|
+
let [name] = args;
|
|
1069
|
+
if (!name) {
|
|
1070
|
+
name = await promptForRouteName("create-backon remove-route");
|
|
1071
|
+
}
|
|
1072
|
+
const shouldRemove = await p2.confirm({
|
|
1073
|
+
message: `Remove src/endpoints/${name} and unmount it? This deletes the folder.`,
|
|
1074
|
+
initialValue: false
|
|
1075
|
+
});
|
|
1076
|
+
if (p2.isCancel(shouldRemove) || !shouldRemove) {
|
|
1077
|
+
p2.cancel("Cancelled.");
|
|
1078
|
+
process.exit(0);
|
|
1079
|
+
}
|
|
1080
|
+
const { route, root, removedDir } = await removeRoute(name);
|
|
1081
|
+
p2.log.success(`Removed ${removedDir} and unmounted "${route}" in ${root}`);
|
|
1082
|
+
}
|
|
1083
|
+
async function runListRoutes() {
|
|
1084
|
+
const { root, routes } = await listRoutes();
|
|
1085
|
+
if (routes.length === 0) {
|
|
1086
|
+
p2.log.info(`No routes mounted in ${root}.`);
|
|
1087
|
+
return;
|
|
1088
|
+
}
|
|
1089
|
+
const summaries = await listEndpointsWithMethods();
|
|
1090
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1091
|
+
}
|
|
1092
|
+
async function runDoctorCommand() {
|
|
1093
|
+
const { root, issues } = await runDoctor();
|
|
1094
|
+
if (issues.length === 0) {
|
|
1095
|
+
p2.log.success(`No issues found in ${root}.`);
|
|
1096
|
+
return;
|
|
1097
|
+
}
|
|
1098
|
+
p2.log.warn(`${issues.length} issue(s) found in ${root}:
|
|
1099
|
+
${issues.map((issue) => ` - ${issue.detail}`).join("\n")}`);
|
|
1100
|
+
process.exitCode = 1;
|
|
1101
|
+
}
|
|
1102
|
+
function suggestMethodName(verb, path) {
|
|
1103
|
+
const params = paramNamesFromPath(path);
|
|
1104
|
+
if (verb === "get" && params.length === 0) return "list";
|
|
1105
|
+
if (verb === "get") return `getBy${pascalCase(params[0] ?? "id")}`;
|
|
1106
|
+
if (verb === "post") return "create";
|
|
1107
|
+
if (verb === "put" || verb === "patch") return "update";
|
|
1108
|
+
return "remove";
|
|
1109
|
+
}
|
|
1110
|
+
var IDENTIFIER_PATTERN = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
1111
|
+
async function runAddMethod() {
|
|
1112
|
+
p2.intro("create-backon add-method");
|
|
1113
|
+
while (true) {
|
|
1114
|
+
const { root, routes } = await listRoutes();
|
|
1115
|
+
const summaries = await listEndpointsWithMethods();
|
|
1116
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1117
|
+
const routeChoice = await p2.select({
|
|
1118
|
+
message: "Add a method to which endpoint?",
|
|
1119
|
+
options: [
|
|
1120
|
+
...routes.map((route2) => ({ value: route2, label: route2 })),
|
|
1121
|
+
{ value: "__new__", label: "+ New blank endpoint" }
|
|
1122
|
+
]
|
|
1123
|
+
});
|
|
1124
|
+
if (p2.isCancel(routeChoice)) {
|
|
1125
|
+
p2.cancel("Cancelled.");
|
|
1126
|
+
return;
|
|
1127
|
+
}
|
|
1128
|
+
let route = routeChoice;
|
|
1129
|
+
if (route === "__new__") {
|
|
1130
|
+
const name2 = await p2.text({
|
|
1131
|
+
message: "New endpoint name",
|
|
1132
|
+
placeholder: "e.g. users",
|
|
1133
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1134
|
+
});
|
|
1135
|
+
if (p2.isCancel(name2)) {
|
|
1136
|
+
p2.cancel("Cancelled.");
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
const added = await addRoute(name2);
|
|
1140
|
+
route = added.route;
|
|
1141
|
+
p2.log.success(`Added blank endpoint src/endpoints/${route}`);
|
|
1142
|
+
}
|
|
1143
|
+
const verb = await p2.select({
|
|
1144
|
+
message: "HTTP method",
|
|
1145
|
+
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
1146
|
+
});
|
|
1147
|
+
if (p2.isCancel(verb)) {
|
|
1148
|
+
p2.cancel("Cancelled.");
|
|
1149
|
+
return;
|
|
1150
|
+
}
|
|
1151
|
+
const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
|
|
1152
|
+
const path = await p2.text({
|
|
1153
|
+
message: "Path (relative to this endpoint's mount)",
|
|
1154
|
+
placeholder: defaultPath,
|
|
1155
|
+
initialValue: defaultPath,
|
|
1156
|
+
validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
|
|
1157
|
+
});
|
|
1158
|
+
if (p2.isCancel(path)) {
|
|
1159
|
+
p2.cancel("Cancelled.");
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
const existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
|
|
1163
|
+
const defaultName = suggestMethodName(verb, path);
|
|
1164
|
+
const name = await p2.text({
|
|
1165
|
+
message: "Name (controller export + service function)",
|
|
1166
|
+
placeholder: defaultName,
|
|
1167
|
+
initialValue: defaultName,
|
|
1168
|
+
validate: (value) => {
|
|
1169
|
+
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
1170
|
+
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
1171
|
+
return void 0;
|
|
1172
|
+
}
|
|
1173
|
+
});
|
|
1174
|
+
if (p2.isCancel(name)) {
|
|
1175
|
+
p2.cancel("Cancelled.");
|
|
1176
|
+
return;
|
|
1177
|
+
}
|
|
1178
|
+
let needsBody = false;
|
|
1179
|
+
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
1180
|
+
const answer = await p2.confirm({ message: "Validate a request body?", initialValue: true });
|
|
1181
|
+
if (p2.isCancel(answer)) {
|
|
1182
|
+
p2.cancel("Cancelled.");
|
|
1183
|
+
return;
|
|
1184
|
+
}
|
|
1185
|
+
needsBody = answer;
|
|
1186
|
+
}
|
|
1187
|
+
const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: false });
|
|
1188
|
+
if (p2.isCancel(needsQuery)) {
|
|
1189
|
+
p2.cancel("Cancelled.");
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
const spec = { verb, path, name, needsBody, needsQuery };
|
|
1193
|
+
try {
|
|
1194
|
+
const { filesWritten } = await addMethod(route, spec);
|
|
1195
|
+
p2.log.success(`Added ${verb.toUpperCase()} ${path} \u2192 ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
|
|
1196
|
+
} catch (err) {
|
|
1197
|
+
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
1198
|
+
}
|
|
1199
|
+
const again = await p2.confirm({ message: "Add another method?", initialValue: true });
|
|
1200
|
+
if (p2.isCancel(again) || !again) break;
|
|
1201
|
+
}
|
|
1202
|
+
p2.outro("Done.");
|
|
1203
|
+
}
|
|
1204
|
+
async function runScaffold() {
|
|
1205
|
+
const answers = await runPrompts();
|
|
1206
|
+
const { root, filesWritten } = await generateProject(answers);
|
|
1207
|
+
const nextSteps = answers.projectName === "." ? "bun install\nbun run dev" : `cd ${answers.projectName}
|
|
1208
|
+
bun install
|
|
1209
|
+
bun run dev`;
|
|
1210
|
+
p2.note(nextSteps, "Next steps");
|
|
1211
|
+
p2.log.success(`Wrote ${filesWritten.length} files to ${root}`);
|
|
1212
|
+
}
|
|
1213
|
+
async function main() {
|
|
1214
|
+
const [subcommand, ...rest] = process.argv.slice(2);
|
|
1215
|
+
if (subcommand && ADD_ROUTE_SUBCOMMANDS.has(subcommand)) {
|
|
1216
|
+
await runAddRoute(rest);
|
|
1217
|
+
return;
|
|
1218
|
+
}
|
|
1219
|
+
if (subcommand && REMOVE_ROUTE_SUBCOMMANDS.has(subcommand)) {
|
|
1220
|
+
await runRemoveRoute(rest);
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
if (subcommand && LIST_ROUTES_SUBCOMMANDS.has(subcommand)) {
|
|
1224
|
+
await runListRoutes();
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
if (subcommand && DOCTOR_SUBCOMMANDS.has(subcommand)) {
|
|
1228
|
+
await runDoctorCommand();
|
|
1229
|
+
return;
|
|
1230
|
+
}
|
|
1231
|
+
if (subcommand && ADD_METHOD_SUBCOMMANDS.has(subcommand)) {
|
|
1232
|
+
await runAddMethod();
|
|
1233
|
+
return;
|
|
1234
|
+
}
|
|
1235
|
+
await runScaffold();
|
|
1236
|
+
}
|
|
1237
|
+
main().catch((err) => {
|
|
1238
|
+
console.error(err);
|
|
1239
|
+
process.exit(1);
|
|
1240
|
+
});
|