create-backon 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/add-method.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { editSource, ensureImports, appendStatements } from "./ast-edit";
3
4
  import { detectProject } from "./detect";
4
5
  import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
5
6
  import { parseRouteMethods } from "./route-methods";
@@ -19,33 +20,16 @@ export interface AddMethodResult {
19
20
  }
20
21
 
21
22
  // The exact placeholder comment each blank file starts with — see
22
- // templates/route.ts. Stripped the first time a real method lands, wherever
23
- // it happens to sit in the file (start of controller.ts/services.ts, but
24
- // mid-file in routes.ts, after the Router()/Hono() line).
23
+ // templates/route.ts. Stripped as plain text before the AST layer below
24
+ // ever sees the file: a file that's only a comment (no statements yet) has
25
+ // nothing for ensureImports()/appendStatements() to attach it to, and this
26
+ // comment isn't code that needs AST-accurate handling anyway.
25
27
  const PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
26
28
 
27
29
  function stripPlaceholder(content: string): string {
28
30
  return content.replace(PLACEHOLDER_PATTERN, "");
29
31
  }
30
32
 
31
- /** Inserts any of importLines not already present, right after the file's existing leading import block. */
32
- function ensureImports(content: string, importLines: string[]): string {
33
- const stripped = stripPlaceholder(content);
34
- const missing = importLines.filter((line) => !stripped.includes(line));
35
- if (missing.length === 0) return stripped;
36
-
37
- const lines = stripped.split("\n");
38
- let insertAt = 0;
39
- while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
40
- lines.splice(insertAt, 0, ...missing);
41
- return lines.join("\n");
42
- }
43
-
44
- function appendBlock(content: string, block: string): string {
45
- const trimmed = content.replace(/\n+$/, "");
46
- return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
47
- }
48
-
49
33
  /**
50
34
  * Adds one HTTP method to an already-mounted, already-blank-or-partial
51
35
  * endpoint: appends a defineRoute() export (with whatever params/body/query
@@ -55,6 +39,13 @@ function appendBlock(content: string, block: string): string {
55
39
  * the route mount line. All three files are read fresh off disk first, so
56
40
  * this is safe to call repeatedly, or after the previous method's stub was
57
41
  * hand-edited.
42
+ *
43
+ * Every file edit goes through ast-edit.ts's ts-morph helpers: an import is
44
+ * only added if the real AST doesn't already have one covering it (not
45
+ * whether an identical line of text happens to appear anywhere), and the
46
+ * new method's code is appended as real parsed statements rather than
47
+ * spliced-in text — so this stays correct even if the file was previously
48
+ * hand-reformatted in a way that would have thrown off a text-based check.
58
49
  */
59
50
  export async function addMethod(route: string, spec: MethodSpec, cwd: string = process.cwd()): Promise<AddMethodResult> {
60
51
  const { root, framework, language, ext } = await detectProject(cwd);
@@ -84,12 +75,20 @@ export async function addMethod(route: string, spec: MethodSpec, cwd: string = p
84
75
  throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
85
76
  }
86
77
 
87
- const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
88
- const newRoutes = appendBlock(
89
- ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
90
- routeMountLine(route, spec)
91
- );
92
- const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
78
+ const newController = editSource(controllerPath, stripPlaceholder(controllerContents), (project, sourceFile) => {
79
+ ensureImports(sourceFile, project, controllerImports(route, framework));
80
+ appendStatements(sourceFile, renderControllerMethod(spec));
81
+ });
82
+
83
+ const newRoutes = editSource(routesPath, stripPlaceholder(routesContents), (project, sourceFile) => {
84
+ ensureImports(sourceFile, project, [`import * as controller from "./${route}.controller";`]);
85
+ appendStatements(sourceFile, routeMountLine(route, spec));
86
+ });
87
+
88
+ const newServices = editSource(servicesPath, stripPlaceholder(servicesContents), (project, sourceFile) => {
89
+ ensureImports(sourceFile, project, serviceImports(route, spec, language));
90
+ appendStatements(sourceFile, renderServiceMethod(spec, language));
91
+ });
93
92
 
94
93
  await Promise.all([
95
94
  writeFile(controllerPath, newController),
@@ -0,0 +1,224 @@
1
+ import { Node, Project, type SourceFile } from "ts-morph";
2
+
3
+ /**
4
+ * The AST-based replacement for the old ensureImports()/appendBlock()
5
+ * (add-method.ts) and removeBlock() (remove-method.ts) pair — both used to
6
+ * find "this method's code" by splitting file content on blank lines and
7
+ * matching text, which only works if nothing nearby ever gets reformatted.
8
+ * ts-morph gives real statement/import identity instead: an import is
9
+ * recognized as already present by its actual module+specifier structure
10
+ * (not by whether an identical line of text happens to appear anywhere in
11
+ * the file), and a method's statements are found and removed by the exact
12
+ * name addMethod()/removeMethod() already enforce is unique per endpoint —
13
+ * so a hand-reformatted quote style, semicolon, or import order doesn't
14
+ * make either operation silently miss its target.
15
+ *
16
+ * One throwaway in-memory Project per file edit — these are cheap and
17
+ * short-lived (one per addMethod()/removeMethod() call), not shared across
18
+ * the CLI's lifetime.
19
+ */
20
+ function makeProject(): Project {
21
+ return new Project({
22
+ useInMemoryFileSystem: true,
23
+ compilerOptions: { allowJs: true, checkJs: false },
24
+ });
25
+ }
26
+
27
+ export function loadSource(path: string, contents: string): { project: Project; sourceFile: SourceFile } {
28
+ const project = makeProject();
29
+ const sourceFile = project.createSourceFile(path, contents);
30
+ return { project, sourceFile };
31
+ }
32
+
33
+ /** Load → mutate → print, in one call — the shape every add-method.ts/remove-method.ts edit follows. */
34
+ export function editSource(path: string, contents: string, mutate: (project: Project, sourceFile: SourceFile) => void): string {
35
+ const { project, sourceFile } = loadSource(path, contents);
36
+ mutate(project, sourceFile);
37
+ return printSource(sourceFile);
38
+ }
39
+
40
+ interface ParsedImportLine {
41
+ moduleSpecifier: string;
42
+ isTypeOnly: boolean;
43
+ namespaceImport?: string;
44
+ namedImports: string[];
45
+ }
46
+
47
+ /** Parses one raw `import ... from "...";` line (as templates/route.ts already produces) into its real structure, via a disposable scratch file in the same project. */
48
+ function parseImportLine(project: Project, line: string): ParsedImportLine {
49
+ const scratch = project.createSourceFile("__scratch_import__.ts", line, { overwrite: true });
50
+ const decl = scratch.getImportDeclarations()[0];
51
+ if (!decl) throw new Error(`Not a valid import statement: ${line}`);
52
+ const parsed: ParsedImportLine = {
53
+ moduleSpecifier: decl.getModuleSpecifierValue(),
54
+ isTypeOnly: decl.isTypeOnly(),
55
+ namespaceImport: decl.getNamespaceImport()?.getText(),
56
+ namedImports: decl.getNamedImports().map((ni) => ni.getName()),
57
+ };
58
+ project.removeSourceFile(scratch);
59
+ return parsed;
60
+ }
61
+
62
+ /**
63
+ * Adds each of `lines` to `sourceFile` unless a declaration already covers
64
+ * it — checked by real import structure, not raw text. Each line becomes
65
+ * its own new import declaration when nothing already covers it (mirrors
66
+ * the old one-declaration-per-addMethod-call granularity, just checked more
67
+ * accurately — this doesn't merge into an existing *different* named-import
68
+ * declaration from the same module, since remove-method.ts's cleanup relies
69
+ * on each method's schema-type import staying in its own declaration).
70
+ */
71
+ export function ensureImports(sourceFile: SourceFile, project: Project, lines: string[]): void {
72
+ for (const line of lines) {
73
+ const spec = parseImportLine(project, line);
74
+ const alreadyPresent = sourceFile.getImportDeclarations().some((d) => {
75
+ if (d.getModuleSpecifierValue() !== spec.moduleSpecifier) return false;
76
+ if (d.isTypeOnly() !== spec.isTypeOnly) return false;
77
+ if (spec.namespaceImport) return d.getNamespaceImport()?.getText() === spec.namespaceImport;
78
+ const names = new Set(d.getNamedImports().map((ni) => ni.getName()));
79
+ return spec.namedImports.length > 0 && spec.namedImports.every((n) => names.has(n));
80
+ });
81
+ if (alreadyPresent) continue;
82
+
83
+ sourceFile.addImportDeclaration({
84
+ moduleSpecifier: spec.moduleSpecifier,
85
+ isTypeOnly: spec.isTypeOnly,
86
+ ...(spec.namespaceImport ? { namespaceImport: spec.namespaceImport } : { namedImports: spec.namedImports }),
87
+ });
88
+ }
89
+ }
90
+
91
+ /** Appends a method's generated code (from templates/route.ts) as real statements at the end of the file. */
92
+ export function appendStatements(sourceFile: SourceFile, code: string): void {
93
+ sourceFile.addStatements(`\n${code}`);
94
+ }
95
+
96
+ /**
97
+ * Removes a method's schema consts (nameParamsSchema/BodySchema/QuerySchema)
98
+ * and its defineRoute() export from a controller file — found by exact
99
+ * declared name, the same uniqueness addMethod() already enforces per
100
+ * endpoint, rather than by which \n\n-delimited block of text they happen
101
+ * to sit in. Returns whether anything was actually removed, so the caller
102
+ * can tell "nothing there" apart from "removed everything there was".
103
+ */
104
+ export function removeControllerMethod(sourceFile: SourceFile, name: string): boolean {
105
+ const targets = new Set([name, `${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
106
+ let removed = false;
107
+ for (const stmt of sourceFile.getVariableStatements()) {
108
+ const decls = stmt.getDeclarations();
109
+ if (decls.length === 1 && targets.has(decls[0]!.getName())) {
110
+ stmt.remove();
111
+ removed = true;
112
+ }
113
+ }
114
+ // renderControllerMethod() puts a "// TODO: replace with the real shape
115
+ // of ..." comment directly above a body/query schema const, with no
116
+ // blank line between them. When a method's schema const sits right next
117
+ // to ANOTHER statement in the same group (e.g. paramsSchema directly
118
+ // above bodySchema, no blank line), ts-morph's leading-trivia detection
119
+ // can attribute that comment to more than one statement, and .remove()
120
+ // above doesn't reliably take it with it — it survives, reattached as
121
+ // leading trivia on whatever statement now comes next. Sweep for it
122
+ // explicitly, matched by this method's own name (never another method's,
123
+ // since the name is unique per endpoint) rather than by position, and
124
+ // only AFTER the statement removals above, once each surviving
125
+ // statement's leading trivia is no longer ambiguous.
126
+ if (removed) stripOrphanedTodoComment(sourceFile, name);
127
+ return removed;
128
+ }
129
+
130
+ function stripOrphanedTodoComment(sourceFile: SourceFile, name: string): void {
131
+ const marker = `replace with the real shape of "${name}"`;
132
+ const ranges: Array<{ pos: number; end: number }> = [];
133
+ for (const stmt of sourceFile.getStatements()) {
134
+ for (const range of stmt.getLeadingCommentRanges()) {
135
+ if (range.getText().includes(marker)) ranges.push({ pos: range.getPos(), end: range.getEnd() });
136
+ }
137
+ }
138
+ // Remove furthest-in-the-file first, so an earlier removal never shifts
139
+ // the position of a range still waiting to be processed.
140
+ ranges.sort((a, b) => b.pos - a.pos);
141
+ const fullText = sourceFile.getFullText();
142
+ for (const { pos, end } of ranges) {
143
+ const end2 = fullText[end] === "\n" ? end + 1 : end; // eat the comment's own newline too, not just its text
144
+ sourceFile.removeText(pos, end2);
145
+ }
146
+ }
147
+
148
+ /** Removes the mount-line ExpressionStatement calling controller.<name> — matched by that reference, not by verb/path text, so a hand-reformatted line (quotes, spacing, a trailing comment) doesn't hide it. */
149
+ export function removeRouteMount(sourceFile: SourceFile, name: string): boolean {
150
+ for (const stmt of sourceFile.getStatements()) {
151
+ if (!Node.isExpressionStatement(stmt)) continue;
152
+ const expr = stmt.getExpression();
153
+ if (!Node.isCallExpression(expr)) continue;
154
+ const args = expr.getArguments();
155
+ const last = args[args.length - 1];
156
+ if (last && Node.isPropertyAccessExpression(last) && last.getName() === name) {
157
+ stmt.remove();
158
+ return true;
159
+ }
160
+ }
161
+ return false;
162
+ }
163
+
164
+ /** Removes a service function by name, plus any import declaration whose entire named-import set belongs to that same method's schema types (each method's type import stays in its own declaration — see ensureImports()'s doc comment — so "entire set" never catches another method's names too). */
165
+ export function removeServiceMethod(sourceFile: SourceFile, name: string): boolean {
166
+ const fn = sourceFile.getFunction(name);
167
+ if (!fn) return false;
168
+ fn.remove();
169
+
170
+ const methodTypeNames = new Set([`${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
171
+ for (const importDecl of sourceFile.getImportDeclarations()) {
172
+ const names = importDecl.getNamedImports().map((ni) => ni.getName());
173
+ if (names.length > 0 && names.every((n) => methodTypeNames.has(n))) {
174
+ importDecl.remove();
175
+ }
176
+ }
177
+ return true;
178
+ }
179
+
180
+ const SCHEMA_CONST_SUFFIXES = ["ParamsSchema", "BodySchema", "QuerySchema"];
181
+
182
+ function isSchemaConstStatement(node: Node): boolean {
183
+ if (!Node.isVariableStatement(node)) return false;
184
+ const decls = node.getDeclarations();
185
+ return decls.length === 1 && SCHEMA_CONST_SUFFIXES.some((suffix) => decls[0]!.getName().endsWith(suffix));
186
+ }
187
+
188
+ /**
189
+ * Reconstructs the file's text from its current AST instead of returning
190
+ * whatever ts-morph's in-place text edits left behind — in-place edits are
191
+ * precise about *removing* a node's own text, but don't reliably leave the
192
+ * same blank-line spacing around the survivors that the old block-based
193
+ * convention had. Import declarations stay packed together with no blank
194
+ * line between them (as generated); every other top-level statement gets
195
+ * its own blank-line-separated paragraph, EXCEPT a schema const
196
+ * (*ParamsSchema/*BodySchema/*QuerySchema) which stays glued to the
197
+ * statement right after it — renderControllerMethod() always emits a
198
+ * method's schema consts immediately followed by its defineRoute() export,
199
+ * with no blank line between them, and this keeps that grouping intact
200
+ * through arbitrary add/remove cycles instead of only on first write.
201
+ */
202
+ export function printSource(sourceFile: SourceFile): string {
203
+ const importDecls = sourceFile.getImportDeclarations();
204
+ const importText = importDecls.map((d) => d.getText()).join("\n");
205
+
206
+ const rest = sourceFile.getStatements().filter((s) => !Node.isImportDeclaration(s));
207
+ const paragraphs: string[] = [];
208
+ let i = 0;
209
+ while (i < rest.length) {
210
+ const parts: string[] = [];
211
+ while (i < rest.length && isSchemaConstStatement(rest[i]!)) {
212
+ parts.push(rest[i]!.getFullText().trim());
213
+ i++;
214
+ }
215
+ if (i < rest.length) {
216
+ parts.push(rest[i]!.getFullText().trim());
217
+ i++;
218
+ }
219
+ paragraphs.push(parts.join("\n"));
220
+ }
221
+
222
+ const blocks = [importText, ...paragraphs].filter((b) => b.length > 0);
223
+ return blocks.length > 0 ? `${blocks.join("\n\n")}\n` : "";
224
+ }
package/src/cli.ts CHANGED
@@ -18,6 +18,7 @@ import { addMethod } from "./add-method";
18
18
  import { removeMethod } from "./remove-method";
19
19
  import { detectDbStatus } from "./db-status";
20
20
  import { detectProject } from "./detect";
21
+ import { addCrudMethods } from "./crud-scaffold";
21
22
  import {
22
23
  detectMethodValidation,
23
24
  formatEndpointsDashboard,
@@ -58,17 +59,42 @@ async function promptForRouteName(introText: string): Promise<string> {
58
59
  return answer;
59
60
  }
60
61
 
62
+ /** Shared by every "just added a CRUD set" log line, interactive or scripted. */
63
+ function logCrudResult(result: Awaited<ReturnType<typeof addCrudMethods>>): void {
64
+ const skippedNote = result.skipped.length ? ` (skipped, already there: ${result.skipped.join(", ")})` : "";
65
+ p.log.success(`Added CRUD methods to ${result.route}: ${result.added.join(", ") || "none"}${skippedNote}`);
66
+ }
67
+
61
68
  async function runAddRoute(args: string[]): Promise<void> {
62
- let [name] = args;
69
+ const crudFlagIndex = args.indexOf("--crud");
70
+ const withCrud = crudFlagIndex !== -1;
71
+ const positional = withCrud ? args.filter((_, i) => i !== crudFlagIndex) : args;
72
+ let [name] = positional;
63
73
 
74
+ let interactive = false;
64
75
  if (!name) {
76
+ interactive = true;
65
77
  name = await promptForRouteName("create-backon add-route");
66
78
  p.outro(`Adding ${name}...`);
67
79
  }
68
80
 
69
81
  const { route, root, filesWritten } = await addRoute(name);
70
82
  p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
71
- p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
83
+
84
+ let scaffoldCrud = withCrud;
85
+ if (!withCrud && interactive) {
86
+ const answer = await p.confirm({
87
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
88
+ initialValue: false,
89
+ });
90
+ scaffoldCrud = !p.isCancel(answer) && answer;
91
+ }
92
+
93
+ if (scaffoldCrud) {
94
+ logCrudResult(await addCrudMethods(route, root));
95
+ } else {
96
+ p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
97
+ }
72
98
  }
73
99
 
74
100
  async function runRemoveRoute(args: string[]): Promise<void> {
@@ -280,6 +306,14 @@ async function serverConfigAddEndpoint(): Promise<void> {
280
306
  }
281
307
  const { route, filesWritten } = await addRoute(name);
282
308
  p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
309
+
310
+ const scaffoldCrud = await p.confirm({
311
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
312
+ initialValue: false,
313
+ });
314
+ if (!p.isCancel(scaffoldCrud) && scaffoldCrud) {
315
+ logCrudResult(await addCrudMethods(route));
316
+ }
283
317
  }
284
318
 
285
319
  async function serverConfigRemoveEndpoint(summaries: EndpointSummary[]): Promise<void> {
@@ -0,0 +1,62 @@
1
+ import { addMethod } from "./add-method";
2
+ import { listEndpointsWithMethods } from "./route-methods";
3
+ import type { MethodSpec } from "./templates/route";
4
+
5
+ /**
6
+ * The standard REST five — list/create/getById/update/remove — named to
7
+ * match exactly what `add-method`'s own name-suggestion logic
8
+ * (suggestMethodName in cli.ts) already produces for GET /, POST /,
9
+ * GET /:id, PUT /:id, DELETE /:id. Not a new convention, just all five of
10
+ * an existing one applied at once instead of one at a time.
11
+ */
12
+ export const CRUD_METHOD_SPECS: readonly MethodSpec[] = [
13
+ { verb: "get", path: "/", name: "list", needsBody: false, needsQuery: false },
14
+ { verb: "post", path: "/", name: "create", needsBody: true, needsQuery: false },
15
+ { verb: "get", path: "/:id", name: "getById", needsBody: false, needsQuery: false },
16
+ { verb: "put", path: "/:id", name: "update", needsBody: true, needsQuery: false },
17
+ { verb: "delete", path: "/:id", name: "remove", needsBody: false, needsQuery: false },
18
+ ];
19
+
20
+ export interface AddCrudMethodsResult {
21
+ route: string;
22
+ /** Method names actually written. */
23
+ added: string[];
24
+ /** Method names skipped because the endpoint already had a same-name method, or something already mounted at that verb+path. */
25
+ skipped: string[];
26
+ }
27
+
28
+ /**
29
+ * Adds the standard CRUD_METHOD_SPECS set to an already-mounted endpoint,
30
+ * via addMethod() — the exact same codegen a manual `add-method` run
31
+ * produces, just five calls run in sequence instead of one at a time.
32
+ * Sequential on purpose: addMethod() reads all three of an endpoint's files
33
+ * fresh off disk on every call, so firing five in parallel at the same
34
+ * endpoint would have them race on stale reads and clobber each other.
35
+ *
36
+ * Any of the five that would collide with a method the endpoint already has
37
+ * (same name, or the same verb+path already mounted) is skipped rather than
38
+ * failing the whole batch — this makes it safe to run on an endpoint that
39
+ * already has some hand-added methods, e.g. re-running it after removing
40
+ * just "remove" to get the other four without erroring on the four that are
41
+ * already there.
42
+ */
43
+ export async function addCrudMethods(route: string, cwd: string = process.cwd()): Promise<AddCrudMethodsResult> {
44
+ const summaries = await listEndpointsWithMethods(cwd);
45
+ const existing = [...(summaries.find((s) => s.route === route)?.methods ?? [])];
46
+
47
+ const added: string[] = [];
48
+ const skipped: string[] = [];
49
+
50
+ for (const spec of CRUD_METHOD_SPECS) {
51
+ const collides = existing.some((m) => m.name === spec.name || (m.verb === spec.verb && m.path === spec.path));
52
+ if (collides) {
53
+ skipped.push(spec.name);
54
+ continue;
55
+ }
56
+ await addMethod(route, spec, cwd);
57
+ added.push(spec.name);
58
+ existing.push({ verb: spec.verb, path: spec.path, name: spec.name });
59
+ }
60
+
61
+ return { route, added, skipped };
62
+ }
package/src/generate.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  renderEndpointsIndex,
7
7
  renderEnvExample,
8
8
  renderExampleMiddleware,
9
+ renderGenerateClientScript,
9
10
  renderGenerateDocsScript,
10
11
  renderIndexTs,
11
12
  renderJsconfig,
@@ -94,7 +95,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
94
95
  [join(root, "README.md"), renderReadme(readmeAnswers)],
95
96
  [
96
97
  join(root, ".gitignore"),
97
- `node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n${
98
+ `node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\nclient/\n${
98
99
  answers.deployTarget === "vercel" ? ".vercel\n" : ""
99
100
  }`,
100
101
  ],
@@ -106,6 +107,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
106
107
  ],
107
108
  [join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
108
109
  [join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
110
+ [join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
109
111
  ...(answers.deployTarget === "vercel"
110
112
  ? ([[join(root, "vercel.json"), renderVercelJson()]] as Array<[string, string]>)
111
113
  : []),
@@ -1,9 +1,10 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { editSource, removeControllerMethod, removeRouteMount, removeServiceMethod } from "./ast-edit";
3
4
  import { detectProject } from "./detect";
4
5
  import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
5
6
  import { parseRouteMethods } from "./route-methods";
6
- import { renderBlankController, renderBlankRoutes, renderBlankServices, routeMountLine, type HttpVerb } from "./templates/route";
7
+ import { renderBlankController, renderBlankRoutes, renderBlankServices, type HttpVerb } from "./templates/route";
7
8
 
8
9
  export interface RemoveMethodResult {
9
10
  route: string;
@@ -11,32 +12,25 @@ export interface RemoveMethodResult {
11
12
  removed: { verb: HttpVerb; path: string; name: string };
12
13
  }
13
14
 
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
15
  /**
32
16
  * The undo for addMethod(): strips one method's mount line from
33
17
  * *.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).
18
+ * schema consts) from *.controller.<ext>, and its matching function (plus
19
+ * its now-unused schema-type import, if any) from *.services.<ext>.
20
+ * Identified by verb+path, the same pair addMethod() itself refuses to let
21
+ * collide — not by name alone, since two different verb/path pairs could
22
+ * theoretically end up with the same name checked against different
23
+ * endpoints (name uniqueness is only enforced per endpoint, not globally).
24
+ *
25
+ * Every removal goes through ast-edit.ts's ts-morph helpers, which find
26
+ * each method's statements by their actual declared/exported name — the
27
+ * same uniqueness addMethod() enforces — rather than by which \n\n-
28
+ * delimited block of text they happen to sit in. That matters because
29
+ * parseRouteMethods() (used above to confirm the method exists) reads
30
+ * mount lines with a lenient regex that tolerates reformatting; the old
31
+ * text-block removal required an exact line match after that same
32
+ * reformatting and could silently fail to find anything to remove, leaving
33
+ * the controller/services files changed but the route still mounted.
40
34
  *
41
35
  * Removing the last method on an endpoint resets all three files back to
42
36
  * their blank, freshly-scaffolded shape (renderBlank*()) rather than
@@ -84,11 +78,15 @@ export async function removeMethod(
84
78
  return { route, root, removed: match };
85
79
  }
86
80
 
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}(`));
81
+ const newController = editSource(controllerPath, controllerContents, (_project, sourceFile) => {
82
+ removeControllerMethod(sourceFile, name);
83
+ });
84
+ const newRoutes = editSource(routesPath, routesContents, (_project, sourceFile) => {
85
+ removeRouteMount(sourceFile, name);
86
+ });
87
+ const newServices = editSource(servicesPath, servicesContents, (_project, sourceFile) => {
88
+ removeServiceMethod(sourceFile, name);
89
+ });
92
90
 
93
91
  await Promise.all([
94
92
  writeFile(controllerPath, newController),