@counterfact/generator 0.1.5 → 0.1.6

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.
@@ -1,6 +1,7 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
2
  import { pathJoin } from "./forward-slash-path.js";
3
- import { CONTEXT_FILE_TOKEN } from "./context-file-token.js";
3
+ import ts from "typescript";
4
+ import { functionType, literalType, neverType, numberType, parameter, stringType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
4
5
  import { buildJsDoc } from "./jsdoc.js";
5
6
  import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
6
7
  import { ParametersTypeCoder } from "./parameters-type-coder.js";
@@ -36,11 +37,7 @@ function sanitizeIdentifier(value) {
36
37
  *
37
38
  * Output is written to `types/paths/<route>.types.ts`.
38
39
  *
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.
40
+ * **Versioned APIs** register a declaration builder on the shared script.
44
41
  * Each version's `$`-argument type is emitted to
45
42
  * `types/<version>/paths/<path>.types.ts` by {@link VersionedArgTypeCoder}.
46
43
  */
@@ -68,6 +65,11 @@ export class OperationTypeCoder extends TypeCoder {
68
65
  jsdoc() {
69
66
  return buildJsDoc(this.requirement.data);
70
67
  }
68
+ get exportId() {
69
+ return this.version === ""
70
+ ? this.id
71
+ : `${this.constructor.name}@${this.modulePath()}:${this.requestMethod.toLowerCase()}`;
72
+ }
71
73
  names() {
72
74
  return super.names(this.getOperationBaseName());
73
75
  }
@@ -80,19 +82,19 @@ export class OperationTypeCoder extends TypeCoder {
80
82
  *
81
83
  * @param script - The script being assembled.
82
84
  * @param parameterKind - `"query"`, `"path"`, `"headers"`, or `"cookie"`.
83
- * @param inlineType - The inline TypeScript type string to export.
85
+ * @param inlineType - The inline TypeScript type node to export.
84
86
  * @param baseName - The base identifier prefix for the exported type name.
85
87
  * @param modulePath - The repository-relative path of the type file.
86
88
  */
87
89
  exportParameterType(script, parameterKind, inlineType, baseName, modulePath) {
88
- if (inlineType === "never") {
89
- return "never";
90
+ if (inlineType.kind === ts.SyntaxKind.NeverKeyword) {
91
+ return inlineType;
90
92
  }
91
93
  const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
92
94
  const typeName = `${baseName}_${capitalize(parameterKind)}`;
93
95
  const coder = new ParameterExportTypeCoder(this.requirement, this.version, typeName, inlineType, parameterKind);
94
96
  coder._modulePath = modulePath;
95
- return script.export(coder, true);
97
+ return typeReference(script.export(coder, true));
96
98
  }
97
99
  /**
98
100
  * Returns the union of all possible response type shapes for this operation.
@@ -100,50 +102,42 @@ export class OperationTypeCoder extends TypeCoder {
100
102
  * @param script - The script being assembled (used to resolve imports).
101
103
  */
102
104
  responseTypes(script) {
103
- return this.requirement
105
+ const shapes = this.requirement
104
106
  .get("responses")
105
- .flatMap((response, responseCode) => {
106
- const status = responseCode === "default"
107
- ? "number | undefined"
108
- : Number.parseInt(responseCode, 10);
107
+ .flatMap((response, code) => {
108
+ const status = code === "default"
109
+ ? unionType([
110
+ numberType(),
111
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),
112
+ ])
113
+ : literalType(Number.parseInt(code, 10));
114
+ const shape = (contentType, body) => typeLiteral([
115
+ typeProperty("status", status),
116
+ typeProperty("contentType", literalType(contentType), true),
117
+ typeProperty("body", body, true),
118
+ ], true);
109
119
  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")
120
+ return response.get("content").map((content, mediaType) => {
121
+ const body = content.has("itemSchema") &&
122
+ STREAMING_CONTENT_TYPES.has(mediaType)
123
+ ? typeReference("AsyncIterable", [
124
+ new SchemaTypeCoder(content.get("itemSchema"), this.version).write(script),
125
+ ])
126
+ : content.has("schema")
118
127
  ? new SchemaTypeCoder(content.get("schema"), this.version).write(script)
119
- : "unknown";
120
- }
121
- return `{
122
- status: ${status},
123
- contentType?: "${contentType}",
124
- body?: ${bodyType}
125
- }`;
128
+ : unknownType();
129
+ return shape(mediaType, body);
126
130
  });
127
131
  }
128
132
  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
- }
133
+ const produces = (this.requirement.get("produces") ??
134
+ this.requirement.specification?.rootRequirement?.get("produces"))?.data;
135
+ if (produces)
136
+ return produces.map((mediaType) => shape(mediaType, new SchemaTypeCoder(response.get("schema"), this.version).write(script)));
141
137
  }
142
- return `{
143
- status: ${status}
144
- }`;
145
- })
146
- .join(" | ");
138
+ return [typeLiteral([typeProperty("status", status)], true)];
139
+ });
140
+ return unionType(shapes);
147
141
  }
148
142
  modulePath() {
149
143
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -156,27 +150,21 @@ export class OperationTypeCoder extends TypeCoder {
156
150
  * `{username?: string, password?: string}`. Otherwise it is `"never"`.
157
151
  */
158
152
  userType() {
159
- if (this.securitySchemes.some(({ scheme, type }) => type === "http" && scheme === "basic")) {
160
- return "{username?: string, password?: string}";
161
- }
162
- return "never";
153
+ return this.securitySchemes.some(({ scheme, type }) => type === "http" && scheme === "basic")
154
+ ? typeLiteral([
155
+ typeProperty("username", stringType(), true),
156
+ typeProperty("password", stringType(), true),
157
+ ])
158
+ : neverType();
163
159
  }
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
160
  authType() {
171
- const fields = new Set();
161
+ const fields = [];
172
162
  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");
163
+ fields.push(typeProperty("username", stringType(), true), typeProperty("password", stringType(), true));
178
164
  }
179
- return fields.size === 0 ? "never" : `{${[...fields].join(", ")}}`;
165
+ if (this.securitySchemes.some(({ type }) => type === "apiKey"))
166
+ fields.push(typeProperty("apiKey", stringType()));
167
+ return fields.length === 0 ? neverType() : typeLiteral(fields);
180
168
  }
181
169
  /**
182
170
  * Returns the effective parameters for this operation by merging path-item-level
@@ -246,7 +234,9 @@ export class OperationTypeCoder extends TypeCoder {
246
234
  const xType = script.importSharedType("WideOperationArgument");
247
235
  script.importSharedType("OmitValueWhenNever");
248
236
  script.importSharedType("COUNTERFACT_RESPONSE");
249
- const contextTypeImportName = script.importExternalType("Context", CONTEXT_FILE_TOKEN);
237
+ const contextTypeImportName = script.importExternalType("Context", {
238
+ context: true,
239
+ });
250
240
  const parameters = this.getEffectiveParameters();
251
241
  const queryType = new ParametersTypeCoder(parameters, this.version, "query").write(script);
252
242
  const pathType = new ParametersTypeCoder(parameters, this.version, "path").write(script);
@@ -259,14 +249,19 @@ export class OperationTypeCoder extends TypeCoder {
259
249
  ?.get("schema")
260
250
  : this.requirement.select("requestBody/content/application~1json/schema");
261
251
  const bodyType = bodyRequirement === undefined
262
- ? "never"
252
+ ? neverType()
263
253
  : new SchemaTypeCoder(bodyRequirement, this.version).write(script);
264
254
  const openApi2MediaTypes = (this.requirement.get("produces")?.data ??
265
255
  this.requirement.specification?.rootRequirement?.get("produces")
266
256
  ?.data);
267
257
  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>";
258
+ const proxyType = functionType([parameter("url", stringType())], typeReference("COUNTERFACT_RESPONSE"));
259
+ const delayType = functionType([
260
+ parameter("milliseconds", numberType()),
261
+ parameter("maxMilliseconds", numberType(), true),
262
+ ], typeReference("Promise", [
263
+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword),
264
+ ]));
270
265
  const queryTypeName = this.exportParameterType(script, "query", queryType, baseName, modulePath);
271
266
  const pathTypeName = this.exportParameterType(script, "path", pathType, baseName, modulePath);
272
267
  const headersTypeName = this.exportParameterType(script, "headers", headersType, baseName, modulePath);
@@ -276,46 +271,54 @@ export class OperationTypeCoder extends TypeCoder {
276
271
  const querystringParam = parameters?.find((parameter) => parameter.get("in")?.data === "querystring");
277
272
  const querystringType = querystringParam?.has("schema") === true
278
273
  ? new SchemaTypeCoder(querystringParam.get("schema"), this.version).write(script)
279
- : "never";
274
+ : neverType();
280
275
  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} }>`;
276
+ const versionLiteralType = this.version !== "" ? literalType(this.version) : neverType();
277
+ return typeReference("OmitValueWhenNever", [
278
+ typeLiteral([
279
+ typeProperty("query", queryTypeName),
280
+ typeProperty("querystring", querystringTypeName),
281
+ typeProperty("path", pathTypeName),
282
+ typeProperty("headers", headersTypeName),
283
+ typeProperty("cookie", cookieTypeName),
284
+ typeProperty("body", bodyType),
285
+ typeProperty("context", typeReference(contextTypeImportName)),
286
+ typeProperty("response", responseType),
287
+ typeProperty("x", typeReference(xType)),
288
+ typeProperty("proxy", proxyType),
289
+ typeProperty("auth", this.authType()),
290
+ typeProperty("user", this.userType()),
291
+ typeProperty("delay", delayType),
292
+ typeProperty("version", versionLiteralType),
293
+ ]),
294
+ ]);
295
+ }
296
+ exportDeclarations(script, name) {
297
+ if (this.version === "")
298
+ return undefined;
299
+ script.comments = READ_ONLY_COMMENTS;
300
+ const versioned = script.importVersionsType("Versioned");
301
+ const promise = script.importSharedType("MaybePromise");
302
+ const response = script.importSharedType("COUNTERFACT_RESPONSE");
303
+ script.setVersionBuilder(this.getOperationBaseName(), (versions) => {
304
+ const mapName = `${name}_$_Versions`;
305
+ return [
306
+ typeAlias(mapName, typeLiteral([...versions].map(([version, type]) => typeProperty(version, type))), false),
307
+ typeAlias(name, functionType([
308
+ parameter("$", typeReference(versioned, [typeReference(mapName)])),
309
+ ], typeReference(promise, [typeReference(response)]))),
310
+ ];
311
+ });
312
+ return [];
283
313
  }
284
314
  writeCode(script) {
285
315
  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
316
  script.importSharedType("WideOperationArgument");
312
317
  script.importSharedType("OmitValueWhenNever");
313
318
  script.importSharedType("MaybePromise");
314
319
  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>`;
320
+ const arg = this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
321
+ return functionType([parameter("$", arg)], typeReference("MaybePromise", [typeReference("COUNTERFACT_RESPONSE")]));
319
322
  }
320
323
  }
321
324
  /**
@@ -332,6 +335,9 @@ export class OperationTypeCoder extends TypeCoder {
332
335
  * is assembled by the shared script's `versionsTypeStatements()`.
333
336
  */
334
337
  export class VersionedArgTypeCoder extends OperationTypeCoder {
338
+ get exportId() {
339
+ return this.id;
340
+ }
335
341
  /**
336
342
  * Include the version in the cache key so v1 and v2 coders are treated as
337
343
  * distinct exports even when they share the same requirement URL.
@@ -369,11 +375,14 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
369
375
  * When called from any other script (e.g. the shared file), export to the
370
376
  * per-version file and import the result back into that script.
371
377
  */
378
+ exportDeclarations() {
379
+ return undefined;
380
+ }
372
381
  write(script) {
373
382
  if (script.path === this.modulePath()) {
374
383
  return this.writeCode(script);
375
384
  }
376
- return script.importType(this);
385
+ return typeReference(script.importType(this));
377
386
  }
378
387
  /**
379
388
  * Generates the `OmitValueWhenNever<{…}>` dollar-argument type and writes
@@ -381,7 +390,6 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
381
390
  */
382
391
  writeCode(script) {
383
392
  script.comments = READ_ONLY_COMMENTS;
384
- const baseName = this.getOperationBaseName();
385
- return this.buildDollarArgType(script, baseName, this.modulePath());
393
+ return this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
386
394
  }
387
395
  }
@@ -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
  /**