create-backon 0.1.1 → 0.2.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
@@ -17,14 +17,17 @@ Or, without the `bun create` shorthand:
17
17
  bunx create-backon
18
18
  ```
19
19
 
20
- Prompts for a project name, a framework (Hono or Express), a database (Neon,
21
- Postgres, SQLite, or none — via [Drizzle](https://orm.drizzle.team)), and any
22
- number of routes, then generates:
20
+ Prompts for a project name (or `.` to scaffold into the current directory,
21
+ same as `bun create vite@latest .`), a framework (Hono or Express), a
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
25
 
24
26
  ```
25
27
  my-api/
26
- index.ts
28
+ index.ts (or .js in JavaScript mode)
27
29
  .env.example
30
+ tsconfig.json (jsconfig.json in JavaScript mode)
28
31
  src/
29
32
  app.ts
30
33
  config/db.ts
@@ -41,7 +44,18 @@ Each route's `*.routes.ts` wires HTTP methods to controller functions,
41
44
  `*.controller.ts` validates the request via `defineRoute` (from
42
45
  `@mednours/backon` or `@mednours/backon/express`, depending on the
43
46
  framework you picked) and calls into `*.services.ts`, which is where real
44
- data access belongs.
47
+ data access belongs. In JavaScript mode every file is generated without any
48
+ TypeScript-only syntax (no `import type`, no generics, no type
49
+ annotations) — it's not TypeScript with the types stripped, it's meant to
50
+ be genuinely plain JavaScript, with JSDoc `@param` comments on the one
51
+ generated function (the example middleware) that would otherwise have had
52
+ a type annotation, so editors still get intellisense without requiring
53
+ TypeScript as a dependency.
54
+
55
+ Scaffolding into `.` (or any directory) refuses to run if the target
56
+ already has real files in it — a few common exceptions (`.git`,
57
+ `.gitignore`, `README.md`, `LICENSE`, editor folders) are allowed through so
58
+ running this right after `git init` on a fresh repo doesn't get blocked.
45
59
 
46
60
  ## Requirements
47
61
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-backon",
3
- "version": "0.1.1",
3
+ "version": "0.2.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/cli.ts CHANGED
@@ -7,7 +7,9 @@ async function main() {
7
7
  const answers = await runPrompts();
8
8
  const { root, filesWritten } = await generateProject(answers);
9
9
 
10
- p.note(`cd ${answers.projectName}\nbun install\nbun run dev`, "Next steps");
10
+ const nextSteps =
11
+ answers.projectName === "." ? "bun install\nbun run dev" : `cd ${answers.projectName}\nbun install\nbun run dev`;
12
+ p.note(nextSteps, "Next steps");
11
13
  p.log.success(`Wrote ${filesWritten.length} files to ${root}`);
12
14
  }
13
15
 
package/src/generate.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { mkdir, writeFile } from "node:fs/promises";
2
- import { dirname, join } from "node:path";
1
+ import { mkdir, readdir, writeFile } from "node:fs/promises";
2
+ import { basename, dirname, join } from "node:path";
3
3
  import type { Answers } from "./prompts";
4
4
  import {
5
5
  renderAppTs,
@@ -7,6 +7,7 @@ import {
7
7
  renderEnvExample,
8
8
  renderExampleMiddleware,
9
9
  renderIndexTs,
10
+ renderJsconfig,
10
11
  renderPackageJson,
11
12
  renderReadme,
12
13
  renderTsconfig,
@@ -19,39 +20,91 @@ async function write(path: string, contents: string): Promise<void> {
19
20
  await writeFile(path, contents);
20
21
  }
21
22
 
23
+ // Entries a target directory is allowed to already have without tripping
24
+ // the "not empty" guard below — mirrors the ignore-list scaffolders like
25
+ // `bun create vite` use, so running this right after `git init` (or in a
26
+ // fresh GitHub-created repo that already has a README/.gitignore/LICENSE)
27
+ // doesn't get blocked over nothing.
28
+ const IGNORABLE_ENTRIES = new Set([
29
+ ".git",
30
+ ".gitignore",
31
+ ".github",
32
+ ".idea",
33
+ ".vscode",
34
+ ".DS_Store",
35
+ "LICENSE",
36
+ "LICENSE.md",
37
+ "README.md",
38
+ ]);
39
+
40
+ async function ensureSafeToWrite(root: string): Promise<void> {
41
+ let entries: string[];
42
+ try {
43
+ entries = await readdir(root);
44
+ } catch (err) {
45
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return; // doesn't exist yet — nothing to worry about
46
+ throw err;
47
+ }
48
+
49
+ const meaningful = entries.filter((name) => !IGNORABLE_ENTRIES.has(name));
50
+ if (meaningful.length > 0) {
51
+ const shown = meaningful.slice(0, 5).join(", ") + (meaningful.length > 5 ? ", ..." : "");
52
+ throw new Error(
53
+ `Refusing to scaffold into ${root} — it already has files in it (${shown}). Clear it out first, or pick an empty/new directory.`
54
+ );
55
+ }
56
+ }
57
+
22
58
  export interface GenerateResult {
23
59
  root: string;
24
60
  filesWritten: string[];
25
61
  }
26
62
 
27
63
  /**
28
- * Writes the whole scaffold to `<cwd>/<projectName>`. Pure file I/O, no
29
- * prompting — kept separate from prompts.ts so it can be tested directly
30
- * with a fixed Answers object instead of driving fake stdin.
64
+ * Writes the whole scaffold to `<cwd>/<projectName>` — or straight into
65
+ * `cwd` itself when projectName is ".", the same convention
66
+ * `bun create vite@latest .` uses. In that case the actual package name
67
+ * (used in package.json and the README) falls back to the current
68
+ * directory's own name, since "." isn't a valid npm package name.
69
+ *
70
+ * Pure file I/O, no prompting — kept separate from prompts.ts so it can be
71
+ * tested directly with a fixed Answers object instead of driving fake
72
+ * stdin.
31
73
  */
32
74
  export async function generateProject(answers: Answers, cwd: string = process.cwd()): Promise<GenerateResult> {
33
- const root = join(cwd, answers.projectName);
75
+ const root = answers.projectName === "." ? cwd : join(cwd, answers.projectName);
76
+ const packageName = answers.projectName === "." ? basename(root) || "app" : answers.projectName;
77
+ const readmeAnswers: Answers = { ...answers, projectName: packageName };
78
+ const ext = answers.language === "javascript" ? "js" : "ts";
79
+
80
+ await ensureSafeToWrite(root);
81
+
34
82
  const filesWritten: string[] = [];
35
83
 
36
84
  const files: Array<[string, string]> = [
37
- [join(root, "index.ts"), renderIndexTs(answers.framework)],
85
+ [join(root, `index.${ext}`), renderIndexTs(answers.framework)],
38
86
  [join(root, ".env.example"), renderEnvExample(answers.db)],
39
- [join(root, "package.json"), renderPackageJson(answers.projectName, answers.framework, answers.db)],
40
- [join(root, "tsconfig.json"), renderTsconfig()],
41
- [join(root, "README.md"), renderReadme(answers)],
87
+ [join(root, "package.json"), renderPackageJson(packageName, answers.framework, answers.language, answers.db)],
88
+ answers.language === "javascript"
89
+ ? [join(root, "jsconfig.json"), renderJsconfig()]
90
+ : [join(root, "tsconfig.json"), renderTsconfig()],
91
+ [join(root, "README.md"), renderReadme(readmeAnswers)],
42
92
  [join(root, ".gitignore"), "node_modules/\ndist/\n*.log\n.env\n.env.local\n"],
43
- [join(root, "src/app.ts"), renderAppTs(answers.framework)],
44
- [join(root, "src/config/db.ts"), renderDbFile(answers.db)],
45
- [join(root, "src/middleware/example.middleware.ts"), renderExampleMiddleware(answers.framework)],
46
- [join(root, "src/endpoints/index.ts"), renderEndpointsIndex(answers.framework, answers.routes)],
93
+ [join(root, `src/app.${ext}`), renderAppTs(answers.framework)],
94
+ [join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
95
+ [
96
+ join(root, `src/middleware/example.middleware.${ext}`),
97
+ renderExampleMiddleware(answers.framework, answers.language),
98
+ ],
99
+ [join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
47
100
  ];
48
101
 
49
102
  for (const route of answers.routes) {
50
103
  const dir = join(root, "src/endpoints", route);
51
104
  files.push(
52
- [join(dir, `${route}.controller.ts`), renderController(route, answers.framework)],
53
- [join(dir, `${route}.routes.ts`), renderRoutes(route, answers.framework)],
54
- [join(dir, `${route}.services.ts`), renderServices(route)]
105
+ [join(dir, `${route}.controller.${ext}`), renderController(route, answers.framework)],
106
+ [join(dir, `${route}.routes.${ext}`), renderRoutes(route, answers.framework, answers.language)],
107
+ [join(dir, `${route}.services.${ext}`), renderServices(route, answers.language)]
55
108
  );
56
109
  }
57
110
 
package/src/prompts.ts CHANGED
@@ -2,10 +2,12 @@ import * as p from "@clack/prompts";
2
2
 
3
3
  export type DbChoice = "neon" | "postgres" | "sqlite" | "none";
4
4
  export type Framework = "hono" | "express";
5
+ export type Language = "typescript" | "javascript";
5
6
 
6
7
  export interface Answers {
7
8
  projectName: string;
8
9
  framework: Framework;
10
+ language: Language;
9
11
  db: DbChoice;
10
12
  routes: string[];
11
13
  }
@@ -27,11 +29,14 @@ export async function runPrompts(): Promise<Answers> {
27
29
  p.intro("create-backon");
28
30
 
29
31
  const projectName = await p.text({
30
- message: "Project name",
32
+ message: 'Project name (or "." to scaffold into the current directory)',
31
33
  placeholder: "my-api",
32
34
  validate: (value) => {
33
35
  if (!value) return "Required.";
34
- if (!/^[a-z0-9-]+$/.test(value)) return "Lowercase letters, numbers, and hyphens only.";
36
+ if (value === ".") return undefined;
37
+ if (!/^[a-z0-9-]+$/.test(value)) {
38
+ return 'Lowercase letters, numbers, and hyphens only (or "." for the current directory).';
39
+ }
35
40
  return undefined;
36
41
  },
37
42
  });
@@ -41,11 +46,20 @@ export async function runPrompts(): Promise<Answers> {
41
46
  message: "Framework",
42
47
  options: [
43
48
  { value: "hono", label: "Hono", hint: "faster, runs anywhere — Bun, edge, serverless" },
44
- { value: "express", label: "Express", hint: "the ecosystem you already know" },
49
+ { value: "express", label: "Express" },
45
50
  ],
46
51
  });
47
52
  if (p.isCancel(framework)) bail();
48
53
 
54
+ const language = await p.select({
55
+ message: "Language",
56
+ options: [
57
+ { value: "typescript", label: "TypeScript" },
58
+ { value: "javascript", label: "JavaScript" },
59
+ ],
60
+ });
61
+ if (p.isCancel(language)) bail();
62
+
49
63
  const db = await p.select({
50
64
  message: "Database",
51
65
  options: [
@@ -62,8 +76,8 @@ export async function runPrompts(): Promise<Answers> {
62
76
  // eslint-disable-next-line no-constant-condition
63
77
  while (true) {
64
78
  const name = await p.text({
65
- message: routes.length === 0 ? "Route name (e.g. telemetry)" : "Another route? (blank to finish)",
66
- placeholder: routes.length === 0 ? "telemetry" : "",
79
+ message: routes.length === 0 ? "Route name" : "Another route? (blank to finish)",
80
+ placeholder: routes.length === 0 ? "e.g. users" : "",
67
81
  });
68
82
  if (p.isCancel(name)) bail();
69
83
  if (!name) break;
@@ -75,6 +89,7 @@ export async function runPrompts(): Promise<Answers> {
75
89
  return {
76
90
  projectName: projectName as string,
77
91
  framework: framework as Framework,
92
+ language: language as Language,
78
93
  db: db as DbChoice,
79
94
  routes,
80
95
  };
@@ -1,7 +1,15 @@
1
- import type { Answers, Framework } from "../prompts";
1
+ import type { Answers, Framework, Language } from "../prompts";
2
2
  import { camelCase } from "./route";
3
3
  import { dbDependencies, dbEnvVars, dbReadmeNote } from "./db";
4
4
 
5
+ // renderIndexTs/renderAppTs/renderEndpointsIndex are intentionally NOT
6
+ // language-aware: none of them contain TypeScript-only syntax (no type
7
+ // annotations, no `import type`, no generics), so the exact same content is
8
+ // valid whether it ends up in a .ts or a .js file. Only the file extension
9
+ // generate.ts writes them under changes between languages. Keeping one
10
+ // function instead of two identical ones avoids drift between copies that
11
+ // would otherwise need to stay in sync forever.
12
+
5
13
  export function renderIndexTs(framework: Framework): string {
6
14
  const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
7
15
  return `import { serve } from "${backonImport}";
@@ -23,7 +31,6 @@ app.use(exampleMiddleware);
23
31
  app.use("/", endpoints);
24
32
  `;
25
33
  }
26
-
27
34
  return `import { createApp } from "@mednours/backon";
28
35
  import { endpoints } from "./endpoints";
29
36
  import { exampleMiddleware } from "./middleware/example.middleware";
@@ -35,8 +42,33 @@ app.route("/", endpoints);
35
42
  `;
36
43
  }
37
44
 
38
- export function renderExampleMiddleware(framework: Framework): string {
45
+ export function renderExampleMiddleware(framework: Framework, language: Language): string {
39
46
  if (framework === "express") {
47
+ if (language === "javascript") {
48
+ return `/**
49
+ * Example middleware, just to show the pattern — stamps a request-start
50
+ * timestamp onto res.locals. Error handling, request logging, secure
51
+ * headers, CORS, and the request body size limit are already wired into
52
+ * createApp() by backon itself; you don't need your own
53
+ * error.middleware.js unless you want to override that default behavior.
54
+ *
55
+ * This is plain Express middleware (req, res, next), not backon's
56
+ * BackonContext — that wrapper only exists inside defineRoute() handlers.
57
+ * Middleware always operates at the framework's own layer. (Also: Express
58
+ * middleware can't safely set a response header after calling next() — by
59
+ * then the response may already be sent — which is why this demonstrates
60
+ * res.locals instead of a header.)
61
+ *
62
+ * @param {import("@mednours/backon/express").Request} req
63
+ * @param {import("@mednours/backon/express").Response} res
64
+ * @param {import("@mednours/backon/express").NextFunction} next
65
+ */
66
+ export function exampleMiddleware(req, res, next) {
67
+ res.locals.requestStartedAt = Date.now();
68
+ next();
69
+ }
70
+ `;
71
+ }
40
72
  return `import type { Request, Response, NextFunction } from "@mednours/backon/express";
41
73
 
42
74
  /**
@@ -60,6 +92,24 @@ export function exampleMiddleware(req: Request, res: Response, next: NextFunctio
60
92
  `;
61
93
  }
62
94
 
95
+ if (language === "javascript") {
96
+ return `/**
97
+ * Example middleware, just to show the pattern — adds a response-time
98
+ * header. Error handling, request logging, secure headers, CORS, and the
99
+ * request body size limit are already wired into createApp() by backon
100
+ * itself; you don't need your own error.middleware.js unless you want to
101
+ * override that default behavior.
102
+ *
103
+ * @param {import("@mednours/backon").BackonContext} c
104
+ * @param {import("@mednours/backon").Next} next
105
+ */
106
+ export async function exampleMiddleware(c, next) {
107
+ const start = performance.now();
108
+ await next();
109
+ c.header("x-response-time-ms", String(Math.round(performance.now() - start)));
110
+ }
111
+ `;
112
+ }
63
113
  return `import type { Next } from "@mednours/backon";
64
114
  import type { BackonContext } from "@mednours/backon";
65
115
 
@@ -132,7 +182,37 @@ export function renderTsconfig(): string {
132
182
  `;
133
183
  }
134
184
 
135
- export function renderPackageJson(projectName: string, framework: Framework, db: Answers["db"]): string {
185
+ /**
186
+ * JavaScript-mode counterpart to renderTsconfig(): no build step and no
187
+ * `tsc --noEmit` script to run against it, but a jsconfig.json still gets
188
+ * editors (VS Code and anything else that reads it) path resolution and
189
+ * JSDoc-based intellisense on the @param annotations in the generated
190
+ * middleware, without requiring TypeScript as a dependency or enforcing
191
+ * type errors on every file.
192
+ */
193
+ export function renderJsconfig(): string {
194
+ return `{
195
+ "compilerOptions": {
196
+ "target": "ESNext",
197
+ "module": "ESNext",
198
+ "moduleResolution": "bundler",
199
+ "lib": ["ESNext"],
200
+ "checkJs": false,
201
+ "allowJs": true
202
+ },
203
+ "include": ["index.js", "src"]
204
+ }
205
+ `;
206
+ }
207
+
208
+ export function renderPackageJson(
209
+ projectName: string,
210
+ framework: Framework,
211
+ language: Language,
212
+ db: Answers["db"]
213
+ ): string {
214
+ const ext = language === "javascript" ? "js" : "ts";
215
+
136
216
  const dependencies: Record<string, string> =
137
217
  framework === "express"
138
218
  ? {
@@ -151,29 +231,31 @@ export function renderPackageJson(projectName: string, framework: Framework, db:
151
231
  ...dbDependencies(db),
152
232
  };
153
233
 
234
+ // JavaScript mode intentionally has zero TypeScript-related devDependencies
235
+ // (no `typescript`, no `@types/*`) — there's nothing being compiled or
236
+ // typechecked, so pulling those in would just be dead weight.
154
237
  const devDependencies: Record<string, string> =
155
- framework === "express"
156
- ? {
157
- "@types/bun": "latest",
158
- "@types/express": "^4.17.21",
159
- typescript: "^5.7.2",
160
- }
161
- : {
162
- "@types/bun": "latest",
163
- typescript: "^5.7.2",
164
- };
238
+ language === "javascript"
239
+ ? {}
240
+ : framework === "express"
241
+ ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" }
242
+ : { "@types/bun": "latest", typescript: "^5.7.2" };
243
+
244
+ const scripts: Record<string, string> = {
245
+ dev: `bun run --watch index.${ext}`,
246
+ start: `bun run index.${ext}`,
247
+ test: "bun test",
248
+ };
249
+ if (language === "typescript") {
250
+ scripts.typecheck = "tsc --noEmit";
251
+ }
165
252
 
166
253
  const pkg = {
167
254
  name: projectName,
168
255
  version: "0.1.0",
169
256
  private: true,
170
257
  type: "module",
171
- scripts: {
172
- dev: "bun run --watch index.ts",
173
- start: "bun run index.ts",
174
- test: "bun test",
175
- typecheck: "tsc --noEmit",
176
- },
258
+ scripts,
177
259
  dependencies,
178
260
  devDependencies,
179
261
  };
@@ -187,10 +269,11 @@ export function renderReadme(answers: Answers): string {
187
269
  : "- (none yet — add one under src/endpoints/)";
188
270
 
189
271
  const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
272
+ const languageLabel = answers.language === "javascript" ? "JavaScript" : "TypeScript";
190
273
 
191
274
  return `# ${answers.projectName}
192
275
 
193
- Generated by \`create-backon\` (${answers.framework}).
276
+ Generated by \`create-backon\` (${answers.framework}, ${languageLabel}).
194
277
 
195
278
  ## Getting started
196
279
 
@@ -208,9 +291,9 @@ ${dbReadmeNote(answers.db)}
208
291
 
209
292
  ${routeList}
210
293
 
211
- Each route folder follows the same shape: \`*.routes.ts\` wires HTTP methods
212
- to controller functions, \`*.controller.ts\` validates the request (via
213
- \`defineRoute\` from \`${backonImport}\`) and calls into \`*.services.ts\`,
214
- which is where real data access belongs.
294
+ Each route folder follows the same shape: \`*.routes.${answers.language === "javascript" ? "js" : "ts"}\` wires HTTP
295
+ methods to controller functions, \`*.controller.${answers.language === "javascript" ? "js" : "ts"}\` validates the
296
+ request (via \`defineRoute\` from \`${backonImport}\`) and calls into
297
+ \`*.services.${answers.language === "javascript" ? "js" : "ts"}\`, which is where real data access belongs.
215
298
  `;
216
299
  }
@@ -1,4 +1,4 @@
1
- import type { Framework } from "../prompts";
1
+ import type { Framework, Language } from "../prompts";
2
2
 
3
3
  function pascalCase(name: string): string {
4
4
  return name
@@ -7,6 +7,10 @@ function pascalCase(name: string): string {
7
7
  .join("");
8
8
  }
9
9
 
10
+ // Not language-aware: defineRoute()'s body/query/params typing in TS comes
11
+ // entirely from generic inference (defineRoute<B, Q, P>(...)) — the
12
+ // generated code itself never writes an explicit type annotation, so this
13
+ // file is already valid JavaScript as-is. Only the file extension changes.
10
14
  export function renderController(route: string, framework: Framework): string {
11
15
  const Route = pascalCase(route);
12
16
  const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
@@ -29,13 +33,31 @@ export const create = defineRoute({ body: create${Route}Schema }, async (c, { bo
29
33
  `;
30
34
  }
31
35
 
32
- export function renderRoutes(route: string, framework: Framework): string {
36
+ export function renderRoutes(route: string, framework: Framework, language: Language): string {
33
37
  if (framework === "express") {
38
+ // Router() takes no generic parameter either way — same content for
39
+ // both languages, same reasoning as renderController above.
34
40
  return `import { Router } from "@mednours/backon/express";
35
41
  import * as controller from "./${route}.controller";
36
42
 
37
43
  export const ${camelCase(route)}Routes = Router();
38
44
 
45
+ ${camelCase(route)}Routes.get("/", controller.list);
46
+ ${camelCase(route)}Routes.post("/", controller.create);
47
+ `;
48
+ }
49
+
50
+ if (language === "javascript") {
51
+ // `new Hono<Env>()` is TypeScript-only syntax (a generic type
52
+ // argument) — not valid JavaScript, so the JS variant drops both the
53
+ // `type Env` import and the `<Env>` argument. The Env generic only
54
+ // affects c.get()/c.set() typing anyway, which doesn't exist in plain
55
+ // JS regardless.
56
+ return `import { Hono } from "@mednours/backon";
57
+ import * as controller from "./${route}.controller";
58
+
59
+ export const ${camelCase(route)}Routes = new Hono();
60
+
39
61
  ${camelCase(route)}Routes.get("/", controller.list);
40
62
  ${camelCase(route)}Routes.post("/", controller.create);
41
63
  `;
@@ -51,7 +73,20 @@ ${camelCase(route)}Routes.post("/", controller.create);
51
73
  `;
52
74
  }
53
75
 
54
- export function renderServices(route: string): string {
76
+ export function renderServices(route: string, language: Language): string {
77
+ if (language === "javascript") {
78
+ return `// TODO: replace with real data access (see src/config/db.js)
79
+
80
+ export async function list() {
81
+ return [];
82
+ }
83
+
84
+ export async function create(data) {
85
+ return { id: crypto.randomUUID(), ...data };
86
+ }
87
+ `;
88
+ }
89
+
55
90
  return `// TODO: replace with real data access (see src/config/db.ts)
56
91
 
57
92
  export async function list() {