create-backon 0.6.2 → 0.10.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 +141 -12
- package/dist/cli.js +1675 -0
- package/package.json +10 -6
- package/src/add-method.ts +101 -0
- package/src/add-route.ts +11 -9
- package/src/cli.ts +512 -3
- package/src/colors.ts +35 -0
- package/src/db-status.ts +117 -0
- package/src/generate.ts +17 -6
- package/src/prompts.ts +26 -0
- package/src/remove-method.ts +100 -0
- package/src/route-methods.ts +100 -0
- package/src/templates/base.ts +95 -5
- package/src/templates/route.ts +143 -64
package/src/db-status.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { dim, ok, warn } from "./colors";
|
|
4
|
+
import { detectProject } from "./detect";
|
|
5
|
+
import type { DbChoice } from "./prompts";
|
|
6
|
+
|
|
7
|
+
export interface DbStatus {
|
|
8
|
+
/**
|
|
9
|
+
* Which driver's actually wired up in src/config/db.<ext> — read from the
|
|
10
|
+
* file's own imports rather than remembered from scaffold time, since
|
|
11
|
+
* there's nowhere the original `bun create backon` db choice is
|
|
12
|
+
* persisted. "custom" means the file doesn't match any of the four
|
|
13
|
+
* generated shapes (hand-edited past recognition); "missing" means
|
|
14
|
+
* src/config/db.<ext> doesn't exist at all.
|
|
15
|
+
*/
|
|
16
|
+
driver: DbChoice | "custom" | "missing";
|
|
17
|
+
/** Whether .env exists in the project root at all. */
|
|
18
|
+
envFileExists: boolean;
|
|
19
|
+
/**
|
|
20
|
+
* Whether this driver has what it needs to run right now, best guess.
|
|
21
|
+
* "none" and "sqlite" (DATABASE_URL optional there — defaults to
|
|
22
|
+
* ./dev.db) are always ready; "neon"/"postgres" need a non-empty
|
|
23
|
+
* DATABASE_URL in .env; "custom"/"missing" can't be assessed at all.
|
|
24
|
+
*/
|
|
25
|
+
ready: boolean | "unknown";
|
|
26
|
+
/** One-line, human-readable, pre-colored summary — this is what actually gets rendered. */
|
|
27
|
+
summary: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Matches exactly the driver-identifying import each db.ts template in
|
|
31
|
+
// templates/db.ts actually has — read off the file's real imports rather
|
|
32
|
+
// than anything remembered from scaffold time, since the original choice
|
|
33
|
+
// isn't persisted anywhere.
|
|
34
|
+
const DRIVER_SIGNATURES: Array<[string, DbChoice]> = [
|
|
35
|
+
["drizzle-orm/neon-http", "neon"],
|
|
36
|
+
["drizzle-orm/node-postgres", "postgres"],
|
|
37
|
+
["drizzle-orm/bun-sqlite", "sqlite"],
|
|
38
|
+
];
|
|
39
|
+
|
|
40
|
+
function detectDriver(dbFileContents: string): DbChoice | "custom" {
|
|
41
|
+
for (const [signature, driver] of DRIVER_SIGNATURES) {
|
|
42
|
+
if (dbFileContents.includes(signature)) return driver;
|
|
43
|
+
}
|
|
44
|
+
if (dbFileContents.includes("No database configured yet")) return "none";
|
|
45
|
+
return "custom";
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function parseEnvValue(envContents: string, key: string): string | undefined {
|
|
49
|
+
const match = envContents.match(new RegExp(`^${key}=(.*)$`, "m"));
|
|
50
|
+
const value = match?.[1]?.trim();
|
|
51
|
+
return value ? value : undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Config-check only, on purpose — no network call or file-existence probe
|
|
56
|
+
* against the actual database is attempted. Reports the driver wired up in
|
|
57
|
+
* src/config/db.<ext> and whether the env var it needs is set in .env.
|
|
58
|
+
* Fast, and behaves the same for every provider; a live connectivity test
|
|
59
|
+
* would need separate driver-specific logic (TCP for Postgres, HTTPS for
|
|
60
|
+
* Neon, a file stat for SQLite) for comparatively little extra signal, and
|
|
61
|
+
* would turn every `bun run project` into a network call.
|
|
62
|
+
*/
|
|
63
|
+
export async function detectDbStatus(cwd: string = process.cwd()): Promise<DbStatus> {
|
|
64
|
+
const { root, ext } = await detectProject(cwd);
|
|
65
|
+
|
|
66
|
+
let dbFileContents: string | undefined;
|
|
67
|
+
try {
|
|
68
|
+
dbFileContents = await readFile(join(root, "src/config", `db.${ext}`), "utf-8");
|
|
69
|
+
} catch {
|
|
70
|
+
dbFileContents = undefined;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const driver = dbFileContents === undefined ? "missing" : detectDriver(dbFileContents);
|
|
74
|
+
|
|
75
|
+
let envContents = "";
|
|
76
|
+
let envFileExists = true;
|
|
77
|
+
try {
|
|
78
|
+
envContents = await readFile(join(root, ".env"), "utf-8");
|
|
79
|
+
} catch {
|
|
80
|
+
envFileExists = false;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const databaseUrl = parseEnvValue(envContents, "DATABASE_URL");
|
|
84
|
+
|
|
85
|
+
if (driver === "missing") {
|
|
86
|
+
return { driver, envFileExists, ready: "unknown", summary: warn("src/config/db file not found.") };
|
|
87
|
+
}
|
|
88
|
+
if (driver === "custom") {
|
|
89
|
+
return {
|
|
90
|
+
driver,
|
|
91
|
+
envFileExists,
|
|
92
|
+
ready: "unknown",
|
|
93
|
+
summary: `${dim("custom")} — src/config/db has been hand-edited, can't tell you its status here.`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (driver === "none") {
|
|
97
|
+
return { driver, envFileExists, ready: true, summary: dim("none — no database configured.") };
|
|
98
|
+
}
|
|
99
|
+
if (driver === "sqlite") {
|
|
100
|
+
const path = databaseUrl ?? "./dev.db";
|
|
101
|
+
return { driver, envFileExists, ready: true, summary: `${ok("sqlite")} — using ${path}.` };
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// neon / postgres both hard-require DATABASE_URL — db.ts itself throws at
|
|
105
|
+
// import time without one, so "missing-env" here means the app won't boot.
|
|
106
|
+
if (databaseUrl) {
|
|
107
|
+
return { driver, envFileExists, ready: true, summary: `${ok(driver)} — DATABASE_URL is set in .env.` };
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
driver,
|
|
111
|
+
envFileExists,
|
|
112
|
+
ready: false,
|
|
113
|
+
summary: `${warn(driver)} — DATABASE_URL missing from .env${
|
|
114
|
+
envFileExists ? "" : " (no .env file)"
|
|
115
|
+
}; src/config/db.ts will throw at startup until it's set.`,
|
|
116
|
+
};
|
|
117
|
+
}
|
package/src/generate.ts
CHANGED
|
@@ -12,8 +12,9 @@ import {
|
|
|
12
12
|
renderPackageJson,
|
|
13
13
|
renderReadme,
|
|
14
14
|
renderTsconfig,
|
|
15
|
+
renderVercelJson,
|
|
15
16
|
} from "./templates/base";
|
|
16
|
-
import {
|
|
17
|
+
import { renderBlankController, renderBlankRoutes, renderBlankServices } from "./templates/route";
|
|
17
18
|
import { renderDbFile } from "./templates/db";
|
|
18
19
|
|
|
19
20
|
async function write(path: string, contents: string): Promise<void> {
|
|
@@ -91,8 +92,13 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
91
92
|
? [join(root, "jsconfig.json"), renderJsconfig()]
|
|
92
93
|
: [join(root, "tsconfig.json"), renderTsconfig()],
|
|
93
94
|
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
94
|
-
[
|
|
95
|
-
|
|
95
|
+
[
|
|
96
|
+
join(root, ".gitignore"),
|
|
97
|
+
`node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n${
|
|
98
|
+
answers.deployTarget === "vercel" ? ".vercel\n" : ""
|
|
99
|
+
}`,
|
|
100
|
+
],
|
|
101
|
+
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
96
102
|
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
97
103
|
[
|
|
98
104
|
join(root, `src/middleware/example.middleware.${ext}`),
|
|
@@ -100,14 +106,19 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
100
106
|
],
|
|
101
107
|
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
102
108
|
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
109
|
+
...(answers.deployTarget === "vercel"
|
|
110
|
+
? ([[join(root, "vercel.json"), renderVercelJson()]] as Array<[string, string]>)
|
|
111
|
+
: []),
|
|
103
112
|
];
|
|
104
113
|
|
|
114
|
+
// Every route starts blank (no methods wired) — `bun run add-method` adds
|
|
115
|
+
// them one at a time afterward. See templates/route.ts for why.
|
|
105
116
|
for (const route of answers.routes) {
|
|
106
117
|
const dir = join(root, "src/endpoints", route);
|
|
107
118
|
files.push(
|
|
108
|
-
[join(dir, `${route}.controller.${ext}`),
|
|
109
|
-
[join(dir, `${route}.routes.${ext}`),
|
|
110
|
-
[join(dir, `${route}.services.${ext}`),
|
|
119
|
+
[join(dir, `${route}.controller.${ext}`), renderBlankController()],
|
|
120
|
+
[join(dir, `${route}.routes.${ext}`), renderBlankRoutes(route, answers.framework, answers.language)],
|
|
121
|
+
[join(dir, `${route}.services.${ext}`), renderBlankServices()]
|
|
111
122
|
);
|
|
112
123
|
}
|
|
113
124
|
|
package/src/prompts.ts
CHANGED
|
@@ -3,6 +3,7 @@ import * as p from "@clack/prompts";
|
|
|
3
3
|
export type DbChoice = "neon" | "postgres" | "sqlite" | "none";
|
|
4
4
|
export type Framework = "hono" | "express";
|
|
5
5
|
export type Language = "typescript" | "javascript";
|
|
6
|
+
export type DeployTarget = "vercel" | "node" | "local" | "undecided";
|
|
6
7
|
|
|
7
8
|
export interface Answers {
|
|
8
9
|
projectName: string;
|
|
@@ -11,6 +12,11 @@ export interface Answers {
|
|
|
11
12
|
db: DbChoice;
|
|
12
13
|
routes: string[];
|
|
13
14
|
copyEnv: boolean;
|
|
15
|
+
// Optional, defaults to "undecided" wherever it's read — generateProject()
|
|
16
|
+
// and its templates all treat a missing value the same as "undecided", so
|
|
17
|
+
// existing callers that build an Answers object without this field (tests,
|
|
18
|
+
// any external embedder) keep working unchanged.
|
|
19
|
+
deployTarget?: DeployTarget;
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
function bail(): never {
|
|
@@ -72,6 +78,25 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
72
78
|
});
|
|
73
79
|
if (p.isCancel(db)) bail();
|
|
74
80
|
|
|
81
|
+
const deployTarget = await p.select({
|
|
82
|
+
message: "Where's this headed?",
|
|
83
|
+
options: [
|
|
84
|
+
{
|
|
85
|
+
value: "vercel",
|
|
86
|
+
label: "Vercel",
|
|
87
|
+
hint: "adds vercel.json + a default export so it deploys with zero config",
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
value: "node",
|
|
91
|
+
label: "Another Node/Bun host",
|
|
92
|
+
hint: "Render, Railway, Fly, a VPS — index.ts's serve() already listens on PORT, nothing extra needed",
|
|
93
|
+
},
|
|
94
|
+
{ value: "local", label: "Local / self-hosted only", hint: "no deploy scaffolding added" },
|
|
95
|
+
{ value: "undecided", label: "Not sure yet", hint: "same as local for now — figure it out later" },
|
|
96
|
+
],
|
|
97
|
+
});
|
|
98
|
+
if (p.isCancel(deployTarget)) bail();
|
|
99
|
+
|
|
75
100
|
const copyEnv = await p.confirm({
|
|
76
101
|
message: "Create .env from .env.example now?",
|
|
77
102
|
initialValue: true,
|
|
@@ -100,5 +125,6 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
100
125
|
db: db as DbChoice,
|
|
101
126
|
routes,
|
|
102
127
|
copyEnv: copyEnv as boolean,
|
|
128
|
+
deployTarget: deployTarget as DeployTarget,
|
|
103
129
|
};
|
|
104
130
|
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { detectProject } from "./detect";
|
|
4
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
5
|
+
import { parseRouteMethods } from "./route-methods";
|
|
6
|
+
import { renderBlankController, renderBlankRoutes, renderBlankServices, routeMountLine, type HttpVerb } from "./templates/route";
|
|
7
|
+
|
|
8
|
+
export interface RemoveMethodResult {
|
|
9
|
+
route: string;
|
|
10
|
+
root: string;
|
|
11
|
+
removed: { verb: HttpVerb; path: string; name: string };
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* addMethod() appends each method as its own \n\n-delimited block (see
|
|
16
|
+
* appendBlock() in add-method.ts) — imports/the Router()-or-Hono()
|
|
17
|
+
* declaration are their own leading block, then one block per method, in
|
|
18
|
+
* insertion order, nothing else in between. That's what makes this safe:
|
|
19
|
+
* find the one block matching the predicate and drop it, leaving every
|
|
20
|
+
* other block (including the leading one) untouched.
|
|
21
|
+
*/
|
|
22
|
+
function removeBlock(content: string, matches: (block: string) => boolean): string {
|
|
23
|
+
const blocks = content.split(/\n\n+/);
|
|
24
|
+
const index = blocks.findIndex(matches);
|
|
25
|
+
if (index === -1) return content;
|
|
26
|
+
blocks.splice(index, 1);
|
|
27
|
+
const joined = blocks.filter((b) => b.length > 0).join("\n\n");
|
|
28
|
+
return joined ? `${joined}\n` : "";
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The undo for addMethod(): strips one method's mount line from
|
|
33
|
+
* *.routes.<ext>, its defineRoute() export (plus any params/body/query
|
|
34
|
+
* schema consts) from *.controller.<ext>, and its matching function from
|
|
35
|
+
* *.services.<ext>. Identified by verb+path, the same pair addMethod()
|
|
36
|
+
* itself refuses to let collide — not by name alone, since two different
|
|
37
|
+
* verb/path pairs could theoretically end up with the same name checked
|
|
38
|
+
* against different endpoints (name uniqueness is only enforced per
|
|
39
|
+
* endpoint, not globally).
|
|
40
|
+
*
|
|
41
|
+
* Removing the last method on an endpoint resets all three files back to
|
|
42
|
+
* their blank, freshly-scaffolded shape (renderBlank*()) rather than
|
|
43
|
+
* leaving behind an import block with nothing left to import for — the
|
|
44
|
+
* same state addRoute() itself would have written.
|
|
45
|
+
*/
|
|
46
|
+
export async function removeMethod(
|
|
47
|
+
route: string,
|
|
48
|
+
verb: HttpVerb,
|
|
49
|
+
path: string,
|
|
50
|
+
cwd: string = process.cwd()
|
|
51
|
+
): Promise<RemoveMethodResult> {
|
|
52
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
53
|
+
|
|
54
|
+
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
55
|
+
const mounted = parseMountedRoutes(indexContents);
|
|
56
|
+
if (!mounted.includes(route)) {
|
|
57
|
+
throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext}.`);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const routeDir = join(root, "src/endpoints", route);
|
|
61
|
+
const controllerPath = join(routeDir, `${route}.controller.${ext}`);
|
|
62
|
+
const routesPath = join(routeDir, `${route}.routes.${ext}`);
|
|
63
|
+
const servicesPath = join(routeDir, `${route}.services.${ext}`);
|
|
64
|
+
|
|
65
|
+
const [controllerContents, routesContents, servicesContents] = await Promise.all([
|
|
66
|
+
readFile(controllerPath, "utf-8"),
|
|
67
|
+
readFile(routesPath, "utf-8"),
|
|
68
|
+
readFile(servicesPath, "utf-8"),
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
const existing = parseRouteMethods(routesContents);
|
|
72
|
+
const match = existing.find((m) => m.verb === verb && m.path === path);
|
|
73
|
+
if (!match) {
|
|
74
|
+
throw new Error(`${verb.toUpperCase()} ${path} isn't mounted in ${routesPath}.`);
|
|
75
|
+
}
|
|
76
|
+
const { name } = match;
|
|
77
|
+
|
|
78
|
+
if (existing.length === 1) {
|
|
79
|
+
await Promise.all([
|
|
80
|
+
writeFile(controllerPath, renderBlankController()),
|
|
81
|
+
writeFile(routesPath, renderBlankRoutes(route, framework, language)),
|
|
82
|
+
writeFile(servicesPath, renderBlankServices()),
|
|
83
|
+
]);
|
|
84
|
+
return { route, root, removed: match };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const expectedMountLine = routeMountLine(route, { verb, path, name, needsBody: false, needsQuery: false });
|
|
88
|
+
|
|
89
|
+
const newController = removeBlock(controllerContents, (block) => block.includes(`export const ${name} = defineRoute(`));
|
|
90
|
+
const newRoutes = removeBlock(routesContents, (block) => block.trim() === expectedMountLine);
|
|
91
|
+
const newServices = removeBlock(servicesContents, (block) => block.includes(`export async function ${name}(`));
|
|
92
|
+
|
|
93
|
+
await Promise.all([
|
|
94
|
+
writeFile(controllerPath, newController),
|
|
95
|
+
writeFile(routesPath, newRoutes),
|
|
96
|
+
writeFile(servicesPath, newServices),
|
|
97
|
+
]);
|
|
98
|
+
|
|
99
|
+
return { route, root, removed: match };
|
|
100
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { colorVerb, dim } from "./colors";
|
|
4
|
+
import { detectProject } from "./detect";
|
|
5
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
6
|
+
import type { HttpVerb } from "./templates/route";
|
|
7
|
+
|
|
8
|
+
export interface EndpointMethod {
|
|
9
|
+
verb: HttpVerb;
|
|
10
|
+
path: string;
|
|
11
|
+
/** The controller export / service function name this method calls into. */
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EndpointSummary {
|
|
16
|
+
route: string;
|
|
17
|
+
methods: EndpointMethod[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Matches exactly what routeMountLine() in templates/route.ts generates:
|
|
21
|
+
// usersRoutes.get("/", controller.list);
|
|
22
|
+
// usersRoutes.post("/", controller.create);
|
|
23
|
+
// Shared here so the dashboard (add-method) and list-routes read mount lines
|
|
24
|
+
// the same way instead of two regexes drifting apart.
|
|
25
|
+
const METHOD_MOUNT_PATTERN = /\.(get|post|put|patch|delete)\(\s*"([^"]*)"\s*,\s*controller\.(\w+)\s*\)/g;
|
|
26
|
+
|
|
27
|
+
export function parseRouteMethods(routesFileContents: string): EndpointMethod[] {
|
|
28
|
+
const methods: EndpointMethod[] = [];
|
|
29
|
+
for (const match of routesFileContents.matchAll(METHOD_MOUNT_PATTERN)) {
|
|
30
|
+
const [, verb, path, name] = match;
|
|
31
|
+
if (verb && path !== undefined && name) {
|
|
32
|
+
methods.push({ verb: verb as HttpVerb, path, name });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return methods;
|
|
36
|
+
}
|
|
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
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Every endpoint currently mounted in src/endpoints/index.<ext>, with the
|
|
64
|
+
* HTTP methods each one's own *.routes.<ext> file actually wires up right
|
|
65
|
+
* now — the same "what's real on disk" read doctor.ts does, rather than
|
|
66
|
+
* anything add-method itself remembers, so this stays correct even after
|
|
67
|
+
* hand-edits.
|
|
68
|
+
*/
|
|
69
|
+
export async function listEndpointsWithMethods(cwd: string = process.cwd()): Promise<EndpointSummary[]> {
|
|
70
|
+
const { root, ext } = await detectProject(cwd);
|
|
71
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
72
|
+
const routes = parseMountedRoutes(contents);
|
|
73
|
+
|
|
74
|
+
const summaries: EndpointSummary[] = [];
|
|
75
|
+
for (const route of routes) {
|
|
76
|
+
const routesFilePath = join(root, "src/endpoints", route, `${route}.routes.${ext}`);
|
|
77
|
+
let routesFileContents: string;
|
|
78
|
+
try {
|
|
79
|
+
routesFileContents = await readFile(routesFilePath, "utf-8");
|
|
80
|
+
} catch {
|
|
81
|
+
summaries.push({ route, methods: [] });
|
|
82
|
+
continue;
|
|
83
|
+
}
|
|
84
|
+
summaries.push({ route, methods: parseRouteMethods(routesFileContents) });
|
|
85
|
+
}
|
|
86
|
+
return summaries;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Plain-text dashboard: every endpoint, and every method it actually has right now, colored by verb. */
|
|
90
|
+
export function formatEndpointsDashboard(summaries: EndpointSummary[]): string {
|
|
91
|
+
if (summaries.length === 0) return dim("No endpoints yet.");
|
|
92
|
+
|
|
93
|
+
return summaries
|
|
94
|
+
.map(({ route, methods }) => {
|
|
95
|
+
if (methods.length === 0) return `${route}\n ${dim("(no methods yet)")}`;
|
|
96
|
+
const lines = methods.map((m) => ` ${colorVerb(m.verb)} ${m.path} ${dim(`→ ${m.name}`)}`);
|
|
97
|
+
return `${route}\n${lines.join("\n")}`;
|
|
98
|
+
})
|
|
99
|
+
.join("\n\n");
|
|
100
|
+
}
|
package/src/templates/base.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { Answers, Framework, Language } from "../prompts";
|
|
1
|
+
import type { Answers, DeployTarget, Framework, Language } from "../prompts";
|
|
2
2
|
import { camelCase } from "./route";
|
|
3
3
|
import { dbDependencies, dbEnvVars, dbReadmeNote } from "./db";
|
|
4
4
|
|
|
@@ -12,10 +12,18 @@ import { dbDependencies, dbEnvVars, dbReadmeNote } from "./db";
|
|
|
12
12
|
|
|
13
13
|
export function renderIndexTs(framework: Framework): string {
|
|
14
14
|
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
15
|
+
// The Hono adapter's serve() is async as of @mednours/backon 0.7.0 (it
|
|
16
|
+
// dynamically imports Bun.serve()/@hono/node-server depending which
|
|
17
|
+
// runtime it's actually on) — top-level await works fine here since
|
|
18
|
+
// generated projects are ESM ("type": "module" in their package.json).
|
|
19
|
+
// The Express adapter's serve() stays synchronous (always app.listen()
|
|
20
|
+
// under the hood, no runtime branching to speak of), so it's left
|
|
21
|
+
// un-awaited rather than implying an async contract that isn't real.
|
|
22
|
+
const call = framework === "express" ? "serve(app);" : "await serve(app);";
|
|
15
23
|
return `import { serve } from "${backonImport}";
|
|
16
24
|
import { app } from "./src/app";
|
|
17
25
|
|
|
18
|
-
|
|
26
|
+
${call}
|
|
19
27
|
`;
|
|
20
28
|
}
|
|
21
29
|
|
|
@@ -23,7 +31,23 @@ serve(app);
|
|
|
23
31
|
// the route table as it stands at call time, so anything registered after
|
|
24
32
|
// this line would be missing from /docs. Same live route this project's
|
|
25
33
|
// bun run docs script generates a static copy of; see generate-docs.<ext>.
|
|
26
|
-
|
|
34
|
+
//
|
|
35
|
+
// The default export (Vercel target only) is additive, not a replacement
|
|
36
|
+
// for index.ts's serve(app) — Vercel's zero-config Hono/Express support
|
|
37
|
+
// imports this file directly and calls the exported app's own request
|
|
38
|
+
// handler, bypassing serve()/index.ts entirely, while index.ts (and its
|
|
39
|
+
// serve() call) keeps working exactly as before for `bun run dev`/`start`
|
|
40
|
+
// anywhere else. src/app.<ext> is already one of Vercel's recognized entry
|
|
41
|
+
// paths — this export is the only thing it was missing.
|
|
42
|
+
export function renderAppTs(projectName: string, framework: Framework, deployTarget?: DeployTarget): string {
|
|
43
|
+
const defaultExport =
|
|
44
|
+
deployTarget === "vercel"
|
|
45
|
+
? `
|
|
46
|
+
// Vercel deploys straight from this export — see vercel.json.
|
|
47
|
+
export default app;
|
|
48
|
+
`
|
|
49
|
+
: "";
|
|
50
|
+
|
|
27
51
|
if (framework === "express") {
|
|
28
52
|
return `import { createApp, serveApiDocs } from "@mednours/backon/express";
|
|
29
53
|
import { endpoints } from "./endpoints";
|
|
@@ -35,7 +59,7 @@ app.use(exampleMiddleware);
|
|
|
35
59
|
app.use("/", endpoints);
|
|
36
60
|
|
|
37
61
|
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
38
|
-
`;
|
|
62
|
+
${defaultExport}`;
|
|
39
63
|
}
|
|
40
64
|
return `import { createApp, serveApiDocs } from "@mednours/backon";
|
|
41
65
|
import { endpoints } from "./endpoints";
|
|
@@ -47,6 +71,21 @@ app.use("*", exampleMiddleware);
|
|
|
47
71
|
app.route("/", endpoints);
|
|
48
72
|
|
|
49
73
|
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
74
|
+
${defaultExport}`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Vercel target only. bunVersion pins the Bun *major* version Vercel runs
|
|
78
|
+
// the deployed function on (currently "1.x" is the only valid value; minor/
|
|
79
|
+
// patch are managed by Vercel automatically) — kept in sync with this
|
|
80
|
+
// being a Bun-first framework, so the deployed function behaves the same
|
|
81
|
+
// runtime as local dev. Not required for the zero-config Hono/Express
|
|
82
|
+
// detection itself (that works on Vercel's default Node runtime too), but
|
|
83
|
+
// there's no reason to switch runtimes between local and deployed.
|
|
84
|
+
export function renderVercelJson(): string {
|
|
85
|
+
return `{
|
|
86
|
+
"$schema": "https://openapi.vercel.sh/vercel.json",
|
|
87
|
+
"bunVersion": "1.x"
|
|
88
|
+
}
|
|
50
89
|
`;
|
|
51
90
|
}
|
|
52
91
|
|
|
@@ -284,9 +323,16 @@ export function renderPackageJson(
|
|
|
284
323
|
// arguments (like the route name) straight through without needing
|
|
285
324
|
// a `--` separator.
|
|
286
325
|
"add-route": "bunx create-backon add-route",
|
|
326
|
+
"add-method": "bunx create-backon add-method",
|
|
287
327
|
"remove-route": "bunx create-backon remove-route",
|
|
288
328
|
"list-routes": "bunx create-backon list-routes",
|
|
289
329
|
doctor: "bunx create-backon doctor",
|
|
330
|
+
// project: read-only overview (db status, endpoints, methods, doctor
|
|
331
|
+
// summary). server-config: the interactive manager for actually
|
|
332
|
+
// changing endpoints/methods — add/remove/modify, without needing to
|
|
333
|
+
// remember which of the individual subcommands above does what.
|
|
334
|
+
project: "bunx create-backon project",
|
|
335
|
+
"server-config": "bunx create-backon server-config",
|
|
290
336
|
docs: `bun run scripts/generate-docs.${ext}`,
|
|
291
337
|
};
|
|
292
338
|
if (language === "typescript") {
|
|
@@ -306,6 +352,48 @@ export function renderPackageJson(
|
|
|
306
352
|
return `${JSON.stringify(pkg, null, 2)}\n`;
|
|
307
353
|
}
|
|
308
354
|
|
|
355
|
+
function renderDeploySection(deployTarget: DeployTarget | undefined, ext: string): string {
|
|
356
|
+
switch (deployTarget) {
|
|
357
|
+
case "vercel":
|
|
358
|
+
return `## Deploying
|
|
359
|
+
|
|
360
|
+
Set up for [Vercel](https://vercel.com)'s zero-config Hono/Express support:
|
|
361
|
+
\`src/app.${ext}\` has a default export (Vercel deploys straight from it,
|
|
362
|
+
bypassing \`index.${ext}\`/\`serve()\` — those keep working locally exactly as
|
|
363
|
+
before), and \`vercel.json\` pins the Bun runtime so the deployed function
|
|
364
|
+
matches local dev. Connect the repo on [vercel.com/new](https://vercel.com/new)
|
|
365
|
+
or run \`vercel deploy\` — no other configuration needed. \`vercel dev\` runs it
|
|
366
|
+
locally the same way it'll run once deployed.
|
|
367
|
+
`;
|
|
368
|
+
case "node":
|
|
369
|
+
return `## Deploying
|
|
370
|
+
|
|
371
|
+
No deploy-specific files here — \`index.${ext}\` calls \`serve(app)\`, which
|
|
372
|
+
listens on \`PORT\` (see \`.env.example\`) wherever it's run. That's what
|
|
373
|
+
Render, Railway, Fly, a plain VPS, or any other Node/Bun host expects: point
|
|
374
|
+
the platform's start command at \`bun run start\` (or \`bun run index.${ext}\`)
|
|
375
|
+
and set \`PORT\`/your database env vars in its dashboard.
|
|
376
|
+
`;
|
|
377
|
+
case "local":
|
|
378
|
+
return `## Deploying
|
|
379
|
+
|
|
380
|
+
Not set up for a specific host — \`bun run start\` runs \`index.${ext}\`, which
|
|
381
|
+
listens on \`PORT\` (see \`.env.example\`). Point any Node/Bun-capable host's
|
|
382
|
+
start command at that when you're ready.
|
|
383
|
+
`;
|
|
384
|
+
default:
|
|
385
|
+
return `## Deploying
|
|
386
|
+
|
|
387
|
+
Not decided yet — \`index.${ext}\` already calls \`serve(app)\`, listening on
|
|
388
|
+
\`PORT\` (see \`.env.example\`), which is all most Node/Bun hosts need. For
|
|
389
|
+
[Vercel](https://vercel.com) specifically, add a default export to
|
|
390
|
+
\`src/app.${ext}\` (\`export default app;\`) and a \`vercel.json\` with
|
|
391
|
+
\`{ "bunVersion": "1.x" }\` — or re-run \`create-backon\` and pick Vercel to get
|
|
392
|
+
both for free.
|
|
393
|
+
`;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
309
397
|
export function renderReadme(answers: Answers): string {
|
|
310
398
|
const routeList = answers.routes.length
|
|
311
399
|
? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n")
|
|
@@ -313,6 +401,7 @@ export function renderReadme(answers: Answers): string {
|
|
|
313
401
|
|
|
314
402
|
const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
315
403
|
const languageLabel = answers.language === "javascript" ? "JavaScript" : "TypeScript";
|
|
404
|
+
const ext = answers.language === "javascript" ? "js" : "ts";
|
|
316
405
|
|
|
317
406
|
return `# ${answers.projectName}
|
|
318
407
|
|
|
@@ -342,5 +431,6 @@ Each route folder follows the same shape: \`*.routes.${answers.language === "jav
|
|
|
342
431
|
methods to controller functions, \`*.controller.${answers.language === "javascript" ? "js" : "ts"}\` validates the
|
|
343
432
|
request (via \`defineRoute\` from \`${backonImport}\`) and calls into
|
|
344
433
|
\`*.services.${answers.language === "javascript" ? "js" : "ts"}\`, which is where real data access belongs.
|
|
345
|
-
|
|
434
|
+
|
|
435
|
+
${renderDeploySection(answers.deployTarget, ext)}`;
|
|
346
436
|
}
|