@counterfact/generator 0.1.6 → 1.1.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/CHANGELOG.md CHANGED
@@ -1,5 +1,56 @@
1
1
  # @counterfact/generator
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a724401: Generate a central `types/index.ts` exporting `Routes`, `Components`, and `Schemas` (an alias of `Components["schemas"]`). Include unused components, preserve lowercase OpenAPI categories, and use indexed `Routes` contracts in new route handlers while preserving existing route edits and deep imports.
8
+
9
+ Deprecate deep imports of generated operation and component types. Use the central exports throughout the manual, API reference, homepage, walkthrough, and agent guidance.
10
+
11
+ Expose `Context$`, `Scenario`, `Scenario$`, and directory-indexed `Middleware` through the central entry point. New context and scenario starters use central imports; context watching refreshes the helper module and middleware directory map. Dedicated helper imports remain compatible but deprecated.
12
+
13
+ Fix versioned handler narrowing after `minVersion()` checks, including early returns, negated conditions, and explicit else branches. Literal checks narrow both request and response contracts; dynamic union thresholds use a boolean overload to avoid incorrectly excluding possible versions.
14
+
15
+ Organize `Routes` as a tree of slash-prefixed path segments. Select `/hello/world` with `Routes["/hello"]["/world"]`; parent operations and child branches coexist, and generated handlers and documentation use the nested indexes.
16
+
17
+ Write watched helper modules atomically and skip unchanged content so TypeScript readers do not observe empty modules during regeneration.
18
+
19
+ Declare a local `Route` alias once per generated route file and annotate handlers with `Route["GET"]`, `Route["POST"]`, and other method keys. Regeneration reuses matching aliases and avoids existing local names while preserving user code.
20
+
21
+ ### Patch Changes
22
+
23
+ - 40656be: Require Node 22.22 or later for Chokidar 6 compatibility.
24
+ - 93944c6: Updated dependency `chokidar` in `@counterfact/generator` to `6.0.0`.
25
+ Updated dependency `chokidar` in `@counterfact/runtime` to `6.0.0`.
26
+ - Updated dependencies [1f340b6]
27
+ - @counterfact/openapi@0.1.7
28
+
29
+ ## 1.0.0
30
+
31
+ ### Major Changes
32
+
33
+ - 442afd2: Generate operation and parameter types with stable HTTP method names such as
34
+ `HTTP_GET` and `HTTP_GET_Query`, independent of OpenAPI operationId. On CLI
35
+ startup, automatically migrate legacy operationId-based route imports and their
36
+ references while preserving route logic, explicit aliases, comments, and strings.
37
+ References outside route files must be updated manually.
38
+
39
+ ### Minor Changes
40
+
41
+ - b0d11b6: Add `response.status(code)` as a typed alternative to `response[code]`. Allow headers and cookies before status selection, narrowing generated status choices by header names and values while preserving required-header and body validation.
42
+
43
+ Deprecate bracket-based `response[statusCode]` selection in favor of `response.status(statusCode)`. Update documentation and generated route stubs to use the function-based selector; existing bracket-based handlers remain supported.
44
+
45
+ ### Patch Changes
46
+
47
+ - 872e12f: Preserve nullable values, primitive constants, inferred object properties, referenced dictionary values, composition properties and required fields, explicit discriminator mappings, and tuple prefixes in generated TypeScript contracts. Keep unrestricted values typed as unknown and retain Counterfact's streaming and server-oriented binary types.
48
+
49
+ Regenerating contracts can expose existing handler type errors where required properties or literal constraints were previously lost.
50
+
51
+ - Updated dependencies [b0d11b6]
52
+ - @counterfact/types@0.2.0
53
+
3
54
  ## 0.1.6
4
55
 
5
56
  ### Patch Changes
@@ -0,0 +1,14 @@
1
+ import type { OperationTypeCoder } from "./operation-type-coder.js";
2
+ import type { Repository } from "./repository.js";
3
+ import type { Specification } from "./specification.js";
4
+ /** One public entry point per API group, assembled after all versions register. */
5
+ declare class CentralTypes {
6
+ private readonly script;
7
+ private readonly routes;
8
+ private readonly components;
9
+ constructor(repository: Repository);
10
+ addOperation(path: string, method: string, coder: OperationTypeCoder): void;
11
+ addComponents(specification: Specification, version: string): void;
12
+ }
13
+ export declare function centralTypes(repository: Repository): CentralTypes;
14
+ export {};
@@ -0,0 +1,128 @@
1
+ import ts from "typescript";
2
+ import { literalType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
3
+ import { pathJoin } from "./forward-slash-path.js";
4
+ import { routesType } from "./route-type-tree.js";
5
+ import { helperTypeExports } from "./scenario-file-generator.js";
6
+ import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
7
+ import { SchemaTypeCoder } from "./schema-type-coder.js";
8
+ import { ResponseTypeCoder } from "./response-type-coder.js";
9
+ import { TypeCoder } from "./type-coder.js";
10
+ import { Requirement } from "./requirement.js";
11
+ const CATEGORIES = [
12
+ "schemas",
13
+ "parameters",
14
+ "responses",
15
+ "requestBodies",
16
+ "headers",
17
+ "examples",
18
+ "securitySchemes",
19
+ "links",
20
+ "callbacks",
21
+ "pathItems",
22
+ "mediaTypes",
23
+ ];
24
+ /** Non-schema components keep their structure; embedded schemas become data types. */
25
+ class ComponentTypeCoder extends TypeCoder {
26
+ modulePath() {
27
+ return pathJoin("types", this.version, (this.requirement.refUrl ?? this.requirement.url).replace(/^#\//u, "") +
28
+ ".ts");
29
+ }
30
+ writeCode(script) {
31
+ const category = this.requirement.url.split("/").at(-2);
32
+ if (category === "parameters" || category === "headers") {
33
+ const schema = this.requirement.get("schema");
34
+ if (schema)
35
+ return new SchemaTypeCoder(schema, this.version).write(script);
36
+ const content = this.requirement.get("content");
37
+ return content ? this.structure(content, script) : unknownType();
38
+ }
39
+ return this.structure(this.requirement, script, !["examples", "securitySchemes", "links"].includes(category ?? ""));
40
+ }
41
+ structure(requirement, script, schemas = true) {
42
+ if (!schemas)
43
+ return literalStructure(requirement.data);
44
+ if (requirement.isReference) {
45
+ return typeReference(script.importType(new ComponentTypeCoder(requirement, this.version)));
46
+ }
47
+ const { data } = requirement;
48
+ if (Array.isArray(data)) {
49
+ return ts.factory.createTupleTypeNode(data.map((_, index) => this.structure(requirement.get(index), script, schemas)));
50
+ }
51
+ if (data !== null && typeof data === "object") {
52
+ return typeLiteral(requirement.map((value, key) => typeProperty(key, schemas && (key === "schema" || key === "itemSchema")
53
+ ? new SchemaTypeCoder(value, this.version).write(script)
54
+ : this.structure(value, script, key !== "example" && key !== "value"))));
55
+ }
56
+ return literalType(data);
57
+ }
58
+ }
59
+ /** One public entry point per API group, assembled after all versions register. */
60
+ class CentralTypes {
61
+ script;
62
+ routes = new Map();
63
+ components = new Map();
64
+ constructor(repository) {
65
+ this.script = repository.get("types/index.ts");
66
+ this.script.comments.push(...READ_ONLY_COMMENTS);
67
+ this.script.reservedNames = new Set([
68
+ "Routes",
69
+ "Components",
70
+ "Schemas",
71
+ "Context$",
72
+ "Scenario",
73
+ "Scenario$",
74
+ "Middleware",
75
+ ]);
76
+ this.script.statementBuilders.set("api-types", () => [
77
+ helperTypeExports(),
78
+ typeAlias("Routes", routesType(this.routes)),
79
+ typeAlias("Components", typeLiteral(CATEGORIES.map((category) => typeProperty(category, typeLiteral([...(this.components.get(category) ?? [])].map(([name, versions]) => typeProperty(name, unionType([...versions.values()])))))))),
80
+ typeAlias("Schemas", ts.factory.createIndexedAccessTypeNode(typeReference("Components"), literalType("schemas"))),
81
+ ]);
82
+ }
83
+ addOperation(path, method, coder) {
84
+ const methods = this.routes.get(path) ?? new Map();
85
+ this.routes.set(path, methods);
86
+ methods.set(method.toUpperCase(), typeReference(this.script.importType(coder, `Route${this.routes.size}_${method.toUpperCase()}`)));
87
+ }
88
+ addComponents(specification, version) {
89
+ for (const category of CATEGORIES) {
90
+ specification
91
+ .getRequirement(`#/components/${category}`)
92
+ ?.forEach((component, name) => {
93
+ const components = this.components.get(category) ??
94
+ new Map();
95
+ this.components.set(category, components);
96
+ const versions = components.get(name) ?? new Map();
97
+ components.set(name, versions);
98
+ // Import by reference so the existing coder chooses the canonical module
99
+ // and resolves component aliases without duplicating their definitions.
100
+ const reference = new Requirement({
101
+ $ref: `#/components/${category}/${name.replaceAll("~", "~0").replaceAll("/", "~1")}`,
102
+ }, component.url, specification);
103
+ const Coder = category === "schemas"
104
+ ? SchemaTypeCoder
105
+ : category === "responses"
106
+ ? ResponseTypeCoder
107
+ : ComponentTypeCoder;
108
+ versions.set(version, typeReference(this.script.importType(new Coder(reference, version))));
109
+ });
110
+ }
111
+ }
112
+ }
113
+ const indexes = new WeakMap();
114
+ export function centralTypes(repository) {
115
+ let index = indexes.get(repository);
116
+ if (!index) {
117
+ index = new CentralTypes(repository);
118
+ indexes.set(repository, index);
119
+ }
120
+ return index;
121
+ }
122
+ function literalStructure(data) {
123
+ if (Array.isArray(data))
124
+ return ts.factory.createTupleTypeNode(data.map(literalStructure));
125
+ if (data !== null && typeof data === "object")
126
+ return typeLiteral(Object.entries(data).map(([key, value]) => typeProperty(key, literalStructure(value))));
127
+ return literalType(data);
128
+ }
@@ -6,9 +6,11 @@ import { watch } from "chokidar";
6
6
  import createDebug from "debug";
7
7
  import { getLocalOpenApiSourcePaths } from "@counterfact/openapi";
8
8
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
9
+ import { centralTypes } from "./central-types.js";
9
10
  import { OperationCoder } from "./operation-coder.js";
10
11
  import { assertNoNormalizedPathCollisions, normalizeOpenApiPath, } from "./openapi-path.js";
11
12
  import { pruneRoutes, pruneTypes } from "./prune.js";
13
+ import { Requirement } from "./requirement.js";
12
14
  import { Repository } from "./repository.js";
13
15
  import { Specification } from "./specification.js";
14
16
  import { waitForEvent } from "./wait-for-event.js";
@@ -67,11 +69,12 @@ export class CodeGenerator extends EventTarget {
67
69
  */
68
70
  async getPathsFromSpecification(specification) {
69
71
  try {
70
- return specification.getRequirement("#/paths") ?? new Set();
72
+ return (specification.getRequirement("#/paths") ??
73
+ new Requirement({}, "#/paths", specification));
71
74
  }
72
75
  catch (error) {
73
76
  process.stderr.write(`Could not find #/paths in the specification.\n${error}\n`);
74
- return undefined;
77
+ return new Requirement({}, "#/paths", specification);
75
78
  }
76
79
  }
77
80
  /**
@@ -94,6 +97,7 @@ export class CodeGenerator extends EventTarget {
94
97
  const specification = await Specification.fromFile(this.openapiPath, this.overlays);
95
98
  debug("created specification: $o", specification);
96
99
  debug("reading the #/paths from the specification");
100
+ centralTypes(repository).addComponents(specification, this.version);
97
101
  const paths = await this.getPathsFromSpecification(specification);
98
102
  debug("got %i paths", paths?.map?.length ?? 0);
99
103
  const openApiPaths = paths.map((_pathDefinition, key) => key);
@@ -115,26 +119,35 @@ export class CodeGenerator extends EventTarget {
115
119
  "patch",
116
120
  "trace",
117
121
  ]);
118
- const operationMethodsForPath = (pathDefinition) => pathDefinition.flatMap((operation, requestMethod) => {
119
- if (requestMethod === "additionalOperations") {
120
- return operation.map((additionalOperation, additionalMethod) => [
121
- additionalOperation,
122
- additionalMethod.toLowerCase(),
123
- ]);
124
- }
125
- if (!HTTP_VERBS.has(requestMethod)) {
126
- return [];
127
- }
128
- return [[operation, requestMethod]];
129
- });
122
+ const operationMethodsForPath = (pathDefinition) => {
123
+ let resolved = pathDefinition;
124
+ while (resolved.isReference)
125
+ resolved = resolved.reference();
126
+ return resolved.flatMap((operation, requestMethod) => {
127
+ if (requestMethod === "additionalOperations") {
128
+ return operation.map((additionalOperation, additionalMethod) => [
129
+ additionalOperation,
130
+ additionalMethod.toLowerCase(),
131
+ ]);
132
+ }
133
+ if (!HTTP_VERBS.has(requestMethod)) {
134
+ return [];
135
+ }
136
+ return [[operation, requestMethod]];
137
+ });
138
+ };
130
139
  paths.forEach((pathDefinition, key) => {
131
140
  debug("processing path %s", key);
132
141
  const normalizedPath = normalizeOpenApiPath(key);
133
142
  const path = normalizedPath === "/" ? "/index" : normalizedPath;
134
143
  operationMethodsForPath(pathDefinition).forEach(([operation, requestMethod]) => {
144
+ // Keep the logical route location when a Path Item is a reference or
145
+ // a method is declared under OpenAPI 3.2 additionalOperations.
146
+ const logicalOperation = new Requirement(operation.data, `${pathDefinition.url}/${requestMethod}`, specification);
147
+ logicalOperation.parent = pathDefinition;
135
148
  repository
136
149
  .get(`routes${path}.ts`)
137
- .export(new OperationCoder(operation, this.version, requestMethod, securitySchemes));
150
+ .export(new OperationCoder(logicalOperation, this.version, requestMethod, securitySchemes));
138
151
  });
139
152
  });
140
153
  if (this.generateOptions.prune && this.generateOptions.types) {
@@ -6,7 +6,7 @@ import type { Script } from "./script.js";
6
6
  /**
7
7
  * Generates the default route handler stub for a single OpenAPI operation.
8
8
  *
9
- * The generated stub calls `$.response[statusCode].random()` (or `.empty()`)
9
+ * The generated stub calls `$.response.status(statusCode).random()` (or `.empty()`)
10
10
  * for the first response defined in the spec. It is only written when no
11
11
  * handler file exists yet — users are expected to replace it with real logic.
12
12
  *
@@ -1,14 +1,16 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
2
  import { pathJoin } from "./forward-slash-path.js";
3
3
  import ts from "typescript";
4
- import { parameter, typeReference } from "./ast.js";
4
+ import { literalType, parameter, typeReference } from "./ast.js";
5
+ import { routeTypeReference } from "./route-type-tree.js";
6
+ import { centralTypes } from "./central-types.js";
5
7
  import { Coder } from "./coder.js";
6
8
  import { normalizeOpenApiPath } from "./openapi-path.js";
7
9
  import { OperationTypeCoder, VersionedArgTypeCoder, } from "./operation-type-coder.js";
8
10
  /**
9
11
  * Generates the default route handler stub for a single OpenAPI operation.
10
12
  *
11
- * The generated stub calls `$.response[statusCode].random()` (or `.empty()`)
13
+ * The generated stub calls `$.response.status(statusCode).random()` (or `.empty()`)
12
14
  * for the first response defined in the spec. It is only written when no
13
15
  * handler file exists yet — users are expected to replace it with real logic.
14
16
  *
@@ -55,11 +57,13 @@ export class OperationCoder extends Coder {
55
57
  const body = ts.factory.createBlock([placeholder], true);
56
58
  statements.push(ts.factory.createFunctionDeclaration([ts.factory.createModifier(ts.SyntaxKind.AsyncKeyword)], ts.factory.createToken(ts.SyntaxKind.AsteriskToken), "items", undefined, [], undefined, body));
57
59
  }
58
- const result = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createElementAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$"), "response"), /^\d+$/u.test(status ?? "")
59
- ? ts.factory.createNumericLiteral(status)
60
- : status === "default"
61
- ? ts.factory.createNumericLiteral(200)
62
- : ts.factory.createStringLiteral(status ?? "200")), method), undefined, streaming
60
+ const result = ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("$"), "response"), "status"), undefined, [
61
+ /^\d+$/u.test(status ?? "")
62
+ ? ts.factory.createNumericLiteral(status)
63
+ : status === "default"
64
+ ? ts.factory.createNumericLiteral(200)
65
+ : ts.factory.createStringLiteral(status ?? "200"),
66
+ ]), method), undefined, streaming
63
67
  ? [
64
68
  ts.factory.createCallExpression(ts.factory.createIdentifier("items"), undefined, []),
65
69
  ]
@@ -77,7 +81,13 @@ export class OperationCoder extends Coder {
77
81
  const sharedScript = script.repository.get(operationTypeCoder.modulePath());
78
82
  sharedScript.declareVersion(versionedArgCoder, operationTypeCoder.getOperationBaseName());
79
83
  }
80
- return typeReference(script.importType(operationTypeCoder));
84
+ const path = this.requirement.parent?.url.split("/").at(-1) ??
85
+ this.requirement.url.split("/").at(-2);
86
+ const routePath = path.replaceAll("~1", "/").replaceAll("~0", "~");
87
+ centralTypes(script.repository).addOperation(routePath, this.requestMethod, operationTypeCoder);
88
+ const routes = script.importExternalType("Routes", pathJoin(script.relativePathToBase, "types/index.js"));
89
+ script.localTypes.set("Route", routeTypeReference(routes, routePath));
90
+ return ts.factory.createIndexedAccessTypeNode(typeReference("Route"), literalType(this.requestMethod.toUpperCase()));
81
91
  }
82
92
  modulePath() {
83
93
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -25,16 +25,13 @@ export declare class OperationTypeCoder extends TypeCoder {
25
25
  requestMethod: string;
26
26
  securitySchemes: SecurityScheme[];
27
27
  constructor(requirement: Requirement, version?: string, requestMethod?: string, securitySchemes?: SecurityScheme[]);
28
- /**
29
- * Returns the base identifier for this operation, derived from its
30
- * `operationId` (sanitised) or falling back to `HTTP_<METHOD>`.
31
- */
28
+ /** Returns the stable HTTP-method identifier, independent of operationId. */
32
29
  getOperationBaseName(): string;
33
30
  jsdoc(): string;
34
31
  get exportId(): string;
35
32
  names(): Generator<string>;
36
33
  /**
37
- * Generates and exports a named parameter type (e.g. `ListPets_Query`) from
34
+ * Generates and exports a named parameter type (e.g. `HTTP_GET_Query`) from
38
35
  * `modulePath` and returns the exported type name.
39
36
  *
40
37
  * Returns `"never"` without creating an export when `inlineType` is
@@ -1,4 +1,5 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
+ import { sanitizeIdentifier } from "./sanitize-identifier.js";
2
3
  import { pathJoin } from "./forward-slash-path.js";
3
4
  import ts from "typescript";
4
5
  import { functionType, literalType, neverType, numberType, parameter, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
@@ -6,28 +7,11 @@ import { buildJsDoc } from "./jsdoc.js";
6
7
  import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
7
8
  import { ParametersTypeCoder } from "./parameters-type-coder.js";
8
9
  import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
9
- import { RESERVED_WORDS } from "./reserved-words.js";
10
10
  import { ResponsesTypeCoder } from "./responses-type-coder.js";
11
11
  import { SchemaTypeCoder } from "./schema-type-coder.js";
12
12
  import { TypeCoder } from "./type-coder.js";
13
13
  import { normalizeOpenApiPath } from "./openapi-path.js";
14
14
  import { Requirement } from "./requirement.js";
15
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
16
- function sanitizeIdentifier(value) {
17
- // Treat any run of non-identifier characters as a camelCase separator
18
- let result = value.replaceAll(/[^\w$]+(?<next>.)/gu, (_, char) => char.toUpperCase());
19
- // Strip any trailing non-identifier characters (no following char to capitalize)
20
- result = result.replaceAll(/[^\w$]/gu, "");
21
- // If the identifier starts with a digit, prefix with an underscore
22
- if (/^\d/u.test(result)) {
23
- result = `_${result}`;
24
- }
25
- // If the identifier is a reserved word, append an underscore
26
- if (RESERVED_WORDS.has(result)) {
27
- result = `${result}_`;
28
- }
29
- return result || "_";
30
- }
31
15
  /**
32
16
  * Generates the TypeScript type for a single OpenAPI operation.
33
17
  *
@@ -52,15 +36,9 @@ export class OperationTypeCoder extends TypeCoder {
52
36
  this.requestMethod = requestMethod;
53
37
  this.securitySchemes = securitySchemes;
54
38
  }
55
- /**
56
- * Returns the base identifier for this operation, derived from its
57
- * `operationId` (sanitised) or falling back to `HTTP_<METHOD>`.
58
- */
39
+ /** Returns the stable HTTP-method identifier, independent of operationId. */
59
40
  getOperationBaseName() {
60
- const operationId = this.requirement.get("operationId")?.data;
61
- return operationId
62
- ? sanitizeIdentifier(operationId)
63
- : `HTTP_${this.requestMethod.toUpperCase()}`;
41
+ return `HTTP_${this.requestMethod.toUpperCase()}`;
64
42
  }
65
43
  jsdoc() {
66
44
  return buildJsDoc(this.requirement.data);
@@ -74,7 +52,7 @@ export class OperationTypeCoder extends TypeCoder {
74
52
  return super.names(this.getOperationBaseName());
75
53
  }
76
54
  /**
77
- * Generates and exports a named parameter type (e.g. `ListPets_Query`) from
55
+ * Generates and exports a named parameter type (e.g. `HTTP_GET_Query`) from
78
56
  * `modulePath` and returns the exported type name.
79
57
  *
80
58
  * Returns `"never"` without creating an export when `inlineType` is
@@ -2,6 +2,7 @@ export type OperationTypeNameMapping = Map<string, Map<string, string>>;
2
2
  /**
3
3
  * Resolves the generated operation type name for each route and HTTP method.
4
4
  * This is the migration-facing API; concrete coder and specification classes
5
- * remain internal implementation details.
5
+ * remain internal implementation details. Set legacyNames only when migrating
6
+ * operationId-based imports from older generated projects.
6
7
  */
7
- export declare function buildOperationTypeNameMapping(source: string, overlays?: readonly string[]): Promise<OperationTypeNameMapping>;
8
+ export declare function buildOperationTypeNameMapping(source: string, overlays?: readonly string[], legacyNames?: boolean): Promise<OperationTypeNameMapping>;
@@ -1,3 +1,5 @@
1
+ import { normalizeOpenApiPath } from "./openapi-path.js";
2
+ import { sanitizeIdentifier } from "./sanitize-identifier.js";
1
3
  import createDebug from "debug";
2
4
  import { OperationTypeCoder, } from "./operation-type-coder.js";
3
5
  import { Specification } from "./specification.js";
@@ -10,9 +12,10 @@ const HTTP_METHODS = new Set([
10
12
  "PATCH",
11
13
  "HEAD",
12
14
  "OPTIONS",
13
- "QUERY",
15
+ "TRACE",
14
16
  ]);
15
17
  function openApiPathToFilePath(openApiPath) {
18
+ openApiPath = normalizeOpenApiPath(openApiPath);
16
19
  if (openApiPath === "/") {
17
20
  return "index";
18
21
  }
@@ -21,9 +24,10 @@ function openApiPathToFilePath(openApiPath) {
21
24
  /**
22
25
  * Resolves the generated operation type name for each route and HTTP method.
23
26
  * This is the migration-facing API; concrete coder and specification classes
24
- * remain internal implementation details.
27
+ * remain internal implementation details. Set legacyNames only when migrating
28
+ * operationId-based imports from older generated projects.
25
29
  */
26
- export async function buildOperationTypeNameMapping(source, overlays = []) {
30
+ export async function buildOperationTypeNameMapping(source, overlays = [], legacyNames = false) {
27
31
  debug("building operation type name mapping from %s", source);
28
32
  const specification = await Specification.fromFile(source, overlays);
29
33
  const mapping = new Map();
@@ -35,16 +39,24 @@ export async function buildOperationTypeNameMapping(source, overlays = []) {
35
39
  const securitySchemes = Object.values(securityRequirement?.data ?? {});
36
40
  paths.forEach((pathDefinition, openApiPath) => {
37
41
  const methodMap = new Map();
38
- pathDefinition.forEach((operation, requestMethod) => {
39
- const method = requestMethod.toUpperCase();
40
- if (!HTTP_METHODS.has(method)) {
41
- return;
42
+ const operations = pathDefinition.flatMap((operation, method) => {
43
+ if (method === "additionalOperations") {
44
+ return operation.map((additionalOperation, additionalMethod) => ({
45
+ operation: additionalOperation,
46
+ method: additionalMethod.toUpperCase(),
47
+ }));
42
48
  }
43
- const typeName = new OperationTypeCoder(operation, "", requestMethod, securitySchemes)
49
+ return HTTP_METHODS.has(method.toUpperCase())
50
+ ? [{ operation, method: method.toUpperCase() }]
51
+ : [];
52
+ });
53
+ for (const { operation, method } of operations) {
54
+ const typeName = new OperationTypeCoder(operation, "", method.toLowerCase(), securitySchemes)
44
55
  .names()
45
56
  .next().value;
46
- methodMap.set(method, typeName);
47
- });
57
+ const operationId = operation.get("operationId")?.data;
58
+ methodMap.set(method, legacyNames && operationId ? sanitizeIdentifier(operationId) : typeName);
59
+ }
48
60
  if (methodMap.size > 0) {
49
61
  mapping.set(openApiPathToFilePath(openApiPath), methodMap);
50
62
  }