create-backon 0.3.0 → 0.4.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 CHANGED
@@ -20,8 +20,9 @@ bunx create-backon
20
20
  Prompts for a project name (or `.` to scaffold into the current directory,
21
21
  same as `bun create vite@latest .`), a framework (Hono or Express), a
22
22
  language (TypeScript or JavaScript), a database (Neon, Postgres, SQLite, or
23
- none — via [Drizzle](https://orm.drizzle.team)), and any number of routes,
24
- then generates:
23
+ none — via [Drizzle](https://orm.drizzle.team)), whether to create `.env`
24
+ from `.env.example` right away (default yes — skips the manual `cp` step),
25
+ and any number of routes, then generates:
25
26
 
26
27
  ```
27
28
  my-api/
@@ -84,6 +85,45 @@ to the ones that were already there. It refuses to run outside a backon
84
85
  project, refuses a route name whose folder already exists, and refuses a
85
86
  name that's already mounted.
86
87
 
88
+ ## Removing a route
89
+
90
+ The undo for `add-route`:
91
+
92
+ ```
93
+ bunx create-backon remove-route users
94
+ ```
95
+
96
+ (`rm-route` also works.) Leave the name off to be prompted for one. Either
97
+ way you'll be asked to confirm before anything is deleted — this removes
98
+ `src/endpoints/users/` and unmounts it from `src/endpoints/index.ts`.
99
+ Refuses if the route isn't currently mounted, rather than guessing at
100
+ deleting a folder that was never wired up.
101
+
102
+ ## Listing routes
103
+
104
+ ```
105
+ bunx create-backon list-routes
106
+ ```
107
+
108
+ (`routes` also works.) Read-only — prints every route currently mounted in
109
+ `src/endpoints/index.ts`.
110
+
111
+ ## Checking a project for drift
112
+
113
+ ```
114
+ bunx create-backon doctor
115
+ ```
116
+
117
+ Compares what's actually in `src/endpoints/` against what `index.<ext>`
118
+ mounts, and flags three things: a route folder that exists but isn't
119
+ mounted (an orphan), a mount in `index.<ext>` pointing at a folder that's
120
+ gone (dangling), and a route folder missing one of its three expected
121
+ files. This kind of drift usually comes from hand-editing `index.ts`,
122
+ deleting a route folder without using `remove-route`, or copy-pasting a
123
+ route folder without wiring it up. `doctor` only reports issues — it
124
+ doesn't fix them — and exits non-zero if it finds any, so it's usable in
125
+ a pre-commit hook or CI step.
126
+
87
127
  ## Requirements
88
128
 
89
129
  Bun >= 1.3.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-backon",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "type": "module",
5
5
  "description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout.",
6
6
  "license": "MIT",
package/src/add-route.ts CHANGED
@@ -1,15 +1,11 @@
1
- import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
1
+ import { mkdir, readdir, writeFile } from "node:fs/promises";
2
2
  import { dirname, join } from "node:path";
3
3
  import { detectProject } from "./detect";
4
+ import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
4
5
  import { toKebabCase } from "./prompts";
5
6
  import { renderEndpointsIndex } from "./templates/base";
6
7
  import { renderController, renderRoutes, renderServices } from "./templates/route";
7
8
 
8
- // Matches the two shapes renderEndpointsIndex() ever generates:
9
- // endpoints.route("/telemetry", telemetryRoutes); (hono)
10
- // endpoints.use("/telemetry", telemetryRoutes); (express)
11
- const MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
12
-
13
9
  export interface AddRouteResult {
14
10
  route: string;
15
11
  root: string;
@@ -50,21 +46,8 @@ export async function addRoute(rawName: string, cwd: string = process.cwd()): Pr
50
46
  throw new Error(`src/endpoints/${route} already exists.`);
51
47
  }
52
48
 
53
- const indexPath = join(endpointsDir, `index.${ext}`);
54
- let indexContents: string;
55
- try {
56
- indexContents = await readFile(indexPath, "utf-8");
57
- } catch (err) {
58
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
59
- throw new Error(`${indexPath} doesn't exist — is this a backon project?`);
60
- }
61
- throw err;
62
- }
63
-
64
- const existingRoutes: string[] = [];
65
- for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
66
- existingRoutes.push(match[1]);
67
- }
49
+ const { path: indexPath, contents: indexContents } = await readEndpointsIndex(root, ext);
50
+ const existingRoutes = parseMountedRoutes(indexContents);
68
51
  if (existingRoutes.includes(route)) {
69
52
  throw new Error(`"${route}" is already mounted in ${indexPath}.`);
70
53
  }
package/src/cli.ts CHANGED
@@ -3,24 +3,34 @@ import * as p from "@clack/prompts";
3
3
  import { runPrompts } from "./prompts";
4
4
  import { generateProject } from "./generate";
5
5
  import { addRoute } from "./add-route";
6
+ import { removeRoute } from "./remove-route";
7
+ import { listRoutes } from "./list-routes";
8
+ import { runDoctor } from "./doctor";
6
9
 
7
10
  const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
11
+ const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
12
+ const LIST_ROUTES_SUBCOMMANDS = new Set(["list-routes", "routes"]);
13
+ const DOCTOR_SUBCOMMANDS = new Set(["doctor"]);
14
+
15
+ async function promptForRouteName(introText: string): Promise<string> {
16
+ p.intro(introText);
17
+ const answer = await p.text({
18
+ message: "Route name",
19
+ placeholder: "e.g. users",
20
+ validate: (value) => (!value ? "Required." : undefined),
21
+ });
22
+ if (p.isCancel(answer)) {
23
+ p.cancel("Cancelled.");
24
+ process.exit(0);
25
+ }
26
+ return answer;
27
+ }
8
28
 
9
29
  async function runAddRoute(args: string[]): Promise<void> {
10
30
  let [name] = args;
11
31
 
12
32
  if (!name) {
13
- p.intro("create-backon add-route");
14
- const answer = await p.text({
15
- message: "Route name",
16
- placeholder: "e.g. users",
17
- validate: (value) => (!value ? "Required." : undefined),
18
- });
19
- if (p.isCancel(answer)) {
20
- p.cancel("Cancelled.");
21
- process.exit(0);
22
- }
23
- name = answer;
33
+ name = await promptForRouteName("create-backon add-route");
24
34
  p.outro(`Adding ${name}...`);
25
35
  }
26
36
 
@@ -28,6 +38,45 @@ async function runAddRoute(args: string[]): Promise<void> {
28
38
  p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files) in ${root}`);
29
39
  }
30
40
 
41
+ async function runRemoveRoute(args: string[]): Promise<void> {
42
+ let [name] = args;
43
+
44
+ if (!name) {
45
+ name = await promptForRouteName("create-backon remove-route");
46
+ }
47
+
48
+ const shouldRemove = await p.confirm({
49
+ message: `Remove src/endpoints/${name} and unmount it? This deletes the folder.`,
50
+ initialValue: false,
51
+ });
52
+ if (p.isCancel(shouldRemove) || !shouldRemove) {
53
+ p.cancel("Cancelled.");
54
+ process.exit(0);
55
+ }
56
+
57
+ const { route, root, removedDir } = await removeRoute(name);
58
+ p.log.success(`Removed ${removedDir} and unmounted "${route}" in ${root}`);
59
+ }
60
+
61
+ async function runListRoutes(): Promise<void> {
62
+ const { root, routes } = await listRoutes();
63
+ if (routes.length === 0) {
64
+ p.log.info(`No routes mounted in ${root}.`);
65
+ return;
66
+ }
67
+ p.log.info(`Routes mounted in ${root}:\n${routes.map((route) => ` - ${route}`).join("\n")}`);
68
+ }
69
+
70
+ async function runDoctorCommand(): Promise<void> {
71
+ const { root, issues } = await runDoctor();
72
+ if (issues.length === 0) {
73
+ p.log.success(`No issues found in ${root}.`);
74
+ return;
75
+ }
76
+ p.log.warn(`${issues.length} issue(s) found in ${root}:\n${issues.map((issue) => ` - ${issue.detail}`).join("\n")}`);
77
+ process.exitCode = 1;
78
+ }
79
+
31
80
  async function runScaffold(): Promise<void> {
32
81
  const answers = await runPrompts();
33
82
  const { root, filesWritten } = await generateProject(answers);
@@ -45,6 +94,18 @@ async function main() {
45
94
  await runAddRoute(rest);
46
95
  return;
47
96
  }
97
+ if (subcommand && REMOVE_ROUTE_SUBCOMMANDS.has(subcommand)) {
98
+ await runRemoveRoute(rest);
99
+ return;
100
+ }
101
+ if (subcommand && LIST_ROUTES_SUBCOMMANDS.has(subcommand)) {
102
+ await runListRoutes();
103
+ return;
104
+ }
105
+ if (subcommand && DOCTOR_SUBCOMMANDS.has(subcommand)) {
106
+ await runDoctorCommand();
107
+ return;
108
+ }
48
109
 
49
110
  await runScaffold();
50
111
  }
package/src/doctor.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { access, readdir } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { detectProject } from "./detect";
4
+ import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
5
+
6
+ export type DoctorIssueKind = "dangling-mount" | "orphaned-folder" | "missing-file";
7
+
8
+ export interface DoctorIssue {
9
+ kind: DoctorIssueKind;
10
+ route: string;
11
+ detail: string;
12
+ }
13
+
14
+ export interface DoctorResult {
15
+ root: string;
16
+ issues: DoctorIssue[];
17
+ }
18
+
19
+ const ROUTE_FILE_SUFFIXES = ["controller", "routes", "services"] as const;
20
+
21
+ /**
22
+ * Checks src/endpoints/ for drift between what's on disk and what
23
+ * index.<ext> actually mounts — the kind of thing that creeps in from
24
+ * hand-editing index.ts, an interrupted addRoute()/removeRoute(), or
25
+ * copy-pasting a route folder without wiring it up. Read-only; reports
26
+ * issues, doesn't fix them.
27
+ */
28
+ export async function runDoctor(cwd: string = process.cwd()): Promise<DoctorResult> {
29
+ const { root, ext } = await detectProject(cwd);
30
+ const endpointsDir = join(root, "src/endpoints");
31
+ const { contents } = await readEndpointsIndex(root, ext);
32
+ const mounted = new Set(parseMountedRoutes(contents));
33
+
34
+ const dirents = await readdir(endpointsDir, { withFileTypes: true }).catch((err) => {
35
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
36
+ throw err;
37
+ });
38
+ const folders = dirents.filter((d) => d.isDirectory()).map((d) => d.name);
39
+ const folderSet = new Set(folders);
40
+
41
+ const issues: DoctorIssue[] = [];
42
+
43
+ for (const route of mounted) {
44
+ if (!folderSet.has(route)) {
45
+ issues.push({
46
+ kind: "dangling-mount",
47
+ route,
48
+ detail: `index.${ext} mounts "/${route}" but src/endpoints/${route}/ doesn't exist.`,
49
+ });
50
+ }
51
+ }
52
+
53
+ for (const route of folders) {
54
+ if (!mounted.has(route)) {
55
+ issues.push({
56
+ kind: "orphaned-folder",
57
+ route,
58
+ detail: `src/endpoints/${route}/ exists but isn't mounted in index.${ext}.`,
59
+ });
60
+ }
61
+
62
+ for (const suffix of ROUTE_FILE_SUFFIXES) {
63
+ const filePath = join(endpointsDir, route, `${route}.${suffix}.${ext}`);
64
+ try {
65
+ await access(filePath);
66
+ } catch {
67
+ issues.push({ kind: "missing-file", route, detail: `${filePath} is missing.` });
68
+ }
69
+ }
70
+ }
71
+
72
+ return { root, issues };
73
+ }
@@ -0,0 +1,37 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+
4
+ // Matches the two shapes renderEndpointsIndex() ever generates:
5
+ // endpoints.route("/telemetry", telemetryRoutes); (hono)
6
+ // endpoints.use("/telemetry", telemetryRoutes); (express)
7
+ // Shared by add-route/remove-route/list-routes/doctor so all four agree on
8
+ // what "mounted" means by reading the same file the same way, instead of
9
+ // four copies of this regex drifting apart over time.
10
+ const MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
11
+
12
+ export function parseMountedRoutes(indexContents: string): string[] {
13
+ const routes: string[] = [];
14
+ for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
15
+ routes.push(match[1]);
16
+ }
17
+ return routes;
18
+ }
19
+
20
+ export interface EndpointsIndexFile {
21
+ path: string;
22
+ contents: string;
23
+ }
24
+
25
+ export async function readEndpointsIndex(root: string, ext: "ts" | "js"): Promise<EndpointsIndexFile> {
26
+ const path = join(root, "src/endpoints", `index.${ext}`);
27
+ let contents: string;
28
+ try {
29
+ contents = await readFile(path, "utf-8");
30
+ } catch (err) {
31
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
32
+ throw new Error(`${path} doesn't exist — is this a backon project?`);
33
+ }
34
+ throw err;
35
+ }
36
+ return { path, contents };
37
+ }
package/src/generate.ts CHANGED
@@ -84,6 +84,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
84
84
  const files: Array<[string, string]> = [
85
85
  [join(root, `index.${ext}`), renderIndexTs(answers.framework)],
86
86
  [join(root, ".env.example"), renderEnvExample(answers.db)],
87
+ ...(answers.copyEnv ? ([[join(root, ".env"), renderEnvExample(answers.db)]] as Array<[string, string]>) : []),
87
88
  [join(root, "package.json"), renderPackageJson(packageName, answers.framework, answers.language, answers.db)],
88
89
  answers.language === "javascript"
89
90
  ? [join(root, "jsconfig.json"), renderJsconfig()]
@@ -0,0 +1,14 @@
1
+ import { detectProject } from "./detect";
2
+ import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
3
+
4
+ export interface ListRoutesResult {
5
+ root: string;
6
+ routes: string[];
7
+ }
8
+
9
+ /** Read-only: what's actually mounted in src/endpoints/index.<ext> right now. */
10
+ export async function listRoutes(cwd: string = process.cwd()): Promise<ListRoutesResult> {
11
+ const { root, ext } = await detectProject(cwd);
12
+ const { contents } = await readEndpointsIndex(root, ext);
13
+ return { root, routes: parseMountedRoutes(contents) };
14
+ }
package/src/prompts.ts CHANGED
@@ -10,6 +10,7 @@ export interface Answers {
10
10
  language: Language;
11
11
  db: DbChoice;
12
12
  routes: string[];
13
+ copyEnv: boolean;
13
14
  }
14
15
 
15
16
  function bail(): never {
@@ -71,6 +72,12 @@ export async function runPrompts(): Promise<Answers> {
71
72
  });
72
73
  if (p.isCancel(db)) bail();
73
74
 
75
+ const copyEnv = await p.confirm({
76
+ message: "Create .env from .env.example now?",
77
+ initialValue: true,
78
+ });
79
+ if (p.isCancel(copyEnv)) bail();
80
+
74
81
  const routes: string[] = [];
75
82
  p.log.step("Add routes one at a time. Leave the name blank when you're done.");
76
83
  // eslint-disable-next-line no-constant-condition
@@ -92,5 +99,6 @@ export async function runPrompts(): Promise<Answers> {
92
99
  language: language as Language,
93
100
  db: db as DbChoice,
94
101
  routes,
102
+ copyEnv: copyEnv as boolean,
95
103
  };
96
104
  }
@@ -0,0 +1,41 @@
1
+ import { rm, 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 { toKebabCase } from "./prompts";
6
+ import { renderEndpointsIndex } from "./templates/base";
7
+
8
+ export interface RemoveRouteResult {
9
+ route: string;
10
+ root: string;
11
+ removedDir: string;
12
+ }
13
+
14
+ /**
15
+ * The undo for addRoute(): unmounts the route from src/endpoints/index.<ext>
16
+ * and deletes its folder. Refuses if the route isn't currently mounted,
17
+ * rather than silently deleting an orphaned folder that was never wired up
18
+ * — that's what `doctor` is for.
19
+ */
20
+ export async function removeRoute(rawName: string, cwd: string = process.cwd()): Promise<RemoveRouteResult> {
21
+ const route = toKebabCase(rawName);
22
+ if (!route) {
23
+ throw new Error("Route name can't be empty.");
24
+ }
25
+
26
+ const { root, framework, ext } = await detectProject(cwd);
27
+ const { path: indexPath, contents } = await readEndpointsIndex(root, ext);
28
+
29
+ const mounted = parseMountedRoutes(contents);
30
+ if (!mounted.includes(route)) {
31
+ throw new Error(`"${route}" isn't mounted in ${indexPath} — nothing to remove.`);
32
+ }
33
+
34
+ const remaining = mounted.filter((name) => name !== route);
35
+ await writeFile(indexPath, renderEndpointsIndex(framework, remaining));
36
+
37
+ const removedDir = join(root, "src/endpoints", route);
38
+ await rm(removedDir, { recursive: true, force: true });
39
+
40
+ return { route, root, removedDir };
41
+ }