@orval/hono 8.14.0 → 8.15.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/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { ClientBuilder, ClientExtraFilesBuilder, ClientFooterBuilder, ClientGeneratorsBuilder, ClientHeaderBuilder, GeneratorDependency } from "@orval/core";
1
+ import { ClientBuilder, ClientExtraFilesBuilder, ClientFooterBuilder, ClientGeneratorsBuilder, ClientHeaderBuilder, GeneratorDependency, GeneratorVerbOptions, HonoHandlerStrategy } from "@orval/core";
2
2
 
3
3
  //#region src/index.d.ts
4
4
  declare const getHonoDependencies: () => GeneratorDependency[];
@@ -6,20 +6,34 @@ declare const getHonoHeader: ClientHeaderBuilder;
6
6
  declare const getHonoFooter: ClientFooterBuilder;
7
7
  declare const generateHono: ClientBuilder;
8
8
  /**
9
- * extractExistingHandlerBodies scans a previously generated handler file and
10
- * returns the user-authored body of each
11
- * `async (c: ...) => { /* body *\/ }` block keyed by handler name.
9
+ * Generates or updates a handler file according to `strategy`:
12
10
  *
13
- * We deliberately preserve only the inner body — not the surrounding
14
- * `factory.createHandlers(...)` call so the regenerated wrapper always
15
- * reflects the current validator chain and imports. The scanner is
16
- * lex-aware: it skips strings, template literals, regex literals, and
17
- * comments while counting parentheses/braces, so user code containing
18
- * `)` or `}` characters in those contexts does not confuse the matcher.
11
+ * - a non-existent file is always freshly generated;
12
+ * - `skip` leaves an existing file byte-for-byte unchanged;
13
+ * - `full` rebuilds the preamble + validator chain and splices back user bodies
14
+ * (drops custom imports/middleware/helpers the thin-handler model);
15
+ * - `smart` non-destructively reconciles orval-owned imports + validators and
16
+ * appends handlers for new operations, preserving all user-authored code.
19
17
  */
20
- declare const extractExistingHandlerBodies: (source: string) => Map<string, string>;
18
+ declare const generateHandlerFile: ({
19
+ verbs,
20
+ path,
21
+ header,
22
+ validatorModule,
23
+ zodModule,
24
+ contextModule,
25
+ strategy
26
+ }: {
27
+ verbs: GeneratorVerbOptions[];
28
+ path: string;
29
+ header: string;
30
+ validatorModule?: string;
31
+ zodModule: string;
32
+ contextModule: string;
33
+ strategy: HonoHandlerStrategy;
34
+ }) => Promise<string>;
21
35
  declare const generateExtraFiles: ClientExtraFilesBuilder;
22
36
  declare const builder: () => () => ClientGeneratorsBuilder;
23
37
  //#endregion
24
- export { builder, builder as default, extractExistingHandlerBodies, generateExtraFiles, generateHono, getHonoDependencies, getHonoFooter, getHonoHeader };
38
+ export { builder, builder as default, generateExtraFiles, generateHandlerFile, generateHono, getHonoDependencies, getHonoFooter, getHonoHeader };
25
39
  //# sourceMappingURL=index.d.mts.map
package/dist/index.mjs CHANGED
@@ -1,7 +1,333 @@
1
1
  import nodePath from "node:path";
2
- import { camel, generateMutatorImports, getFileInfo, getOrvalGeneratedTypes, getParamsInPath, isObject, jsDoc, kebab, pascal, sanitize, upath } from "@orval/core";
2
+ import { camel, generateMutatorImports, getFileInfo, getOrvalGeneratedTypes, getParamsInPath, isObject, jsDoc, kebab, logWarning, pascal, sanitize, upath } from "@orval/core";
3
3
  import { generateZod } from "@orval/zod";
4
4
  import fs from "fs-extra";
5
+ //#region src/handler-merge.ts
6
+ /**
7
+ * AST-based reconciliation of an existing hono handler file.
8
+ *
9
+ * The `smart` handler strategy regenerates only the regions orval owns — its own
10
+ * imports (names + module specifier) and the `zValidator(...)` arguments of each
11
+ * handler — while leaving every user-authored construct untouched: custom imports,
12
+ * middleware passed to `factory.createHandlers(...)`, the `async (c) => { ... }`
13
+ * body, and any top-level helpers, constants, types, or comments.
14
+ *
15
+ * We edit the original source text in place using node offsets from the
16
+ * TypeScript compiler API, so formatting and comments of untouched regions are
17
+ * preserved. On any parse failure we return the source unchanged — user code is
18
+ * never destroyed by a parser hiccup.
19
+ */
20
+ /**
21
+ * `typescript` is an optional peer dependency, imported lazily. Consumers who do
22
+ * not have it installed — and every non-hono or `skip` code path — never trigger
23
+ * the import; `smart`/`full` fall back to `skip` when it is unavailable. Loading
24
+ * the consumer's own typescript also avoids shipping a second copy of it.
25
+ */
26
+ let ts;
27
+ let typeScriptAvailable;
28
+ const ensureTypeScript = async () => {
29
+ if (typeScriptAvailable === void 0) try {
30
+ const mod = await import("typescript");
31
+ ts = mod.default ?? mod;
32
+ typeScriptAvailable = true;
33
+ } catch {
34
+ typeScriptAvailable = false;
35
+ }
36
+ return typeScriptAvailable;
37
+ };
38
+ const VALIDATOR_TARGETS = new Set([
39
+ "header",
40
+ "param",
41
+ "query",
42
+ "json",
43
+ "form",
44
+ "response"
45
+ ]);
46
+ const parse = (source) => {
47
+ const sourceFile = ts.createSourceFile("handler.ts", source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);
48
+ const diagnostics = sourceFile.parseDiagnostics;
49
+ if (diagnostics && diagnostics.length > 0) return void 0;
50
+ return sourceFile;
51
+ };
52
+ const findHandlers = (sourceFile) => {
53
+ const handlers = [];
54
+ for (const statement of sourceFile.statements) {
55
+ if (!ts.isVariableStatement(statement)) continue;
56
+ for (const declaration of statement.declarationList.declarations) {
57
+ if (!ts.isIdentifier(declaration.name)) continue;
58
+ const name = declaration.name.text;
59
+ if (!name.endsWith("Handlers")) continue;
60
+ const init = declaration.initializer;
61
+ if (init && ts.isCallExpression(init) && ts.isPropertyAccessExpression(init.expression) && init.expression.name.text === "createHandlers") handlers.push({
62
+ name,
63
+ call: init
64
+ });
65
+ }
66
+ }
67
+ return handlers;
68
+ };
69
+ const importedNames = (declaration) => {
70
+ const bindings = declaration.importClause?.namedBindings;
71
+ if (!bindings || !ts.isNamedImports(bindings)) return [];
72
+ return bindings.elements.map((element) => element.name.text);
73
+ };
74
+ const moduleText = (declaration) => ts.isStringLiteral(declaration.moduleSpecifier) ? declaration.moduleSpecifier.text : "";
75
+ /**
76
+ * A "plain" named import — no default binding, no namespace (`* as x`), and no
77
+ * aliases (`x as y`). Only plain named imports are safe for orval to rewrite;
78
+ * default / namespace / aliased / mixed imports are user-authored and must be
79
+ * left untouched.
80
+ */
81
+ const isPlainNamedImport = (declaration) => {
82
+ const clause = declaration.importClause;
83
+ if (!clause || clause.name) return false;
84
+ const bindings = clause.namedBindings;
85
+ if (!bindings || !ts.isNamedImports(bindings)) return false;
86
+ return bindings.elements.every((element) => element.propertyName === void 0);
87
+ };
88
+ const setEquals = (a, b) => a.length === b.length && a.every((value) => b.includes(value));
89
+ const escapeRegExp = (value) => value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
90
+ /**
91
+ * The local binding name an imported symbol is bound to, honouring aliases —
92
+ * e.g. `import { zValidator as zv }` → `'zv'`. Returns undefined when the symbol
93
+ * is not imported. Used so a handler that aliases `zValidator` is detected and
94
+ * its new validators are inserted under the same alias (never an unimported name).
95
+ */
96
+ const localNameFor = (importDeclarations, importedName, module) => {
97
+ for (const declaration of importDeclarations) {
98
+ if (moduleText(declaration) !== module) continue;
99
+ const bindings = declaration.importClause?.namedBindings;
100
+ if (!bindings || !ts.isNamedImports(bindings)) continue;
101
+ for (const element of bindings.elements) if ((element.propertyName?.text ?? element.name.text) === importedName) return element.name.text;
102
+ }
103
+ };
104
+ const renderImport = ({ names, module }) => names.length <= 1 ? `import { ${names.join("")} } from '${module}';` : `import {\n ${names.join(",\n ")}\n} from '${module}';`;
105
+ const lineStart = (source, position) => source.lastIndexOf("\n", position - 1) + 1;
106
+ /** Whether only whitespace sits between the line start and `position`. */
107
+ const startsLine = (source, position) => /^\s*$/.test(source.slice(lineStart(source, position), position));
108
+ const reconcileHandlerFile = async (source, desired) => {
109
+ if (!await ensureTypeScript()) return source;
110
+ const sourceFile = parse(source);
111
+ if (!sourceFile) return source;
112
+ const edits = [];
113
+ const importDeclarations = sourceFile.statements.filter((statement) => ts.isImportDeclaration(statement));
114
+ const handlers = findHandlers(sourceFile);
115
+ const existingNames = new Set(handlers.map((handler) => handler.name));
116
+ const pendingInsertions = [];
117
+ const byModule = (module) => module ? importDeclarations.find((declaration) => moduleText(declaration) === module) : void 0;
118
+ const plainExact = (signature) => signature.length === 0 ? void 0 : importDeclarations.find((declaration) => isPlainNamedImport(declaration) && setEquals(importedNames(declaration), signature));
119
+ const removeImportEdit = (declaration) => {
120
+ let end = declaration.getEnd();
121
+ if (source.slice(end, end + 2) === "\r\n") end += 2;
122
+ else if (source[end] === "\n") end += 1;
123
+ edits.push({
124
+ start: declaration.getStart(sourceFile),
125
+ end,
126
+ text: ""
127
+ });
128
+ };
129
+ const isImportedBare = (name) => importDeclarations.some((declaration) => {
130
+ const clause = declaration.importClause;
131
+ if (!clause) return false;
132
+ if (clause.name?.text === name) return true;
133
+ return importedNames(declaration).includes(name);
134
+ });
135
+ /**
136
+ * Reconcile an orval-owned import to `names`. We only rewrite/remove a PLAIN
137
+ * named import whose names are ALL orval-owned (per `isOrvalName`). A
138
+ * user-authored import (aliased / namespace / default / mixed) is never
139
+ * rewritten; instead, when `augment` is provided, we add any orval name that
140
+ * is genuinely needed as a bare reference but isn't yet importable bare — e.g.
141
+ * a newly appended handler's context, or a newly-inserted validator's schema.
142
+ */
143
+ const reconcileImport = (existing, names, module, isOrvalName, augment, collectRenames) => {
144
+ if (!existing) {
145
+ const toInsert = (augment ? names.filter((name) => augment(name)) : names).filter((name) => !isImportedBare(name));
146
+ if (toInsert.length > 0) pendingInsertions.push(renderImport({
147
+ names: toInsert,
148
+ module
149
+ }));
150
+ return;
151
+ }
152
+ if (!(isPlainNamedImport(existing) && importedNames(existing).every((name) => isOrvalName(name)))) {
153
+ if (augment) {
154
+ const missing = names.filter((name) => augment(name) && !isImportedBare(name));
155
+ if (missing.length > 0) pendingInsertions.push(renderImport({
156
+ names: missing,
157
+ module
158
+ }));
159
+ }
160
+ return;
161
+ }
162
+ if (names.length === 0) {
163
+ removeImportEdit(existing);
164
+ return;
165
+ }
166
+ if (setEquals(importedNames(existing), names) && moduleText(existing) === module) return;
167
+ if (collectRenames) for (const old of importedNames(existing)) {
168
+ const next = names.find((name) => name !== old && name.toLowerCase() === old.toLowerCase());
169
+ if (next) collectRenames.set(old, next);
170
+ }
171
+ edits.push({
172
+ start: existing.getStart(sourceFile),
173
+ end: existing.getEnd(),
174
+ text: renderImport({
175
+ names,
176
+ module
177
+ })
178
+ });
179
+ };
180
+ const validatorModule = desired.imports.validator?.module ?? "";
181
+ const zValidatorName = validatorModule ? localNameFor(importDeclarations, "zValidator", validatorModule) ?? "zValidator" : "zValidator";
182
+ const requiredSchemas = /* @__PURE__ */ new Set();
183
+ const removedValidatorRanges = [];
184
+ for (const desiredHandler of desired.handlers) {
185
+ const parsed = handlers.find((handler) => handler.name === desiredHandler.handlerName);
186
+ if (parsed) reconcileValidators(sourceFile, source, parsed.call, desiredHandler.validators, edits, zValidatorName, requiredSchemas, removedValidatorRanges);
187
+ }
188
+ const schemaRenames = /* @__PURE__ */ new Map();
189
+ const toAppend = desired.handlers.filter((handler) => !existingNames.has(handler.handlerName));
190
+ let bodySource = source;
191
+ for (const declaration of importDeclarations) {
192
+ const start = declaration.getStart(sourceFile);
193
+ const end = declaration.getEnd();
194
+ bodySource = bodySource.slice(0, start) + " ".repeat(end - start) + bodySource.slice(end);
195
+ }
196
+ const referencedBare = (name) => new RegExp(String.raw`(?<!\.)\b${escapeRegExp(name)}\b`).test(bodySource);
197
+ const inAppendedStub = (name) => toAppend.some((handler) => handler.stub.includes(name));
198
+ const needsBareContext = (name) => referencedBare(name) || inAppendedStub(name);
199
+ const needsBareZod = (name) => referencedBare(name) || requiredSchemas.has(name) || inAppendedStub(name);
200
+ const contextNames = desired.imports.context.names.filter((name) => needsBareContext(name));
201
+ const zodLower = new Set((desired.imports.zod?.names ?? []).map((name) => name.toLowerCase()));
202
+ const factoryModule = desired.imports.factory.module;
203
+ reconcileImport(byModule(factoryModule) ?? plainExact(["createFactory"]), desired.imports.factory.names, factoryModule, (name) => name === "createFactory");
204
+ reconcileImport(byModule(validatorModule) ?? plainExact(["zValidator"]), desired.imports.validator ? ["zValidator"] : [], validatorModule, (name) => name === "zValidator");
205
+ reconcileImport(byModule(desired.imports.context.module) ?? plainExact(contextNames), contextNames, desired.imports.context.module, (name) => desired.imports.context.names.includes(name), needsBareContext);
206
+ const zodModule = desired.imports.zod?.module ?? "";
207
+ const zodNames = desired.imports.zod?.names ?? [];
208
+ reconcileImport(byModule(zodModule) ?? plainExact(zodNames), zodNames, zodModule, (name) => zodLower.has(name.toLowerCase()), needsBareZod, schemaRenames);
209
+ if (schemaRenames.size > 0) {
210
+ const inSkippedRange = (pos) => importDeclarations.some((declaration) => pos >= declaration.getStart(sourceFile) && pos < declaration.getEnd()) || removedValidatorRanges.some(([start, end]) => pos >= start && pos < end);
211
+ const renameReferences = (node) => {
212
+ if (ts.isIdentifier(node)) {
213
+ const replacement = schemaRenames.get(node.text);
214
+ if (replacement) {
215
+ const parent = node.parent;
216
+ const isMemberName = ts.isPropertyAccessExpression(parent) && parent.name === node;
217
+ const isDeclarationName = ts.isVariableDeclaration(parent) && parent.name === node || ts.isParameter(parent) && parent.name === node || ts.isBindingElement(parent) && parent.name === node || ts.isPropertyAssignment(parent) && parent.name === node || ts.isPropertySignature(parent) && parent.name === node;
218
+ const start = node.getStart(sourceFile);
219
+ if (!isMemberName && !isDeclarationName && !inSkippedRange(start)) edits.push({
220
+ start,
221
+ end: node.getEnd(),
222
+ text: replacement
223
+ });
224
+ }
225
+ }
226
+ ts.forEachChild(node, renameReferences);
227
+ };
228
+ renameReferences(sourceFile);
229
+ }
230
+ if (pendingInsertions.length > 0) {
231
+ const lastImport = importDeclarations.at(-1);
232
+ let insertPos = 0;
233
+ if (lastImport) {
234
+ const newline = source.indexOf("\n", lastImport.getEnd());
235
+ insertPos = newline === -1 ? source.length : newline + 1;
236
+ }
237
+ edits.push({
238
+ start: insertPos,
239
+ end: insertPos,
240
+ text: pendingInsertions.map((line) => `${line}\n`).join("")
241
+ });
242
+ }
243
+ if (toAppend.length > 0) edits.push({
244
+ start: source.length,
245
+ end: source.length,
246
+ text: toAppend.map((handler) => handler.stub).join("")
247
+ });
248
+ return applyEdits(source, edits);
249
+ };
250
+ const reconcileValidators = (sourceFile, source, call, desiredValidators, edits, zValidatorName, requiredSchemas, removedRanges) => {
251
+ const existing = [];
252
+ for (const arg of call.arguments) if (ts.isCallExpression(arg) && ts.isIdentifier(arg.expression) && arg.expression.text === zValidatorName) {
253
+ const target = arg.arguments[0];
254
+ if (arg.arguments.length > 0 && ts.isStringLiteralLike(target) && VALIDATOR_TARGETS.has(target.text)) existing.push({
255
+ target: target.text,
256
+ arg
257
+ });
258
+ }
259
+ const desiredByTarget = new Map(desiredValidators.map((validator) => [validator.target, validator]));
260
+ const existingByTarget = new Set(existing.map((item) => item.target));
261
+ for (const item of existing) if (!desiredByTarget.has(item.target)) {
262
+ const edit = removeArgumentEdit(sourceFile, source, item.arg);
263
+ edits.push(edit);
264
+ removedRanges.push([edit.start, edit.end]);
265
+ }
266
+ const missing = desiredValidators.filter((validator) => !existingByTarget.has(validator.target));
267
+ if (missing.length > 0) {
268
+ const insertPos = validatorInsertPos(sourceFile, source, call);
269
+ const text = missing.map((validator) => {
270
+ requiredSchemas.add(validator.schema);
271
+ return ` ${zValidatorName}('${validator.target}', ${validator.schema}),\n`;
272
+ }).join("");
273
+ edits.push({
274
+ start: insertPos,
275
+ end: insertPos,
276
+ text
277
+ });
278
+ }
279
+ };
280
+ /** Position to insert new validators: the line start of the trailing handler. */
281
+ const validatorInsertPos = (sourceFile, source, call) => {
282
+ const handler = call.arguments.findLast((arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg));
283
+ if (handler) {
284
+ const start = handler.getStart(sourceFile);
285
+ return startsLine(source, start) ? lineStart(source, start) : start;
286
+ }
287
+ return call.getEnd() - 1;
288
+ };
289
+ const removeArgumentEdit = (sourceFile, source, arg) => {
290
+ const argStart = arg.getStart(sourceFile);
291
+ const start = startsLine(source, argStart) ? lineStart(source, argStart) : argStart;
292
+ const commaIdx = source.indexOf(",", arg.getEnd());
293
+ let end = commaIdx === -1 ? arg.getEnd() : commaIdx + 1;
294
+ while (source[end] === " " || source[end] === " ") end += 1;
295
+ if (source.slice(end, end + 2) === "\r\n") end += 2;
296
+ else if (source[end] === "\n") end += 1;
297
+ return {
298
+ start,
299
+ end,
300
+ text: ""
301
+ };
302
+ };
303
+ const applyEdits = (source, edits) => {
304
+ let result = source;
305
+ for (const edit of edits.toSorted((a, b) => b.start - a.start)) result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);
306
+ return result;
307
+ };
308
+ /**
309
+ * Extracts the inner body of each handler's `async (c) => { ... }` block, keyed
310
+ * by handler name. Used by the `full` strategy to splice user bodies back into a
311
+ * freshly-regenerated wrapper. Returns `undefined` when the source can't be
312
+ * parsed (or typescript is unavailable) — distinct from an empty map (parsed, no
313
+ * handlers) — so callers can preserve the file instead of dropping its bodies.
314
+ */
315
+ const extractHandlerBodies = async (source) => {
316
+ if (!await ensureTypeScript()) return void 0;
317
+ const sourceFile = parse(source);
318
+ if (!sourceFile) return void 0;
319
+ const bodies = /* @__PURE__ */ new Map();
320
+ for (const { name, call } of findHandlers(sourceFile)) {
321
+ const handler = call.arguments.findLast((arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg));
322
+ if (handler?.body && ts.isBlock(handler.body)) {
323
+ const bodyStart = handler.body.getStart(sourceFile) + 1;
324
+ const bodyEnd = handler.body.getEnd() - 1;
325
+ bodies.set(name, source.slice(bodyStart, bodyEnd));
326
+ }
327
+ }
328
+ return bodies;
329
+ };
330
+ //#endregion
5
331
  //#region src/route.ts
6
332
  const hasParam = (path) => /[^{]*{[\w*_-]*}.*/.test(path);
7
333
  const getRoutePath = (path) => {
@@ -28,6 +354,7 @@ const getRoute = (route) => {
28
354
  };
29
355
  //#endregion
30
356
  //#region src/index.ts
357
+ let warnedMissingTypeScript = false;
31
358
  const ZVALIDATOR_SOURCE = fs.readFileSync(nodePath.join(import.meta.dirname, "zValidator.ts")).toString("utf8");
32
359
  const HONO_DEPENDENCIES = [{
33
360
  exports: [
@@ -98,19 +425,48 @@ const generateHono = (verbOptions, options) => {
98
425
  * whether the code requires zValidator.
99
426
  */
100
427
  const DEFAULT_HANDLER_BODY = "\n\n ";
428
+ const FORM_CONTENT_TYPES = new Set(["multipart/form-data", "application/x-www-form-urlencoded"]);
429
+ /**
430
+ * Whether a request body uses a form encoding. Hono validates these with
431
+ * `zValidator('form', …)` against `c.req.parseBody()`, not `'json'`.
432
+ */
433
+ const isFormBody = (body) => FORM_CONTENT_TYPES.has(body.contentType);
434
+ /**
435
+ * getDesiredValidators returns the `zValidator` targets (and their PascalCase zod
436
+ * schema identifiers) required by a verb, in canonical order. This is the single
437
+ * source of truth shared by fresh generation and the `smart` reconcile.
438
+ */
439
+ const getDesiredValidators = (verbOption, validator) => {
440
+ if (!validator) return [];
441
+ const pascalOperationName = pascal(verbOption.operationName);
442
+ const validators = [];
443
+ if (verbOption.headers) validators.push({
444
+ target: "header",
445
+ schema: `${pascalOperationName}Header`
446
+ });
447
+ if (verbOption.params.length > 0) validators.push({
448
+ target: "param",
449
+ schema: `${pascalOperationName}Params`
450
+ });
451
+ if (verbOption.queryParams) validators.push({
452
+ target: "query",
453
+ schema: `${pascalOperationName}QueryParams`
454
+ });
455
+ if (verbOption.body.definition) validators.push({
456
+ target: isFormBody(verbOption.body) ? "form" : "json",
457
+ schema: `${pascalOperationName}Body`
458
+ });
459
+ if (validator !== "hono" && verbOption.response.originalSchema?.["200"]?.content?.["application/json"]) validators.push({
460
+ target: "response",
461
+ schema: `${pascalOperationName}Response`
462
+ });
463
+ return validators;
464
+ };
101
465
  const getHonoHandlers = (...opts) => {
102
466
  let code = "";
103
467
  let hasZValidator = false;
104
468
  for (const { handlerName, contextTypeName, verbOption, validator, bodyOverride } of opts) {
105
- let currentValidator = "";
106
- if (validator) {
107
- const pascalOperationName = pascal(verbOption.operationName);
108
- if (verbOption.headers) currentValidator += `zValidator('header', ${pascalOperationName}Header),\n`;
109
- if (verbOption.params.length > 0) currentValidator += `zValidator('param', ${pascalOperationName}Params),\n`;
110
- if (verbOption.queryParams) currentValidator += `zValidator('query', ${pascalOperationName}QueryParams),\n`;
111
- if (verbOption.body.definition) currentValidator += `zValidator('json', ${pascalOperationName}Body),\n`;
112
- if (validator !== "hono" && verbOption.response.originalSchema?.["200"]?.content?.["application/json"]) currentValidator += `zValidator('response', ${pascalOperationName}Response),\n`;
113
- }
469
+ const currentValidator = getDesiredValidators(verbOption, validator).map((v) => `zValidator('${v.target}', ${v.schema}),\n`).join("");
114
470
  code += `
115
471
  export const ${handlerName} = factory.createHandlers(
116
472
  ${currentValidator}async (c: ${contextTypeName}) => {${bodyOverride ?? DEFAULT_HANDLER_BODY}},
@@ -140,219 +496,115 @@ const getVerbOptionGroupByTag = (verbOptions) => {
140
496
  }
141
497
  return grouped;
142
498
  };
143
- const generateHandlerFile = async ({ verbs, path, header, validatorModule, zodModule, contextModule }) => {
144
- const validator = validatorModule === "@hono/zod-validator" ? "hono" : validatorModule != void 0;
145
- const verbList = Object.values(verbs);
146
- const [, hasZValidator] = getHonoHandlers(...verbList.map((verbOption) => ({
499
+ /** Computes the orval-owned imports a handler file should contain. */
500
+ const buildDesiredImports = ({ verbList, path, validatorModule, zodModule, contextModule, validator }) => {
501
+ const contextNames = verbList.map((verb) => `${pascal(verb.operationName)}Context`);
502
+ const zodNames = verbList.flatMap((verb) => getDesiredValidators(verb, validator).map((v) => v.schema));
503
+ const hasValidators = zodNames.length > 0;
504
+ return {
505
+ factory: {
506
+ names: ["createFactory"],
507
+ module: "hono/factory"
508
+ },
509
+ validator: hasValidators && validatorModule != void 0 ? {
510
+ names: ["zValidator"],
511
+ module: generateModuleSpecifier(path, validatorModule)
512
+ } : void 0,
513
+ context: {
514
+ names: contextNames,
515
+ module: generateModuleSpecifier(path, contextModule)
516
+ },
517
+ zod: hasValidators ? {
518
+ names: zodNames,
519
+ module: generateModuleSpecifier(path, zodModule)
520
+ } : void 0
521
+ };
522
+ };
523
+ /** Generates a complete handler file from scratch (no existing file to merge). */
524
+ const generateFreshHandlerFile = ({ verbList, path, header, validatorModule, zodModule, contextModule, validator, bodyFor }) => {
525
+ const [handlerCode, hasZValidator] = getHonoHandlers(...verbList.map((verbOption) => ({
147
526
  handlerName: `${verbOption.operationName}Handlers`,
148
527
  contextTypeName: `${pascal(verbOption.operationName)}Context`,
149
528
  verbOption,
150
- validator
529
+ validator,
530
+ bodyOverride: bodyFor?.(verbOption.operationName)
151
531
  })));
152
532
  const imports = ["import { createFactory } from 'hono/factory';"];
153
533
  if (hasZValidator && validatorModule != void 0) imports.push(`import { zValidator } from '${generateModuleSpecifier(path, validatorModule)}';`);
154
534
  imports.push(`import { ${verbList.map((verb) => `${pascal(verb.operationName)}Context`).join(",\n")} } from '${generateModuleSpecifier(path, contextModule)}';`);
155
535
  if (hasZValidator) imports.push(getZvalidatorImports(verbList, generateModuleSpecifier(path, zodModule), validatorModule === "@hono/zod-validator"));
156
- const preamble = `${header}${imports.filter((imp) => imp !== "").join("\n")}\n\nconst factory = createFactory();`;
157
- const existingBodies = fs.existsSync(path) ? extractExistingHandlerBodies(await fs.readFile(path, "utf8")) : /* @__PURE__ */ new Map();
158
- const [handlerCode] = getHonoHandlers(...verbList.map((verbOption) => ({
159
- handlerName: `${verbOption.operationName}Handlers`,
160
- contextTypeName: `${pascal(verbOption.operationName)}Context`,
161
- verbOption,
162
- validator,
163
- bodyOverride: existingBodies.get(`${verbOption.operationName}Handlers`)
164
- })));
165
- return `${preamble}${handlerCode}`;
536
+ return `${header}${imports.filter((imp) => imp !== "").join("\n")}\n\nconst factory = createFactory();${handlerCode}`;
166
537
  };
167
538
  /**
168
- * extractExistingHandlerBodies scans a previously generated handler file and
169
- * returns the user-authored body of each
170
- * `async (c: ...) => { /* body *\/ }` block keyed by handler name.
539
+ * Generates or updates a handler file according to `strategy`:
171
540
  *
172
- * We deliberately preserve only the inner body — not the surrounding
173
- * `factory.createHandlers(...)` call so the regenerated wrapper always
174
- * reflects the current validator chain and imports. The scanner is
175
- * lex-aware: it skips strings, template literals, regex literals, and
176
- * comments while counting parentheses/braces, so user code containing
177
- * `)` or `}` characters in those contexts does not confuse the matcher.
541
+ * - a non-existent file is always freshly generated;
542
+ * - `skip` leaves an existing file byte-for-byte unchanged;
543
+ * - `full` rebuilds the preamble + validator chain and splices back user bodies
544
+ * (drops custom imports/middleware/helpers the thin-handler model);
545
+ * - `smart` non-destructively reconciles orval-owned imports + validators and
546
+ * appends handlers for new operations, preserving all user-authored code.
178
547
  */
179
- const extractExistingHandlerBodies = (source) => {
180
- const bodies = /* @__PURE__ */ new Map();
181
- const exportRegex = /export\s+const\s+(\w+Handlers)\s*=\s*factory\.createHandlers\s*\(/g;
182
- let match;
183
- while ((match = exportRegex.exec(source)) !== null) {
184
- const handlerName = match[1];
185
- const callOpenIdx = match.index + match[0].length - 1;
186
- const callCloseIdx = findMatchingClose(source, callOpenIdx, "(", ")");
187
- if (callCloseIdx === -1) continue;
188
- const body = extractAsyncArrowBody(source.slice(callOpenIdx + 1, callCloseIdx));
189
- if (body !== void 0) bodies.set(handlerName, body);
190
- }
191
- return bodies;
192
- };
193
- /**
194
- * findMatchingClose returns the index of the closing bracket that pairs with
195
- * the opening bracket at `openIdx`, or -1 if unbalanced. The scan skips
196
- * strings, template literals, regex literals, and comments so brackets in
197
- * those contexts do not affect depth.
198
- */
199
- const findMatchingClose = (source, openIdx, open, close) => {
200
- let depth = 0;
201
- let i = openIdx;
202
- while (i < source.length) {
203
- const ch = source[i];
204
- const next = source[i + 1];
205
- if (ch === "/" && next === "/") {
206
- const nl = source.indexOf("\n", i + 2);
207
- i = nl === -1 ? source.length : nl + 1;
208
- continue;
209
- }
210
- if (ch === "/" && next === "*") {
211
- const end = source.indexOf("*/", i + 2);
212
- i = end === -1 ? source.length : end + 2;
213
- continue;
214
- }
215
- if (ch === "'" || ch === "\"" || ch === "`") {
216
- i = skipString(source, i, ch);
217
- continue;
218
- }
219
- if (ch === "/" && isRegexContext(source, i)) {
220
- i = skipRegex(source, i);
221
- continue;
222
- }
223
- if (ch === open) depth++;
224
- else if (ch === close) {
225
- depth--;
226
- if (depth === 0) return i;
227
- }
228
- i++;
229
- }
230
- return -1;
231
- };
232
- const skipString = (source, start, quote) => {
233
- let i = start + 1;
234
- while (i < source.length) {
235
- const ch = source[i];
236
- if (ch === "\\") {
237
- i += 2;
238
- continue;
239
- }
240
- if (quote === "`" && ch === "$" && source[i + 1] === "{") {
241
- const end = findMatchingClose(source, i + 1, "{", "}");
242
- i = end === -1 ? source.length : end + 1;
243
- continue;
244
- }
245
- if (ch === quote) return i + 1;
246
- i++;
247
- }
248
- return source.length;
249
- };
250
- const skipRegex = (source, start) => {
251
- let i = start + 1;
252
- let inClass = false;
253
- while (i < source.length) {
254
- const ch = source[i];
255
- if (ch === "\\") {
256
- i += 2;
257
- continue;
258
- }
259
- if (ch === "[") inClass = true;
260
- else if (ch === "]") inClass = false;
261
- else if (ch === "/" && !inClass) {
262
- i++;
263
- while (i < source.length && /[gimsuy]/.test(source[i])) i++;
264
- return i;
548
+ const generateHandlerFile = async ({ verbs, path, header, validatorModule, zodModule, contextModule, strategy }) => {
549
+ const validator = validatorModule === "@hono/zod-validator" ? "hono" : validatorModule != void 0;
550
+ const verbList = Object.values(verbs);
551
+ if (!fs.existsSync(path)) return generateFreshHandlerFile({
552
+ verbList,
553
+ path,
554
+ header,
555
+ validatorModule,
556
+ zodModule,
557
+ contextModule,
558
+ validator
559
+ });
560
+ const source = await fs.readFile(path, "utf8");
561
+ if (strategy === "skip") return source;
562
+ if (!await ensureTypeScript()) {
563
+ if (!warnedMissingTypeScript) {
564
+ warnedMissingTypeScript = true;
565
+ logWarning(`hono handlerGenerationStrategy '${strategy}' requires the optional peer dependency "typescript", which is not installed. Existing handler files are left unchanged (as with 'skip'). Install typescript to enable handler reconciliation.`);
265
566
  }
266
- if (ch === "\n") return start + 1;
267
- i++;
268
- }
269
- return source.length;
270
- };
271
- const REGEX_PRECEDING_KEYWORDS = new Set([
272
- "return",
273
- "throw",
274
- "yield",
275
- "await",
276
- "case",
277
- "new",
278
- "typeof",
279
- "void",
280
- "delete",
281
- "in",
282
- "of",
283
- "instanceof"
284
- ]);
285
- const isRegexContext = (source, slashIdx) => {
286
- let j = slashIdx - 1;
287
- while (j >= 0 && (source[j] === " " || source[j] === " " || source[j] === "\n")) j--;
288
- if (j < 0) return true;
289
- const c = source[j];
290
- if (c === ".") {
291
- if (j >= 2 && source[j - 1] === "." && source[j - 2] === ".") return true;
292
- return false;
293
- }
294
- if (/[A-Za-z0-9_$]/.test(c)) {
295
- let k = j;
296
- while (k >= 0 && /[A-Za-z0-9_$]/.test(source[k])) k--;
297
- const token = source.slice(k + 1, j + 1);
298
- return REGEX_PRECEDING_KEYWORDS.has(token);
567
+ return source;
299
568
  }
300
- if (c === ")" || c === "]") return false;
301
- return true;
302
- };
303
- /**
304
- * extractAsyncArrowBody finds the trailing `async (c: ...) => { ... }`
305
- * argument inside `factory.createHandlers(...)` and returns the inner body
306
- * (without the surrounding braces). Returns undefined when the call does not
307
- * end with the expected arrow function shape.
308
- */
309
- const extractAsyncArrowBody = (callBody) => {
310
- let i = 0;
311
- let lastTopLevelArrow = -1;
312
- while (i < callBody.length) {
313
- const ch = callBody[i];
314
- const next = callBody[i + 1];
315
- if (ch === "/" && next === "/") {
316
- const nl = callBody.indexOf("\n", i + 2);
317
- i = nl === -1 ? callBody.length : nl + 1;
318
- continue;
319
- }
320
- if (ch === "/" && next === "*") {
321
- const end = callBody.indexOf("*/", i + 2);
322
- i = end === -1 ? callBody.length : end + 2;
323
- continue;
324
- }
325
- if (ch === "'" || ch === "\"" || ch === "`") {
326
- i = skipString(callBody, i, ch);
327
- continue;
328
- }
329
- if (ch === "/" && isRegexContext(callBody, i)) {
330
- i = skipRegex(callBody, i);
331
- continue;
332
- }
333
- if (ch === "(" || ch === "{") {
334
- const end = findMatchingClose(callBody, i, ch, ch === "(" ? ")" : "}");
335
- i = end === -1 ? callBody.length : end + 1;
336
- continue;
337
- }
338
- if (ch === "=" && next === ">") {
339
- lastTopLevelArrow = i;
340
- i += 2;
341
- continue;
342
- }
343
- i++;
569
+ if (strategy === "full") {
570
+ const bodies = await extractHandlerBodies(source);
571
+ if (!bodies) return source;
572
+ return generateFreshHandlerFile({
573
+ verbList,
574
+ path,
575
+ header,
576
+ validatorModule,
577
+ zodModule,
578
+ contextModule,
579
+ validator,
580
+ bodyFor: (operationName) => bodies.get(`${operationName}Handlers`)
581
+ });
344
582
  }
345
- if (lastTopLevelArrow === -1) return void 0;
346
- let j = lastTopLevelArrow + 2;
347
- while (j < callBody.length && /\s/.test(callBody[j])) j++;
348
- if (callBody[j] !== "{") return void 0;
349
- const closeIdx = findMatchingClose(callBody, j, "{", "}");
350
- if (closeIdx === -1) return void 0;
351
- return callBody.slice(j + 1, closeIdx);
583
+ return reconcileHandlerFile(source, {
584
+ imports: buildDesiredImports({
585
+ verbList,
586
+ path,
587
+ validatorModule,
588
+ zodModule,
589
+ contextModule,
590
+ validator
591
+ }),
592
+ handlers: verbList.map((verbOption) => ({
593
+ handlerName: `${verbOption.operationName}Handlers`,
594
+ validators: getDesiredValidators(verbOption, validator),
595
+ stub: getHonoHandlers({
596
+ handlerName: `${verbOption.operationName}Handlers`,
597
+ contextTypeName: `${pascal(verbOption.operationName)}Context`,
598
+ verbOption,
599
+ validator
600
+ })[0]
601
+ }))
602
+ });
352
603
  };
353
604
  const generateHandlerFiles = async (verbOptions, output, context, validatorModule) => {
354
605
  const header = getHeader(output.override.header, getSpecInfo(context));
355
606
  const { extension, dirname, filename } = getFileInfo(output.target);
607
+ const strategy = output.override.hono.handlerGenerationStrategy;
356
608
  if (output.override.hono.handlers) return Promise.all(Object.values(verbOptions).map(async (verbOption) => {
357
609
  const tag = kebab(verbOption.tags[0] ?? "default");
358
610
  const path = nodePath.join(output.override.hono.handlers ?? "", `./${verbOption.operationName}` + extension);
@@ -375,7 +627,8 @@ const generateHandlerFiles = async (verbOptions, output, context, validatorModul
375
627
  verbs: [verbOption],
376
628
  validatorModule,
377
629
  zodModule,
378
- contextModule
630
+ contextModule,
631
+ strategy
379
632
  }),
380
633
  path
381
634
  };
@@ -391,7 +644,8 @@ const generateHandlerFiles = async (verbOptions, output, context, validatorModul
391
644
  verbs,
392
645
  validatorModule,
393
646
  zodModule: output.mode === "tags" ? nodePath.join(dirname, `${kebab(tag)}.zod`) : nodePath.join(dirname, tag, tag + ".zod"),
394
- contextModule: output.mode === "tags" ? nodePath.join(dirname, `${kebab(tag)}.context`) : nodePath.join(dirname, tag, tag + ".context")
647
+ contextModule: output.mode === "tags" ? nodePath.join(dirname, `${kebab(tag)}.context`) : nodePath.join(dirname, tag, tag + ".context"),
648
+ strategy
395
649
  }),
396
650
  path: handlerPath
397
651
  };
@@ -405,7 +659,8 @@ const generateHandlerFiles = async (verbOptions, output, context, validatorModul
405
659
  verbs: Object.values(verbOptions),
406
660
  validatorModule,
407
661
  zodModule: nodePath.join(dirname, `${filename}.zod`),
408
- contextModule: nodePath.join(dirname, `${filename}.context`)
662
+ contextModule: nodePath.join(dirname, `${filename}.context`),
663
+ strategy
409
664
  }),
410
665
  path: handlerPath
411
666
  }];
@@ -418,7 +673,7 @@ const getContext = (verbOption) => {
418
673
  return { definition: `${name}${param?.required ?? false ? "" : "?"}:${definition}` };
419
674
  }).map((property) => property.definition).join(",\n ")},\n },`;
420
675
  const queryType = verbOption.queryParams ? `query: ${verbOption.queryParams.schema.name},` : "";
421
- const bodyType = verbOption.body.definition ? `json: ${verbOption.body.definition},` : "";
676
+ const bodyType = verbOption.body.definition ? `${isFormBody(verbOption.body) ? "form" : "json"}: ${verbOption.body.definition},` : "";
422
677
  const hasIn = !!paramType || !!queryType || !!bodyType;
423
678
  return `export type ${pascal(verbOption.operationName)}Context<E extends Env = any> = Context<E, '${getRoute(verbOption.pathRoute)}'${hasIn ? `, { in: { ${paramType}${queryType}${bodyType} }, out: { ${paramType}${queryType}${bodyType} } }` : ""}>`;
424
679
  };
@@ -493,7 +748,10 @@ const generateZodFiles = async (verbOptions, output, context) => {
493
748
  content: "",
494
749
  path: ""
495
750
  };
496
- let content = `${header}import { z as zod } from 'zod';\n${generateMutatorImports({ mutators: new Map(zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m])).values().toArray() })}\n`;
751
+ let content = `${header}import { z as zod } from 'zod';\n${generateMutatorImports({
752
+ mutators: new Map(zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m])).values().toArray(),
753
+ oneMore: output.mode === "tags-split"
754
+ })}\n`;
497
755
  const zodPath = output.mode === "tags" ? nodePath.join(dirname, `${kebab(tag)}.zod${extension}`) : nodePath.join(dirname, tag, tag + ".zod" + extension);
498
756
  content += zods.map((zod) => zod.implementation).join("\n");
499
757
  return {
@@ -587,6 +845,6 @@ const honoClientBuilder = {
587
845
  };
588
846
  const builder = () => () => honoClientBuilder;
589
847
  //#endregion
590
- export { builder, builder as default, extractExistingHandlerBodies, generateExtraFiles, generateHono, getHonoDependencies, getHonoFooter, getHonoHeader };
848
+ export { builder, builder as default, generateExtraFiles, generateHandlerFile, generateHono, getHonoDependencies, getHonoFooter, getHonoHeader };
591
849
 
592
850
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/route.ts","../src/index.ts"],"sourcesContent":["import { sanitize } from '@orval/core';\n\nconst hasParam = (path: string): boolean => /[^{]*{[\\w*_-]*}.*/.test(path);\n\nconst getRoutePath = (path: string): string => {\n const matches = /([^{]*){?([\\w*_-]*)}?(.*)/.exec(path);\n if (!matches?.length) return path; // impossible due to regexp grouping here, but for TS\n\n const prev = matches[1];\n const param = sanitize(matches[2], {\n es5keyword: true,\n underscore: true,\n dash: true,\n dot: true,\n });\n const next = hasParam(matches[3]) ? getRoutePath(matches[3]) : matches[3];\n\n return hasParam(path) ? `${prev}:${param}${next}` : `${prev}${param}${next}`;\n};\n\nexport const getRoute = (route: string) => {\n const splittedRoute = route.split('/');\n\n let acc = '';\n for (const [i, path] of splittedRoute.entries()) {\n if (!path && i === 0) continue;\n\n acc += path.includes('{') ? `/${getRoutePath(path)}` : `/${path}`;\n }\n\n return acc;\n};\n","import nodePath from 'node:path';\n\nimport {\n camel,\n type ClientBuilder,\n type ClientExtraFilesBuilder,\n type ClientFooterBuilder,\n type ClientGeneratorsBuilder,\n type ClientHeaderBuilder,\n type ContextSpec,\n generateMutatorImports,\n type GeneratorDependency,\n type GeneratorImport,\n type GeneratorVerbOptions,\n getFileInfo,\n getOrvalGeneratedTypes,\n getParamsInPath,\n isObject,\n jsDoc,\n kebab,\n type NormalizedMutator,\n type NormalizedOutputOptions,\n type OpenApiInfoObject,\n pascal,\n sanitize,\n upath,\n} from '@orval/core';\nimport { generateZod } from '@orval/zod';\nimport fs from 'fs-extra';\n\nimport { getRoute } from './route';\n\nconst ZVALIDATOR_SOURCE = fs\n .readFileSync(nodePath.join(import.meta.dirname, 'zValidator.ts'))\n .toString('utf8');\n\nconst HONO_DEPENDENCIES: GeneratorDependency[] = [\n {\n exports: [\n {\n name: 'Hono',\n values: true,\n },\n {\n name: 'Context',\n },\n {\n name: 'Env',\n },\n ],\n dependency: 'hono',\n },\n];\n\n/**\n * generateModuleSpecifier generates the specifier that _from_ would use to\n * import _to_. This is syntactical and does not validate the paths.\n *\n * @param from The filesystem path to the importer.\n * @param to If a filesystem path, it and _from_ must be use the same frame of\n * reference, such as process.cwd() or both be absolute. If only one is\n * absolute, the other must be relative to process.cwd().\n *\n * Otherwise, treated as a package name and returned directly.\n *\n * @return A module specifier that can be used at _from_ to import _to_. It is\n * extensionless to conform with the rest of orval.\n */\nconst generateModuleSpecifier = (from: string, to: string) => {\n if (to.startsWith('.') || nodePath.isAbsolute(to)) {\n return upath\n .getRelativeImportPath(nodePath.resolve(from), nodePath.resolve(to), true)\n .replace(/\\.ts$/, '');\n }\n\n // Not a relative or absolute file path. Import as-is.\n return to;\n};\n\nexport const getHonoDependencies = () => HONO_DEPENDENCIES;\n\nexport const getHonoHeader: ClientHeaderBuilder = ({\n verbOptions,\n output,\n tag,\n clientImplementation,\n}) => {\n const targetInfo = getFileInfo(output.target);\n\n let handlers: string;\n\n const importHandlers = Object.values(verbOptions).filter((verbOption) =>\n clientImplementation.includes(`${verbOption.operationName}Handlers`),\n );\n\n if (output.override.hono.handlers) {\n const handlerFileInfo = getFileInfo(output.override.hono.handlers);\n handlers = importHandlers\n .map((verbOption) => {\n // Only `tags-split` puts each tag's client file inside its own\n // sub-directory. `tags` mode flattens them next to `target`, so the\n // import must be resolved from `targetInfo.dirname` directly.\n const isSplitDir = output.mode === 'tags-split';\n const tag = kebab(verbOption.tags[0] ?? 'default');\n\n const handlersPath = upath.relativeSafe(\n nodePath.join(targetInfo.dirname, isSplitDir ? tag : ''),\n nodePath.join(\n handlerFileInfo.dirname,\n `./${verbOption.operationName}`,\n ),\n );\n\n return `import { ${verbOption.operationName}Handlers } from '${handlersPath}';`;\n })\n .join('\\n');\n } else {\n const importHandlerNames = importHandlers\n .map((verbOption) => ` ${verbOption.operationName}Handlers`)\n .join(`, \\n`);\n\n handlers = `import {\\n${importHandlerNames}\\n} from './${tag ?? targetInfo.filename}.handlers';`;\n }\n\n return `${handlers}\\n\\nconst app = new Hono()\\n`;\n};\n\nexport const getHonoFooter: ClientFooterBuilder = () =>\n ';\\n\\nexport default app;\\n';\n\nconst generateHonoRoute = (\n { operationName, verb }: GeneratorVerbOptions,\n pathRoute: string,\n) => {\n const path = getRoute(pathRoute);\n\n return `\\n .${verb.toLowerCase()}('${path}', ...${operationName}Handlers)`;\n};\n\nexport const generateHono: ClientBuilder = (verbOptions, options) => {\n if (options.override.hono.compositeRoute) {\n return {\n implementation: '',\n imports: [],\n };\n }\n\n const routeImplementation = generateHonoRoute(verbOptions, options.pathRoute);\n\n return {\n implementation: `${routeImplementation}\\n`,\n imports: [\n ...verbOptions.params.flatMap((param) => param.imports),\n ...verbOptions.body.imports,\n ...(verbOptions.queryParams\n ? [\n {\n name: verbOptions.queryParams.schema.name,\n },\n ]\n : []),\n ],\n };\n};\n\n/**\n * getHonoHandlers generates TypeScript code for the given verbs and reports\n * whether the code requires zValidator.\n */\nconst DEFAULT_HANDLER_BODY = '\\n\\n ';\n\nconst getHonoHandlers = (\n ...opts: {\n handlerName: string;\n contextTypeName: string;\n verbOption: GeneratorVerbOptions;\n validator: boolean | 'hono' | NormalizedMutator;\n /**\n * Optional async-handler body to splice into the generated wrapper. When\n * supplied the validator chain is still rebuilt from the current verb\n * options, but the body inside `async (c) => { ... }` is taken verbatim\n * from the existing file so user logic survives regeneration.\n */\n bodyOverride?: string;\n }[]\n): [\n /** The combined TypeScript handler code snippets. */\n handlerCode: string,\n /** Whether any of the handler code snippets requires importing zValidator. */\n hasZValidator: boolean,\n] => {\n let code = '';\n let hasZValidator = false;\n\n for (const {\n handlerName,\n contextTypeName,\n verbOption,\n validator,\n bodyOverride,\n } of opts) {\n let currentValidator = '';\n\n if (validator) {\n const pascalOperationName = pascal(verbOption.operationName);\n\n if (verbOption.headers) {\n currentValidator += `zValidator('header', ${pascalOperationName}Header),\\n`;\n }\n if (verbOption.params.length > 0) {\n currentValidator += `zValidator('param', ${pascalOperationName}Params),\\n`;\n }\n if (verbOption.queryParams) {\n currentValidator += `zValidator('query', ${pascalOperationName}QueryParams),\\n`;\n }\n if (verbOption.body.definition) {\n currentValidator += `zValidator('json', ${pascalOperationName}Body),\\n`;\n }\n if (\n validator !== 'hono' &&\n verbOption.response.originalSchema?.['200']?.content?.[\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n 'application/json'\n ]\n ) {\n currentValidator += `zValidator('response', ${pascalOperationName}Response),\\n`;\n }\n }\n\n const body = bodyOverride ?? DEFAULT_HANDLER_BODY;\n\n code += `\nexport const ${handlerName} = factory.createHandlers(\n${currentValidator}async (c: ${contextTypeName}) => {${body}},\n);`;\n\n hasZValidator ||= currentValidator !== '';\n }\n\n return [code, hasZValidator];\n};\n\nconst getZvalidatorImports = (\n verbOptions: GeneratorVerbOptions[],\n importPath: string,\n isHonoValidator: boolean,\n) => {\n const specifiers = [];\n\n for (const {\n operationName,\n headers,\n params,\n queryParams,\n body,\n response,\n } of verbOptions) {\n const pascalOperationName = pascal(operationName);\n\n if (headers) {\n specifiers.push(`${pascalOperationName}Header`);\n }\n\n if (params.length > 0) {\n specifiers.push(`${pascalOperationName}Params`);\n }\n\n if (queryParams) {\n specifiers.push(`${pascalOperationName}QueryParams`);\n }\n\n if (body.definition) {\n specifiers.push(`${pascalOperationName}Body`);\n }\n\n if (\n !isHonoValidator &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n response.originalSchema?.['200']?.content?.['application/json'] !=\n undefined\n ) {\n specifiers.push(`${pascalOperationName}Response`);\n }\n }\n\n return specifiers.length === 0\n ? ''\n : `import {\\n${specifiers.join(',\\n')}\\n} from '${importPath}'`;\n};\n\nconst getVerbOptionGroupByTag = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n) => {\n const grouped: Record<string, GeneratorVerbOptions[]> = {};\n\n for (const value of Object.values(verbOptions)) {\n const tag = value.tags[0];\n // this is not always false\n // TODO look into types\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!grouped[tag]) {\n grouped[tag] = [];\n }\n grouped[tag].push(value);\n }\n\n return grouped;\n};\n\nconst generateHandlerFile = async ({\n verbs,\n path,\n header,\n validatorModule,\n zodModule,\n contextModule,\n}: {\n verbs: GeneratorVerbOptions[];\n path: string;\n header: string;\n validatorModule?: string;\n zodModule: string;\n contextModule: string;\n}) => {\n const validator =\n validatorModule === '@hono/zod-validator'\n ? ('hono' as const)\n : validatorModule != undefined;\n\n const verbList = Object.values(verbs);\n\n const [, hasZValidator] = getHonoHandlers(\n ...verbList.map((verbOption) => ({\n handlerName: `${verbOption.operationName}Handlers`,\n contextTypeName: `${pascal(verbOption.operationName)}Context`,\n verbOption,\n validator,\n })),\n );\n\n const imports = [\"import { createFactory } from 'hono/factory';\"];\n\n if (hasZValidator && validatorModule != undefined) {\n imports.push(\n `import { zValidator } from '${generateModuleSpecifier(path, validatorModule)}';`,\n );\n }\n\n imports.push(\n `import { ${verbList\n .map((verb) => `${pascal(verb.operationName)}Context`)\n .join(',\\n')} } from '${generateModuleSpecifier(path, contextModule)}';`,\n );\n\n if (hasZValidator) {\n imports.push(\n getZvalidatorImports(\n verbList,\n generateModuleSpecifier(path, zodModule),\n validatorModule === '@hono/zod-validator',\n ),\n );\n }\n\n const preamble = `${header}${imports.filter((imp) => imp !== '').join('\\n')}\\n\\nconst factory = createFactory();`;\n\n const existingBodies = fs.existsSync(path)\n ? extractExistingHandlerBodies(await fs.readFile(path, 'utf8'))\n : new Map<string, string>();\n\n // Always rebuild the preamble (header + imports + factory) and the validator\n // chain from current metadata so import paths, casing, and middleware match\n // the latest configuration. We only splice the user-authored async body\n // back in — preserving the wrapper would risk keeping stale `zValidator`\n // calls whose imports we just rewrote.\n const [handlerCode] = getHonoHandlers(\n ...verbList.map((verbOption) => ({\n handlerName: `${verbOption.operationName}Handlers`,\n contextTypeName: `${pascal(verbOption.operationName)}Context`,\n verbOption,\n validator,\n bodyOverride: existingBodies.get(`${verbOption.operationName}Handlers`),\n })),\n );\n\n return `${preamble}${handlerCode}`;\n};\n\n/**\n * extractExistingHandlerBodies scans a previously generated handler file and\n * returns the user-authored body of each\n * `async (c: ...) => { /* body *\\/ }` block keyed by handler name.\n *\n * We deliberately preserve only the inner body — not the surrounding\n * `factory.createHandlers(...)` call — so the regenerated wrapper always\n * reflects the current validator chain and imports. The scanner is\n * lex-aware: it skips strings, template literals, regex literals, and\n * comments while counting parentheses/braces, so user code containing\n * `)` or `}` characters in those contexts does not confuse the matcher.\n */\nexport const extractExistingHandlerBodies = (\n source: string,\n): Map<string, string> => {\n const bodies = new Map<string, string>();\n const exportRegex =\n /export\\s+const\\s+(\\w+Handlers)\\s*=\\s*factory\\.createHandlers\\s*\\(/g;\n\n let match: RegExpExecArray | null;\n while ((match = exportRegex.exec(source)) !== null) {\n const handlerName = match[1];\n const callOpenIdx = match.index + match[0].length - 1; // points at '('\n const callCloseIdx = findMatchingClose(source, callOpenIdx, '(', ')');\n if (callCloseIdx === -1) continue;\n\n const callBody = source.slice(callOpenIdx + 1, callCloseIdx);\n const body = extractAsyncArrowBody(callBody);\n if (body !== undefined) {\n bodies.set(handlerName, body);\n }\n }\n\n return bodies;\n};\n\n/**\n * findMatchingClose returns the index of the closing bracket that pairs with\n * the opening bracket at `openIdx`, or -1 if unbalanced. The scan skips\n * strings, template literals, regex literals, and comments so brackets in\n * those contexts do not affect depth.\n */\nconst findMatchingClose = (\n source: string,\n openIdx: number,\n open: '(' | '{',\n close: ')' | '}',\n): number => {\n let depth = 0;\n let i = openIdx;\n while (i < source.length) {\n const ch = source[i];\n const next = source[i + 1];\n\n // Line comment\n if (ch === '/' && next === '/') {\n const nl = source.indexOf('\\n', i + 2);\n i = nl === -1 ? source.length : nl + 1;\n continue;\n }\n // Block comment\n if (ch === '/' && next === '*') {\n const end = source.indexOf('*/', i + 2);\n i = end === -1 ? source.length : end + 2;\n continue;\n }\n // String / template literal\n if (ch === \"'\" || ch === '\"' || ch === '`') {\n i = skipString(source, i, ch);\n continue;\n }\n // Regex literal — only when a regex is syntactically possible. A `/`\n // following an identifier or closing bracket is division, not a regex.\n if (ch === '/' && isRegexContext(source, i)) {\n i = skipRegex(source, i);\n continue;\n }\n\n if (ch === open) depth++;\n else if (ch === close) {\n depth--;\n if (depth === 0) return i;\n }\n i++;\n }\n return -1;\n};\n\nconst skipString = (\n source: string,\n start: number,\n quote: \"'\" | '\"' | '`',\n): number => {\n let i = start + 1;\n while (i < source.length) {\n const ch = source[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (quote === '`' && ch === '$' && source[i + 1] === '{') {\n const end = findMatchingClose(source, i + 1, '{', '}');\n i = end === -1 ? source.length : end + 1;\n continue;\n }\n if (ch === quote) return i + 1;\n i++;\n }\n return source.length;\n};\n\nconst skipRegex = (source: string, start: number): number => {\n let i = start + 1;\n let inClass = false;\n while (i < source.length) {\n const ch = source[i];\n if (ch === '\\\\') {\n i += 2;\n continue;\n }\n if (ch === '[') inClass = true;\n else if (ch === ']') inClass = false;\n else if (ch === '/' && !inClass) {\n i++;\n while (i < source.length && /[gimsuy]/.test(source[i])) i++;\n return i;\n }\n if (ch === '\\n') return start + 1; // not a regex after all; bail\n i++;\n }\n return source.length;\n};\n\nconst REGEX_PRECEDING_KEYWORDS = new Set([\n 'return',\n 'throw',\n 'yield',\n 'await',\n 'case',\n 'new',\n 'typeof',\n 'void',\n 'delete',\n 'in',\n 'of',\n 'instanceof',\n]);\n\nconst isRegexContext = (source: string, slashIdx: number): boolean => {\n let j = slashIdx - 1;\n while (\n j >= 0 &&\n (source[j] === ' ' || source[j] === '\\t' || source[j] === '\\n')\n ) {\n j--;\n }\n if (j < 0) return true;\n\n const c = source[j];\n\n // Spread `...` allows a regex literal as the spread target.\n if (c === '.') {\n if (j >= 2 && source[j - 1] === '.' && source[j - 2] === '.') return true;\n return false;\n }\n\n // Identifier char: scan backward to extract token, check keyword set.\n if (/[A-Za-z0-9_$]/.test(c)) {\n let k = j;\n while (k >= 0 && /[A-Za-z0-9_$]/.test(source[k])) k--;\n const token = source.slice(k + 1, j + 1);\n return REGEX_PRECEDING_KEYWORDS.has(token);\n }\n\n // Closing brackets imply a value precedes — division.\n if (c === ')' || c === ']') return false;\n\n return true;\n};\n\n/**\n * extractAsyncArrowBody finds the trailing `async (c: ...) => { ... }`\n * argument inside `factory.createHandlers(...)` and returns the inner body\n * (without the surrounding braces). Returns undefined when the call does not\n * end with the expected arrow function shape.\n */\nconst extractAsyncArrowBody = (callBody: string): string | undefined => {\n // Walk the argument list at depth 0 only, skipping strings, templates,\n // regex literals, comments, and nested parens/braces, so arrows inside\n // user-authored callbacks (e.g. `pets.map(p => p.id)`) are ignored.\n let i = 0;\n let lastTopLevelArrow = -1;\n while (i < callBody.length) {\n const ch = callBody[i];\n const next = callBody[i + 1];\n\n if (ch === '/' && next === '/') {\n const nl = callBody.indexOf('\\n', i + 2);\n i = nl === -1 ? callBody.length : nl + 1;\n continue;\n }\n if (ch === '/' && next === '*') {\n const end = callBody.indexOf('*/', i + 2);\n i = end === -1 ? callBody.length : end + 2;\n continue;\n }\n if (ch === \"'\" || ch === '\"' || ch === '`') {\n i = skipString(callBody, i, ch);\n continue;\n }\n if (ch === '/' && isRegexContext(callBody, i)) {\n i = skipRegex(callBody, i);\n continue;\n }\n if (ch === '(' || ch === '{') {\n const open = ch;\n const close = ch === '(' ? ')' : '}';\n const end = findMatchingClose(callBody, i, open, close);\n i = end === -1 ? callBody.length : end + 1;\n continue;\n }\n if (ch === '=' && next === '>') {\n lastTopLevelArrow = i;\n i += 2;\n continue;\n }\n i++;\n }\n\n if (lastTopLevelArrow === -1) return undefined;\n\n let j = lastTopLevelArrow + 2;\n while (j < callBody.length && /\\s/.test(callBody[j])) j++;\n if (callBody[j] !== '{') return undefined;\n\n const closeIdx = findMatchingClose(callBody, j, '{', '}');\n if (closeIdx === -1) return undefined;\n\n return callBody.slice(j + 1, closeIdx);\n};\n\nconst generateHandlerFiles = async (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n validatorModule: string,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n // This function _does not control_ where the .zod and .context modules land.\n // That determination is made elsewhere and this function must implement the\n // same conventions.\n\n if (output.override.hono.handlers) {\n // One file per operation in the user-provided directory.\n return Promise.all(\n Object.values(verbOptions).map(async (verbOption) => {\n const tag = kebab(verbOption.tags[0] ?? 'default');\n\n const path = nodePath.join(\n output.override.hono.handlers ?? '',\n `./${verbOption.operationName}` + extension,\n );\n\n // Mirror the layout used by generateZodFiles/generateContextFiles so\n // imports resolve to the actual emitted modules.\n let zodModule: string;\n let contextModule: string;\n if (output.mode === 'tags') {\n zodModule = nodePath.join(dirname, `${kebab(tag)}.zod`);\n contextModule = nodePath.join(dirname, `${kebab(tag)}.context`);\n } else if (output.mode === 'tags-split') {\n zodModule = nodePath.join(dirname, tag, tag + '.zod');\n contextModule = nodePath.join(dirname, tag, tag + '.context');\n } else {\n zodModule = nodePath.join(dirname, `${filename}.zod`);\n contextModule = nodePath.join(dirname, `${filename}.context`);\n }\n\n return {\n content: await generateHandlerFile({\n path,\n header,\n verbs: [verbOption],\n validatorModule,\n zodModule,\n contextModule,\n }),\n path,\n };\n }),\n );\n }\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n // One file per operation _tag_ under dirname.\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n return Promise.all(\n Object.entries(groupByTags).map(async ([tag, verbs]) => {\n const handlerPath =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.handlers${extension}`)\n : nodePath.join(dirname, tag, tag + '.handlers' + extension);\n\n return {\n content: await generateHandlerFile({\n path: handlerPath,\n header,\n verbs,\n validatorModule,\n zodModule:\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.zod`)\n : nodePath.join(dirname, tag, tag + '.zod'),\n contextModule:\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.context`)\n : nodePath.join(dirname, tag, tag + '.context'),\n }),\n path: handlerPath,\n };\n }),\n );\n }\n\n // One file with all operations.\n const handlerPath = nodePath.join(\n dirname,\n `${filename}.handlers${extension}`,\n );\n\n return [\n {\n content: await generateHandlerFile({\n path: handlerPath,\n header,\n verbs: Object.values(verbOptions),\n validatorModule,\n zodModule: nodePath.join(dirname, `${filename}.zod`),\n contextModule: nodePath.join(dirname, `${filename}.context`),\n }),\n path: handlerPath,\n },\n ];\n};\n\nconst getContext = (verbOption: GeneratorVerbOptions) => {\n let paramType = '';\n if (verbOption.params.length > 0) {\n const params = getParamsInPath(verbOption.pathRoute).map((name) => {\n const param = verbOption.params.find(\n (p) => p.name === sanitize(camel(name), { es5keyword: true }),\n );\n const definition = param?.definition.split(':')[1];\n const required = param?.required ?? false;\n return {\n definition: `${name}${required ? '' : '?'}:${definition}`,\n };\n });\n paramType = `param: {\\n ${params\n .map((property) => property.definition)\n .join(',\\n ')},\\n },`;\n }\n\n const queryType = verbOption.queryParams\n ? `query: ${verbOption.queryParams.schema.name},`\n : '';\n const bodyType = verbOption.body.definition\n ? `json: ${verbOption.body.definition},`\n : '';\n const hasIn = !!paramType || !!queryType || !!bodyType;\n\n return `export type ${pascal(\n verbOption.operationName,\n )}Context<E extends Env = any> = Context<E, '${getRoute(\n verbOption.pathRoute,\n )}'${\n hasIn\n ? `, { in: { ${paramType}${queryType}${bodyType} }, out: { ${paramType}${queryType}${bodyType} } }`\n : ''\n }>`;\n};\n\nconst getHeader = (\n option: false | ((info: OpenApiInfoObject) => string | string[]),\n info: OpenApiInfoObject,\n): string => {\n if (!option) {\n return '';\n }\n\n const header = option(info);\n\n return Array.isArray(header) ? jsDoc({ description: header }) : header;\n};\n\nconst getSpecInfo = (context: ContextSpec): OpenApiInfoObject =>\n context.spec.info ?? {\n title: 'API',\n version: '1.0.0',\n };\n\nconst generateContextFile = ({\n path,\n verbs,\n schemaModule,\n}: {\n path: string;\n verbs: GeneratorVerbOptions[];\n schemaModule: string;\n}) => {\n let content = `import type { Context, Env } from 'hono';\\n\\n`;\n\n const contexts = verbs.map((verb) => getContext(verb));\n\n const imps = new Set(\n verbs\n .flatMap((verb) => {\n const imports: GeneratorImport[] = [];\n if (verb.params.length > 0) {\n imports.push(...verb.params.flatMap((param) => param.imports));\n }\n\n if (verb.queryParams) {\n imports.push({\n name: verb.queryParams.schema.name,\n });\n }\n\n if (verb.body.definition) {\n imports.push(...verb.body.imports);\n }\n\n return imports;\n })\n .map((imp) => imp.name)\n .filter((imp) => contexts.some((context) => context.includes(imp))),\n );\n\n if (contexts.some((context) => context.includes('NonReadonly<'))) {\n content += getOrvalGeneratedTypes();\n content += '\\n';\n }\n\n if (imps.size > 0) {\n content += `import type {\\n${[...imps]\n .toSorted()\n .join(\n ',\\n ',\n )}\\n} from '${generateModuleSpecifier(path, schemaModule)}';\\n\\n`;\n }\n\n content += contexts.join('\\n');\n\n return content;\n};\n\nconst generateContextFiles = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n schemaModule: string,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n return Object.entries(groupByTags).map(([tag, verbs]) => {\n const path =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.context${extension}`)\n : nodePath.join(dirname, tag, tag + '.context' + extension);\n const code = generateContextFile({\n verbs,\n path,\n schemaModule: schemaModule,\n });\n return { content: `${header}${code}`, path };\n });\n }\n\n const path = nodePath.join(dirname, `${filename}.context${extension}`);\n const code = generateContextFile({\n verbs: Object.values(verbOptions),\n path,\n schemaModule: schemaModule,\n });\n\n return [\n {\n content: `${header}${code}`,\n path,\n },\n ];\n};\n\nconst generateZodFiles = async (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n const builderContexts = await Promise.all(\n Object.entries(groupByTags).map(async ([tag, verbs]) => {\n const zods = await Promise.all(\n verbs.map(async (verbOption) =>\n generateZod(\n verbOption,\n {\n route: verbOption.route,\n pathRoute: verbOption.pathRoute,\n override: output.override,\n context,\n output: output.target,\n },\n output.client,\n ),\n ),\n );\n\n if (zods.every((z) => z.implementation === '')) {\n return {\n content: '',\n path: '',\n };\n }\n\n const allMutators = new Map(\n zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m]),\n )\n .values()\n .toArray();\n\n const mutatorsImports = generateMutatorImports({\n mutators: allMutators,\n });\n\n let content = `${header}import { z as zod } from 'zod';\\n${mutatorsImports}\\n`;\n\n const zodPath =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.zod${extension}`)\n : nodePath.join(dirname, tag, tag + '.zod' + extension);\n\n content += zods.map((zod) => zod.implementation).join('\\n');\n\n return {\n content,\n path: zodPath,\n };\n }),\n );\n\n return builderContexts.filter((context) => context.content !== '');\n }\n\n const zods = await Promise.all(\n Object.values(verbOptions).map(async (verbOption) =>\n generateZod(\n verbOption,\n {\n route: verbOption.route,\n pathRoute: verbOption.pathRoute,\n override: output.override,\n context,\n output: output.target,\n },\n output.client,\n ),\n ),\n );\n\n const allMutators = new Map(\n zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m]),\n )\n .values()\n .toArray();\n\n const mutatorsImports = generateMutatorImports({\n mutators: allMutators,\n });\n\n let content = `${header}import { z as zod } from 'zod';\\n${mutatorsImports}\\n`;\n\n const zodPath = nodePath.join(dirname, `${filename}.zod${extension}`);\n\n content += zods.map((zod) => zod.implementation).join('\\n');\n\n return [\n {\n content,\n path: zodPath,\n },\n ];\n};\n\nconst generateZvalidator = (\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n let validatorPath = output.override.hono.validatorOutputPath;\n if (!output.override.hono.validatorOutputPath) {\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n validatorPath = nodePath.join(dirname, `${filename}.validator${extension}`);\n }\n\n return {\n content: `${header}${ZVALIDATOR_SOURCE}`,\n path: validatorPath,\n };\n};\n\nconst generateCompositeRoutes = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const targetInfo = getFileInfo(output.target);\n const compositeRouteInfo = getFileInfo(output.override.hono.compositeRoute);\n\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n const routes = Object.values(verbOptions)\n .map((verbOption) => {\n return generateHonoRoute(verbOption, verbOption.pathRoute);\n })\n .join('');\n\n const importHandlers = Object.values(verbOptions);\n\n let ImportHandlersImplementation: string;\n if (output.override.hono.handlers) {\n const handlerFileInfo = getFileInfo(output.override.hono.handlers);\n const operationNames = importHandlers.map(\n (verbOption) => verbOption.operationName,\n );\n\n ImportHandlersImplementation = operationNames\n .map((operationName) => {\n const importHandlerName = `${operationName}Handlers`;\n\n const handlersPath = generateModuleSpecifier(\n compositeRouteInfo.path,\n nodePath.join(handlerFileInfo.dirname, `./${operationName}`),\n );\n\n return `import { ${importHandlerName} } from '${handlersPath}';`;\n })\n .join('\\n');\n } else {\n const tags = importHandlers.map((verbOption) =>\n kebab(verbOption.tags[0] ?? 'default'),\n );\n const uniqueTags = tags.filter((t, i) => tags.indexOf(t) === i);\n\n ImportHandlersImplementation = uniqueTags\n .map((tag) => {\n const importHandlerNames = importHandlers\n .filter((verbOption) => verbOption.tags[0] === tag)\n .map((verbOption) => ` ${verbOption.operationName}Handlers`)\n .join(`, \\n`);\n\n const handlersPath = generateModuleSpecifier(\n compositeRouteInfo.path,\n nodePath.join(targetInfo.dirname, tag),\n );\n\n return `import {\\n${importHandlerNames}\\n} from '${handlersPath}/${tag}.handlers';`;\n })\n .join('\\n');\n }\n\n const honoImport = `import { Hono } from 'hono';`;\n const honoInitialization = `\\nconst app = new Hono()`;\n const honoAppExport = `\\nexport default app;`;\n\n const content = `${header}${honoImport}\n${ImportHandlersImplementation}\n${honoInitialization}${routes};\n${honoAppExport}\n`;\n\n return [\n {\n content,\n path: output.override.hono.compositeRoute || '',\n },\n ];\n};\n\nexport const generateExtraFiles: ClientExtraFilesBuilder = async (\n verbOptions,\n output,\n context,\n) => {\n const { path, pathWithoutExtension } = getFileInfo(output.target);\n const validator = generateZvalidator(output, context);\n let schemaModule: string;\n\n if (output.schemas != undefined) {\n const schemasPath = (\n isObject(output.schemas) ? output.schemas.path : output.schemas\n ) as string;\n const basePath = getFileInfo(schemasPath).dirname;\n schemaModule = basePath;\n } else if (output.mode === 'single') {\n schemaModule = path;\n } else {\n schemaModule = `${pathWithoutExtension}.schemas`;\n }\n\n const contexts = generateContextFiles(\n verbOptions,\n output,\n context,\n schemaModule,\n );\n const compositeRoutes = output.override.hono.compositeRoute\n ? generateCompositeRoutes(verbOptions, output, context)\n : [];\n const [handlers, zods] = await Promise.all([\n generateHandlerFiles(verbOptions, output, context, validator.path),\n generateZodFiles(verbOptions, output, context),\n ]);\n\n return [\n ...handlers,\n ...contexts,\n ...zods,\n ...(output.override.hono.validator &&\n output.override.hono.validator !== 'hono'\n ? [validator]\n : []),\n ...compositeRoutes,\n ];\n};\n\nconst honoClientBuilder: ClientGeneratorsBuilder = {\n client: generateHono,\n dependencies: getHonoDependencies,\n header: getHonoHeader,\n footer: getHonoFooter,\n extraFiles: generateExtraFiles,\n};\n\nexport const builder = () => () => honoClientBuilder;\n\nexport default builder;\n"],"mappings":";;;;;AAEA,MAAM,YAAY,SAA0B,oBAAoB,KAAK,KAAK;AAE1E,MAAM,gBAAgB,SAAyB;CAC7C,MAAM,UAAU,4BAA4B,KAAK,KAAK;AACtD,KAAI,CAAC,SAAS,OAAQ,QAAO;CAE7B,MAAM,OAAO,QAAQ;CACrB,MAAM,QAAQ,SAAS,QAAQ,IAAI;EACjC,YAAY;EACZ,YAAY;EACZ,MAAM;EACN,KAAK;EACN,CAAC;CACF,MAAM,OAAO,SAAS,QAAQ,GAAG,GAAG,aAAa,QAAQ,GAAG,GAAG,QAAQ;AAEvE,QAAO,SAAS,KAAK,GAAG,GAAG,KAAK,GAAG,QAAQ,SAAS,GAAG,OAAO,QAAQ;;AAGxE,MAAa,YAAY,UAAkB;CACzC,MAAM,gBAAgB,MAAM,MAAM,IAAI;CAEtC,IAAI,MAAM;AACV,MAAK,MAAM,CAAC,GAAG,SAAS,cAAc,SAAS,EAAE;AAC/C,MAAI,CAAC,QAAQ,MAAM,EAAG;AAEtB,SAAO,KAAK,SAAS,IAAI,GAAG,IAAI,aAAa,KAAK,KAAK,IAAI;;AAG7D,QAAO;;;;ACET,MAAM,oBAAoB,GACvB,aAAa,SAAS,KAAK,OAAO,K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B,aAAa,QAAQ,QAAQ,GACrD,EAAE;CACN,MAAM,CAAC,UAAU,QAAQ,MAAM,QAAQ,IAAI,CACzC,qBAAqB,aAAa,QAAQ,SAAS,UAAU,KAAK,EAClE,iBAAiB,aAAa,QAAQ,QAAQ,CAC/C,CAAC;AAEF,QAAO;EACL,GAAG;EACH,GAAG;EACH,GAAG;EACH,GAAI,OAAO,SAAS,KAAK,aACzB,OAAO,SAAS,KAAK,cAAc,SAC/B,CAAC,UAAU,GACX,EAAE;EACN,GAAG;EACJ;;AAGH,MAAM,oBAA6C;CACjD,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,QAAQ;CACR,YAAY;CACb;AAED,MAAa,sBAAsB"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../src/handler-merge.ts","../src/route.ts","../src/index.ts"],"sourcesContent":["import type * as TS from 'typescript';\n\n/**\n * AST-based reconciliation of an existing hono handler file.\n *\n * The `smart` handler strategy regenerates only the regions orval owns — its own\n * imports (names + module specifier) and the `zValidator(...)` arguments of each\n * handler — while leaving every user-authored construct untouched: custom imports,\n * middleware passed to `factory.createHandlers(...)`, the `async (c) => { ... }`\n * body, and any top-level helpers, constants, types, or comments.\n *\n * We edit the original source text in place using node offsets from the\n * TypeScript compiler API, so formatting and comments of untouched regions are\n * preserved. On any parse failure we return the source unchanged — user code is\n * never destroyed by a parser hiccup.\n */\n\n/**\n * `typescript` is an optional peer dependency, imported lazily. Consumers who do\n * not have it installed — and every non-hono or `skip` code path — never trigger\n * the import; `smart`/`full` fall back to `skip` when it is unavailable. Loading\n * the consumer's own typescript also avoids shipping a second copy of it.\n */\nlet ts!: typeof TS;\nlet typeScriptAvailable: boolean | undefined;\n\nexport const ensureTypeScript = async (): Promise<boolean> => {\n if (typeScriptAvailable === undefined) {\n try {\n const mod = await import('typescript');\n ts = (mod as unknown as { default?: typeof TS }).default ?? mod;\n typeScriptAvailable = true;\n } catch {\n typeScriptAvailable = false;\n }\n }\n return typeScriptAvailable;\n};\n\nexport type ValidatorTarget =\n | 'header'\n | 'param'\n | 'query'\n | 'json'\n | 'form'\n | 'response';\n\nexport interface DesiredValidator {\n target: ValidatorTarget;\n /** PascalCase zod schema identifier, e.g. `VerifyAccountResponse`. */\n schema: string;\n}\n\nexport interface DesiredHandler {\n /** e.g. `verifyAccountHandlers`. */\n handlerName: string;\n /** Validators required by the spec, in canonical order. */\n validators: DesiredValidator[];\n /** Full handler block, used only when the handler is missing and appended. */\n stub: string;\n}\n\nexport interface OrvalImport {\n names: string[];\n /** Module specifier as orval would emit it (relative, extensionless). */\n module: string;\n}\n\nexport interface DesiredImports {\n /** `createFactory` from `hono/factory`. */\n factory: OrvalImport;\n /** `zValidator` from the validator module; omitted when no validators exist. */\n validator?: OrvalImport;\n /** `<Op>Context` identifiers from the context module. */\n context: OrvalImport;\n /** zod schema identifiers from the zod module; omitted when none are needed. */\n zod?: OrvalImport;\n}\n\nconst VALIDATOR_TARGETS = new Set<string>([\n 'header',\n 'param',\n 'query',\n 'json',\n 'form',\n 'response',\n]);\n\ninterface Edit {\n start: number;\n end: number;\n text: string;\n}\n\nconst parse = (source: string): TS.SourceFile | undefined => {\n const sourceFile = ts.createSourceFile(\n 'handler.ts',\n source,\n ts.ScriptTarget.Latest,\n /* setParentNodes */ true,\n ts.ScriptKind.TS,\n );\n const diagnostics = (\n sourceFile as unknown as { parseDiagnostics?: TS.Diagnostic[] }\n ).parseDiagnostics;\n if (diagnostics && diagnostics.length > 0) return undefined;\n return sourceFile;\n};\n\ninterface ParsedHandler {\n name: string;\n call: TS.CallExpression;\n}\n\nconst findHandlers = (sourceFile: TS.SourceFile): ParsedHandler[] => {\n const handlers: ParsedHandler[] = [];\n for (const statement of sourceFile.statements) {\n if (!ts.isVariableStatement(statement)) continue;\n for (const declaration of statement.declarationList.declarations) {\n if (!ts.isIdentifier(declaration.name)) continue;\n const name = declaration.name.text;\n if (!name.endsWith('Handlers')) continue;\n const init = declaration.initializer;\n if (\n init &&\n ts.isCallExpression(init) &&\n ts.isPropertyAccessExpression(init.expression) &&\n init.expression.name.text === 'createHandlers'\n ) {\n handlers.push({ name, call: init });\n }\n }\n }\n return handlers;\n};\n\nconst importedNames = (declaration: TS.ImportDeclaration): string[] => {\n const bindings = declaration.importClause?.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return [];\n return bindings.elements.map((element) => element.name.text);\n};\n\nconst moduleText = (declaration: TS.ImportDeclaration): string =>\n ts.isStringLiteral(declaration.moduleSpecifier)\n ? declaration.moduleSpecifier.text\n : '';\n\n/**\n * A \"plain\" named import — no default binding, no namespace (`* as x`), and no\n * aliases (`x as y`). Only plain named imports are safe for orval to rewrite;\n * default / namespace / aliased / mixed imports are user-authored and must be\n * left untouched.\n */\nconst isPlainNamedImport = (declaration: TS.ImportDeclaration): boolean => {\n const clause = declaration.importClause;\n if (!clause || clause.name) return false;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return false;\n return bindings.elements.every(\n (element) => element.propertyName === undefined,\n );\n};\n\nconst setEquals = (a: string[], b: string[]): boolean =>\n a.length === b.length && a.every((value) => b.includes(value));\n\n// Escape regex metacharacters so an identifier can be interpolated literally.\n// JS identifiers may contain `$`, which would otherwise act as an anchor.\nconst escapeRegExp = (value: string): string =>\n value.replaceAll(/[.*+?^${}()|[\\]\\\\]/g, String.raw`\\$&`);\n\n/**\n * The local binding name an imported symbol is bound to, honouring aliases —\n * e.g. `import { zValidator as zv }` → `'zv'`. Returns undefined when the symbol\n * is not imported. Used so a handler that aliases `zValidator` is detected and\n * its new validators are inserted under the same alias (never an unimported name).\n */\nconst localNameFor = (\n importDeclarations: TS.ImportDeclaration[],\n importedName: string,\n module: string,\n): string | undefined => {\n for (const declaration of importDeclarations) {\n if (moduleText(declaration) !== module) continue;\n const bindings = declaration.importClause?.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) continue;\n for (const element of bindings.elements) {\n if ((element.propertyName?.text ?? element.name.text) === importedName) {\n return element.name.text;\n }\n }\n }\n return undefined;\n};\n\nconst renderImport = ({ names, module }: OrvalImport): string =>\n names.length <= 1\n ? `import { ${names.join('')} } from '${module}';`\n : `import {\\n ${names.join(',\\n ')}\\n} from '${module}';`;\n\nconst lineStart = (source: string, position: number): number =>\n source.lastIndexOf('\\n', position - 1) + 1;\n\n/** Whether only whitespace sits between the line start and `position`. */\nconst startsLine = (source: string, position: number): boolean =>\n /^\\s*$/.test(source.slice(lineStart(source, position), position));\n\nexport const reconcileHandlerFile = async (\n source: string,\n desired: { imports: DesiredImports; handlers: DesiredHandler[] },\n): Promise<string> => {\n if (!(await ensureTypeScript())) return source;\n\n const sourceFile = parse(source);\n if (!sourceFile) return source;\n\n const edits: Edit[] = [];\n const importDeclarations = sourceFile.statements.filter(\n (statement): statement is TS.ImportDeclaration =>\n ts.isImportDeclaration(statement),\n );\n const handlers = findHandlers(sourceFile);\n const existingNames = new Set(handlers.map((handler) => handler.name));\n const pendingInsertions: string[] = [];\n\n // Locate an orval-owned import by its module specifier (authoritative).\n const byModule = (module: string): TS.ImportDeclaration | undefined =>\n module\n ? importDeclarations.find(\n (declaration) => moduleText(declaration) === module,\n )\n : undefined;\n\n // Fallback used only when the module specifier has moved: a PLAIN named import\n // whose names are EXACTLY `signature` (case-sensitive). This relocates an\n // orval import without the case-folding hazard of fuzzy name matching, which\n // could otherwise clobber an unrelated user import (e.g. `listPetsResponse`).\n const plainExact = (signature: string[]): TS.ImportDeclaration | undefined =>\n signature.length === 0\n ? undefined\n : importDeclarations.find(\n (declaration) =>\n isPlainNamedImport(declaration) &&\n setEquals(importedNames(declaration), signature),\n );\n\n const removeImportEdit = (declaration: TS.ImportDeclaration) => {\n let end = declaration.getEnd();\n if (source.slice(end, end + 2) === '\\r\\n') end += 2;\n else if (source[end] === '\\n') end += 1;\n edits.push({ start: declaration.getStart(sourceFile), end, text: '' });\n };\n\n // Whether `name` is already bound as a bare identifier by some import (a named\n // import's local name, or a default import). Namespace imports do NOT bind\n // their members bare. Used to avoid duplicate imports when augmenting.\n const isImportedBare = (name: string): boolean =>\n importDeclarations.some((declaration) => {\n const clause = declaration.importClause;\n if (!clause) return false;\n if (clause.name?.text === name) return true;\n return importedNames(declaration).includes(name);\n });\n\n /**\n * Reconcile an orval-owned import to `names`. We only rewrite/remove a PLAIN\n * named import whose names are ALL orval-owned (per `isOrvalName`). A\n * user-authored import (aliased / namespace / default / mixed) is never\n * rewritten; instead, when `augment` is provided, we add any orval name that\n * is genuinely needed as a bare reference but isn't yet importable bare — e.g.\n * a newly appended handler's context, or a newly-inserted validator's schema.\n */\n const reconcileImport = (\n existing: TS.ImportDeclaration | undefined,\n names: string[],\n module: string,\n isOrvalName: (name: string) => boolean,\n augment?: (name: string) => boolean,\n collectRenames?: Map<string, string>,\n ) => {\n if (!existing) {\n // Never insert a name that is already bound bare elsewhere (e.g. a default\n // or namespace import from another module) — that would create a duplicate\n // binding.\n const toInsert = (\n augment ? names.filter((name) => augment(name)) : names\n ).filter((name) => !isImportedBare(name));\n if (toInsert.length > 0) {\n pendingInsertions.push(renderImport({ names: toInsert, module }));\n }\n return;\n }\n\n const isOurs =\n isPlainNamedImport(existing) &&\n importedNames(existing).every((name) => isOrvalName(name));\n if (!isOurs) {\n if (augment) {\n const missing = names.filter(\n (name) => augment(name) && !isImportedBare(name),\n );\n if (missing.length > 0) {\n pendingInsertions.push(renderImport({ names: missing, module }));\n }\n }\n return;\n }\n\n if (names.length === 0) {\n removeImportEdit(existing);\n return;\n }\n\n if (\n setEquals(importedNames(existing), names) &&\n moduleText(existing) === module\n ) {\n return;\n }\n\n // Record the camelCase→PascalCase migrations this rewrite implies, so every\n // OTHER reference to the old binding (validator args, `z.infer<typeof X>` in\n // bodies, etc.) can be renamed too — not just the import itself.\n if (collectRenames) {\n for (const old of importedNames(existing)) {\n const next = names.find(\n (name) => name !== old && name.toLowerCase() === old.toLowerCase(),\n );\n if (next) collectRenames.set(old, next);\n }\n }\n\n edits.push({\n start: existing.getStart(sourceFile),\n end: existing.getEnd(),\n text: renderImport({ names, module }),\n });\n };\n\n // --- validators first, so schema names referenced by reconciled validators\n // (newly inserted, or renamed camelCase → PascalCase) are known to the import\n // step below. The local name `zValidator` is bound to in the DESIRED validator\n // module (honours `import { zValidator as zv } from '<validatorModule>'`); a\n // zValidator imported from a different module is the user's own and ignored,\n // so new validators always route through orval's validator. ---\n const validatorModule = desired.imports.validator?.module ?? '';\n const zValidatorName = validatorModule\n ? (localNameFor(importDeclarations, 'zValidator', validatorModule) ??\n 'zValidator')\n : 'zValidator';\n\n const requiredSchemas = new Set<string>();\n const removedValidatorRanges: [number, number][] = [];\n for (const desiredHandler of desired.handlers) {\n const parsed = handlers.find(\n (handler) => handler.name === desiredHandler.handlerName,\n );\n if (parsed) {\n reconcileValidators(\n sourceFile,\n source,\n parsed.call,\n desiredHandler.validators,\n edits,\n zValidatorName,\n requiredSchemas,\n removedValidatorRanges,\n );\n }\n }\n\n // Schema migrations (old camelCase → new PascalCase) implied by rewriting the\n // zod import; applied file-wide below so every reference is migrated.\n const schemaRenames = new Map<string, string>();\n\n const toAppend = desired.handlers.filter(\n (handler) => !existingNames.has(handler.handlerName),\n );\n\n // --- imports ---\n // Source with import declarations blanked out, so an import's own text (e.g.\n // `import { ListPetsResponse as Resp }`) is never counted as a usage.\n let bodySource = source;\n for (const declaration of importDeclarations) {\n const start = declaration.getStart(sourceFile);\n const end = declaration.getEnd();\n bodySource =\n bodySource.slice(0, start) +\n ' '.repeat(end - start) +\n bodySource.slice(end);\n }\n\n // A name needs a bare import when it is referenced unqualified in the body\n // (not as `Ns.Name`), is a schema a reconciled validator now references\n // (inserted or renamed), or is used by an appended handler stub.\n const referencedBare = (name: string): boolean =>\n new RegExp(String.raw`(?<!\\.)\\b${escapeRegExp(name)}\\b`).test(bodySource);\n const inAppendedStub = (name: string): boolean =>\n toAppend.some((handler) => handler.stub.includes(name));\n const needsBareContext = (name: string): boolean =>\n referencedBare(name) || inAppendedStub(name);\n const needsBareZod = (name: string): boolean =>\n referencedBare(name) || requiredSchemas.has(name) || inAppendedStub(name);\n\n // Context types are orval-owned only where a handler references one bare (a\n // typed `async (c: XContext)`) or an appended stub uses it. Match by EXACT\n // orval name — never `endsWith('Context')`, which would clobber a user import\n // such as `getCommunityFilterContext`.\n const contextNames = desired.imports.context.names.filter((name) =>\n needsBareContext(name),\n );\n const zodLower = new Set(\n (desired.imports.zod?.names ?? []).map((name) => name.toLowerCase()),\n );\n\n const factoryModule = desired.imports.factory.module;\n reconcileImport(\n byModule(factoryModule) ?? plainExact(['createFactory']),\n desired.imports.factory.names,\n factoryModule,\n (name) => name === 'createFactory',\n );\n\n reconcileImport(\n byModule(validatorModule) ?? plainExact(['zValidator']),\n desired.imports.validator ? ['zValidator'] : [],\n validatorModule,\n (name) => name === 'zValidator',\n );\n\n reconcileImport(\n byModule(desired.imports.context.module) ?? plainExact(contextNames),\n contextNames,\n desired.imports.context.module,\n (name) => desired.imports.context.names.includes(name),\n needsBareContext,\n );\n\n const zodModule = desired.imports.zod?.module ?? '';\n const zodNames = desired.imports.zod?.names ?? [];\n reconcileImport(\n byModule(zodModule) ?? plainExact(zodNames),\n zodNames,\n zodModule,\n (name) => zodLower.has(name.toLowerCase()),\n needsBareZod,\n schemaRenames,\n );\n\n // Apply the schema migrations file-wide: rename every remaining reference to a\n // migrated schema (validator args, `z.infer<typeof X>` in bodies, helper code).\n // The import is rewritten above (its decl range is skipped here); ranges of\n // removed validators are skipped too (their args are already deleted).\n if (schemaRenames.size > 0) {\n const inSkippedRange = (pos: number): boolean =>\n importDeclarations.some(\n (declaration) =>\n pos >= declaration.getStart(sourceFile) && pos < declaration.getEnd(),\n ) ||\n removedValidatorRanges.some(([start, end]) => pos >= start && pos < end);\n\n const renameReferences = (node: TS.Node): void => {\n if (ts.isIdentifier(node)) {\n const replacement = schemaRenames.get(node.text);\n if (replacement) {\n const parent = node.parent;\n const isMemberName =\n ts.isPropertyAccessExpression(parent) && parent.name === node;\n const isDeclarationName =\n (ts.isVariableDeclaration(parent) && parent.name === node) ||\n (ts.isParameter(parent) && parent.name === node) ||\n (ts.isBindingElement(parent) && parent.name === node) ||\n (ts.isPropertyAssignment(parent) && parent.name === node) ||\n (ts.isPropertySignature(parent) && parent.name === node);\n const start = node.getStart(sourceFile);\n if (!isMemberName && !isDeclarationName && !inSkippedRange(start)) {\n edits.push({ start, end: node.getEnd(), text: replacement });\n }\n }\n }\n ts.forEachChild(node, renameReferences);\n };\n renameReferences(sourceFile);\n }\n\n if (pendingInsertions.length > 0) {\n const lastImport = importDeclarations.at(-1);\n let insertPos = 0;\n if (lastImport) {\n // Guard the EOF case: when the last import has no trailing newline,\n // indexOf returns -1 and `+ 1` would prepend to the top of the file.\n const newline = source.indexOf('\\n', lastImport.getEnd());\n insertPos = newline === -1 ? source.length : newline + 1;\n }\n edits.push({\n start: insertPos,\n end: insertPos,\n text: pendingInsertions.map((line) => `${line}\\n`).join(''),\n });\n }\n\n if (toAppend.length > 0) {\n edits.push({\n start: source.length,\n end: source.length,\n text: toAppend.map((handler) => handler.stub).join(''),\n });\n }\n\n return applyEdits(source, edits);\n};\n\nconst reconcileValidators = (\n sourceFile: TS.SourceFile,\n source: string,\n call: TS.CallExpression,\n desiredValidators: DesiredValidator[],\n edits: Edit[],\n zValidatorName: string,\n requiredSchemas: Set<string>,\n removedRanges: [number, number][],\n) => {\n const existing: { target: string; arg: TS.CallExpression }[] = [];\n\n for (const arg of call.arguments) {\n if (\n ts.isCallExpression(arg) &&\n ts.isIdentifier(arg.expression) &&\n arg.expression.text === zValidatorName\n ) {\n const target = arg.arguments[0];\n if (\n arg.arguments.length > 0 &&\n ts.isStringLiteralLike(target) &&\n VALIDATOR_TARGETS.has(target.text)\n ) {\n existing.push({ target: target.text, arg });\n }\n }\n }\n\n const desiredByTarget = new Map(\n desiredValidators.map((validator) => [validator.target, validator]),\n );\n const existingByTarget = new Set(existing.map((item) => item.target));\n\n // Remove validators the spec no longer requires. (Schema RENAMES — e.g.\n // camelCase→PascalCase — are handled by the file-wide rename pass driven by the\n // zod-import rewrite, so every reference is migrated, not just the arg here.)\n for (const item of existing) {\n if (!desiredByTarget.has(item.target as ValidatorTarget)) {\n const edit = removeArgumentEdit(sourceFile, source, item.arg);\n edits.push(edit);\n removedRanges.push([edit.start, edit.end]);\n }\n }\n\n const missing = desiredValidators.filter(\n (validator) => !existingByTarget.has(validator.target),\n );\n if (missing.length > 0) {\n const insertPos = validatorInsertPos(sourceFile, source, call);\n const text = missing\n .map((validator) => {\n requiredSchemas.add(validator.schema);\n return ` ${zValidatorName}('${validator.target}', ${validator.schema}),\\n`;\n })\n .join('');\n edits.push({ start: insertPos, end: insertPos, text });\n }\n};\n\n/** Position to insert new validators: the line start of the trailing handler. */\nconst validatorInsertPos = (\n sourceFile: TS.SourceFile,\n source: string,\n call: TS.CallExpression,\n): number => {\n // The handler is the LAST function argument; earlier function args may be\n // inline middleware, so search from the end.\n const handler = call.arguments.findLast(\n (arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg),\n );\n if (handler) {\n // Insert at the handler's line start when it's on its own line; otherwise\n // (single-line `createHandlers(async (c) => {})`) insert right before it so\n // the validator isn't pushed to the start of the statement.\n const start = handler.getStart(sourceFile);\n return startsLine(source, start) ? lineStart(source, start) : start;\n }\n // No trailing handler found — insert just before the closing paren.\n return call.getEnd() - 1;\n};\n\nconst removeArgumentEdit = (\n sourceFile: TS.SourceFile,\n source: string,\n arg: TS.Node,\n): Edit => {\n const argStart = arg.getStart(sourceFile);\n const start = startsLine(source, argStart)\n ? lineStart(source, argStart)\n : argStart;\n\n const commaIdx = source.indexOf(',', arg.getEnd());\n let end = commaIdx === -1 ? arg.getEnd() : commaIdx + 1;\n while (source[end] === ' ' || source[end] === '\\t') end += 1;\n if (source.slice(end, end + 2) === '\\r\\n') end += 2;\n else if (source[end] === '\\n') end += 1;\n\n return { start, end, text: '' };\n};\n\nconst applyEdits = (source: string, edits: Edit[]): string => {\n let result = source;\n for (const edit of edits.toSorted((a, b) => b.start - a.start)) {\n result = result.slice(0, edit.start) + edit.text + result.slice(edit.end);\n }\n return result;\n};\n\n/**\n * Extracts the inner body of each handler's `async (c) => { ... }` block, keyed\n * by handler name. Used by the `full` strategy to splice user bodies back into a\n * freshly-regenerated wrapper. Returns `undefined` when the source can't be\n * parsed (or typescript is unavailable) — distinct from an empty map (parsed, no\n * handlers) — so callers can preserve the file instead of dropping its bodies.\n */\nexport const extractHandlerBodies = async (\n source: string,\n): Promise<Map<string, string> | undefined> => {\n if (!(await ensureTypeScript())) return undefined;\n\n const sourceFile = parse(source);\n if (!sourceFile) return undefined;\n\n const bodies = new Map<string, string>();\n for (const { name, call } of findHandlers(sourceFile)) {\n // The handler is the LAST function argument (earlier ones may be inline\n // middleware), so its body — not a middleware's — is what `full` splices.\n const handler = call.arguments.findLast(\n (arg) => ts.isArrowFunction(arg) || ts.isFunctionExpression(arg),\n );\n if (handler?.body && ts.isBlock(handler.body)) {\n const bodyStart = handler.body.getStart(sourceFile) + 1;\n const bodyEnd = handler.body.getEnd() - 1;\n bodies.set(name, source.slice(bodyStart, bodyEnd));\n }\n }\n\n return bodies;\n};\n","import { sanitize } from '@orval/core';\n\nconst hasParam = (path: string): boolean => /[^{]*{[\\w*_-]*}.*/.test(path);\n\nconst getRoutePath = (path: string): string => {\n const matches = /([^{]*){?([\\w*_-]*)}?(.*)/.exec(path);\n if (!matches?.length) return path; // impossible due to regexp grouping here, but for TS\n\n const prev = matches[1];\n const param = sanitize(matches[2], {\n es5keyword: true,\n underscore: true,\n dash: true,\n dot: true,\n });\n const next = hasParam(matches[3]) ? getRoutePath(matches[3]) : matches[3];\n\n return hasParam(path) ? `${prev}:${param}${next}` : `${prev}${param}${next}`;\n};\n\nexport const getRoute = (route: string) => {\n const splittedRoute = route.split('/');\n\n let acc = '';\n for (const [i, path] of splittedRoute.entries()) {\n if (!path && i === 0) continue;\n\n acc += path.includes('{') ? `/${getRoutePath(path)}` : `/${path}`;\n }\n\n return acc;\n};\n","import nodePath from 'node:path';\n\nimport {\n camel,\n type ClientBuilder,\n type ClientExtraFilesBuilder,\n type ClientFooterBuilder,\n type ClientGeneratorsBuilder,\n type ClientHeaderBuilder,\n type ContextSpec,\n generateMutatorImports,\n type GeneratorDependency,\n type GeneratorImport,\n type GeneratorVerbOptions,\n getFileInfo,\n getOrvalGeneratedTypes,\n getParamsInPath,\n type HonoHandlerStrategy,\n isObject,\n jsDoc,\n kebab,\n logWarning,\n type NormalizedMutator,\n type NormalizedOutputOptions,\n type OpenApiInfoObject,\n pascal,\n sanitize,\n upath,\n} from '@orval/core';\nimport { generateZod } from '@orval/zod';\nimport fs from 'fs-extra';\n\nimport {\n type DesiredImports,\n type DesiredValidator,\n ensureTypeScript,\n extractHandlerBodies,\n reconcileHandlerFile,\n} from './handler-merge';\n\n// Warn at most once per run when the optional `typescript` peer is missing and a\n// non-`skip` strategy was requested, so the degraded behavior is never silent.\nlet warnedMissingTypeScript = false;\nimport { getRoute } from './route';\n\nconst ZVALIDATOR_SOURCE = fs\n .readFileSync(nodePath.join(import.meta.dirname, 'zValidator.ts'))\n .toString('utf8');\n\nconst HONO_DEPENDENCIES: GeneratorDependency[] = [\n {\n exports: [\n {\n name: 'Hono',\n values: true,\n },\n {\n name: 'Context',\n },\n {\n name: 'Env',\n },\n ],\n dependency: 'hono',\n },\n];\n\n/**\n * generateModuleSpecifier generates the specifier that _from_ would use to\n * import _to_. This is syntactical and does not validate the paths.\n *\n * @param from The filesystem path to the importer.\n * @param to If a filesystem path, it and _from_ must be use the same frame of\n * reference, such as process.cwd() or both be absolute. If only one is\n * absolute, the other must be relative to process.cwd().\n *\n * Otherwise, treated as a package name and returned directly.\n *\n * @return A module specifier that can be used at _from_ to import _to_. It is\n * extensionless to conform with the rest of orval.\n */\nconst generateModuleSpecifier = (from: string, to: string) => {\n if (to.startsWith('.') || nodePath.isAbsolute(to)) {\n return upath\n .getRelativeImportPath(nodePath.resolve(from), nodePath.resolve(to), true)\n .replace(/\\.ts$/, '');\n }\n\n // Not a relative or absolute file path. Import as-is.\n return to;\n};\n\nexport const getHonoDependencies = () => HONO_DEPENDENCIES;\n\nexport const getHonoHeader: ClientHeaderBuilder = ({\n verbOptions,\n output,\n tag,\n clientImplementation,\n}) => {\n const targetInfo = getFileInfo(output.target);\n\n let handlers: string;\n\n const importHandlers = Object.values(verbOptions).filter((verbOption) =>\n clientImplementation.includes(`${verbOption.operationName}Handlers`),\n );\n\n if (output.override.hono.handlers) {\n const handlerFileInfo = getFileInfo(output.override.hono.handlers);\n handlers = importHandlers\n .map((verbOption) => {\n // Only `tags-split` puts each tag's client file inside its own\n // sub-directory. `tags` mode flattens them next to `target`, so the\n // import must be resolved from `targetInfo.dirname` directly.\n const isSplitDir = output.mode === 'tags-split';\n const tag = kebab(verbOption.tags[0] ?? 'default');\n\n const handlersPath = upath.relativeSafe(\n nodePath.join(targetInfo.dirname, isSplitDir ? tag : ''),\n nodePath.join(\n handlerFileInfo.dirname,\n `./${verbOption.operationName}`,\n ),\n );\n\n return `import { ${verbOption.operationName}Handlers } from '${handlersPath}';`;\n })\n .join('\\n');\n } else {\n const importHandlerNames = importHandlers\n .map((verbOption) => ` ${verbOption.operationName}Handlers`)\n .join(`, \\n`);\n\n handlers = `import {\\n${importHandlerNames}\\n} from './${tag ?? targetInfo.filename}.handlers';`;\n }\n\n return `${handlers}\\n\\nconst app = new Hono()\\n`;\n};\n\nexport const getHonoFooter: ClientFooterBuilder = () =>\n ';\\n\\nexport default app;\\n';\n\nconst generateHonoRoute = (\n { operationName, verb }: GeneratorVerbOptions,\n pathRoute: string,\n) => {\n const path = getRoute(pathRoute);\n\n return `\\n .${verb.toLowerCase()}('${path}', ...${operationName}Handlers)`;\n};\n\nexport const generateHono: ClientBuilder = (verbOptions, options) => {\n if (options.override.hono.compositeRoute) {\n return {\n implementation: '',\n imports: [],\n };\n }\n\n const routeImplementation = generateHonoRoute(verbOptions, options.pathRoute);\n\n return {\n implementation: `${routeImplementation}\\n`,\n imports: [\n ...verbOptions.params.flatMap((param) => param.imports),\n ...verbOptions.body.imports,\n ...(verbOptions.queryParams\n ? [\n {\n name: verbOptions.queryParams.schema.name,\n },\n ]\n : []),\n ],\n };\n};\n\n/**\n * getHonoHandlers generates TypeScript code for the given verbs and reports\n * whether the code requires zValidator.\n */\nconst DEFAULT_HANDLER_BODY = '\\n\\n ';\n\nconst FORM_CONTENT_TYPES = new Set([\n 'multipart/form-data',\n 'application/x-www-form-urlencoded',\n]);\n\n/**\n * Whether a request body uses a form encoding. Hono validates these with\n * `zValidator('form', …)` against `c.req.parseBody()`, not `'json'`.\n */\nconst isFormBody = (body: GeneratorVerbOptions['body']): boolean =>\n FORM_CONTENT_TYPES.has(body.contentType);\n\n/**\n * getDesiredValidators returns the `zValidator` targets (and their PascalCase zod\n * schema identifiers) required by a verb, in canonical order. This is the single\n * source of truth shared by fresh generation and the `smart` reconcile.\n */\nconst getDesiredValidators = (\n verbOption: GeneratorVerbOptions,\n validator: boolean | 'hono' | NormalizedMutator,\n): DesiredValidator[] => {\n if (!validator) return [];\n\n const pascalOperationName = pascal(verbOption.operationName);\n const validators: DesiredValidator[] = [];\n\n if (verbOption.headers) {\n validators.push({\n target: 'header',\n schema: `${pascalOperationName}Header`,\n });\n }\n if (verbOption.params.length > 0) {\n validators.push({\n target: 'param',\n schema: `${pascalOperationName}Params`,\n });\n }\n if (verbOption.queryParams) {\n validators.push({\n target: 'query',\n schema: `${pascalOperationName}QueryParams`,\n });\n }\n if (verbOption.body.definition) {\n validators.push({\n target: isFormBody(verbOption.body) ? 'form' : 'json',\n schema: `${pascalOperationName}Body`,\n });\n }\n if (\n validator !== 'hono' &&\n verbOption.response.originalSchema?.['200']?.content?.[\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n 'application/json'\n ]\n ) {\n validators.push({\n target: 'response',\n schema: `${pascalOperationName}Response`,\n });\n }\n\n return validators;\n};\n\nconst getHonoHandlers = (\n ...opts: {\n handlerName: string;\n contextTypeName: string;\n verbOption: GeneratorVerbOptions;\n validator: boolean | 'hono' | NormalizedMutator;\n /**\n * Optional async-handler body to splice into the generated wrapper. Used by\n * the `full` strategy to preserve user logic across regeneration.\n */\n bodyOverride?: string;\n }[]\n): [\n /** The combined TypeScript handler code snippets. */\n handlerCode: string,\n /** Whether any of the handler code snippets requires importing zValidator. */\n hasZValidator: boolean,\n] => {\n let code = '';\n let hasZValidator = false;\n\n for (const {\n handlerName,\n contextTypeName,\n verbOption,\n validator,\n bodyOverride,\n } of opts) {\n const currentValidator = getDesiredValidators(verbOption, validator)\n .map((v) => `zValidator('${v.target}', ${v.schema}),\\n`)\n .join('');\n\n const body = bodyOverride ?? DEFAULT_HANDLER_BODY;\n\n code += `\nexport const ${handlerName} = factory.createHandlers(\n${currentValidator}async (c: ${contextTypeName}) => {${body}},\n);`;\n\n hasZValidator ||= currentValidator !== '';\n }\n\n return [code, hasZValidator];\n};\n\nconst getZvalidatorImports = (\n verbOptions: GeneratorVerbOptions[],\n importPath: string,\n isHonoValidator: boolean,\n) => {\n const specifiers = [];\n\n for (const {\n operationName,\n headers,\n params,\n queryParams,\n body,\n response,\n } of verbOptions) {\n const pascalOperationName = pascal(operationName);\n\n if (headers) {\n specifiers.push(`${pascalOperationName}Header`);\n }\n\n if (params.length > 0) {\n specifiers.push(`${pascalOperationName}Params`);\n }\n\n if (queryParams) {\n specifiers.push(`${pascalOperationName}QueryParams`);\n }\n\n if (body.definition) {\n specifiers.push(`${pascalOperationName}Body`);\n }\n\n if (\n !isHonoValidator &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n response.originalSchema?.['200']?.content?.['application/json'] !=\n undefined\n ) {\n specifiers.push(`${pascalOperationName}Response`);\n }\n }\n\n return specifiers.length === 0\n ? ''\n : `import {\\n${specifiers.join(',\\n')}\\n} from '${importPath}'`;\n};\n\nconst getVerbOptionGroupByTag = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n) => {\n const grouped: Record<string, GeneratorVerbOptions[]> = {};\n\n for (const value of Object.values(verbOptions)) {\n const tag = value.tags[0];\n // this is not always false\n // TODO look into types\n // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n if (!grouped[tag]) {\n grouped[tag] = [];\n }\n grouped[tag].push(value);\n }\n\n return grouped;\n};\n\n/** Computes the orval-owned imports a handler file should contain. */\nconst buildDesiredImports = ({\n verbList,\n path,\n validatorModule,\n zodModule,\n contextModule,\n validator,\n}: {\n verbList: GeneratorVerbOptions[];\n path: string;\n validatorModule?: string;\n zodModule: string;\n contextModule: string;\n validator: boolean | 'hono';\n}): DesiredImports => {\n const contextNames = verbList.map(\n (verb) => `${pascal(verb.operationName)}Context`,\n );\n const zodNames = verbList.flatMap((verb) =>\n getDesiredValidators(verb, validator).map((v) => v.schema),\n );\n const hasValidators = zodNames.length > 0;\n\n return {\n factory: { names: ['createFactory'], module: 'hono/factory' },\n validator:\n hasValidators && validatorModule != undefined\n ? {\n names: ['zValidator'],\n module: generateModuleSpecifier(path, validatorModule),\n }\n : undefined,\n context: {\n names: contextNames,\n module: generateModuleSpecifier(path, contextModule),\n },\n zod: hasValidators\n ? { names: zodNames, module: generateModuleSpecifier(path, zodModule) }\n : undefined,\n };\n};\n\n/** Generates a complete handler file from scratch (no existing file to merge). */\nconst generateFreshHandlerFile = ({\n verbList,\n path,\n header,\n validatorModule,\n zodModule,\n contextModule,\n validator,\n bodyFor,\n}: {\n verbList: GeneratorVerbOptions[];\n path: string;\n header: string;\n validatorModule?: string;\n zodModule: string;\n contextModule: string;\n validator: boolean | 'hono';\n bodyFor?: (operationName: string) => string | undefined;\n}): string => {\n const [handlerCode, hasZValidator] = getHonoHandlers(\n ...verbList.map((verbOption) => ({\n handlerName: `${verbOption.operationName}Handlers`,\n contextTypeName: `${pascal(verbOption.operationName)}Context`,\n verbOption,\n validator,\n bodyOverride: bodyFor?.(verbOption.operationName),\n })),\n );\n\n const imports = [\"import { createFactory } from 'hono/factory';\"];\n\n if (hasZValidator && validatorModule != undefined) {\n imports.push(\n `import { zValidator } from '${generateModuleSpecifier(path, validatorModule)}';`,\n );\n }\n\n imports.push(\n `import { ${verbList\n .map((verb) => `${pascal(verb.operationName)}Context`)\n .join(',\\n')} } from '${generateModuleSpecifier(path, contextModule)}';`,\n );\n\n if (hasZValidator) {\n imports.push(\n getZvalidatorImports(\n verbList,\n generateModuleSpecifier(path, zodModule),\n validatorModule === '@hono/zod-validator',\n ),\n );\n }\n\n return `${header}${imports.filter((imp) => imp !== '').join('\\n')}\\n\\nconst factory = createFactory();${handlerCode}`;\n};\n\n/**\n * Generates or updates a handler file according to `strategy`:\n *\n * - a non-existent file is always freshly generated;\n * - `skip` leaves an existing file byte-for-byte unchanged;\n * - `full` rebuilds the preamble + validator chain and splices back user bodies\n * (drops custom imports/middleware/helpers — the thin-handler model);\n * - `smart` non-destructively reconciles orval-owned imports + validators and\n * appends handlers for new operations, preserving all user-authored code.\n */\nexport const generateHandlerFile = async ({\n verbs,\n path,\n header,\n validatorModule,\n zodModule,\n contextModule,\n strategy,\n}: {\n verbs: GeneratorVerbOptions[];\n path: string;\n header: string;\n validatorModule?: string;\n zodModule: string;\n contextModule: string;\n strategy: HonoHandlerStrategy;\n}) => {\n const validator =\n validatorModule === '@hono/zod-validator'\n ? ('hono' as const)\n : validatorModule != undefined;\n\n const verbList = Object.values(verbs);\n\n if (!fs.existsSync(path)) {\n return generateFreshHandlerFile({\n verbList,\n path,\n header,\n validatorModule,\n zodModule,\n contextModule,\n validator,\n });\n }\n\n const source = await fs.readFile(path, 'utf8');\n\n if (strategy === 'skip') {\n return source;\n }\n\n // `smart` and `full` parse the existing file with the TypeScript compiler API.\n // typescript is an optional peer dependency; without it we cannot safely\n // reconcile or splice, so we preserve the existing file untouched and warn.\n if (!(await ensureTypeScript())) {\n if (!warnedMissingTypeScript) {\n warnedMissingTypeScript = true;\n logWarning(\n `hono handlerGenerationStrategy '${strategy}' requires the optional peer dependency \"typescript\", which is not installed. Existing handler files are left unchanged (as with 'skip'). Install typescript to enable handler reconciliation.`,\n );\n }\n return source;\n }\n\n if (strategy === 'full') {\n const bodies = await extractHandlerBodies(source);\n // A parse failure yields `undefined` (not an empty map): preserve the file\n // rather than regenerate with empty bodies and drop the user's logic.\n if (!bodies) {\n return source;\n }\n return generateFreshHandlerFile({\n verbList,\n path,\n header,\n validatorModule,\n zodModule,\n contextModule,\n validator,\n bodyFor: (operationName) => bodies.get(`${operationName}Handlers`),\n });\n }\n\n return reconcileHandlerFile(source, {\n imports: buildDesiredImports({\n verbList,\n path,\n validatorModule,\n zodModule,\n contextModule,\n validator,\n }),\n handlers: verbList.map((verbOption) => ({\n handlerName: `${verbOption.operationName}Handlers`,\n validators: getDesiredValidators(verbOption, validator),\n stub: getHonoHandlers({\n handlerName: `${verbOption.operationName}Handlers`,\n contextTypeName: `${pascal(verbOption.operationName)}Context`,\n verbOption,\n validator,\n })[0],\n })),\n });\n};\n\nconst generateHandlerFiles = async (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n validatorModule: string,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n const { extension, dirname, filename } = getFileInfo(output.target);\n const strategy = output.override.hono.handlerGenerationStrategy;\n\n // This function _does not control_ where the .zod and .context modules land.\n // That determination is made elsewhere and this function must implement the\n // same conventions.\n\n if (output.override.hono.handlers) {\n // One file per operation in the user-provided directory.\n return Promise.all(\n Object.values(verbOptions).map(async (verbOption) => {\n const tag = kebab(verbOption.tags[0] ?? 'default');\n\n const path = nodePath.join(\n output.override.hono.handlers ?? '',\n `./${verbOption.operationName}` + extension,\n );\n\n // Mirror the layout used by generateZodFiles/generateContextFiles so\n // imports resolve to the actual emitted modules.\n let zodModule: string;\n let contextModule: string;\n if (output.mode === 'tags') {\n zodModule = nodePath.join(dirname, `${kebab(tag)}.zod`);\n contextModule = nodePath.join(dirname, `${kebab(tag)}.context`);\n } else if (output.mode === 'tags-split') {\n zodModule = nodePath.join(dirname, tag, tag + '.zod');\n contextModule = nodePath.join(dirname, tag, tag + '.context');\n } else {\n zodModule = nodePath.join(dirname, `${filename}.zod`);\n contextModule = nodePath.join(dirname, `${filename}.context`);\n }\n\n return {\n content: await generateHandlerFile({\n path,\n header,\n verbs: [verbOption],\n validatorModule,\n zodModule,\n contextModule,\n strategy,\n }),\n path,\n };\n }),\n );\n }\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n // One file per operation _tag_ under dirname.\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n return Promise.all(\n Object.entries(groupByTags).map(async ([tag, verbs]) => {\n const handlerPath =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.handlers${extension}`)\n : nodePath.join(dirname, tag, tag + '.handlers' + extension);\n\n return {\n content: await generateHandlerFile({\n path: handlerPath,\n header,\n verbs,\n validatorModule,\n zodModule:\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.zod`)\n : nodePath.join(dirname, tag, tag + '.zod'),\n contextModule:\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.context`)\n : nodePath.join(dirname, tag, tag + '.context'),\n strategy,\n }),\n path: handlerPath,\n };\n }),\n );\n }\n\n // One file with all operations.\n const handlerPath = nodePath.join(\n dirname,\n `${filename}.handlers${extension}`,\n );\n\n return [\n {\n content: await generateHandlerFile({\n path: handlerPath,\n header,\n verbs: Object.values(verbOptions),\n validatorModule,\n zodModule: nodePath.join(dirname, `${filename}.zod`),\n contextModule: nodePath.join(dirname, `${filename}.context`),\n strategy,\n }),\n path: handlerPath,\n },\n ];\n};\n\nconst getContext = (verbOption: GeneratorVerbOptions) => {\n let paramType = '';\n if (verbOption.params.length > 0) {\n const params = getParamsInPath(verbOption.pathRoute).map((name) => {\n const param = verbOption.params.find(\n (p) => p.name === sanitize(camel(name), { es5keyword: true }),\n );\n const definition = param?.definition.split(':')[1];\n const required = param?.required ?? false;\n return {\n definition: `${name}${required ? '' : '?'}:${definition}`,\n };\n });\n paramType = `param: {\\n ${params\n .map((property) => property.definition)\n .join(',\\n ')},\\n },`;\n }\n\n const queryType = verbOption.queryParams\n ? `query: ${verbOption.queryParams.schema.name},`\n : '';\n const bodyType = verbOption.body.definition\n ? `${isFormBody(verbOption.body) ? 'form' : 'json'}: ${verbOption.body.definition},`\n : '';\n const hasIn = !!paramType || !!queryType || !!bodyType;\n\n return `export type ${pascal(\n verbOption.operationName,\n )}Context<E extends Env = any> = Context<E, '${getRoute(\n verbOption.pathRoute,\n )}'${\n hasIn\n ? `, { in: { ${paramType}${queryType}${bodyType} }, out: { ${paramType}${queryType}${bodyType} } }`\n : ''\n }>`;\n};\n\nconst getHeader = (\n option: false | ((info: OpenApiInfoObject) => string | string[]),\n info: OpenApiInfoObject,\n): string => {\n if (!option) {\n return '';\n }\n\n const header = option(info);\n\n return Array.isArray(header) ? jsDoc({ description: header }) : header;\n};\n\nconst getSpecInfo = (context: ContextSpec): OpenApiInfoObject =>\n context.spec.info ?? {\n title: 'API',\n version: '1.0.0',\n };\n\nconst generateContextFile = ({\n path,\n verbs,\n schemaModule,\n}: {\n path: string;\n verbs: GeneratorVerbOptions[];\n schemaModule: string;\n}) => {\n let content = `import type { Context, Env } from 'hono';\\n\\n`;\n\n const contexts = verbs.map((verb) => getContext(verb));\n\n const imps = new Set(\n verbs\n .flatMap((verb) => {\n const imports: GeneratorImport[] = [];\n if (verb.params.length > 0) {\n imports.push(...verb.params.flatMap((param) => param.imports));\n }\n\n if (verb.queryParams) {\n imports.push({\n name: verb.queryParams.schema.name,\n });\n }\n\n if (verb.body.definition) {\n imports.push(...verb.body.imports);\n }\n\n return imports;\n })\n .map((imp) => imp.name)\n .filter((imp) => contexts.some((context) => context.includes(imp))),\n );\n\n if (contexts.some((context) => context.includes('NonReadonly<'))) {\n content += getOrvalGeneratedTypes();\n content += '\\n';\n }\n\n if (imps.size > 0) {\n content += `import type {\\n${[...imps]\n .toSorted()\n .join(\n ',\\n ',\n )}\\n} from '${generateModuleSpecifier(path, schemaModule)}';\\n\\n`;\n }\n\n content += contexts.join('\\n');\n\n return content;\n};\n\nconst generateContextFiles = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n schemaModule: string,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n return Object.entries(groupByTags).map(([tag, verbs]) => {\n const path =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.context${extension}`)\n : nodePath.join(dirname, tag, tag + '.context' + extension);\n const code = generateContextFile({\n verbs,\n path,\n schemaModule: schemaModule,\n });\n return { content: `${header}${code}`, path };\n });\n }\n\n const path = nodePath.join(dirname, `${filename}.context${extension}`);\n const code = generateContextFile({\n verbs: Object.values(verbOptions),\n path,\n schemaModule: schemaModule,\n });\n\n return [\n {\n content: `${header}${code}`,\n path,\n },\n ];\n};\n\nconst generateZodFiles = async (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n if (output.mode === 'tags' || output.mode === 'tags-split') {\n const groupByTags = getVerbOptionGroupByTag(verbOptions);\n\n const builderContexts = await Promise.all(\n Object.entries(groupByTags).map(async ([tag, verbs]) => {\n const zods = await Promise.all(\n verbs.map(async (verbOption) =>\n generateZod(\n verbOption,\n {\n route: verbOption.route,\n pathRoute: verbOption.pathRoute,\n override: output.override,\n context,\n output: output.target,\n },\n output.client,\n ),\n ),\n );\n\n if (zods.every((z) => z.implementation === '')) {\n return {\n content: '',\n path: '',\n };\n }\n\n const allMutators = new Map(\n zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m]),\n )\n .values()\n .toArray();\n\n const mutatorsImports = generateMutatorImports({\n mutators: allMutators,\n oneMore: output.mode === 'tags-split',\n });\n\n let content = `${header}import { z as zod } from 'zod';\\n${mutatorsImports}\\n`;\n\n const zodPath =\n output.mode === 'tags'\n ? nodePath.join(dirname, `${kebab(tag)}.zod${extension}`)\n : nodePath.join(dirname, tag, tag + '.zod' + extension);\n\n content += zods.map((zod) => zod.implementation).join('\\n');\n\n return {\n content,\n path: zodPath,\n };\n }),\n );\n\n return builderContexts.filter((context) => context.content !== '');\n }\n\n const zods = await Promise.all(\n Object.values(verbOptions).map(async (verbOption) =>\n generateZod(\n verbOption,\n {\n route: verbOption.route,\n pathRoute: verbOption.pathRoute,\n override: output.override,\n context,\n output: output.target,\n },\n output.client,\n ),\n ),\n );\n\n const allMutators = new Map(\n zods.flatMap((z) => z.mutators ?? []).map((m) => [m.name, m]),\n )\n .values()\n .toArray();\n\n const mutatorsImports = generateMutatorImports({\n mutators: allMutators,\n });\n\n let content = `${header}import { z as zod } from 'zod';\\n${mutatorsImports}\\n`;\n\n const zodPath = nodePath.join(dirname, `${filename}.zod${extension}`);\n\n content += zods.map((zod) => zod.implementation).join('\\n');\n\n return [\n {\n content,\n path: zodPath,\n },\n ];\n};\n\nconst generateZvalidator = (\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n let validatorPath = output.override.hono.validatorOutputPath;\n if (!output.override.hono.validatorOutputPath) {\n const { extension, dirname, filename } = getFileInfo(output.target);\n\n validatorPath = nodePath.join(dirname, `${filename}.validator${extension}`);\n }\n\n return {\n content: `${header}${ZVALIDATOR_SOURCE}`,\n path: validatorPath,\n };\n};\n\nconst generateCompositeRoutes = (\n verbOptions: Record<string, GeneratorVerbOptions>,\n output: NormalizedOutputOptions,\n context: ContextSpec,\n) => {\n const targetInfo = getFileInfo(output.target);\n const compositeRouteInfo = getFileInfo(output.override.hono.compositeRoute);\n\n const header = getHeader(output.override.header, getSpecInfo(context));\n\n const routes = Object.values(verbOptions)\n .map((verbOption) => {\n return generateHonoRoute(verbOption, verbOption.pathRoute);\n })\n .join('');\n\n const importHandlers = Object.values(verbOptions);\n\n let ImportHandlersImplementation: string;\n if (output.override.hono.handlers) {\n const handlerFileInfo = getFileInfo(output.override.hono.handlers);\n const operationNames = importHandlers.map(\n (verbOption) => verbOption.operationName,\n );\n\n ImportHandlersImplementation = operationNames\n .map((operationName) => {\n const importHandlerName = `${operationName}Handlers`;\n\n const handlersPath = generateModuleSpecifier(\n compositeRouteInfo.path,\n nodePath.join(handlerFileInfo.dirname, `./${operationName}`),\n );\n\n return `import { ${importHandlerName} } from '${handlersPath}';`;\n })\n .join('\\n');\n } else {\n const tags = importHandlers.map((verbOption) =>\n kebab(verbOption.tags[0] ?? 'default'),\n );\n const uniqueTags = tags.filter((t, i) => tags.indexOf(t) === i);\n\n ImportHandlersImplementation = uniqueTags\n .map((tag) => {\n const importHandlerNames = importHandlers\n .filter((verbOption) => verbOption.tags[0] === tag)\n .map((verbOption) => ` ${verbOption.operationName}Handlers`)\n .join(`, \\n`);\n\n const handlersPath = generateModuleSpecifier(\n compositeRouteInfo.path,\n nodePath.join(targetInfo.dirname, tag),\n );\n\n return `import {\\n${importHandlerNames}\\n} from '${handlersPath}/${tag}.handlers';`;\n })\n .join('\\n');\n }\n\n const honoImport = `import { Hono } from 'hono';`;\n const honoInitialization = `\\nconst app = new Hono()`;\n const honoAppExport = `\\nexport default app;`;\n\n const content = `${header}${honoImport}\n${ImportHandlersImplementation}\n${honoInitialization}${routes};\n${honoAppExport}\n`;\n\n return [\n {\n content,\n path: output.override.hono.compositeRoute || '',\n },\n ];\n};\n\nexport const generateExtraFiles: ClientExtraFilesBuilder = async (\n verbOptions,\n output,\n context,\n) => {\n const { path, pathWithoutExtension } = getFileInfo(output.target);\n const validator = generateZvalidator(output, context);\n let schemaModule: string;\n\n if (output.schemas != undefined) {\n const schemasPath = (\n isObject(output.schemas) ? output.schemas.path : output.schemas\n ) as string;\n const basePath = getFileInfo(schemasPath).dirname;\n schemaModule = basePath;\n } else if (output.mode === 'single') {\n schemaModule = path;\n } else {\n schemaModule = `${pathWithoutExtension}.schemas`;\n }\n\n const contexts = generateContextFiles(\n verbOptions,\n output,\n context,\n schemaModule,\n );\n const compositeRoutes = output.override.hono.compositeRoute\n ? generateCompositeRoutes(verbOptions, output, context)\n : [];\n const [handlers, zods] = await Promise.all([\n generateHandlerFiles(verbOptions, output, context, validator.path),\n generateZodFiles(verbOptions, output, context),\n ]);\n\n return [\n ...handlers,\n ...contexts,\n ...zods,\n ...(output.override.hono.validator &&\n output.override.hono.validator !== 'hono'\n ? [validator]\n : []),\n ...compositeRoutes,\n ];\n};\n\nconst honoClientBuilder: ClientGeneratorsBuilder = {\n client: generateHono,\n dependencies: getHonoDependencies,\n header: getHonoHeader,\n footer: getHonoFooter,\n extraFiles: generateExtraFiles,\n};\n\nexport const builder = () => () => honoClientBuilder;\n\nexport default builder;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuBA,IAAI;AACJ,IAAI;AAEJ,MAAa,mBAAmB,YAA8B;AAC5D,KAAI,wBAAwB,KAAA,EAC1B,KAAI;EACF,MAAM,MAAM,MAAM,OAAO;AACzB,OAAM,IAA2C,WAAW;AAC5D,wBAAsB;SAChB;AACN,wBAAsB;;AAG1B,QAAO;;AA2CT,MAAM,oBAAoB,IAAI,IAAY;CACxC;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AAQF,MAAM,SAAS,WAA8C;CAC3D,MAAM,aAAa,GAAG,iBACpB,cACA,QACA,GAAG,aAAa,QACK,MACrB,GAAG,WAAW,GACf;CACD,MAAM,cACJ,WACA;AACF,KAAI,eAAe,YAAY,SAAS,EAAG,QAAO,KAAA;AAClD,QAAO;;AAQT,MAAM,gBAAgB,eAA+C;CACnE,MAAM,WAA4B,EAAE;AACpC,MAAK,MAAM,aAAa,WAAW,YAAY;AAC7C,MAAI,CAAC,GAAG,oBAAoB,UAAU,CAAE;AACxC,OAAK,MAAM,eAAe,UAAU,gBAAgB,cAAc;AAChE,OAAI,CAAC,GAAG,aAAa,YAAY,K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AAO,SAAS,KAAK,aACzB,OAAO,SAAS,KAAK,cAAc,SAC/B,CAAC,UAAU,GACX,EAAE;EACN,GAAG;EACJ;;AAGH,MAAM,oBAA6C;CACjD,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,QAAQ;CACR,YAAY;CACb;AAED,MAAa,sBAAsB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@orval/hono",
3
- "version": "8.14.0",
3
+ "version": "8.15.0",
4
4
  "license": "MIT",
5
5
  "repository": {
6
6
  "type": "git",
@@ -35,11 +35,19 @@
35
35
  "nuke": "rimraf .turbo dist node_modules"
36
36
  },
37
37
  "dependencies": {
38
- "@orval/core": "8.14.0",
39
- "@orval/zod": "8.14.0",
38
+ "@orval/core": "8.15.0",
39
+ "@orval/zod": "8.15.0",
40
40
  "fs-extra": "^11.3.2",
41
41
  "remeda": "^2.33.6"
42
42
  },
43
+ "peerDependencies": {
44
+ "typescript": ">=5"
45
+ },
46
+ "peerDependenciesMeta": {
47
+ "typescript": {
48
+ "optional": true
49
+ }
50
+ },
43
51
  "devDependencies": {
44
52
  "@hono/zod-validator": "0.7.6",
45
53
  "@types/fs-extra": "^11.0.4",