@counterfact/generator 0.1.5 → 1.0.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.
Files changed (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/ast.d.ts +23 -0
  3. package/dist/ast.js +142 -0
  4. package/dist/coder.d.ts +16 -22
  5. package/dist/coder.js +15 -17
  6. package/dist/operation-coder.d.ts +5 -3
  7. package/dist/operation-coder.js +40 -25
  8. package/dist/operation-type-coder.d.ts +17 -25
  9. package/dist/operation-type-coder.js +115 -129
  10. package/dist/operation-type-name-mapping.d.ts +3 -2
  11. package/dist/operation-type-name-mapping.js +22 -10
  12. package/dist/parameter-export-type-coder.d.ts +4 -3
  13. package/dist/parameters-type-coder.d.ts +2 -1
  14. package/dist/parameters-type-coder.js +7 -18
  15. package/dist/repository.d.ts +3 -10
  16. package/dist/repository.js +244 -95
  17. package/dist/response-type-coder.d.ts +7 -7
  18. package/dist/response-type-coder.js +37 -53
  19. package/dist/responses-type-coder.d.ts +4 -4
  20. package/dist/responses-type-coder.js +39 -26
  21. package/dist/sanitize-identifier.d.ts +1 -0
  22. package/dist/sanitize-identifier.js +17 -0
  23. package/dist/scenario-file-generator.js +137 -134
  24. package/dist/schema-coder.d.ts +6 -4
  25. package/dist/schema-coder.js +31 -22
  26. package/dist/schema-required-properties.d.ts +3 -0
  27. package/dist/schema-required-properties.js +47 -0
  28. package/dist/schema-type-coder.d.ts +10 -8
  29. package/dist/schema-type-coder.js +157 -64
  30. package/dist/script.d.ts +18 -95
  31. package/dist/script.js +137 -212
  32. package/dist/templates/counterfact-types/middleware.ts +15 -2
  33. package/dist/templates/counterfact-types/response-builder-factory.ts +102 -6
  34. package/dist/templates/counterfact-types/response-builder.ts +1 -0
  35. package/dist/templates/counterfact-types/wide-operation-argument.ts +13 -1
  36. package/dist/type-coder.d.ts +3 -1
  37. package/dist/type-coder.js +5 -1
  38. package/dist/versions-ts-generator.d.ts +0 -9
  39. package/dist/versions-ts-generator.js +46 -77
  40. package/package.json +5 -4
  41. package/src/README.md +23 -2
  42. package/dist/context-file-token.d.ts +0 -1
  43. package/dist/context-file-token.js +0 -1
  44. package/dist/printers.d.ts +0 -2
  45. package/dist/printers.js +0 -10
@@ -1,32 +1,17 @@
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
- import { CONTEXT_FILE_TOKEN } from "./context-file-token.js";
4
+ import ts from "typescript";
5
+ import { functionType, literalType, neverType, numberType, parameter, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
4
6
  import { buildJsDoc } from "./jsdoc.js";
5
7
  import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
6
8
  import { ParametersTypeCoder } from "./parameters-type-coder.js";
7
9
  import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
8
- import { RESERVED_WORDS } from "./reserved-words.js";
9
10
  import { ResponsesTypeCoder } from "./responses-type-coder.js";
10
11
  import { SchemaTypeCoder } from "./schema-type-coder.js";
11
12
  import { TypeCoder } from "./type-coder.js";
12
13
  import { normalizeOpenApiPath } from "./openapi-path.js";
13
14
  import { Requirement } from "./requirement.js";
14
- // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#reserved_words
15
- function sanitizeIdentifier(value) {
16
- // Treat any run of non-identifier characters as a camelCase separator
17
- let result = value.replaceAll(/[^\w$]+(?<next>.)/gu, (_, char) => char.toUpperCase());
18
- // Strip any trailing non-identifier characters (no following char to capitalize)
19
- result = result.replaceAll(/[^\w$]/gu, "");
20
- // If the identifier starts with a digit, prefix with an underscore
21
- if (/^\d/u.test(result)) {
22
- result = `_${result}`;
23
- }
24
- // If the identifier is a reserved word, append an underscore
25
- if (RESERVED_WORDS.has(result)) {
26
- result = `${result}_`;
27
- }
28
- return result || "_";
29
- }
30
15
  /**
31
16
  * Generates the TypeScript type for a single OpenAPI operation.
32
17
  *
@@ -36,11 +21,7 @@ function sanitizeIdentifier(value) {
36
21
  *
37
22
  * Output is written to `types/paths/<route>.types.ts`.
38
23
  *
39
- * **Versioned APIs**: when `version` is non-empty this coder emits only a
40
- * sentinel `{raw: ""}` export (suppressing the normal flat type) and
41
- * registers a formatter on the shared script so that
42
- * {@link Script.versionsTypeStatements} can later emit the merged
43
- * `HTTP_<METHOD>_$_Versions` map and the `HTTP_<METHOD>` handler type.
24
+ * **Versioned APIs** register a declaration builder on the shared script.
44
25
  * Each version's `$`-argument type is emitted to
45
26
  * `types/<version>/paths/<path>.types.ts` by {@link VersionedArgTypeCoder}.
46
27
  */
@@ -55,24 +36,23 @@ export class OperationTypeCoder extends TypeCoder {
55
36
  this.requestMethod = requestMethod;
56
37
  this.securitySchemes = securitySchemes;
57
38
  }
58
- /**
59
- * Returns the base identifier for this operation, derived from its
60
- * `operationId` (sanitised) or falling back to `HTTP_<METHOD>`.
61
- */
39
+ /** Returns the stable HTTP-method identifier, independent of operationId. */
62
40
  getOperationBaseName() {
63
- const operationId = this.requirement.get("operationId")?.data;
64
- return operationId
65
- ? sanitizeIdentifier(operationId)
66
- : `HTTP_${this.requestMethod.toUpperCase()}`;
41
+ return `HTTP_${this.requestMethod.toUpperCase()}`;
67
42
  }
68
43
  jsdoc() {
69
44
  return buildJsDoc(this.requirement.data);
70
45
  }
46
+ get exportId() {
47
+ return this.version === ""
48
+ ? this.id
49
+ : `${this.constructor.name}@${this.modulePath()}:${this.requestMethod.toLowerCase()}`;
50
+ }
71
51
  names() {
72
52
  return super.names(this.getOperationBaseName());
73
53
  }
74
54
  /**
75
- * 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
76
56
  * `modulePath` and returns the exported type name.
77
57
  *
78
58
  * Returns `"never"` without creating an export when `inlineType` is
@@ -80,19 +60,19 @@ export class OperationTypeCoder extends TypeCoder {
80
60
  *
81
61
  * @param script - The script being assembled.
82
62
  * @param parameterKind - `"query"`, `"path"`, `"headers"`, or `"cookie"`.
83
- * @param inlineType - The inline TypeScript type string to export.
63
+ * @param inlineType - The inline TypeScript type node to export.
84
64
  * @param baseName - The base identifier prefix for the exported type name.
85
65
  * @param modulePath - The repository-relative path of the type file.
86
66
  */
87
67
  exportParameterType(script, parameterKind, inlineType, baseName, modulePath) {
88
- if (inlineType === "never") {
89
- return "never";
68
+ if (inlineType.kind === ts.SyntaxKind.NeverKeyword) {
69
+ return inlineType;
90
70
  }
91
71
  const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
92
72
  const typeName = `${baseName}_${capitalize(parameterKind)}`;
93
73
  const coder = new ParameterExportTypeCoder(this.requirement, this.version, typeName, inlineType, parameterKind);
94
74
  coder._modulePath = modulePath;
95
- return script.export(coder, true);
75
+ return typeReference(script.export(coder, true));
96
76
  }
97
77
  /**
98
78
  * Returns the union of all possible response type shapes for this operation.
@@ -100,50 +80,42 @@ export class OperationTypeCoder extends TypeCoder {
100
80
  * @param script - The script being assembled (used to resolve imports).
101
81
  */
102
82
  responseTypes(script) {
103
- return this.requirement
83
+ const shapes = this.requirement
104
84
  .get("responses")
105
- .flatMap((response, responseCode) => {
106
- const status = responseCode === "default"
107
- ? "number | undefined"
108
- : Number.parseInt(responseCode, 10);
85
+ .flatMap((response, code) => {
86
+ const status = code === "default"
87
+ ? unionType([
88
+ numberType(),
89
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
90
+ ])
91
+ : literalType(Number.parseInt(code, 10));
92
+ const shape = (contentType, body) => typeLiteral([
93
+ typeProperty("status", status),
94
+ typeProperty("contentType", literalType(contentType), true),
95
+ typeProperty("body", body, true),
96
+ ], true);
109
97
  if (response.has("content")) {
110
- return response.get("content").map((content, contentType) => {
111
- let bodyType;
112
- if (content.has("itemSchema") &&
113
- STREAMING_CONTENT_TYPES.has(contentType)) {
114
- bodyType = `AsyncIterable<${new SchemaTypeCoder(content.get("itemSchema"), this.version).write(script)}>`;
115
- }
116
- else {
117
- bodyType = content.has("schema")
98
+ return response.get("content").map((content, mediaType) => {
99
+ const body = content.has("itemSchema") &&
100
+ STREAMING_CONTENT_TYPES.has(mediaType)
101
+ ? typeReference("AsyncIterable", [
102
+ new SchemaTypeCoder(content.get("itemSchema"), this.version).write(script),
103
+ ])
104
+ : content.has("schema")
118
105
  ? new SchemaTypeCoder(content.get("schema"), this.version).write(script)
119
- : "unknown";
120
- }
121
- return `{
122
- status: ${status},
123
- contentType?: "${contentType}",
124
- body?: ${bodyType}
125
- }`;
106
+ : unknownType();
107
+ return shape(mediaType, body);
126
108
  });
127
109
  }
128
110
  if (response.has("schema")) {
129
- const producesReq = this.requirement?.get("produces") ??
130
- this.requirement.specification?.rootRequirement?.get("produces");
131
- const produces = producesReq?.data;
132
- if (produces) {
133
- return produces
134
- .map((contentType) => `{
135
- status: ${status},
136
- contentType?: "${contentType}",
137
- body?: ${new SchemaTypeCoder(response.get("schema"), this.version).write(script)}
138
- }`)
139
- .join(" | ");
140
- }
111
+ const produces = (this.requirement.get("produces") ??
112
+ this.requirement.specification?.rootRequirement?.get("produces"))?.data;
113
+ if (produces)
114
+ return produces.map((mediaType) => shape(mediaType, new SchemaTypeCoder(response.get("schema"), this.version).write(script)));
141
115
  }
142
- return `{
143
- status: ${status}
144
- }`;
145
- })
146
- .join(" | ");
116
+ return [typeLiteral([typeProperty("status", status)], true)];
117
+ });
118
+ return unionType(shapes);
147
119
  }
148
120
  modulePath() {
149
121
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -156,27 +128,21 @@ export class OperationTypeCoder extends TypeCoder {
156
128
  * `{username?: string, password?: string}`. Otherwise it is `"never"`.
157
129
  */
158
130
  userType() {
159
- if (this.securitySchemes.some(({ scheme, type }) => type === "http" && scheme === "basic")) {
160
- return "{username?: string, password?: string}";
161
- }
162
- return "never";
131
+ return this.securitySchemes.some(({ scheme, type }) => type === "http" && scheme === "basic")
132
+ ? typeLiteral([
133
+ typeProperty("username", stringType(), true),
134
+ typeProperty("password", stringType(), true),
135
+ ])
136
+ : neverType();
163
137
  }
164
- /**
165
- * Returns the TypeScript type for the `auth` argument.
166
- *
167
- * Includes basic-auth credentials when present and `apiKey` when at least one
168
- * apiKey security scheme is configured.
169
- */
170
138
  authType() {
171
- const fields = new Set();
139
+ const fields = [];
172
140
  if (this.securitySchemes.some(({ scheme, type }) => type === "http" && scheme === "basic")) {
173
- fields.add("username?: string");
174
- fields.add("password?: string");
175
- }
176
- if (this.securitySchemes.some(({ type }) => type === "apiKey")) {
177
- fields.add("apiKey: string");
141
+ fields.push(typeProperty("username", stringType(), true), typeProperty("password", stringType(), true));
178
142
  }
179
- return fields.size === 0 ? "never" : `{${[...fields].join(", ")}}`;
143
+ if (this.securitySchemes.some(({ type }) => type === "apiKey"))
144
+ fields.push(typeProperty("apiKey", stringType()));
145
+ return fields.length === 0 ? neverType() : typeLiteral(fields);
180
146
  }
181
147
  /**
182
148
  * Returns the effective parameters for this operation by merging path-item-level
@@ -246,7 +212,9 @@ export class OperationTypeCoder extends TypeCoder {
246
212
  const xType = script.importSharedType("WideOperationArgument");
247
213
  script.importSharedType("OmitValueWhenNever");
248
214
  script.importSharedType("COUNTERFACT_RESPONSE");
249
- const contextTypeImportName = script.importExternalType("Context", CONTEXT_FILE_TOKEN);
215
+ const contextTypeImportName = script.importExternalType("Context", {
216
+ context: true,
217
+ });
250
218
  const parameters = this.getEffectiveParameters();
251
219
  const queryType = new ParametersTypeCoder(parameters, this.version, "query").write(script);
252
220
  const pathType = new ParametersTypeCoder(parameters, this.version, "path").write(script);
@@ -259,14 +227,19 @@ export class OperationTypeCoder extends TypeCoder {
259
227
  ?.get("schema")
260
228
  : this.requirement.select("requestBody/content/application~1json/schema");
261
229
  const bodyType = bodyRequirement === undefined
262
- ? "never"
230
+ ? neverType()
263
231
  : new SchemaTypeCoder(bodyRequirement, this.version).write(script);
264
232
  const openApi2MediaTypes = (this.requirement.get("produces")?.data ??
265
233
  this.requirement.specification?.rootRequirement?.get("produces")
266
234
  ?.data);
267
235
  const responseType = new ResponsesTypeCoder(this.requirement.get("responses"), this.version, openApi2MediaTypes).write(script);
268
- const proxyType = "(url: string) => COUNTERFACT_RESPONSE";
269
- const delayType = "(milliseconds: number, maxMilliseconds?: number) => Promise<void>";
236
+ const proxyType = functionType([parameter("url", stringType())], typeReference("COUNTERFACT_RESPONSE"));
237
+ const delayType = functionType([
238
+ parameter("milliseconds", numberType()),
239
+ parameter("maxMilliseconds", numberType(), true),
240
+ ], typeReference("Promise", [
241
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
242
+ ]));
270
243
  const queryTypeName = this.exportParameterType(script, "query", queryType, baseName, modulePath);
271
244
  const pathTypeName = this.exportParameterType(script, "path", pathType, baseName, modulePath);
272
245
  const headersTypeName = this.exportParameterType(script, "headers", headersType, baseName, modulePath);
@@ -276,46 +249,54 @@ export class OperationTypeCoder extends TypeCoder {
276
249
  const querystringParam = parameters?.find((parameter) => parameter.get("in")?.data === "querystring");
277
250
  const querystringType = querystringParam?.has("schema") === true
278
251
  ? new SchemaTypeCoder(querystringParam.get("schema"), this.version).write(script)
279
- : "never";
252
+ : neverType();
280
253
  const querystringTypeName = this.exportParameterType(script, "querystring", querystringType, baseName, modulePath);
281
- const versionLiteralType = this.version !== "" ? `"${this.version}"` : "never";
282
- return `OmitValueWhenNever<{ query: ${queryTypeName}, querystring: ${querystringTypeName}, path: ${pathTypeName}, headers: ${headersTypeName}, cookie: ${cookieTypeName}, body: ${bodyType}, context: ${contextTypeImportName}, response: ${responseType}, x: ${xType}, proxy: ${proxyType}, auth: ${this.authType()}, user: ${this.userType()}, delay: ${delayType}, version: ${versionLiteralType} }>`;
254
+ const versionLiteralType = this.version !== "" ? literalType(this.version) : neverType();
255
+ return typeReference("OmitValueWhenNever", [
256
+ typeLiteral([
257
+ typeProperty("query", queryTypeName),
258
+ typeProperty("querystring", querystringTypeName),
259
+ typeProperty("path", pathTypeName),
260
+ typeProperty("headers", headersTypeName),
261
+ typeProperty("cookie", cookieTypeName),
262
+ typeProperty("body", bodyType),
263
+ typeProperty("context", typeReference(contextTypeImportName)),
264
+ typeProperty("response", responseType),
265
+ typeProperty("x", typeReference(xType)),
266
+ typeProperty("proxy", proxyType),
267
+ typeProperty("auth", this.authType()),
268
+ typeProperty("user", this.userType()),
269
+ typeProperty("delay", delayType),
270
+ typeProperty("version", versionLiteralType),
271
+ ]),
272
+ ]);
273
+ }
274
+ exportDeclarations(script, name) {
275
+ if (this.version === "")
276
+ return undefined;
277
+ script.comments = READ_ONLY_COMMENTS;
278
+ const versioned = script.importVersionsType("Versioned");
279
+ const promise = script.importSharedType("MaybePromise");
280
+ const response = script.importSharedType("COUNTERFACT_RESPONSE");
281
+ script.setVersionBuilder(this.getOperationBaseName(), (versions) => {
282
+ const mapName = `${name}_$_Versions`;
283
+ return [
284
+ typeAlias(mapName, typeLiteral([...versions].map(([version, type]) => typeProperty(version, type))), false),
285
+ typeAlias(name, functionType([
286
+ parameter("$", typeReference(versioned, [typeReference(mapName)])),
287
+ ], typeReference(promise, [typeReference(response)]))),
288
+ ];
289
+ });
290
+ return [];
283
291
  }
284
292
  writeCode(script) {
285
293
  script.comments = READ_ONLY_COMMENTS;
286
- if (this.version !== "") {
287
- // Versioned case: suppress the normal flat export and register a
288
- // formatter so that Script.versionsTypeStatements() can emit the
289
- // merged HTTP_<METHOD>_$_Versions + HTTP_<METHOD> types after all
290
- // versions have been declared via declareVersion().
291
- const versionedType = script.importVersionsType("Versioned");
292
- const maybePromiseType = script.importSharedType("MaybePromise");
293
- const counterfactResponseType = script.importSharedType("COUNTERFACT_RESPONSE");
294
- const baseName = this.getOperationBaseName();
295
- script.setVersionFormatter(baseName, (versionCodes) => {
296
- const versionsTypeName = `${baseName}_$_Versions`;
297
- const versionMap = Array.from(versionCodes, ([v, code]) => `"${v}": ${code}`).join("; ");
298
- return [
299
- `type ${versionsTypeName} = { ${versionMap} };`,
300
- `export type ${baseName} = ($: ${versionedType}<${versionsTypeName}>) => ${maybePromiseType}<${counterfactResponseType}>;`,
301
- ].join("\n");
302
- });
303
- // Return a raw-empty sentinel so exportStatements() emits nothing for
304
- // this export entry. The real export is produced by
305
- // versionsTypeStatements().
306
- return { raw: "" };
307
- }
308
- // Non-versioned case: existing flat-type output.
309
- // Import in the same order as the original writeCode so that the emitted
310
- // import block is identical to the pre-refactor output (snapshot-safe).
311
294
  script.importSharedType("WideOperationArgument");
312
295
  script.importSharedType("OmitValueWhenNever");
313
296
  script.importSharedType("MaybePromise");
314
297
  script.importSharedType("COUNTERFACT_RESPONSE");
315
- const baseName = this.getOperationBaseName();
316
- const modulePath = this.modulePath();
317
- const dollarArgType = this.buildDollarArgType(script, baseName, modulePath);
318
- return `($: ${dollarArgType}) => MaybePromise<COUNTERFACT_RESPONSE>`;
298
+ const arg = this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
299
+ return functionType([parameter("$", arg)], typeReference("MaybePromise", [typeReference("COUNTERFACT_RESPONSE")]));
319
300
  }
320
301
  }
321
302
  /**
@@ -332,6 +313,9 @@ export class OperationTypeCoder extends TypeCoder {
332
313
  * is assembled by the shared script's `versionsTypeStatements()`.
333
314
  */
334
315
  export class VersionedArgTypeCoder extends OperationTypeCoder {
316
+ get exportId() {
317
+ return this.id;
318
+ }
335
319
  /**
336
320
  * Include the version in the cache key so v1 and v2 coders are treated as
337
321
  * distinct exports even when they share the same requirement URL.
@@ -369,11 +353,14 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
369
353
  * When called from any other script (e.g. the shared file), export to the
370
354
  * per-version file and import the result back into that script.
371
355
  */
356
+ exportDeclarations() {
357
+ return undefined;
358
+ }
372
359
  write(script) {
373
360
  if (script.path === this.modulePath()) {
374
361
  return this.writeCode(script);
375
362
  }
376
- return script.importType(this);
363
+ return typeReference(script.importType(this));
377
364
  }
378
365
  /**
379
366
  * Generates the `OmitValueWhenNever<{…}>` dollar-argument type and writes
@@ -381,7 +368,6 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
381
368
  */
382
369
  writeCode(script) {
383
370
  script.comments = READ_ONLY_COMMENTS;
384
- const baseName = this.getOperationBaseName();
385
- return this.buildDollarArgType(script, baseName, this.modulePath());
371
+ return this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
386
372
  }
387
373
  }
@@ -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
  }
@@ -1,13 +1,14 @@
1
+ import type ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import type { Requirement } from "./requirement.js";
3
4
  export declare class ParameterExportTypeCoder extends TypeCoder {
4
5
  _typeName: string;
5
- _typeCode: string;
6
+ _typeCode: ts.TypeNode;
6
7
  _parameterKind: string;
7
8
  _modulePath: string;
8
- constructor(requirement: Requirement, version: string, typeName: string, typeCode: string, parameterKind: string);
9
+ constructor(requirement: Requirement, version: string, typeName: string, typeCode: ts.TypeNode, parameterKind: string);
9
10
  get id(): string;
10
11
  names(): Generator<string>;
11
- writeCode(): string;
12
+ writeCode(): ts.TypeNode;
12
13
  modulePath(): string;
13
14
  }
@@ -1,3 +1,4 @@
1
+ import type ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import type { Requirement } from "./requirement.js";
3
4
  import type { Script } from "./script.js";
@@ -5,6 +6,6 @@ export declare class ParametersTypeCoder extends TypeCoder {
5
6
  placement: string;
6
7
  constructor(requirement: Requirement, version?: string, placement?: string);
7
8
  names(): Generator<string>;
8
- writeCode(script: Script): string;
9
+ writeCode(script: Script): ts.TypeNode;
9
10
  modulePath(): string;
10
11
  }
@@ -1,7 +1,7 @@
1
+ import { neverType, typeLiteral, typeProperty } from "./ast.js";
2
+ import { TypeCoder } from "./type-coder.js";
1
3
  import { pathJoin } from "./forward-slash-path.js";
2
- import { buildJsDoc } from "./jsdoc.js";
3
4
  import { SchemaTypeCoder } from "./schema-type-coder.js";
4
- import { TypeCoder } from "./type-coder.js";
5
5
  export class ParametersTypeCoder extends TypeCoder {
6
6
  placement;
7
7
  constructor(requirement, version = "", placement = "") {
@@ -12,27 +12,16 @@ export class ParametersTypeCoder extends TypeCoder {
12
12
  return super.names("parameters");
13
13
  }
14
14
  writeCode(script) {
15
- const typeDefinitions = (this.requirement?.data ?? [])
16
- .map((_, index) => {
17
- return this.requirement.get(index);
18
- })
15
+ const members = (this.requirement?.data ?? [])
16
+ .map((_, index) => this.requirement.get(index))
19
17
  .filter((parameter) => parameter.get("in").data === this.placement)
20
18
  .map((parameter) => {
21
19
  const name = parameter.get("name")?.data;
22
20
  const required = parameter.get("required")?.data;
23
- const optionalFlag = required ? "" : "?";
24
- const schema = parameter.has("schema")
25
- ? parameter.get("schema")
26
- : parameter;
27
- const comment = buildJsDoc(parameter.data);
28
- const commentPrefix = comment ? `\n${comment}` : "";
29
- const typeString = new SchemaTypeCoder(schema, this.version).write(script);
30
- return `${commentPrefix}"${name}"${optionalFlag}: ${typeString}`;
21
+ const schema = parameter.get("schema") ?? parameter;
22
+ return typeProperty(String(name), new SchemaTypeCoder(schema, this.version).write(script), !required, parameter.data);
31
23
  });
32
- if (typeDefinitions.length === 0) {
33
- return "never";
34
- }
35
- return `{${typeDefinitions.join(", ")}}`;
24
+ return members.length === 0 ? neverType() : typeLiteral(members);
36
25
  }
37
26
  modulePath() {
38
27
  const pathString = this.requirement.url
@@ -55,16 +55,9 @@ export declare class Repository {
55
55
  */
56
56
  createDefaultContextFile(destination: string): Promise<void>;
57
57
  /**
58
- * Appends any HTTP-method handler exports that appear in `generatedContent`
59
- * but are absent from the existing file at `fullPath`.
60
- *
61
- * For each new export the corresponding `import type` statement is inserted
62
- * after the last existing import line (or prepended when no imports exist),
63
- * and the export block is appended at the end of the file.
64
- *
65
- * @param fullPath - Absolute path of the route file to update.
66
- * @param generatedContent - The fully-generated file content (used as the
67
- * source of new import and export statements).
58
+ * Inserts newly generated handlers and their type imports without reprinting
59
+ * existing user code. Only the existing file is parsed; generated declarations
60
+ * are taken directly from the Script's AST.
68
61
  */
69
62
  private appendNewHandlers;
70
63
  /**