@counterfact/generator 0.1.4 → 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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,41 @@
1
1
  # @counterfact/generator
2
2
 
3
+ ## 0.1.6
4
+
5
+ ### Patch Changes
6
+
7
+ - ce0bb3a: Generate TypeScript contracts, route scaffolds, versions, scenarios, middleware, and starter files from AST nodes. Preserve escaped literal names and enum values, and correctly group nested unions within intersections. Resolve context imports before printing and preserve existing route text when inserting new handlers, including function exports, aliases, and multiline imports.
8
+
9
+ Unsupported schema type strings produce `unknown` instead of being interpreted as TypeScript identifiers or syntax.
10
+
11
+ Keep shared handler exports stable across separate versioned specifications, and add missing runtime handlers alongside existing type-only declarations and re-exports.
12
+
13
+ - Updated dependencies [865750a]
14
+ - Updated dependencies [376ec98]
15
+ - Updated dependencies [91428ea]
16
+ - @counterfact/openapi@0.1.6
17
+
18
+ ## 0.1.5
19
+
20
+ ### Patch Changes
21
+
22
+ - 1714e9a: Classify OpenAPI sources consistently and hot-reload local base documents and overlays without mistaking local `http`-prefixed paths for remote URLs.
23
+ - 1145bb3: Updated dependency `prettier` in `@counterfact/generator` to `3.9.9`.
24
+ - 6d4af72: Updated dependency `prettier` in `@counterfact/generator` to `3.9.10`.
25
+ - Updated dependencies [1714e9a]
26
+ - Updated dependencies [a2ee147]
27
+ - Updated dependencies [dfe2472]
28
+ - Updated dependencies [25215f4]
29
+ - Updated dependencies [befb686]
30
+ - Updated dependencies [2e0cadd]
31
+ - Updated dependencies [15b30fb]
32
+ - Updated dependencies [cfcedc9]
33
+ - Updated dependencies [e5105a0]
34
+ - Updated dependencies [2707325]
35
+ - Updated dependencies [66ab7eb]
36
+ - Updated dependencies [d175f35]
37
+ - @counterfact/openapi@0.1.5
38
+
3
39
  ## 0.1.4
4
40
 
5
41
  ### Patch Changes
package/dist/ast.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import ts from "typescript";
2
+ export declare function printNode(node: ts.Node): string;
3
+ export declare function printStatements(statements: readonly ts.Statement[], comments?: readonly string[]): string;
4
+ export declare function formatStatements(statements: readonly ts.Statement[], comments?: readonly string[]): Promise<string>;
5
+ export declare function stringType(): ts.TypeNode;
6
+ export declare function numberType(): ts.TypeNode;
7
+ export declare function literalType(value: string | number | boolean | null): ts.LiteralTypeNode;
8
+ export declare function parameter(name: string, type?: ts.TypeNode, optional?: boolean): ts.ParameterDeclaration;
9
+ export declare function functionType(parameters: readonly ts.ParameterDeclaration[], result: ts.TypeNode): ts.FunctionTypeNode;
10
+ export declare function typeAlias(name: string, type: ts.TypeNode, exported?: boolean, parameters?: readonly ts.TypeParameterDeclaration[]): ts.TypeAliasDeclaration;
11
+ export declare function importDeclaration(name: string, modulePath: string, isType?: boolean, isDefault?: boolean, exportedName?: string): ts.ImportDeclaration;
12
+ export declare function valueExpression(value: unknown): ts.Expression;
13
+ export declare function objectExpression(entries: readonly (readonly [string, ts.Expression])[], multiline?: boolean): ts.ObjectLiteralExpression;
14
+ export declare function exportedConst(name: string, value: ts.Expression, type?: ts.TypeNode): ts.VariableStatement;
15
+ export declare function readonlyProperty(name: string, type: ts.TypeNode, description: string): ts.PropertySignature;
16
+ export declare function typeReference(name: string, arguments_?: readonly ts.TypeNode[]): ts.TypeReferenceNode;
17
+ export declare function unknownType(): ts.TypeNode;
18
+ export declare function neverType(): ts.TypeNode;
19
+ export declare function typeLiteral(members: readonly ts.TypeElement[], multiline?: boolean): ts.TypeLiteralNode;
20
+ export declare function unionType(types: readonly ts.TypeNode[]): ts.TypeNode;
21
+ export declare function withJsDoc<T extends ts.Node>(node: T, data: unknown): T;
22
+ export declare function withComment<T extends ts.Node>(node: T, comment: string): T;
23
+ export declare function typeProperty(name: string, type: ts.TypeNode, optional?: boolean, data?: unknown): ts.PropertySignature;
package/dist/ast.js ADDED
@@ -0,0 +1,142 @@
1
+ import ts from "typescript";
2
+ import { format } from "prettier";
3
+ import { buildJsDoc } from "./jsdoc.js";
4
+ const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });
5
+ const sourceFile = ts.createSourceFile("generated.ts", "", ts.ScriptTarget.Latest, false, ts.ScriptKind.TS);
6
+ export function printNode(node) {
7
+ return printer.printNode(ts.EmitHint.Unspecified, node, sourceFile);
8
+ }
9
+ export function printStatements(statements, comments = []) {
10
+ const nodes = [...statements];
11
+ if (comments.length > 0) {
12
+ const banner = ts.factory.createNotEmittedStatement(sourceFile);
13
+ for (const comment of comments) {
14
+ for (const line of comment.split("\n")) {
15
+ ts.addSyntheticLeadingComment(banner, ts.SyntaxKind.SingleLineCommentTrivia, ` ${line}`, true);
16
+ }
17
+ }
18
+ nodes.unshift(banner);
19
+ }
20
+ return printer.printFile(ts.factory.updateSourceFile(sourceFile, nodes));
21
+ }
22
+ export async function formatStatements(statements, comments = []) {
23
+ return format(printStatements(statements, comments), {
24
+ parser: "typescript",
25
+ });
26
+ }
27
+ export function stringType() {
28
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.StringKeyword);
29
+ }
30
+ export function numberType() {
31
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword);
32
+ }
33
+ export function literalType(value) {
34
+ let expression;
35
+ if (typeof value === "string")
36
+ expression = ts.factory.createStringLiteral(value);
37
+ else if (typeof value === "number") {
38
+ const number = ts.factory.createNumericLiteral(Math.abs(value));
39
+ expression =
40
+ value < 0
41
+ ? ts.factory.createPrefixUnaryExpression(ts.SyntaxKind.MinusToken, number)
42
+ : number;
43
+ }
44
+ else if (value === null)
45
+ expression = ts.factory.createNull();
46
+ else
47
+ expression = value ? ts.factory.createTrue() : ts.factory.createFalse();
48
+ return ts.factory.createLiteralTypeNode(expression);
49
+ }
50
+ export function parameter(name, type, optional = false) {
51
+ return ts.factory.createParameterDeclaration(undefined, undefined, name, optional ? ts.factory.createToken(ts.SyntaxKind.QuestionToken) : undefined, type);
52
+ }
53
+ export function functionType(parameters, result) {
54
+ return ts.factory.createFunctionTypeNode(undefined, parameters, result);
55
+ }
56
+ export function typeAlias(name, type, exported = true, parameters) {
57
+ return ts.factory.createTypeAliasDeclaration(exported
58
+ ? [ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)]
59
+ : undefined, name, parameters, type);
60
+ }
61
+ export function importDeclaration(name, modulePath, isType = false, isDefault = false, exportedName = name) {
62
+ return ts.factory.createImportDeclaration(undefined, ts.factory.createImportClause(isType, isDefault ? ts.factory.createIdentifier(name) : undefined, isDefault
63
+ ? undefined
64
+ : ts.factory.createNamedImports([
65
+ ts.factory.createImportSpecifier(false, exportedName === name
66
+ ? undefined
67
+ : ts.factory.createIdentifier(exportedName), ts.factory.createIdentifier(name)),
68
+ ])), ts.setEmitFlags(ts.factory.createStringLiteral(modulePath), ts.EmitFlags.NoAsciiEscaping));
69
+ }
70
+ export function valueExpression(value) {
71
+ // Normalize JSON data as the previous serializer did, including dates and
72
+ // omitted undefined properties. This parses data, never TypeScript fragments.
73
+ const json = JSON.stringify(value);
74
+ if (json === undefined)
75
+ throw new Error(`Cannot generate a JSON expression for ${typeof value}`);
76
+ return jsonExpression(JSON.parse(json));
77
+ }
78
+ function jsonExpression(value) {
79
+ if (value === null)
80
+ return ts.factory.createNull();
81
+ if (typeof value === "string")
82
+ return ts.factory.createStringLiteral(value);
83
+ if (typeof value === "number")
84
+ return literalType(value).literal;
85
+ if (typeof value === "boolean")
86
+ return value ? ts.factory.createTrue() : ts.factory.createFalse();
87
+ if (Array.isArray(value))
88
+ return ts.factory.createArrayLiteralExpression(value.map(jsonExpression));
89
+ if (typeof value === "object")
90
+ return objectExpression(Object.entries(value).map(([name, item]) => [name, jsonExpression(item)]));
91
+ throw new Error(`Cannot generate a JSON expression for ${typeof value}`);
92
+ }
93
+ export function objectExpression(entries, multiline = false) {
94
+ return ts.factory.createObjectLiteralExpression(entries.map(([name, value]) => ts.factory.createPropertyAssignment(name === "__proto__"
95
+ ? ts.factory.createComputedPropertyName(ts.factory.createStringLiteral(name))
96
+ : ts.factory.createStringLiteral(name), value)), multiline);
97
+ }
98
+ export function exportedConst(name, value, type) {
99
+ return ts.factory.createVariableStatement([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], ts.factory.createVariableDeclarationList([ts.factory.createVariableDeclaration(name, undefined, type, value)], ts.NodeFlags.Const));
100
+ }
101
+ export function readonlyProperty(name, type, description) {
102
+ return withJsDoc(ts.factory.createPropertySignature([ts.factory.createModifier(ts.SyntaxKind.ReadonlyKeyword)], name, undefined, type), { description });
103
+ }
104
+ export function typeReference(name, arguments_ = []) {
105
+ return ts.factory.createTypeReferenceNode(name, arguments_);
106
+ }
107
+ export function unknownType() {
108
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword);
109
+ }
110
+ export function neverType() {
111
+ return ts.factory.createKeywordTypeNode(ts.SyntaxKind.NeverKeyword);
112
+ }
113
+ export function typeLiteral(members, multiline = false) {
114
+ const node = ts.factory.createTypeLiteralNode(members);
115
+ // Keep JSDoc on its own line and attached to the following member.
116
+ return multiline ||
117
+ members.some((member) => ts.getSyntheticLeadingComments(member)?.length)
118
+ ? node
119
+ : ts.setEmitFlags(node, ts.EmitFlags.SingleLine);
120
+ }
121
+ export function unionType(types) {
122
+ return types.length === 0
123
+ ? neverType()
124
+ : ts.factory.createUnionTypeNode(types);
125
+ }
126
+ export function withJsDoc(node, data) {
127
+ const comment = buildJsDoc(data);
128
+ return withComment(node, comment);
129
+ }
130
+ export function withComment(node, comment) {
131
+ if (comment === "") {
132
+ return node;
133
+ }
134
+ return ts.addSyntheticLeadingComment(node, ts.SyntaxKind.MultiLineCommentTrivia, comment.slice(2, comment.lastIndexOf("*/")).replaceAll("*/", "* /"), true);
135
+ }
136
+ export function typeProperty(name, type, optional = false, data) {
137
+ return withJsDoc(ts.factory.createPropertySignature(undefined, /^[A-Za-z_$][\w$]*$/u.test(name)
138
+ ? ts.factory.createIdentifier(name)
139
+ : ts.factory.createStringLiteral(name), optional
140
+ ? ts.factory.createToken(ts.SyntaxKind.QuestionToken)
141
+ : undefined, type), data);
142
+ }
@@ -4,6 +4,7 @@ import nodePath from "node:path";
4
4
  /* eslint-disable security/detect-non-literal-fs-filename -- generated files are written under the caller-provided destination tree. */
5
5
  import { watch } from "chokidar";
6
6
  import createDebug from "debug";
7
+ import { getLocalOpenApiSourcePaths } from "@counterfact/openapi";
7
8
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
8
9
  import { OperationCoder } from "./operation-coder.js";
9
10
  import { assertNoNormalizedPathCollisions, normalizeOpenApiPath, } from "./openapi-path.js";
@@ -158,9 +159,10 @@ export class CodeGenerator extends EventTarget {
158
159
  * Resolves once the watcher is ready.
159
160
  */
160
161
  async watch() {
161
- const watchablePaths = this.openapiPath.startsWith("http")
162
- ? [...this.overlays]
163
- : [this.openapiPath, ...this.overlays];
162
+ const watchablePaths = getLocalOpenApiSourcePaths([
163
+ this.openapiPath,
164
+ ...this.overlays,
165
+ ]);
164
166
  if (watchablePaths.length === 0) {
165
167
  return;
166
168
  }
package/dist/coder.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import type { Requirement } from "./requirement.js";
2
3
  import type { Script } from "./script.js";
3
4
  /**
@@ -5,7 +6,7 @@ import type { Script } from "./script.js";
5
6
  *
6
7
  * A `Coder` wraps a single {@link Requirement} node from the OpenAPI spec and
7
8
  * knows how to emit TypeScript code for it. Subclasses override
8
- * {@link writeCode} to produce the actual source text.
9
+ * {@link writeCode} to produce an AST node.
9
10
  *
10
11
  * Coders are used by {@link Script} and {@link Repository} to lazily generate
11
12
  * exports and imports, resolving `$ref` references through the
@@ -20,15 +21,10 @@ export declare class Coder {
20
21
  * either the `$ref` value (for references) or the requirement URL.
21
22
  */
22
23
  get id(): string;
23
- /**
24
- * Optional preamble emitted before the `export` keyword.
25
- *
26
- * Subclasses can return a string (e.g. a type alias) that must appear in the
27
- * output before this coder's export statement.
28
- *
29
- * @param _path - The path of the script being written (unused in base class).
30
- */
31
- beforeExport(_path?: string): string;
24
+ /** Identity of a logical export, which may be shared by versioned inputs. */
25
+ get exportId(): string;
26
+ /** Override when one export requires several declarations or deferred assembly. */
27
+ exportDeclarations(_script: Script, _name: string): ts.Statement[] | undefined;
32
28
  /**
33
29
  * Returns a JSDoc comment block to be placed immediately before the export.
34
30
  *
@@ -44,18 +40,18 @@ export declare class Coder {
44
40
  * {@link writeCode}.
45
41
  *
46
42
  * @param script - The script being assembled.
47
- * @returns The TypeScript source text for this coder's export value.
43
+ * @returns The type or expression node for this coder's export value.
48
44
  */
49
- write(script: Script): string;
45
+ write(script: Script): ts.Expression | ts.TypeNode;
50
46
  /**
51
- * Generates the TypeScript source text for this coder's value.
47
+ * Generates the AST node for this coder's value.
52
48
  *
53
49
  * This method is abstract — subclasses **must** override it.
54
50
  *
55
51
  * @param _script - The script being assembled.
56
52
  * @throws Always — callers should never reach the base implementation.
57
53
  */
58
- writeCode(_script: Script): string;
54
+ writeCode(_script: Script): ts.Expression | ts.TypeNode;
59
55
  /**
60
56
  * Resolves `$ref` references by returning the target coder.
61
57
  *
@@ -75,12 +71,12 @@ export declare class Coder {
75
71
  */
76
72
  names(rawName?: string): Generator<string>;
77
73
  /**
78
- * Returns an optional TypeScript type annotation string to be placed between
74
+ * Returns an optional TypeScript type annotation node to be placed between
79
75
  * the export name and its value (`export const name: <type> = value`).
80
76
  *
81
- * Returns `""` by default.
77
+ * Returns `undefined` by default.
82
78
  */
83
- typeDeclaration(_namespace?: Map<string, ExportStatement>, _script?: Script): string;
79
+ typeDeclaration(_namespace?: Map<string, ExportStatement>, _script?: Script): ts.TypeNode | undefined;
84
80
  /**
85
81
  * Returns the repository-relative path of the script where this coder's
86
82
  * export should live when imported by another script.
@@ -91,17 +87,15 @@ export declare class Coder {
91
87
  modulePath(): string;
92
88
  }
93
89
  export interface ExportStatement {
94
- beforeExport: string;
95
90
  done: boolean;
96
91
  id: string;
97
92
  isDefault: boolean;
98
93
  isType: boolean;
99
94
  jsdoc: string;
100
- typeDeclaration: string;
95
+ typeDeclaration?: ts.TypeNode;
101
96
  name?: string;
102
- code?: string | {
103
- raw: string;
104
- };
97
+ node?: ts.Expression | ts.TypeNode;
98
+ statements?: ts.Statement[];
105
99
  error?: Error;
106
100
  promise?: Promise<Coder | undefined>;
107
101
  }
package/dist/coder.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { RESERVED_WORDS } from "./reserved-words.js";
2
+ import ts from "typescript";
2
3
  /**
3
4
  * Base class for all code-generation helpers in the TypeScript generator.
4
5
  *
5
6
  * A `Coder` wraps a single {@link Requirement} node from the OpenAPI spec and
6
7
  * knows how to emit TypeScript code for it. Subclasses override
7
- * {@link writeCode} to produce the actual source text.
8
+ * {@link writeCode} to produce an AST node.
8
9
  *
9
10
  * Coders are used by {@link Script} and {@link Repository} to lazily generate
10
11
  * exports and imports, resolving `$ref` references through the
@@ -27,16 +28,13 @@ export class Coder {
27
28
  }
28
29
  return `${this.constructor.name}@${this.requirement.url}`;
29
30
  }
30
- /**
31
- * Optional preamble emitted before the `export` keyword.
32
- *
33
- * Subclasses can return a string (e.g. a type alias) that must appear in the
34
- * output before this coder's export statement.
35
- *
36
- * @param _path - The path of the script being written (unused in base class).
37
- */
38
- beforeExport(_path) {
39
- return "";
31
+ /** Identity of a logical export, which may be shared by versioned inputs. */
32
+ get exportId() {
33
+ return this.id;
34
+ }
35
+ /** Override when one export requires several declarations or deferred assembly. */
36
+ exportDeclarations(_script, _name) {
37
+ return undefined;
40
38
  }
41
39
  /**
42
40
  * Returns a JSDoc comment block to be placed immediately before the export.
@@ -55,16 +53,16 @@ export class Coder {
55
53
  * {@link writeCode}.
56
54
  *
57
55
  * @param script - The script being assembled.
58
- * @returns The TypeScript source text for this coder's export value.
56
+ * @returns The type or expression node for this coder's export value.
59
57
  */
60
58
  write(script) {
61
59
  if (this.requirement.isReference) {
62
- return script.import(this);
60
+ return ts.factory.createIdentifier(script.import(this));
63
61
  }
64
62
  return this.writeCode(script);
65
63
  }
66
64
  /**
67
- * Generates the TypeScript source text for this coder's value.
65
+ * Generates the AST node for this coder's value.
68
66
  *
69
67
  * This method is abstract — subclasses **must** override it.
70
68
  *
@@ -111,13 +109,13 @@ export class Coder {
111
109
  }
112
110
  }
113
111
  /**
114
- * Returns an optional TypeScript type annotation string to be placed between
112
+ * Returns an optional TypeScript type annotation node to be placed between
115
113
  * the export name and its value (`export const name: <type> = value`).
116
114
  *
117
- * Returns `""` by default.
115
+ * Returns `undefined` by default.
118
116
  */
119
117
  typeDeclaration(_namespace, _script) {
120
- return "";
118
+ return undefined;
121
119
  }
122
120
  /**
123
121
  * Returns the repository-relative path of the script where this coder's
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { Coder } from "./coder.js";
2
3
  import { type SecurityScheme } from "./operation-type-coder.js";
3
4
  import type { Requirement } from "./requirement.js";
@@ -16,8 +17,9 @@ export declare class OperationCoder extends Coder {
16
17
  requestMethod: string;
17
18
  securitySchemes: SecurityScheme[];
18
19
  constructor(requirement: Requirement, version?: string, requestMethod?: string, securitySchemes?: SecurityScheme[]);
20
+ get exportId(): string;
19
21
  names(): Generator<string>;
20
- write(): string;
21
- typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script): string;
22
+ write(): ts.Expression;
23
+ typeDeclaration(_namespace: Map<string, unknown> | undefined, script: Script): ts.TypeNode;
22
24
  modulePath(): string;
23
25
  }
@@ -1,5 +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 ts from "typescript";
4
+ import { parameter, typeReference } from "./ast.js";
3
5
  import { Coder } from "./coder.js";
4
6
  import { normalizeOpenApiPath } from "./openapi-path.js";
5
7
  import { OperationTypeCoder, VersionedArgTypeCoder, } from "./operation-type-coder.js";
@@ -24,35 +26,46 @@ export class OperationCoder extends Coder {
24
26
  this.requestMethod = requestMethod;
25
27
  this.securitySchemes = securitySchemes;
26
28
  }
29
+ get exportId() {
30
+ return this.version === ""
31
+ ? this.id
32
+ : `${this.constructor.name}@${this.modulePath()}:${this.requestMethod.toLowerCase()}`;
33
+ }
27
34
  names() {
28
35
  return super.names(this.requestMethod.toUpperCase());
29
36
  }
30
37
  write() {
31
38
  const responses = this.requirement.get("responses");
32
- const [firstStatusCode] = responses.map((_response, statusCode) => statusCode);
33
- const [firstResponse] = responses.map((response) => response.data);
34
- if (firstResponse === undefined ||
35
- !("content" in firstResponse || "schema" in firstResponse)) {
36
- return `async ($) => {
37
- return $.response[${firstStatusCode === "default" ? 200 : firstStatusCode}].empty();
38
- }`;
39
- }
40
- // Detect streaming responses (OpenAPI 3.2 itemSchema)
41
- const content = firstResponse.content;
42
- const hasStreamingContent = content !== undefined &&
43
- Object.keys(content).some((ct) => STREAMING_CONTENT_TYPES.has(ct) &&
44
- content[ct]?.itemSchema !== undefined);
45
- if (hasStreamingContent) {
46
- return `async ($) => {
47
- async function* items() {
48
- // yield items here
49
- }
50
- return $.response[${firstStatusCode === "default" ? 200 : firstStatusCode}].stream(items());
51
- }`;
39
+ const [status] = responses.map((_response, code) => code);
40
+ const [response] = responses.map((item) => item.data);
41
+ const content = response?.content;
42
+ const streaming = content !== undefined &&
43
+ Object.keys(content).some((media) => STREAMING_CONTENT_TYPES.has(media) &&
44
+ content[media]?.itemSchema !== undefined);
45
+ const method = streaming
46
+ ? "stream"
47
+ : response !== undefined &&
48
+ ("content" in response || "schema" in response)
49
+ ? "random"
50
+ : "empty";
51
+ const statements = [];
52
+ if (streaming) {
53
+ const placeholder = ts.factory.createNotEmittedStatement(ts.factory.createIdentifier("items"));
54
+ ts.addSyntheticLeadingComment(placeholder, ts.SyntaxKind.SingleLineCommentTrivia, " yield items here", true);
55
+ const body = ts.factory.createBlock([placeholder], true);
56
+ statements.push(ts.factory.createFunctionDeclaration([ts.factory.createModifier(ts.SyntaxKind.AsyncKeyword)], ts.factory.createToken(ts.SyntaxKind.AsteriskToken), "items", undefined, [], undefined, body));
52
57
  }
53
- return `async ($) => {
54
- return $.response[${firstStatusCode === "default" ? 200 : firstStatusCode}].random();
55
- }`;
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
63
+ ? [
64
+ ts.factory.createCallExpression(ts.factory.createIdentifier("items"), undefined, []),
65
+ ]
66
+ : []);
67
+ statements.push(ts.factory.createReturnStatement(result));
68
+ return ts.factory.createArrowFunction([ts.factory.createModifier(ts.SyntaxKind.AsyncKeyword)], undefined, [parameter("$")], undefined, ts.factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken), ts.factory.createBlock(statements, true));
56
69
  }
57
70
  typeDeclaration(_namespace, script) {
58
71
  const operationTypeCoder = new OperationTypeCoder(this.requirement, this.version, this.requestMethod, this.securitySchemes);
@@ -64,7 +77,7 @@ export class OperationCoder extends Coder {
64
77
  const sharedScript = script.repository.get(operationTypeCoder.modulePath());
65
78
  sharedScript.declareVersion(versionedArgCoder, operationTypeCoder.getOperationBaseName());
66
79
  }
67
- return script.importType(operationTypeCoder);
80
+ return typeReference(script.importType(operationTypeCoder));
68
81
  }
69
82
  modulePath() {
70
83
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -1,3 +1,4 @@
1
+ import ts from "typescript";
1
2
  import { TypeCoder } from "./type-coder.js";
2
3
  import { Requirement } from "./requirement.js";
3
4
  import type { Script } from "./script.js";
@@ -16,11 +17,7 @@ export interface SecurityScheme {
16
17
  *
17
18
  * Output is written to `types/paths/<route>.types.ts`.
18
19
  *
19
- * **Versioned APIs**: when `version` is non-empty this coder emits only a
20
- * sentinel `{raw: ""}` export (suppressing the normal flat type) and
21
- * registers a formatter on the shared script so that
22
- * {@link Script.versionsTypeStatements} can later emit the merged
23
- * `HTTP_<METHOD>_$_Versions` map and the `HTTP_<METHOD>` handler type.
20
+ * **Versioned APIs** register a declaration builder on the shared script.
24
21
  * Each version's `$`-argument type is emitted to
25
22
  * `types/<version>/paths/<path>.types.ts` by {@link VersionedArgTypeCoder}.
26
23
  */
@@ -34,6 +31,7 @@ export declare class OperationTypeCoder extends TypeCoder {
34
31
  */
35
32
  getOperationBaseName(): string;
36
33
  jsdoc(): string;
34
+ get exportId(): string;
37
35
  names(): Generator<string>;
38
36
  /**
39
37
  * Generates and exports a named parameter type (e.g. `ListPets_Query`) from
@@ -44,17 +42,17 @@ export declare class OperationTypeCoder extends TypeCoder {
44
42
  *
45
43
  * @param script - The script being assembled.
46
44
  * @param parameterKind - `"query"`, `"path"`, `"headers"`, or `"cookie"`.
47
- * @param inlineType - The inline TypeScript type string to export.
45
+ * @param inlineType - The inline TypeScript type node to export.
48
46
  * @param baseName - The base identifier prefix for the exported type name.
49
47
  * @param modulePath - The repository-relative path of the type file.
50
48
  */
51
- exportParameterType(script: Script, parameterKind: string, inlineType: string, baseName: string, modulePath: string): string;
49
+ exportParameterType(script: Script, parameterKind: string, inlineType: ts.TypeNode, baseName: string, modulePath: string): ts.TypeNode;
52
50
  /**
53
51
  * Returns the union of all possible response type shapes for this operation.
54
52
  *
55
53
  * @param script - The script being assembled (used to resolve imports).
56
54
  */
57
- responseTypes(script: Script): string;
55
+ responseTypes(script: Script): ts.TypeNode;
58
56
  modulePath(): string;
59
57
  /**
60
58
  * Returns the TypeScript type for the `user` argument.
@@ -62,14 +60,8 @@ export declare class OperationTypeCoder extends TypeCoder {
62
60
  * When the operation is protected by HTTP Basic auth, the type is
63
61
  * `{username?: string, password?: string}`. Otherwise it is `"never"`.
64
62
  */
65
- userType(): string;
66
- /**
67
- * Returns the TypeScript type for the `auth` argument.
68
- *
69
- * Includes basic-auth credentials when present and `apiKey` when at least one
70
- * apiKey security scheme is configured.
71
- */
72
- authType(): string;
63
+ userType(): ts.TypeNode;
64
+ authType(): ts.TypeNode;
73
65
  /**
74
66
  * Returns the effective parameters for this operation by merging path-item-level
75
67
  * parameters with operation-level parameters. Per the OpenAPI specification,
@@ -94,8 +86,9 @@ export declare class OperationTypeCoder extends TypeCoder {
94
86
  * @param baseName - Identifier prefix used for named parameter-type exports.
95
87
  * @param modulePath - Repository-relative path for parameter-type exports.
96
88
  */
97
- protected buildDollarArgType(script: Script, baseName: string, modulePath: string): string;
98
- writeCode(script: Script): string;
89
+ protected buildDollarArgType(script: Script, baseName: string, modulePath: string): ts.TypeNode;
90
+ exportDeclarations(script: Script, name: string): ts.Statement[] | undefined;
91
+ writeCode(script: Script): ts.TypeNode;
99
92
  }
100
93
  /**
101
94
  * Emits a per-version `$`-argument type to
@@ -111,6 +104,7 @@ export declare class OperationTypeCoder extends TypeCoder {
111
104
  * is assembled by the shared script's `versionsTypeStatements()`.
112
105
  */
113
106
  export declare class VersionedArgTypeCoder extends OperationTypeCoder {
107
+ get exportId(): string;
114
108
  /**
115
109
  * Include the version in the cache key so v1 and v2 coders are treated as
116
110
  * distinct exports even when they share the same requirement URL.
@@ -131,10 +125,11 @@ export declare class VersionedArgTypeCoder extends OperationTypeCoder {
131
125
  * When called from any other script (e.g. the shared file), export to the
132
126
  * per-version file and import the result back into that script.
133
127
  */
134
- write(script: Script): string;
128
+ exportDeclarations(): undefined;
129
+ write(script: Script): ts.TypeNode;
135
130
  /**
136
131
  * Generates the `OmitValueWhenNever<{…}>` dollar-argument type and writes
137
132
  * it to the per-version script.
138
133
  */
139
- writeCode(script: Script): string;
134
+ writeCode(script: Script): ts.TypeNode;
140
135
  }