@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/dist/script.d.ts CHANGED
@@ -27,13 +27,16 @@ export declare class Script {
27
27
  imports: Map<string, ImportEntry>;
28
28
  externalImport: Map<string, ExternalImportEntry>;
29
29
  cache: Map<string, string>;
30
+ reservedNames: Set<string>;
31
+ localTypes: Map<string, ts.TypeNode>;
32
+ statementBuilders: Map<string, () => ts.Statement[]>;
30
33
  constructor(repository: Repository, path: string);
31
34
  get relativePathToBase(): string;
32
35
  firstUniqueName(coder: Coder, isType?: boolean, isDefault?: boolean): string;
33
36
  export(coder: Coder, isType?: boolean, isDefault?: boolean): string;
34
37
  exportDefault(coder: Coder, isType?: boolean): void;
35
- import(coder: Coder, isType?: boolean, isDefault?: boolean): string;
36
- importType(coder: Coder): string;
38
+ import(coder: Coder, isType?: boolean, isDefault?: boolean, preferredName?: string): string;
39
+ importType(coder: Coder, preferredName?: string): string;
37
40
  importDefault(coder: Coder, isType?: boolean): string;
38
41
  importExternal(name: string, modulePath: ModuleReference, isType?: boolean): string;
39
42
  importExternalType(name: string, path: ModuleReference): string;
package/dist/script.js CHANGED
@@ -15,6 +15,9 @@ export class Script {
15
15
  imports = new Map();
16
16
  externalImport = new Map();
17
17
  cache = new Map();
18
+ reservedNames = new Set();
19
+ localTypes = new Map();
20
+ statementBuilders = new Map();
18
21
  constructor(repository, path) {
19
22
  this.path = path;
20
23
  this.repository = repository;
@@ -28,10 +31,12 @@ export class Script {
28
31
  }
29
32
  firstUniqueName(coder, isType = false, isDefault = false) {
30
33
  for (const name of coder.names()) {
31
- if ((!this.imports.has(name) ||
32
- (this.imports.get(name).id === coder.exportId &&
33
- this.imports.get(name).isType === isType &&
34
- this.imports.get(name).isDefault === isDefault)) &&
34
+ if (!this.reservedNames.has(name) &&
35
+ (!this.imports.has(name) ||
36
+ (this.imports.get(name).id === coder.exportId &&
37
+ this.imports.get(name).script.path === coder.modulePath() &&
38
+ this.imports.get(name).isType === isType &&
39
+ this.imports.get(name).isDefault === isDefault)) &&
35
40
  (!this.exports.has(name) ||
36
41
  (this.exports.get(name).id === coder.exportId &&
37
42
  this.exports.get(name).isType === isType &&
@@ -80,14 +85,25 @@ export class Script {
80
85
  exportDefault(coder, isType = false) {
81
86
  this.export(coder, isType, true);
82
87
  }
83
- import(coder, isType = false, isDefault = false) {
88
+ import(coder, isType = false, isDefault = false, preferredName) {
84
89
  const modulePath = coder.modulePath();
85
90
  const key = `${coder.id}@${modulePath}:${isType}:${isDefault}`;
86
91
  if (this.cache.has(key))
87
92
  return this.cache.get(key);
88
93
  if (modulePath === this.path)
89
94
  return this.export(coder, isType, isDefault);
90
- const name = this.firstUniqueName(coder, isType, isDefault);
95
+ let name;
96
+ if (preferredName) {
97
+ name = preferredName;
98
+ let suffix = 2;
99
+ while (this.imports.has(name) ||
100
+ this.exports.has(name) ||
101
+ this.externalImport.has(name) ||
102
+ this.reservedNames.has(name))
103
+ name = preferredName + suffix++;
104
+ }
105
+ else
106
+ name = this.firstUniqueName(coder, isType, isDefault);
91
107
  this.cache.set(key, name);
92
108
  const script = this.repository.get(modulePath);
93
109
  const exportedName = script.export(coder, isType, isDefault);
@@ -101,8 +117,8 @@ export class Script {
101
117
  debug("import %s as %s from %s", exportedName, name, modulePath);
102
118
  return name;
103
119
  }
104
- importType(coder) {
105
- return this.import(coder, true);
120
+ importType(coder, preferredName) {
121
+ return this.import(coder, true, false, preferredName);
106
122
  }
107
123
  importDefault(coder, isType = false) {
108
124
  return this.import(coder, isType, true);
@@ -241,7 +257,9 @@ export class Script {
241
257
  ...this.externalImportStatements(contextPath),
242
258
  ...this.importStatements(),
243
259
  ...this.versionsTypeStatements(),
260
+ ...[...this.localTypes].map(([name, type]) => typeAlias(name, type, false)),
244
261
  ...this.exportStatements(),
262
+ ...[...this.statementBuilders.values()].flatMap((build) => build()),
245
263
  ], this.comments);
246
264
  }
247
265
  }
@@ -1,3 +1,4 @@
1
+ import type { CookieOptions } from "./cookie-options.js";
1
2
  import type { COUNTERFACT_RESPONSE } from "./counterfact-response.js";
2
3
  import type { HttpStatusCode } from "./http-status-code.js";
3
4
  import type { MaybePromise } from "./maybe-promise.js";
@@ -26,8 +27,20 @@ export interface MiddlewareTools {
26
27
 
27
28
  /** A response-builder factory with every standard status code available. */
28
29
  export type MiddlewareResponseBuilderFactory = {
30
+ /** @deprecated Use response.status(statusCode) instead. */
29
31
  [StatusCode in HttpStatusCode]: ResponseBuilder;
30
- } & { [key: number | `${number} ${string}`]: ResponseBuilder };
32
+ } & {
33
+ /** @deprecated Use response.status(statusCode) instead. */
34
+ [key: number | `${number} ${string}`]: ResponseBuilder;
35
+ } & {
36
+ status: (statusCode: number | `${number} ${string}`) => ResponseBuilder;
37
+ header: (name: string, value: string) => MiddlewareResponseBuilderFactory;
38
+ cookie: (
39
+ name: string,
40
+ value: string,
41
+ options?: CookieOptions,
42
+ ) => MiddlewareResponseBuilderFactory;
43
+ };
31
44
 
32
45
  /**
33
46
  * The request argument passed to a custom middleware function.
@@ -74,7 +87,7 @@ export type RespondTo<Context = unknown> = (
74
87
  *
75
88
  * export const middleware: Middleware<Context> = async ($, respondTo) => {
76
89
  * if (!$.context.isAuthorized($.auth?.apiKey)) {
77
- * return $.response[401].json({ error: "Unauthorized" });
90
+ * return $.response.status(401).json({ error: "Unauthorized" });
78
91
  * }
79
92
  *
80
93
  * return respondTo($);
@@ -1,16 +1,112 @@
1
+ import type { CookieOptions } from "./cookie-options.js";
1
2
  import type { GenericResponseBuilder } from "./generic-response-builder.js";
2
- import type { OpenApiResponses } from "./open-api-response.js";
3
+ import type { OpenApiResponse, OpenApiResponses } from "./open-api-response.js";
4
+
5
+ type StatusCodes<Responses> =
6
+ | keyof Responses
7
+ | {
8
+ [Key in keyof Responses]: Key extends `${infer Code extends number}`
9
+ ? Code
10
+ : never;
11
+ }[keyof Responses];
12
+
13
+ type ResponseAt<Responses, Code> = Code extends keyof Responses
14
+ ? Responses[Code]
15
+ : Code extends number
16
+ ? `${Code}` extends keyof Responses
17
+ ? Responses[`${Code}`]
18
+ : Responses extends { default: infer Default }
19
+ ? Default
20
+ : never
21
+ : Responses extends { default: infer Default }
22
+ ? Default
23
+ : never;
24
+
25
+ type HeaderNames<Responses extends OpenApiResponses> = {
26
+ [Code in keyof Responses]: [Responses[Code]["headers"]] extends [never]
27
+ ? never
28
+ : keyof Responses[Code]["headers"];
29
+ }[keyof Responses] &
30
+ string;
31
+
32
+ type HeaderValues<Responses extends OpenApiResponses, Name extends string> = {
33
+ [Code in keyof Responses]: Name extends keyof Responses[Code]["headers"]
34
+ ? Responses[Code]["headers"][Name]["schema"]
35
+ : never;
36
+ }[keyof Responses];
37
+
38
+ // Filter each response independently, preserving the relationship between a
39
+ // status code and its remaining body/header requirements.
40
+ type WithHeader<
41
+ Responses extends OpenApiResponses,
42
+ Name extends string,
43
+ Value,
44
+ > = {
45
+ [
46
+ Code in keyof Responses as [Responses[Code]["headers"]] extends [never]
47
+ ? never
48
+ : [Name] extends [keyof Responses[Code]["headers"]]
49
+ ? [Value] extends [Responses[Code]["headers"][Name]["schema"]]
50
+ ? Code
51
+ : never
52
+ : never
53
+ ]: {
54
+ content: Responses[Code]["content"];
55
+ headers: Omit<Responses[Code]["headers"], Name>;
56
+ requiredHeaders: Exclude<Responses[Code]["requiredHeaders"], Name>;
57
+ };
58
+ };
3
59
 
4
60
  /**
5
- * Maps each HTTP status code (or `"default"`) in an OpenAPI operation's
6
- * response definitions to the corresponding `GenericResponseBuilder`.
7
- * This is the type of the `response` property in a generated route handler's
8
- * argument object, allowing handlers to call e.g. `response[200].json(body)`.
61
+ * Select a response with `response.status(200)`.
62
+ * Headers supplied before selection narrow the available status codes and
63
+ * satisfy the same requirements as headers supplied after selection.
9
64
  */
10
65
  export type ResponseBuilderFactory<
11
66
  Responses extends OpenApiResponses = OpenApiResponses,
67
+ ExcludedStatuses extends PropertyKey = never,
12
68
  > = {
69
+ /** @deprecated Use response.status(statusCode) instead. */
13
70
  [StatusCode in keyof Responses]: GenericResponseBuilder<
14
71
  Responses[StatusCode]
15
72
  >;
16
- } & { [key: string]: GenericResponseBuilder<Responses["default"]> };
73
+ } & {
74
+ /** @deprecated Use response.status(statusCode) instead. */
75
+ [key: string]: GenericResponseBuilder<Responses["default"]>;
76
+ } & {
77
+ status: <
78
+ Code extends
79
+ | StatusCodes<Responses>
80
+ | ("default" extends keyof Responses
81
+ ? number | `${number} ${string}`
82
+ : never),
83
+ >(
84
+ statusCode: Code extends ExcludedStatuses
85
+ ? never
86
+ : Code extends number
87
+ ? `${Code}` extends ExcludedStatuses
88
+ ? never
89
+ : Code
90
+ : Code,
91
+ ) => Code extends unknown
92
+ ? ResponseAt<Responses, Code> extends infer Response extends OpenApiResponse
93
+ ? GenericResponseBuilder<Response>
94
+ : never
95
+ : never;
96
+ header: <
97
+ Name extends HeaderNames<Responses>,
98
+ const Value extends HeaderValues<Responses, Name>,
99
+ >(
100
+ name: Name,
101
+ value: Value,
102
+ ) => ResponseBuilderFactory<
103
+ WithHeader<Responses, Name, Value>,
104
+ | ExcludedStatuses
105
+ | Exclude<keyof Responses, keyof WithHeader<Responses, Name, Value>>
106
+ >;
107
+ cookie: (
108
+ name: string,
109
+ value: string,
110
+ options?: CookieOptions,
111
+ ) => ResponseBuilderFactory<Responses, ExcludedStatuses>;
112
+ };
@@ -8,6 +8,7 @@ import type { MaybePromise } from "./maybe-promise.js";
8
8
  * strongly-typed `GenericResponseBuilder`.
9
9
  */
10
10
  export interface ResponseBuilder {
11
+ /** @deprecated Select a status with response.status(statusCode) instead. */
11
12
  [status: number | `${number} ${string}`]: ResponseBuilder;
12
13
  binary: (body: Uint8Array | string) => ResponseBuilder;
13
14
  content?: { body: unknown; type: string }[];
@@ -1,3 +1,4 @@
1
+ import type { CookieOptions } from "./cookie-options.js";
1
2
  import type { HttpStatusCode } from "./http-status-code.js";
2
3
  import type { WideResponseBuilder } from "./wide-response-builder.js";
3
4
 
@@ -14,7 +15,18 @@ export interface WideOperationArgument {
14
15
  path: { [key: string]: string };
15
16
  proxy: (url: string) => { proxyUrl: string };
16
17
  query: { [key: string]: string };
17
- response: { [StatusCode in HttpStatusCode]: WideResponseBuilder } & {
18
+ response: {
19
+ /** @deprecated Use response.status(statusCode) instead. */
20
+ [StatusCode in HttpStatusCode]: WideResponseBuilder;
21
+ } & {
22
+ /** @deprecated Use response.status(statusCode) instead. */
18
23
  [key: number]: WideResponseBuilder;
24
+ status: (statusCode: number | `${number} ${string}`) => WideResponseBuilder;
25
+ header: (name: string, value: string) => WideOperationArgument["response"];
26
+ cookie: (
27
+ name: string,
28
+ value: string,
29
+ options?: CookieOptions,
30
+ ) => WideOperationArgument["response"];
19
31
  };
20
32
  }
@@ -1,5 +1,5 @@
1
1
  import ts from "typescript";
2
- import { formatStatements, literalType, parameter, typeAlias, typeLiteral, typeProperty, typeReference, unionType, withJsDoc, } from "./ast.js";
2
+ import { formatStatements, literalType, neverType, stringType, parameter, typeAlias, typeLiteral, typeProperty, typeReference, unionType, withJsDoc, } from "./ast.js";
3
3
  function buildVersionsGTE(versions) {
4
4
  return new Map(versions.map((version, index) => [version, versions.slice(index)]));
5
5
  }
@@ -10,10 +10,11 @@ const VERSIONED_DESCRIPTION = `The type of the \u0060$\u0060 argument in a versi
10
10
  @typeParam V - The union of currently active version keys; defaults to all keys of \u0060T\u0060.
11
11
 
12
12
  An instance of \u0060Versioned<T, V>\u0060 exposes:
13
- - All properties of the intersection \u0060T[V]\u0060 (request data, response builders, etc.)
13
+ - A discriminated union of the active version arguments (request data, response builders, etc.)
14
14
  - \u0060version\u0060 — the version string for the current request (e.g. \u0060"v2"\u0060).
15
15
  - \u0060minVersion(min)\u0060 — type predicate that returns \u0060true\u0060 when the current version
16
- is at or after \u0060min\u0060 in the declared version order and narrows \u0060$\u0060 accordingly.`;
16
+ is at or after \u0060min\u0060 in the declared version order. A literal threshold narrows
17
+ both branches; a dynamic union threshold returns boolean without narrowing.`;
17
18
  export async function generateVersionsTsContent(versions) {
18
19
  if (versions.length === 0)
19
20
  return "";
@@ -24,9 +25,14 @@ export async function generateVersionsTsContent(versions) {
24
25
  const activeVersionMap = ts.factory.createIndexedAccessTypeNode(typeReference("VersionsGTE"), typeReference("M"));
25
26
  const narrowing = ts.factory.createTypePredicateNode(undefined, ts.factory.createThisTypeNode(), typeReference("Versioned", [
26
27
  typeReference("T"),
27
- typeReference("Extract", [typeReference("V"), activeVersionMap]),
28
+ typeReference("Extract", [activeKeys(), activeVersionMap]),
28
29
  ]));
29
- const minVersion = ts.factory.createMethodSignature(undefined, "minVersion", undefined, [ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys())], [parameter("min", typeReference("M"))], narrowing);
30
+ const minVersion = ts.factory.createMethodSignature(undefined, "minVersion", undefined, [ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys())], [
31
+ parameter("min", ts.factory.createIntersectionTypeNode([
32
+ typeReference("M"),
33
+ typeReference("SingleVersion", [typeReference("M")]),
34
+ ])),
35
+ ], narrowing);
30
36
  return formatStatements([
31
37
  withJsDoc(typeAlias("Versions", unionType(versions.map(literalType))), {
32
38
  description: 'Union of all version strings declared for this API group (e.g. \u0060"v1" | "v2" | "v3"\u0060).',
@@ -40,10 +46,22 @@ export async function generateVersionsTsContent(versions) {
40
46
  ts.factory.createKeywordTypeNode(ts.SyntaxKind.ObjectKeyword),
41
47
  ]),
42
48
  ]), false),
43
- withJsDoc(typeAlias("Versioned", ts.factory.createIntersectionTypeNode([
44
- ts.factory.createIndexedAccessTypeNode(typeReference("T"), typeReference("V")),
45
- typeLiteral([typeProperty("version", typeReference("V")), minVersion], true),
46
- ]), true, [
49
+ // Distribute over a threshold's possible values. Only a single literal
50
+ // can safely exclude versions from a guard's false branch.
51
+ typeAlias("SingleVersion", ts.factory.createConditionalTypeNode(stringType(), typeReference("V"), neverType(), ts.factory.createConditionalTypeNode(typeReference("V"), typeReference("All"), ts.factory.createConditionalTypeNode(ts.factory.createTupleTypeNode([typeReference("All")]), ts.factory.createTupleTypeNode([typeReference("V")]), typeReference("V"), neverType()), neverType())), false, [
52
+ ts.factory.createTypeParameterDeclaration(undefined, "V"),
53
+ ts.factory.createTypeParameterDeclaration(undefined, "All", undefined, typeReference("V")),
54
+ ]),
55
+ withJsDoc(typeAlias("Versioned", ts.factory.createIndexedAccessTypeNode(ts.factory.createMappedTypeNode(undefined, ts.factory.createTypeParameterDeclaration(undefined, "K", typeReference("V")), undefined, undefined, ts.factory.createIntersectionTypeNode([
56
+ ts.factory.createIndexedAccessTypeNode(typeReference("T"), typeReference("K")),
57
+ typeLiteral([
58
+ typeProperty("version", typeReference("K")),
59
+ minVersion,
60
+ ts.factory.createMethodSignature(undefined, "minVersion", undefined, [
61
+ ts.factory.createTypeParameterDeclaration(undefined, "M", activeKeys()),
62
+ ], [parameter("min", typeReference("M"))], ts.factory.createKeywordTypeNode(ts.SyntaxKind.BooleanKeyword)),
63
+ ], true),
64
+ ]), undefined), typeReference("V")), true, [
47
65
  ts.factory.createTypeParameterDeclaration(undefined, "T", typeReference("VersionMap")),
48
66
  ts.factory.createTypeParameterDeclaration(undefined, "V", activeKeys(), activeKeys()),
49
67
  ]), { description: VERSIONED_DESCRIPTION }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "0.1.6",
3
+ "version": "1.1.0",
4
4
  "description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -40,7 +40,7 @@
40
40
  "testing"
41
41
  ],
42
42
  "engines": {
43
- "node": ">=22"
43
+ "node": ">=22.22"
44
44
  },
45
45
  "publishConfig": {
46
46
  "access": "public"
@@ -52,9 +52,9 @@
52
52
  "test:packed-consumer": "node test/package/generator-consumer-smoke.mjs"
53
53
  },
54
54
  "dependencies": {
55
- "@counterfact/openapi": "0.1.6",
56
- "@counterfact/types": "0.1.0",
57
- "chokidar": "5.0.0",
55
+ "@counterfact/openapi": "0.1.7",
56
+ "@counterfact/types": "0.2.0",
57
+ "chokidar": "6.0.0",
58
58
  "debug": "4.4.3",
59
59
  "prettier": "3.9.10",
60
60
  "typescript": "6.0.3"
package/src/README.md CHANGED
@@ -10,6 +10,25 @@ Fortunately, we _do_ have pretty much all the information we need to generate _t
10
10
 
11
11
  We can also use those types on the _client_ side, assuming the client is written in TypeScript.
12
12
 
13
+ ## Public generated types
14
+
15
+ Generated projects expose `Routes`, `Components`, and `Schemas` through
16
+ `types/index.ts`. `Routes` is a tree of slash-prefixed segments: an operation on
17
+ `/hello/world` uses `Routes["/hello"]["/world"]["GET"]`. Parent operations and
18
+ child paths can share one branch. Routes import `Routes` from that entry point and use
19
+ `Routes["/hello-world"]["GET"]`; model consumers use `Schemas["Message"]`
20
+ or `Components["schemas"]["Message"]`. Direct imports of operation and
21
+ component types are deprecated for consumers.
22
+
23
+ The individual operation and component modules remain generator implementation
24
+ and compatibility surfaces. Internal coders continue importing dependencies
25
+ directly. `central-types.ts` registers operations and all declared components,
26
+ then emits the central maps after the repository has resolved their types.
27
+ The central entry point also re-exports `Context$`, `Scenario`, `Scenario$`, and
28
+ the directory-indexed `Middleware` map from `types/helpers.ts`. Helper generation
29
+ and context watching own that module; OpenAPI generation owns the API maps.
30
+ Both writers serialize helper updates without rewriting each other's exports.
31
+
13
32
  ## Files
14
33
 
15
34
  | File | Description |
@@ -21,6 +40,7 @@ We can also use those types on the _client_ side, assuming the client is written
21
40
  | `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
22
41
  | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
23
42
  | `type-coder.ts` | Abstract `TypeCoder` base class (extends `Coder`): specialises `Coder` for type-generating components |
43
+ | `central-types.ts` | Assembles the public `Routes`, `Components`, and `Schemas` maps, preserving logical paths and combining component versions |
24
44
  | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
25
45
  | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
26
46
  | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
@@ -29,7 +49,7 @@ We can also use those types on the _client_ side, assuming the client is written
29
49
  | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
30
50
  | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
31
51
  | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
32
- | `ast.ts` | TypeScript AST construction and printing helpers |
52
+ | `ast.ts` | TypeScript AST construction and printing helpers |
33
53
  | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
34
54
 
35
55
  ## Architecture
@@ -136,14 +156,20 @@ paths:
136
156
  type: string
137
157
  ```
138
158
 
139
- Our goal is to produce a file at `/routes/hello.ts` that exports a function named `GET` (1). Our implementation will depend on a type for the `GET` function which lives in `/routes/types-hello.ts` (2). That type, in turn, will depend on a type named `Message` which lives in `/components/message.ts` (3).
140
-
141
- (1) We kick off the process by iterating over the paths. (In our simple example there's only one path, at `/hello`.) In our model, each path is represented as a `Requirement`. We give each path / `Requirement` to an `OperationCoder` who will write the code. We ask the repository for a `Script` and then hand the `Script` our `OperationCoder` instance and ask it to create an export.
142
-
143
- (2a) The `OperationCoder` knows that the function has to have a type, but it doesn't know to create that type. So it recruits an `OperationTypeCoder` and hands it the `Requirement`. It then asks the `Script` to _import_ a type, passing along the `OperationTypeCoder`. The `Script` returns the name of the variable to which the imported type will be assigned. That name is all the `OperationCoder` needs to know to continue writing its portion of the code. The `OperationCoder` continues on, writing the `GET` function. Depending on what it finds in the `Requirement`, it will break off parts and delegate some of the work to other `Coder`s.
144
-
145
- (2b) The `Script` has promised that it will import the type from `/types/paths/hello.type.ts` so it needs to make sure that file exists and has a matching export. It goes to the repository to get another `Script` and asks it to _export_ the type, passing along the `OperationTypeCoder` in the process. It's a little tricky here because `OperationTypeCoder`'s `Requirement` may not have the information it needs to proceed. It might have a `$ref` pointer to some _other_ requirement that might be in a different file. So before asking for the export, it asks the `OperationTypeCoder` to give it _another_ `OperationTypeCoder` that definitely has the requirement. Because the other requirement may be in another file that the `Repository` hasn't loaded yet, this part happens asynchronously.
146
-
147
- (2c) When it's ready, the `Script` asks the `OperationTypeCoder` which definitely has an immediately usable requirement to write the export for the `Script` at `/types/paths/hello.types.ts`.
148
-
149
- (3) The `OperationTypeCoder` needs the help of a `SchemaCoder` so it asks the `Script` at `/types/paths/hello.types.ts` for an export...
159
+ Our goal is to produce `routes/hello-world.ts`, exporting a `GET` handler typed
160
+ as `Routes["/hello-world"]["GET"]`, and a reusable model available as
161
+ `Schemas["Message"]`.
162
+
163
+ 1. `CodeGenerator` registers every declared component with the central index,
164
+ including unused schemas. It traverses path operations and exports each
165
+ `OperationCoder` to its route script.
166
+ 2. `OperationCoder.typeDeclaration()` registers its `OperationTypeCoder` with
167
+ the central index and imports `Routes` into the route. The index imports the
168
+ handler contract from its existing operation module. Versioned operations
169
+ still register each version's argument type on the shared operation script.
170
+ 3. The operation contract uses other coders for parameters, responses, and
171
+ schemas. `Script.importType()` resolves their exports through `Repository`,
172
+ keeping those internal imports direct and collision-safe.
173
+ 4. After all types resolve, the central script emits `Routes`, `Components`,
174
+ and `Schemas = Components["schemas"]` through a deferred statement builder.
175
+ `Repository` writes regenerated types and preserves user-edited route text.