@counterfact/generator 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @counterfact/generator
2
2
 
3
+ ## 1.2.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 354e288: Support OpenAPI 3 multipart/form-data request bodies in generated handler types
8
+ and the built-in Koa server. Expose uploaded bytes and metadata through
9
+ MultipartFile, decode declared fields and repeated arrays, validate required
10
+ fields and uploads, and reject malformed or oversized multipart requests.
11
+
12
+ ### Patch Changes
13
+
14
+ - 498c47d: Resolve generated handler context types from the endpoint directory before checking ancestors, matching runtime context resolution for collection endpoints in ordinary and versioned APIs.
15
+ - 9995fa2: Restore the string index signature in the generated default Context class so handlers can add shared state immediately. Remove the index signature to opt into strict typing; existing context files are preserved during regeneration.
16
+ - Updated dependencies [354e288]
17
+ - @counterfact/types@0.3.0
18
+
19
+ ## 1.1.0
20
+
21
+ ### Minor Changes
22
+
23
+ - a724401: Generate a central `types/index.ts` exporting `Routes`, `Components`, and `Schemas` (an alias of `Components["schemas"]`). Include unused components, preserve lowercase OpenAPI categories, and use indexed `Routes` contracts in new route handlers while preserving existing route edits and deep imports.
24
+
25
+ Deprecate deep imports of generated operation and component types. Use the central exports throughout the manual, API reference, homepage, walkthrough, and agent guidance.
26
+
27
+ Expose `Context$`, `Scenario`, `Scenario$`, and directory-indexed `Middleware` through the central entry point. New context and scenario starters use central imports; context watching refreshes the helper module and middleware directory map. Dedicated helper imports remain compatible but deprecated.
28
+
29
+ Fix versioned handler narrowing after `minVersion()` checks, including early returns, negated conditions, and explicit else branches. Literal checks narrow both request and response contracts; dynamic union thresholds use a boolean overload to avoid incorrectly excluding possible versions.
30
+
31
+ Organize `Routes` as a tree of slash-prefixed path segments. Select `/hello/world` with `Routes["/hello"]["/world"]`; parent operations and child branches coexist, and generated handlers and documentation use the nested indexes.
32
+
33
+ Write watched helper modules atomically and skip unchanged content so TypeScript readers do not observe empty modules during regeneration.
34
+
35
+ Declare a local `Route` alias once per generated route file and annotate handlers with `Route["GET"]`, `Route["POST"]`, and other method keys. Regeneration reuses matching aliases and avoids existing local names while preserving user code.
36
+
37
+ ### Patch Changes
38
+
39
+ - 40656be: Require Node 22.22 or later for Chokidar 6 compatibility.
40
+ - 93944c6: Updated dependency `chokidar` in `@counterfact/generator` to `6.0.0`.
41
+ Updated dependency `chokidar` in `@counterfact/runtime` to `6.0.0`.
42
+ - Updated dependencies [1f340b6]
43
+ - @counterfact/openapi@0.1.7
44
+
3
45
  ## 1.0.0
4
46
 
5
47
  ### Major Changes
@@ -0,0 +1,14 @@
1
+ import type { OperationTypeCoder } from "./operation-type-coder.js";
2
+ import type { Repository } from "./repository.js";
3
+ import type { Specification } from "./specification.js";
4
+ /** One public entry point per API group, assembled after all versions register. */
5
+ declare class CentralTypes {
6
+ private readonly script;
7
+ private readonly routes;
8
+ private readonly components;
9
+ constructor(repository: Repository);
10
+ addOperation(path: string, method: string, coder: OperationTypeCoder): void;
11
+ addComponents(specification: Specification, version: string): void;
12
+ }
13
+ export declare function centralTypes(repository: Repository): CentralTypes;
14
+ export {};
@@ -0,0 +1,128 @@
1
+ import ts from "typescript";
2
+ import { literalType, typeAlias, typeLiteral, typeProperty, typeReference, unionType, unknownType, } from "./ast.js";
3
+ import { pathJoin } from "./forward-slash-path.js";
4
+ import { routesType } from "./route-type-tree.js";
5
+ import { helperTypeExports } from "./scenario-file-generator.js";
6
+ import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
7
+ import { SchemaTypeCoder } from "./schema-type-coder.js";
8
+ import { ResponseTypeCoder } from "./response-type-coder.js";
9
+ import { TypeCoder } from "./type-coder.js";
10
+ import { Requirement } from "./requirement.js";
11
+ const CATEGORIES = [
12
+ "schemas",
13
+ "parameters",
14
+ "responses",
15
+ "requestBodies",
16
+ "headers",
17
+ "examples",
18
+ "securitySchemes",
19
+ "links",
20
+ "callbacks",
21
+ "pathItems",
22
+ "mediaTypes",
23
+ ];
24
+ /** Non-schema components keep their structure; embedded schemas become data types. */
25
+ class ComponentTypeCoder extends TypeCoder {
26
+ modulePath() {
27
+ return pathJoin("types", this.version, (this.requirement.refUrl ?? this.requirement.url).replace(/^#\//u, "") +
28
+ ".ts");
29
+ }
30
+ writeCode(script) {
31
+ const category = this.requirement.url.split("/").at(-2);
32
+ if (category === "parameters" || category === "headers") {
33
+ const schema = this.requirement.get("schema");
34
+ if (schema)
35
+ return new SchemaTypeCoder(schema, this.version).write(script);
36
+ const content = this.requirement.get("content");
37
+ return content ? this.structure(content, script) : unknownType();
38
+ }
39
+ return this.structure(this.requirement, script, !["examples", "securitySchemes", "links"].includes(category ?? ""));
40
+ }
41
+ structure(requirement, script, schemas = true) {
42
+ if (!schemas)
43
+ return literalStructure(requirement.data);
44
+ if (requirement.isReference) {
45
+ return typeReference(script.importType(new ComponentTypeCoder(requirement, this.version)));
46
+ }
47
+ const { data } = requirement;
48
+ if (Array.isArray(data)) {
49
+ return ts.factory.createTupleTypeNode(data.map((_, index) => this.structure(requirement.get(index), script, schemas)));
50
+ }
51
+ if (data !== null && typeof data === "object") {
52
+ return typeLiteral(requirement.map((value, key) => typeProperty(key, schemas && (key === "schema" || key === "itemSchema")
53
+ ? new SchemaTypeCoder(value, this.version).write(script)
54
+ : this.structure(value, script, key !== "example" && key !== "value"))));
55
+ }
56
+ return literalType(data);
57
+ }
58
+ }
59
+ /** One public entry point per API group, assembled after all versions register. */
60
+ class CentralTypes {
61
+ script;
62
+ routes = new Map();
63
+ components = new Map();
64
+ constructor(repository) {
65
+ this.script = repository.get("types/index.ts");
66
+ this.script.comments.push(...READ_ONLY_COMMENTS);
67
+ this.script.reservedNames = new Set([
68
+ "Routes",
69
+ "Components",
70
+ "Schemas",
71
+ "Context$",
72
+ "Scenario",
73
+ "Scenario$",
74
+ "Middleware",
75
+ ]);
76
+ this.script.statementBuilders.set("api-types", () => [
77
+ helperTypeExports(),
78
+ typeAlias("Routes", routesType(this.routes)),
79
+ typeAlias("Components", typeLiteral(CATEGORIES.map((category) => typeProperty(category, typeLiteral([...(this.components.get(category) ?? [])].map(([name, versions]) => typeProperty(name, unionType([...versions.values()])))))))),
80
+ typeAlias("Schemas", ts.factory.createIndexedAccessTypeNode(typeReference("Components"), literalType("schemas"))),
81
+ ]);
82
+ }
83
+ addOperation(path, method, coder) {
84
+ const methods = this.routes.get(path) ?? new Map();
85
+ this.routes.set(path, methods);
86
+ methods.set(method.toUpperCase(), typeReference(this.script.importType(coder, `Route${this.routes.size}_${method.toUpperCase()}`)));
87
+ }
88
+ addComponents(specification, version) {
89
+ for (const category of CATEGORIES) {
90
+ specification
91
+ .getRequirement(`#/components/${category}`)
92
+ ?.forEach((component, name) => {
93
+ const components = this.components.get(category) ??
94
+ new Map();
95
+ this.components.set(category, components);
96
+ const versions = components.get(name) ?? new Map();
97
+ components.set(name, versions);
98
+ // Import by reference so the existing coder chooses the canonical module
99
+ // and resolves component aliases without duplicating their definitions.
100
+ const reference = new Requirement({
101
+ $ref: `#/components/${category}/${name.replaceAll("~", "~0").replaceAll("/", "~1")}`,
102
+ }, component.url, specification);
103
+ const Coder = category === "schemas"
104
+ ? SchemaTypeCoder
105
+ : category === "responses"
106
+ ? ResponseTypeCoder
107
+ : ComponentTypeCoder;
108
+ versions.set(version, typeReference(this.script.importType(new Coder(reference, version))));
109
+ });
110
+ }
111
+ }
112
+ }
113
+ const indexes = new WeakMap();
114
+ export function centralTypes(repository) {
115
+ let index = indexes.get(repository);
116
+ if (!index) {
117
+ index = new CentralTypes(repository);
118
+ indexes.set(repository, index);
119
+ }
120
+ return index;
121
+ }
122
+ function literalStructure(data) {
123
+ if (Array.isArray(data))
124
+ return ts.factory.createTupleTypeNode(data.map(literalStructure));
125
+ if (data !== null && typeof data === "object")
126
+ return typeLiteral(Object.entries(data).map(([key, value]) => typeProperty(key, literalStructure(value))));
127
+ return literalType(data);
128
+ }
@@ -6,9 +6,11 @@ import { watch } from "chokidar";
6
6
  import createDebug from "debug";
7
7
  import { getLocalOpenApiSourcePaths } from "@counterfact/openapi";
8
8
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
9
+ import { centralTypes } from "./central-types.js";
9
10
  import { OperationCoder } from "./operation-coder.js";
10
11
  import { assertNoNormalizedPathCollisions, normalizeOpenApiPath, } from "./openapi-path.js";
11
12
  import { pruneRoutes, pruneTypes } from "./prune.js";
13
+ import { Requirement } from "./requirement.js";
12
14
  import { Repository } from "./repository.js";
13
15
  import { Specification } from "./specification.js";
14
16
  import { waitForEvent } from "./wait-for-event.js";
@@ -67,11 +69,12 @@ export class CodeGenerator extends EventTarget {
67
69
  */
68
70
  async getPathsFromSpecification(specification) {
69
71
  try {
70
- return specification.getRequirement("#/paths") ?? new Set();
72
+ return (specification.getRequirement("#/paths") ??
73
+ new Requirement({}, "#/paths", specification));
71
74
  }
72
75
  catch (error) {
73
76
  process.stderr.write(`Could not find #/paths in the specification.\n${error}\n`);
74
- return undefined;
77
+ return new Requirement({}, "#/paths", specification);
75
78
  }
76
79
  }
77
80
  /**
@@ -94,6 +97,7 @@ export class CodeGenerator extends EventTarget {
94
97
  const specification = await Specification.fromFile(this.openapiPath, this.overlays);
95
98
  debug("created specification: $o", specification);
96
99
  debug("reading the #/paths from the specification");
100
+ centralTypes(repository).addComponents(specification, this.version);
97
101
  const paths = await this.getPathsFromSpecification(specification);
98
102
  debug("got %i paths", paths?.map?.length ?? 0);
99
103
  const openApiPaths = paths.map((_pathDefinition, key) => key);
@@ -115,26 +119,35 @@ export class CodeGenerator extends EventTarget {
115
119
  "patch",
116
120
  "trace",
117
121
  ]);
118
- const operationMethodsForPath = (pathDefinition) => pathDefinition.flatMap((operation, requestMethod) => {
119
- if (requestMethod === "additionalOperations") {
120
- return operation.map((additionalOperation, additionalMethod) => [
121
- additionalOperation,
122
- additionalMethod.toLowerCase(),
123
- ]);
124
- }
125
- if (!HTTP_VERBS.has(requestMethod)) {
126
- return [];
127
- }
128
- return [[operation, requestMethod]];
129
- });
122
+ const operationMethodsForPath = (pathDefinition) => {
123
+ let resolved = pathDefinition;
124
+ while (resolved.isReference)
125
+ resolved = resolved.reference();
126
+ return resolved.flatMap((operation, requestMethod) => {
127
+ if (requestMethod === "additionalOperations") {
128
+ return operation.map((additionalOperation, additionalMethod) => [
129
+ additionalOperation,
130
+ additionalMethod.toLowerCase(),
131
+ ]);
132
+ }
133
+ if (!HTTP_VERBS.has(requestMethod)) {
134
+ return [];
135
+ }
136
+ return [[operation, requestMethod]];
137
+ });
138
+ };
130
139
  paths.forEach((pathDefinition, key) => {
131
140
  debug("processing path %s", key);
132
141
  const normalizedPath = normalizeOpenApiPath(key);
133
142
  const path = normalizedPath === "/" ? "/index" : normalizedPath;
134
143
  operationMethodsForPath(pathDefinition).forEach(([operation, requestMethod]) => {
144
+ // Keep the logical route location when a Path Item is a reference or
145
+ // a method is declared under OpenAPI 3.2 additionalOperations.
146
+ const logicalOperation = new Requirement(operation.data, `${pathDefinition.url}/${requestMethod}`, specification);
147
+ logicalOperation.parent = pathDefinition;
135
148
  repository
136
149
  .get(`routes${path}.ts`)
137
- .export(new OperationCoder(operation, this.version, requestMethod, securitySchemes));
150
+ .export(new OperationCoder(logicalOperation, this.version, requestMethod, securitySchemes));
138
151
  });
139
152
  });
140
153
  if (this.generateOptions.prune && this.generateOptions.types) {
@@ -0,0 +1,10 @@
1
+ import type ts from "typescript";
2
+ import { SchemaTypeCoder } from "./schema-type-coder.js";
3
+ import type { Requirement } from "./requirement.js";
4
+ import type { Script } from "./script.js";
5
+ /** Multipart file types must not change the same model's JSON representation. */
6
+ export declare class MultipartSchemaTypeCoder extends SchemaTypeCoder {
7
+ protected child(requirement: Requirement): SchemaTypeCoder;
8
+ modulePath(): string;
9
+ protected writeSchema(script: Script): ts.TypeNode;
10
+ }
@@ -0,0 +1,26 @@
1
+ import { typeReference, literalType, unionType } from "./ast.js";
2
+ import { SchemaTypeCoder } from "./schema-type-coder.js";
3
+ /** Multipart file types must not change the same model's JSON representation. */
4
+ export class MultipartSchemaTypeCoder extends SchemaTypeCoder {
5
+ child(requirement) {
6
+ return new MultipartSchemaTypeCoder(requirement, this.version);
7
+ }
8
+ modulePath() {
9
+ return super.modulePath().replace("types/", "types/multipart/");
10
+ }
11
+ writeSchema(script) {
12
+ const rawType = this.requirement.get("type")?.data;
13
+ const types = Array.isArray(rawType) ? rawType : [rawType];
14
+ if ((types.includes("string") &&
15
+ this.requirement.get("format")?.data === "binary") ||
16
+ types.includes("file")) {
17
+ const file = typeReference(script.importSharedType("MultipartFile"));
18
+ const alternatives = [file];
19
+ if (types.includes("null") ||
20
+ this.requirement.get("nullable")?.data === true)
21
+ alternatives.push(literalType(null));
22
+ return unionType(alternatives);
23
+ }
24
+ return super.writeSchema(script);
25
+ }
26
+ }
@@ -1,7 +1,9 @@
1
1
  import { STREAMING_CONTENT_TYPES } from "@counterfact/types/streaming-content-types";
2
2
  import { pathJoin } from "./forward-slash-path.js";
3
3
  import ts from "typescript";
4
- import { parameter, typeReference } from "./ast.js";
4
+ import { literalType, parameter, typeReference } from "./ast.js";
5
+ import { routeTypeReference } from "./route-type-tree.js";
6
+ import { centralTypes } from "./central-types.js";
5
7
  import { Coder } from "./coder.js";
6
8
  import { normalizeOpenApiPath } from "./openapi-path.js";
7
9
  import { OperationTypeCoder, VersionedArgTypeCoder, } from "./operation-type-coder.js";
@@ -79,7 +81,13 @@ export class OperationCoder extends Coder {
79
81
  const sharedScript = script.repository.get(operationTypeCoder.modulePath());
80
82
  sharedScript.declareVersion(versionedArgCoder, operationTypeCoder.getOperationBaseName());
81
83
  }
82
- return typeReference(script.importType(operationTypeCoder));
84
+ const path = this.requirement.parent?.url.split("/").at(-1) ??
85
+ this.requirement.url.split("/").at(-2);
86
+ const routePath = path.replaceAll("~1", "/").replaceAll("~0", "~");
87
+ centralTypes(script.repository).addOperation(routePath, this.requestMethod, operationTypeCoder);
88
+ const routes = script.importExternalType("Routes", pathJoin(script.relativePathToBase, "types/index.js"));
89
+ script.localTypes.set("Route", routeTypeReference(routes, routePath));
90
+ return ts.factory.createIndexedAccessTypeNode(typeReference("Route"), literalType(this.requestMethod.toUpperCase()));
83
91
  }
84
92
  modulePath() {
85
93
  const pathString = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
@@ -8,6 +8,7 @@ import { ParameterExportTypeCoder } from "./parameter-export-type-coder.js";
8
8
  import { ParametersTypeCoder } from "./parameters-type-coder.js";
9
9
  import { READ_ONLY_COMMENTS } from "./read-only-comments.js";
10
10
  import { ResponsesTypeCoder } from "./responses-type-coder.js";
11
+ import { MultipartSchemaTypeCoder } from "./multipart-schema-type-coder.js";
11
12
  import { SchemaTypeCoder } from "./schema-type-coder.js";
12
13
  import { TypeCoder } from "./type-coder.js";
13
14
  import { normalizeOpenApiPath } from "./openapi-path.js";
@@ -212,6 +213,7 @@ export class OperationTypeCoder extends TypeCoder {
212
213
  const xType = script.importSharedType("WideOperationArgument");
213
214
  script.importSharedType("OmitValueWhenNever");
214
215
  script.importSharedType("COUNTERFACT_RESPONSE");
216
+ script.contextRoutePath = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
215
217
  const contextTypeImportName = script.importExternalType("Context", {
216
218
  context: true,
217
219
  });
@@ -220,15 +222,39 @@ export class OperationTypeCoder extends TypeCoder {
220
222
  const pathType = new ParametersTypeCoder(parameters, this.version, "path").write(script);
221
223
  const headersType = new ParametersTypeCoder(parameters, this.version, "header").write(script);
222
224
  const cookieType = new ParametersTypeCoder(parameters, this.version, "cookie").write(script);
223
- const bodyRequirement = (this.requirement.get("consumes") ??
224
- this.requirement.specification?.rootRequirement?.get("consumes"))
225
+ const consumes = this.requirement.get("consumes") ??
226
+ this.requirement.specification?.rootRequirement?.get("consumes");
227
+ const legacyBody = consumes
225
228
  ? parameters
226
229
  ?.find((parameter) => ["body", "formData"].includes(parameter.get("in")?.data))
227
230
  ?.get("schema")
228
- : this.requirement.select("requestBody/content/application~1json/schema");
229
- const bodyType = bodyRequirement === undefined
230
- ? neverType()
231
- : new SchemaTypeCoder(bodyRequirement, this.version).write(script);
231
+ : undefined;
232
+ const bodyTypes = legacyBody
233
+ ? [new SchemaTypeCoder(legacyBody, this.version).write(script)]
234
+ : [];
235
+ const seenBodySchemas = new Set();
236
+ for (const mediaType of [
237
+ "application/json",
238
+ "application/x-www-form-urlencoded",
239
+ "multipart/form-data",
240
+ ]) {
241
+ const schema = this.requirement
242
+ .get("requestBody")
243
+ ?.get("content")
244
+ ?.get(mediaType)
245
+ ?.get("schema");
246
+ if (schema) {
247
+ const Coder = mediaType === "multipart/form-data"
248
+ ? MultipartSchemaTypeCoder
249
+ : SchemaTypeCoder;
250
+ const coder = new Coder(schema, this.version);
251
+ if (!seenBodySchemas.has(coder.id)) {
252
+ seenBodySchemas.add(coder.id);
253
+ bodyTypes.push(coder.write(script));
254
+ }
255
+ }
256
+ }
257
+ const bodyType = bodyTypes.length === 0 ? neverType() : unionType(bodyTypes);
232
258
  const openApi2MediaTypes = (this.requirement.get("produces")?.data ??
233
259
  this.requirement.specification?.rootRequirement?.get("produces")
234
260
  ?.data);
package/dist/prune.js CHANGED
@@ -110,6 +110,7 @@ function isGeneratorOwnedTypePath(path) {
110
110
  const [first, second] = toForwardSlashPath(path).split("/");
111
111
  const generatedCategory = (segment) => segment === "paths" || segment === "components" || segment === "#";
112
112
  return (path === "versions.ts" ||
113
+ first === "multipart" ||
113
114
  generatedCategory(first) ||
114
115
  generatedCategory(second));
115
116
  }
@@ -67,7 +67,7 @@ export declare class Repository {
67
67
  * @param destination - Output root directory.
68
68
  * @param path - Repository-relative path of the script being generated.
69
69
  */
70
- findContextPath(destination: string, path: string): string;
70
+ findContextPath(destination: string, path: string, logicalPath?: string): string;
71
71
  /**
72
72
  * Walks up the directory tree from `path` to find the nearest
73
73
  * `_.context.ts` file, falling back to `routes/_.context.ts` at the root.
@@ -75,6 +75,6 @@ export declare class Repository {
75
75
  * @param destination - Output root directory.
76
76
  * @param path - Repository-relative path to start from.
77
77
  */
78
- nearestContextFile(destination: string, path: string): string;
78
+ nearestContextFile(destination: string, path: string, logicalPath?: string): string;
79
79
  }
80
80
  export {};
@@ -5,9 +5,10 @@ import { fileURLToPath } from "node:url";
5
5
  /* eslint-disable security/detect-non-literal-fs-filename -- repository writes and stats generated files only inside destination output directories. */
6
6
  import createDebug from "debug";
7
7
  import ts from "typescript";
8
- import { formatStatements, importDeclaration, parameter, typeReference, withJsDoc, } from "./ast.js";
8
+ import { formatStatements, importDeclaration, parameter, stringType, typeAlias, typeReference, withJsDoc, withComment, } from "./ast.js";
9
9
  import { ensureDirectoryExists } from "./ensure-directory-exists.js";
10
10
  import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
+ import { writeHelperTypes } from "./scenario-file-generator.js";
11
12
  import { Script } from "./script.js";
12
13
  import { escapePathForWindows } from "./windows-escape.js";
13
14
  const debug = createDebug("counterfact:server:repository");
@@ -114,7 +115,7 @@ export class Repository {
114
115
  debug("all %i scripts are finished", this.scripts.size);
115
116
  const writeFiles = Array.from(this.scripts.entries(), async ([path, script]) => {
116
117
  const fullPath = resolveDestinationPath(destination, path);
117
- const contents = await script.contents(this.findContextPath(destination, path));
118
+ const contents = await script.contents(this.findContextPath(destination, path, script.contextRoutePath));
118
119
  await ensureDirectoryExists(fullPath);
119
120
  const shouldWriteRoutes = routes && path.startsWith("routes");
120
121
  const shouldWriteTypes = types && !path.startsWith("routes");
@@ -140,6 +141,8 @@ export class Repository {
140
141
  if (routes) {
141
142
  await this.createDefaultContextFile(destination);
142
143
  }
144
+ if (types)
145
+ await writeHelperTypes(destination, destination, true);
143
146
  }
144
147
  /**
145
148
  * Creates the default `routes/_.context.ts` file if it does not already
@@ -154,6 +157,7 @@ export class Repository {
154
157
  }
155
158
  await ensureDirectoryExists(contextFilePath);
156
159
  const context = withJsDoc(ts.factory.createClassDeclaration([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], "Context", undefined, undefined, [
160
+ withComment(ts.factory.createIndexSignature(undefined, [parameter("key", stringType())], ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)), "/* Delete this line to make the context type safe. */"),
157
161
  ts.factory.createConstructorDeclaration(undefined, [parameter("$", typeReference("Context$"))], ts.factory.createBlock([
158
162
  ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$"))),
159
163
  ], true)),
@@ -164,7 +168,7 @@ export class Repository {
164
168
  "See https://github.com/counterfact/api-simulator/blob/main/docs/features/state.md",
165
169
  });
166
170
  await fs.writeFile(contextFilePath, await formatStatements([
167
- importDeclaration("Context$", "../types/_.context.js", true),
171
+ importDeclaration("Context$", "../types/index.js", true),
168
172
  context,
169
173
  ]));
170
174
  }
@@ -297,8 +301,36 @@ export class Repository {
297
301
  }
298
302
  }
299
303
  const newImports = [];
304
+ const newAliases = [];
305
+ const aliases = new Map();
306
+ const typeKey = (node) => {
307
+ const keys = [];
308
+ while (ts.isIndexedAccessTypeNode(node)) {
309
+ if (!ts.isLiteralTypeNode(node.indexType) ||
310
+ !ts.isStringLiteral(node.indexType.literal))
311
+ return undefined;
312
+ keys.unshift(node.indexType.literal.text);
313
+ node = node.objectType;
314
+ }
315
+ return ts.isTypeReferenceNode(node) &&
316
+ ts.isIdentifier(node.typeName) &&
317
+ !node.typeArguments?.length
318
+ ? JSON.stringify([node.typeName.text, ...keys])
319
+ : undefined;
320
+ };
321
+ for (const statement of source.statements) {
322
+ if (ts.isTypeAliasDeclaration(statement) &&
323
+ !statement.typeParameters?.length) {
324
+ const key = typeKey(statement.type);
325
+ if (key)
326
+ aliases.set(key, statement.name.text);
327
+ }
328
+ }
300
329
  const handlers = [];
301
- const generatedImports = script.importStatements();
330
+ const generatedImports = [
331
+ ...script.importStatements(),
332
+ ...script.externalImportStatements(),
333
+ ];
302
334
  for (const statement of script.exportStatements()) {
303
335
  if (!ts.isVariableStatement(statement))
304
336
  continue;
@@ -312,12 +344,24 @@ export class Repository {
312
344
  declaration.name.text +
313
345
  ": a local binding already exists in " +
314
346
  fullPath);
315
- if (!declaration.type ||
316
- !ts.isTypeReferenceNode(declaration.type) ||
317
- !ts.isIdentifier(declaration.type.typeName)) {
347
+ let handlerType = declaration.type;
348
+ const generatedAlias = ts.isIndexedAccessTypeNode(handlerType) &&
349
+ ts.isTypeReferenceNode(handlerType.objectType) &&
350
+ ts.isIdentifier(handlerType.objectType.typeName)
351
+ ? script.localTypes.get(handlerType.objectType.typeName.text)
352
+ : undefined;
353
+ if (generatedAlias && ts.isIndexedAccessTypeNode(handlerType)) {
354
+ handlerType = ts.factory.createIndexedAccessTypeNode(generatedAlias, handlerType.indexType);
355
+ }
356
+ let rootType = handlerType;
357
+ while (rootType && ts.isIndexedAccessTypeNode(rootType))
358
+ rootType = rootType.objectType;
359
+ if (!rootType ||
360
+ !ts.isTypeReferenceNode(rootType) ||
361
+ !ts.isIdentifier(rootType.typeName)) {
318
362
  throw new Error("Generated handler lacks a named type: " + declaration.name.text);
319
363
  }
320
- let localType = declaration.type.typeName.text;
364
+ let localType = rootType.typeName.text;
321
365
  const originalType = localType;
322
366
  const imported = generatedImports.flatMap((item) => {
323
367
  const named = item.importClause?.namedBindings;
@@ -331,6 +375,9 @@ export class Repository {
331
375
  throw new Error("Cannot find handler type import for " + declaration.name.text);
332
376
  const module = imported.item.moduleSpecifier.text;
333
377
  const exportedType = imported.element.propertyName?.text ?? imported.element.name.text;
378
+ const matchingImport = [...imports].find(([, entry]) => entry.module === module && entry.exported === exportedType);
379
+ if (matchingImport)
380
+ localType = matchingImport[0];
334
381
  const existingImport = imports.get(localType);
335
382
  if (!existingImport ||
336
383
  existingImport.module !== module ||
@@ -342,8 +389,23 @@ export class Repository {
342
389
  imports.set(localType, { module, exported: exportedType });
343
390
  bindings.add(localType);
344
391
  }
392
+ handlerType = renameTypeRoot(handlerType, localType);
393
+ if (generatedAlias && ts.isIndexedAccessTypeNode(handlerType)) {
394
+ const key = typeKey(handlerType.objectType);
395
+ let alias = aliases.get(key);
396
+ if (!alias) {
397
+ alias = "Route";
398
+ let suffix = 2;
399
+ while (bindings.has(alias))
400
+ alias = "Route" + suffix++;
401
+ newAliases.push(typeAlias(alias, handlerType.objectType, false));
402
+ aliases.set(key, alias);
403
+ bindings.add(alias);
404
+ }
405
+ handlerType = ts.factory.createIndexedAccessTypeNode(typeReference(alias), handlerType.indexType);
406
+ }
345
407
  handlers.push(ts.factory.updateVariableStatement(statement, statement.modifiers, ts.factory.updateVariableDeclarationList(statement.declarationList, [
346
- ts.factory.updateVariableDeclaration(declaration, declaration.name, declaration.exclamationToken, typeReference(localType), declaration.initializer),
408
+ ts.factory.updateVariableDeclaration(declaration, declaration.name, declaration.exclamationToken, handlerType, declaration.initializer),
347
409
  ])));
348
410
  exported.add(declaration.name.text);
349
411
  bindings.add(declaration.name.text);
@@ -392,12 +454,12 @@ export class Repository {
392
454
  }
393
455
  }
394
456
  let updated = existing;
395
- if (newImports.length > 0) {
457
+ if (newImports.length > 0 || newAliases.length > 0) {
396
458
  const prefix = existing.slice(0, insertAt);
397
459
  updated =
398
460
  prefix +
399
461
  (prefix !== "" && !prefix.endsWith("\n") ? "\n" : "") +
400
- (await formatStatements(newImports)) +
462
+ (await formatStatements([...newImports, ...newAliases])) +
401
463
  existing.slice(insertAt);
402
464
  }
403
465
  updated +=
@@ -412,8 +474,8 @@ export class Repository {
412
474
  * @param destination - Output root directory.
413
475
  * @param path - Repository-relative path of the script being generated.
414
476
  */
415
- findContextPath(destination, path) {
416
- return pathRelative(nodePath.join(destination, nodePath.dirname(path)), this.nearestContextFile(destination, path));
477
+ findContextPath(destination, path, logicalPath) {
478
+ return pathRelative(nodePath.join(destination, nodePath.dirname(path)), this.nearestContextFile(destination, path, logicalPath));
417
479
  }
418
480
  /**
419
481
  * Walks up the directory tree from `path` to find the nearest
@@ -422,16 +484,30 @@ export class Repository {
422
484
  * @param destination - Output root directory.
423
485
  * @param path - Repository-relative path to start from.
424
486
  */
425
- nearestContextFile(destination, path) {
426
- const directory = pathDirname(path).replace("types/paths", "routes");
427
- const candidate = nodePath.join(destination, directory, "_.context.ts");
428
- if (directory.length <= 1) {
429
- // No _context.ts was found so import the one that should be in the root
430
- return nodePath.join(destination, "routes", "_.context.ts");
431
- }
432
- if (existsSync(candidate)) {
433
- return candidate;
487
+ nearestContextFile(destination, path, logicalPath) {
488
+ // Operation contracts describe the endpoint itself, not just its parent.
489
+ const parts = path
490
+ .replace(/(?:\.types)?\.ts$/u, "")
491
+ .split("/")
492
+ .filter((part) => part !== ".");
493
+ const pathsIndex = parts[0] === "types" ? parts.indexOf("paths") : -1;
494
+ let directory = pathsIndex === 1 || pathsIndex === 2
495
+ ? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
496
+ : parts.join("/");
497
+ if (logicalPath !== undefined)
498
+ directory = ["routes", ...logicalPath.split("/").filter(Boolean)].join("/");
499
+ while (directory !== "." && directory !== "routes") {
500
+ const candidate = nodePath.join(destination, directory, "_.context.ts");
501
+ if (existsSync(candidate)) {
502
+ return candidate;
503
+ }
504
+ directory = pathDirname(directory);
434
505
  }
435
- return this.nearestContextFile(destination, nodePath.join(path, ".."));
506
+ return nodePath.join(destination, "routes", "_.context.ts");
436
507
  }
437
508
  }
509
+ function renameTypeRoot(type, name) {
510
+ return ts.isIndexedAccessTypeNode(type)
511
+ ? ts.factory.updateIndexedAccessTypeNode(type, renameTypeRoot(type.objectType, name), type.indexType)
512
+ : typeReference(name);
513
+ }
@@ -0,0 +1,6 @@
1
+ import ts from "typescript";
2
+ /** Preserve the leading slash on each segment, including root/trailing slashes. */
3
+ export declare function routeTypeSegments(path: string): string[];
4
+ export declare function routeTypeReference(name: string, path: string): ts.TypeNode;
5
+ /** Parent operations and child paths share a branch, regardless of input order. */
6
+ export declare function routesType(routes: ReadonlyMap<string, ReadonlyMap<string, ts.TypeNode>>): ts.TypeNode;