@counterfact/generator 1.1.0 → 1.3.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,37 @@
1
1
  # @counterfact/generator
2
2
 
3
+ ## 1.3.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 43770e6: Add `--generate-schemas-only`, which writes only the schema types directly into the destination directory (`<destination>/[<group>/][<version>/]<Name>.ts`) without routes, scenarios, helper types, a cache, or a server. It requires an explicit destination and rejects conflicting flags, Swagger 2.0 documents, and schemas that depend on non-schema components. Config-file action options are ignored with a notice.
8
+
9
+ `CodeGenerator` gains `generateSchemas()` and `Repository` gains `writeSchemas()` for the same behavior.
10
+
11
+ ## 1.2.1
12
+
13
+ ### Patch Changes
14
+
15
+ - 2e52024: Include undefined in generated handler body types for optional OpenAPI 3 request bodies, including JSON, URL-encoded forms, and multipart forms. Preserve required and nullable body distinctions so strict TypeScript catches unguarded access to an absent body.
16
+ - ba0649f: Preserve all versions in shared handler types when a watched OpenAPI specification changes. Regenerate the complete API group in declaration order so version guards retain the older branch and removed operations leave the version map.
17
+ - 14b24e1: Emit operation argument types as plain object types, omitting unavailable request inputs during generation instead of wrapping them in `OmitValueWhenNever`. Apply the same pruning to versioned operation arguments.
18
+
19
+ ## 1.2.0
20
+
21
+ ### Minor Changes
22
+
23
+ - 354e288: Support OpenAPI 3 multipart/form-data request bodies in generated handler types
24
+ and the built-in Koa server. Expose uploaded bytes and metadata through
25
+ MultipartFile, decode declared fields and repeated arrays, validate required
26
+ fields and uploads, and reject malformed or oversized multipart requests.
27
+
28
+ ### Patch Changes
29
+
30
+ - 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.
31
+ - 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.
32
+ - Updated dependencies [354e288]
33
+ - @counterfact/types@0.3.0
34
+
3
35
  ## 1.1.0
4
36
 
5
37
  ### Minor Changes
@@ -1,6 +1,7 @@
1
1
  import type { OperationTypeCoder } from "./operation-type-coder.js";
2
2
  import type { Repository } from "./repository.js";
3
3
  import type { Specification } from "./specification.js";
4
+ declare const CATEGORIES: readonly ["schemas", "parameters", "responses", "requestBodies", "headers", "examples", "securitySchemes", "links", "callbacks", "pathItems", "mediaTypes"];
4
5
  /** One public entry point per API group, assembled after all versions register. */
5
6
  declare class CentralTypes {
6
7
  private readonly script;
@@ -8,7 +9,7 @@ declare class CentralTypes {
8
9
  private readonly components;
9
10
  constructor(repository: Repository);
10
11
  addOperation(path: string, method: string, coder: OperationTypeCoder): void;
11
- addComponents(specification: Specification, version: string): void;
12
+ addComponents(specification: Specification, version: string, categories?: readonly (typeof CATEGORIES)[number][]): void;
12
13
  }
13
14
  export declare function centralTypes(repository: Repository): CentralTypes;
14
15
  export {};
@@ -85,8 +85,8 @@ class CentralTypes {
85
85
  this.routes.set(path, methods);
86
86
  methods.set(method.toUpperCase(), typeReference(this.script.importType(coder, `Route${this.routes.size}_${method.toUpperCase()}`)));
87
87
  }
88
- addComponents(specification, version) {
89
- for (const category of CATEGORIES) {
88
+ addComponents(specification, version, categories = CATEGORIES) {
89
+ for (const category of categories) {
90
90
  specification
91
91
  .getRequirement(`#/components/${category}`)
92
92
  ?.forEach((component, name) => {
@@ -47,14 +47,26 @@ export declare class CodeGenerator extends EventTarget {
47
47
  * (primarily useful in tests).
48
48
  */
49
49
  generate(repository?: Repository): Promise<void>;
50
+ /**
51
+ * Writes only the schema types, directly into `destination`
52
+ * (or `destination/<version>` for a versioned spec), and nothing else.
53
+ *
54
+ * Unlike {@link generate}, this creates no `.cache`, routes, scenarios,
55
+ * helper types or central `types/index.ts`.
56
+ *
57
+ * @param repository - Injectable repository instance; defaults to a fresh one.
58
+ * @returns The written file paths, relative to `destination`.
59
+ */
60
+ generateSchemas(repository?: Repository): Promise<string[]>;
50
61
  /**
51
62
  * Starts watching the OpenAPI document and any overlay files for changes.
52
63
  *
53
64
  * Has no effect when neither source is watchable (for example, an HTTP
54
65
  * OpenAPI source with no local overlays).
55
66
  * Resolves once the watcher is ready.
67
+ * A caller may supply regeneration for a whole group of versioned sources.
56
68
  */
57
- watch(): Promise<void>;
69
+ watch(regenerate?: () => Promise<void>): Promise<void>;
58
70
  /** Closes the file-system watcher. */
59
71
  stopWatching(): Promise<void>;
60
72
  }
@@ -164,14 +164,35 @@ export class CodeGenerator extends EventTarget {
164
164
  await repository.writeFiles(destination, this.generateOptions);
165
165
  debug("finished writing the files");
166
166
  }
167
+ /**
168
+ * Writes only the schema types, directly into `destination`
169
+ * (or `destination/<version>` for a versioned spec), and nothing else.
170
+ *
171
+ * Unlike {@link generate}, this creates no `.cache`, routes, scenarios,
172
+ * helper types or central `types/index.ts`.
173
+ *
174
+ * @param repository - Injectable repository instance; defaults to a fresh one.
175
+ * @returns The written file paths, relative to `destination`.
176
+ */
177
+ async generateSchemas(repository = new Repository()) {
178
+ const specification = await Specification.fromFile(this.openapiPath, this.overlays);
179
+ if (specification.getRequirement("#/swagger") !== undefined) {
180
+ throw new Error("Schema-only generation does not support Swagger 2.0 documents because their schemas live under #/definitions. Convert the document to OpenAPI 3.x first.");
181
+ }
182
+ centralTypes(repository).addComponents(specification, this.version, [
183
+ "schemas",
184
+ ]);
185
+ return repository.writeSchemas(this.destination, this.version);
186
+ }
167
187
  /**
168
188
  * Starts watching the OpenAPI document and any overlay files for changes.
169
189
  *
170
190
  * Has no effect when neither source is watchable (for example, an HTTP
171
191
  * OpenAPI source with no local overlays).
172
192
  * Resolves once the watcher is ready.
193
+ * A caller may supply regeneration for a whole group of versioned sources.
173
194
  */
174
- async watch() {
195
+ async watch(regenerate = () => this.generate()) {
175
196
  const watchablePaths = getLocalOpenApiSourcePaths([
176
197
  this.openapiPath,
177
198
  ...this.overlays,
@@ -180,7 +201,7 @@ export class CodeGenerator extends EventTarget {
180
201
  return;
181
202
  }
182
203
  this.watcher = watch(watchablePaths, CHOKIDAR_OPTIONS).on("change", () => {
183
- void this.generate().then(() => {
204
+ void regenerate().then(() => {
184
205
  this.dispatchEvent(new Event("generate"));
185
206
  return true;
186
207
  }, () => {
@@ -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
+ }
@@ -42,8 +42,8 @@ export class OperationCoder extends Coder {
42
42
  const [response] = responses.map((item) => item.data);
43
43
  const content = response?.content;
44
44
  const streaming = content !== undefined &&
45
- Object.keys(content).some((media) => STREAMING_CONTENT_TYPES.has(media) &&
46
- content[media]?.itemSchema !== undefined);
45
+ Object.entries(content).some(([media, definition]) => STREAMING_CONTENT_TYPES.has(media) &&
46
+ definition?.itemSchema !== undefined);
47
47
  const method = streaming
48
48
  ? "stream"
49
49
  : response !== undefined &&
@@ -73,7 +73,7 @@ export declare class OperationTypeCoder extends TypeCoder {
73
73
  */
74
74
  protected getEffectiveParameters(): Requirement | undefined;
75
75
  /**
76
- * Builds the `OmitValueWhenNever<{…}>` dollar-argument type body and sets
76
+ * Builds the dollar-argument type body and sets
77
77
  * up all required shared-type imports on `script`.
78
78
  *
79
79
  * This helper is reused by both {@link writeCode} (non-versioned) and
@@ -96,7 +96,7 @@ export declare class OperationTypeCoder extends TypeCoder {
96
96
  * `script.importType(this)` so that the type is written to the per-version
97
97
  * file and an import is added to the calling script.
98
98
  *
99
- * Only the `OmitValueWhenNever<{…}>` type body is emitted — the
99
+ * Only the dollar-argument type body is emitted — the
100
100
  * function-wrapper `($: Versioned<…>) => MaybePromise<COUNTERFACT_RESPONSE>`
101
101
  * is assembled by the shared script's `versionsTypeStatements()`.
102
102
  */
@@ -125,7 +125,7 @@ export declare class VersionedArgTypeCoder extends OperationTypeCoder {
125
125
  exportDeclarations(): undefined;
126
126
  write(script: Script): ts.TypeNode;
127
127
  /**
128
- * Generates the `OmitValueWhenNever<{…}>` dollar-argument type and writes
128
+ * Generates the dollar-argument type and writes
129
129
  * it to the per-version script.
130
130
  */
131
131
  writeCode(script: Script): ts.TypeNode;
@@ -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";
@@ -198,7 +199,7 @@ export class OperationTypeCoder extends TypeCoder {
198
199
  return new Requirement([...map.values()], this.requirement.url, this.requirement.specification);
199
200
  }
200
201
  /**
201
- * Builds the `OmitValueWhenNever<{…}>` dollar-argument type body and sets
202
+ * Builds the dollar-argument type body and sets
202
203
  * up all required shared-type imports on `script`.
203
204
  *
204
205
  * This helper is reused by both {@link writeCode} (non-versioned) and
@@ -210,8 +211,8 @@ export class OperationTypeCoder extends TypeCoder {
210
211
  */
211
212
  buildDollarArgType(script, baseName, modulePath) {
212
213
  const xType = script.importSharedType("WideOperationArgument");
213
- script.importSharedType("OmitValueWhenNever");
214
214
  script.importSharedType("COUNTERFACT_RESPONSE");
215
+ script.contextRoutePath = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
215
216
  const contextTypeImportName = script.importExternalType("Context", {
216
217
  context: true,
217
218
  });
@@ -220,15 +221,41 @@ export class OperationTypeCoder extends TypeCoder {
220
221
  const pathType = new ParametersTypeCoder(parameters, this.version, "path").write(script);
221
222
  const headersType = new ParametersTypeCoder(parameters, this.version, "header").write(script);
222
223
  const cookieType = new ParametersTypeCoder(parameters, this.version, "cookie").write(script);
223
- const bodyRequirement = (this.requirement.get("consumes") ??
224
- this.requirement.specification?.rootRequirement?.get("consumes"))
224
+ const consumes = this.requirement.get("consumes") ??
225
+ this.requirement.specification?.rootRequirement?.get("consumes");
226
+ const legacyBody = consumes
225
227
  ? parameters
226
228
  ?.find((parameter) => ["body", "formData"].includes(parameter.get("in")?.data))
227
229
  ?.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);
230
+ : undefined;
231
+ const bodyTypes = legacyBody
232
+ ? [new SchemaTypeCoder(legacyBody, this.version).write(script)]
233
+ : [];
234
+ const requestBody = this.requirement.get("requestBody");
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 = requestBody?.get("content")?.get(mediaType)?.get("schema");
242
+ if (schema) {
243
+ const Coder = mediaType === "multipart/form-data"
244
+ ? MultipartSchemaTypeCoder
245
+ : SchemaTypeCoder;
246
+ const coder = new Coder(schema, this.version);
247
+ if (!seenBodySchemas.has(coder.id)) {
248
+ seenBodySchemas.add(coder.id);
249
+ bodyTypes.push(coder.write(script));
250
+ }
251
+ }
252
+ }
253
+ if (requestBody &&
254
+ bodyTypes.length > 0 &&
255
+ requestBody.get("required")?.data !== true) {
256
+ bodyTypes.push(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword));
257
+ }
258
+ const bodyType = bodyTypes.length === 0 ? neverType() : unionType(bodyTypes);
232
259
  const openApi2MediaTypes = (this.requirement.get("produces")?.data ??
233
260
  this.requirement.specification?.rootRequirement?.get("produces")
234
261
  ?.data);
@@ -252,24 +279,22 @@ export class OperationTypeCoder extends TypeCoder {
252
279
  : neverType();
253
280
  const querystringTypeName = this.exportParameterType(script, "querystring", querystringType, baseName, modulePath);
254
281
  const versionLiteralType = this.version !== "" ? literalType(this.version) : neverType();
255
- return typeReference("OmitValueWhenNever", [
256
- typeLiteral([
257
- typeProperty("query", queryTypeName),
258
- typeProperty("querystring", querystringTypeName),
259
- typeProperty("path", pathTypeName),
260
- typeProperty("headers", headersTypeName),
261
- typeProperty("cookie", cookieTypeName),
262
- typeProperty("body", bodyType),
263
- typeProperty("context", typeReference(contextTypeImportName)),
264
- typeProperty("response", responseType),
265
- typeProperty("x", typeReference(xType)),
266
- typeProperty("proxy", proxyType),
267
- typeProperty("auth", this.authType()),
268
- typeProperty("user", this.userType()),
269
- typeProperty("delay", delayType),
270
- typeProperty("version", versionLiteralType),
271
- ]),
272
- ]);
282
+ return typeLiteral([
283
+ typeProperty("query", queryTypeName),
284
+ typeProperty("querystring", querystringTypeName),
285
+ typeProperty("path", pathTypeName),
286
+ typeProperty("headers", headersTypeName),
287
+ typeProperty("cookie", cookieTypeName),
288
+ typeProperty("body", bodyType),
289
+ typeProperty("context", typeReference(contextTypeImportName)),
290
+ typeProperty("response", responseType),
291
+ typeProperty("x", typeReference(xType)),
292
+ typeProperty("proxy", proxyType),
293
+ typeProperty("auth", this.authType()),
294
+ typeProperty("user", this.userType()),
295
+ typeProperty("delay", delayType),
296
+ typeProperty("version", versionLiteralType),
297
+ ].filter((property) => property.type?.kind !== ts.SyntaxKind.NeverKeyword));
273
298
  }
274
299
  exportDeclarations(script, name) {
275
300
  if (this.version === "")
@@ -292,7 +317,6 @@ export class OperationTypeCoder extends TypeCoder {
292
317
  writeCode(script) {
293
318
  script.comments = READ_ONLY_COMMENTS;
294
319
  script.importSharedType("WideOperationArgument");
295
- script.importSharedType("OmitValueWhenNever");
296
320
  script.importSharedType("MaybePromise");
297
321
  script.importSharedType("COUNTERFACT_RESPONSE");
298
322
  const arg = this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
@@ -308,7 +332,7 @@ export class OperationTypeCoder extends TypeCoder {
308
332
  * `script.importType(this)` so that the type is written to the per-version
309
333
  * file and an import is added to the calling script.
310
334
  *
311
- * Only the `OmitValueWhenNever<{…}>` type body is emitted — the
335
+ * Only the dollar-argument type body is emitted — the
312
336
  * function-wrapper `($: Versioned<…>) => MaybePromise<COUNTERFACT_RESPONSE>`
313
337
  * is assembled by the shared script's `versionsTypeStatements()`.
314
338
  */
@@ -363,7 +387,7 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
363
387
  return typeReference(script.importType(this));
364
388
  }
365
389
  /**
366
- * Generates the `OmitValueWhenNever<{…}>` dollar-argument type and writes
390
+ * Generates the dollar-argument type and writes
367
391
  * it to the per-version script.
368
392
  */
369
393
  writeCode(script) {
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
  }
@@ -47,6 +47,21 @@ export declare class Repository {
47
47
  * @param options - Controls which artefacts are written.
48
48
  */
49
49
  writeFiles(destination: string, { routes, types }: WriteFilesOptions): Promise<void>;
50
+ /**
51
+ * Waits for all scripts to finish, then writes only the schemas for
52
+ * `version` directly under `destination`, without the
53
+ * `types/<version>/components/schemas/` prefix. Versioned schemas are written
54
+ * to `<destination>/<version>/`.
55
+ *
56
+ * Every other script in the repository is left unwritten. Fails, naming the
57
+ * schema, when a schema imports anything that would not be written, because
58
+ * the flattened file would then contain a broken import.
59
+ *
60
+ * @param destination - Absolute path to the output directory.
61
+ * @param version - Version label of the schemas to write (`""` when unversioned).
62
+ * @returns The output paths written, relative to `destination`.
63
+ */
64
+ writeSchemas(destination: string, version?: string): Promise<string[]>;
50
65
  /**
51
66
  * Creates the default `routes/_.context.ts` file if it does not already
52
67
  * exist.
@@ -67,7 +82,7 @@ export declare class Repository {
67
82
  * @param destination - Output root directory.
68
83
  * @param path - Repository-relative path of the script being generated.
69
84
  */
70
- findContextPath(destination: string, path: string): string;
85
+ findContextPath(destination: string, path: string, logicalPath?: string): string;
71
86
  /**
72
87
  * Walks up the directory tree from `path` to find the nearest
73
88
  * `_.context.ts` file, falling back to `routes/_.context.ts` at the root.
@@ -75,6 +90,6 @@ export declare class Repository {
75
90
  * @param destination - Output root directory.
76
91
  * @param path - Repository-relative path to start from.
77
92
  */
78
- nearestContextFile(destination: string, path: string): string;
93
+ nearestContextFile(destination: string, path: string, logicalPath?: string): string;
79
94
  }
80
95
  export {};
@@ -5,9 +5,9 @@ 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, typeAlias, 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
- import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
10
+ import { toForwardSlashPath, pathJoin, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
11
  import { writeHelperTypes } from "./scenario-file-generator.js";
12
12
  import { Script } from "./script.js";
13
13
  import { escapePathForWindows } from "./windows-escape.js";
@@ -115,7 +115,7 @@ export class Repository {
115
115
  debug("all %i scripts are finished", this.scripts.size);
116
116
  const writeFiles = Array.from(this.scripts.entries(), async ([path, script]) => {
117
117
  const fullPath = resolveDestinationPath(destination, path);
118
- const contents = await script.contents(this.findContextPath(destination, path));
118
+ const contents = await script.contents(this.findContextPath(destination, path, script.contextRoutePath));
119
119
  await ensureDirectoryExists(fullPath);
120
120
  const shouldWriteRoutes = routes && path.startsWith("routes");
121
121
  const shouldWriteTypes = types && !path.startsWith("routes");
@@ -144,6 +144,45 @@ export class Repository {
144
144
  if (types)
145
145
  await writeHelperTypes(destination, destination, true);
146
146
  }
147
+ /**
148
+ * Waits for all scripts to finish, then writes only the schemas for
149
+ * `version` directly under `destination`, without the
150
+ * `types/<version>/components/schemas/` prefix. Versioned schemas are written
151
+ * to `<destination>/<version>/`.
152
+ *
153
+ * Every other script in the repository is left unwritten. Fails, naming the
154
+ * schema, when a schema imports anything that would not be written, because
155
+ * the flattened file would then contain a broken import.
156
+ *
157
+ * @param destination - Absolute path to the output directory.
158
+ * @param version - Version label of the schemas to write (`""` when unversioned).
159
+ * @returns The output paths written, relative to `destination`.
160
+ */
161
+ async writeSchemas(destination, version = "") {
162
+ await this.finished();
163
+ const schemaPrefix = `${pathJoin("types", version, "components", "schemas")}/`;
164
+ const outputPrefix = version === "" ? "" : `${version}/`;
165
+ const schemaScripts = Array.from(this.scripts).filter(([path]) => path.startsWith(schemaPrefix));
166
+ for (const [path, script] of schemaScripts) {
167
+ const unsupportedImport = [...script.externalImport.values()].map((entry) => typeof entry.modulePath === "string" ? entry.modulePath : "context")[0] ??
168
+ [...script.imports.values()]
169
+ .map((entry) => entry.script.path)
170
+ .find((importedPath) => !importedPath.startsWith(schemaPrefix));
171
+ if (unsupportedImport !== undefined) {
172
+ throw new Error(`Cannot generate schema ${JSON.stringify(path.slice(schemaPrefix.length).replace(/\.ts$/u, ""))} on its own: it depends on ${JSON.stringify(unsupportedImport)}, which is not a schema.`);
173
+ }
174
+ }
175
+ const outputs = schemaScripts.map(([path, script]) => ({
176
+ outputPath: outputPrefix + path.slice(schemaPrefix.length),
177
+ script,
178
+ }));
179
+ await Promise.all(outputs.map(async ({ outputPath, script }) => {
180
+ const fullPath = resolveDestinationPath(destination, outputPath);
181
+ await ensureDirectoryExists(fullPath);
182
+ await fs.writeFile(fullPath, await script.contents());
183
+ }));
184
+ return outputs.map(({ outputPath }) => outputPath);
185
+ }
147
186
  /**
148
187
  * Creates the default `routes/_.context.ts` file if it does not already
149
188
  * exist.
@@ -157,6 +196,7 @@ export class Repository {
157
196
  }
158
197
  await ensureDirectoryExists(contextFilePath);
159
198
  const context = withJsDoc(ts.factory.createClassDeclaration([ts.factory.createModifier(ts.SyntaxKind.ExportKeyword)], "Context", undefined, undefined, [
199
+ withComment(ts.factory.createIndexSignature(undefined, [parameter("key", stringType())], ts.factory.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword)), "/* Delete this line to make the context type safe. */"),
160
200
  ts.factory.createConstructorDeclaration(undefined, [parameter("$", typeReference("Context$"))], ts.factory.createBlock([
161
201
  ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$"))),
162
202
  ], true)),
@@ -417,12 +457,12 @@ export class Repository {
417
457
  const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, existing);
418
458
  scanner.setTextPos(position);
419
459
  let end = position;
420
- for (let token = scanner.scan(); token !== ts.SyntaxKind.EndOfFileToken; token = scanner.scan()) {
421
- if (token === ts.SyntaxKind.NewLineTrivia)
460
+ for (let syntaxKind = scanner.scan(); syntaxKind !== ts.SyntaxKind.EndOfFileToken; syntaxKind = scanner.scan()) {
461
+ if (syntaxKind === ts.SyntaxKind.NewLineTrivia)
422
462
  return scanner.getTextPos();
423
- if (token !== ts.SyntaxKind.WhitespaceTrivia &&
424
- token !== ts.SyntaxKind.SingleLineCommentTrivia &&
425
- token !== ts.SyntaxKind.MultiLineCommentTrivia)
463
+ if (syntaxKind !== ts.SyntaxKind.WhitespaceTrivia &&
464
+ syntaxKind !== ts.SyntaxKind.SingleLineCommentTrivia &&
465
+ syntaxKind !== ts.SyntaxKind.MultiLineCommentTrivia)
426
466
  break;
427
467
  end = scanner.getTextPos();
428
468
  }
@@ -473,8 +513,8 @@ export class Repository {
473
513
  * @param destination - Output root directory.
474
514
  * @param path - Repository-relative path of the script being generated.
475
515
  */
476
- findContextPath(destination, path) {
477
- return pathRelative(nodePath.join(destination, nodePath.dirname(path)), this.nearestContextFile(destination, path));
516
+ findContextPath(destination, path, logicalPath) {
517
+ return pathRelative(nodePath.join(destination, nodePath.dirname(path)), this.nearestContextFile(destination, path, logicalPath));
478
518
  }
479
519
  /**
480
520
  * Walks up the directory tree from `path` to find the nearest
@@ -483,23 +523,26 @@ export class Repository {
483
523
  * @param destination - Output root directory.
484
524
  * @param path - Repository-relative path to start from.
485
525
  */
486
- nearestContextFile(destination, path) {
487
- const parts = pathDirname(path)
526
+ nearestContextFile(destination, path, logicalPath) {
527
+ // Operation contracts describe the endpoint itself, not just its parent.
528
+ const parts = path
529
+ .replace(/(?:\.types)?\.ts$/u, "")
488
530
  .split("/")
489
531
  .filter((part) => part !== ".");
490
532
  const pathsIndex = parts[0] === "types" ? parts.indexOf("paths") : -1;
491
- const directory = pathsIndex === 1 || pathsIndex === 2
533
+ let directory = pathsIndex === 1 || pathsIndex === 2
492
534
  ? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
493
535
  : parts.join("/");
494
- const candidate = nodePath.join(destination, directory, "_.context.ts");
495
- if (directory.length <= 1) {
496
- // No _context.ts was found so import the one that should be in the root
497
- return nodePath.join(destination, "routes", "_.context.ts");
498
- }
499
- if (existsSync(candidate)) {
500
- return candidate;
536
+ if (logicalPath !== undefined)
537
+ directory = ["routes", ...logicalPath.split("/").filter(Boolean)].join("/");
538
+ while (directory !== "." && directory !== "routes") {
539
+ const candidate = nodePath.join(destination, directory, "_.context.ts");
540
+ if (existsSync(candidate)) {
541
+ return candidate;
542
+ }
543
+ directory = pathDirname(directory);
501
544
  }
502
- return this.nearestContextFile(destination, nodePath.join(path, ".."));
545
+ return nodePath.join(destination, "routes", "_.context.ts");
503
546
  }
504
547
  }
505
548
  function renameTypeRoot(type, name) {
@@ -81,7 +81,9 @@ export class Requirement {
81
81
  return undefined;
82
82
  }
83
83
  const objectData = this.data;
84
- const child = new Requirement(objectData[key], `${this.url}/${this.escapeJsonPointer(key)}`, this.specification);
84
+ const child = new Requirement(
85
+ // eslint-disable-next-line security/detect-object-injection -- Requirement traversal intentionally resolves dynamic OpenAPI property/index names after has(key) checks.
86
+ objectData[key], `${this.url}/${this.escapeJsonPointer(key)}`, this.specification);
85
87
  child.parent = this;
86
88
  return child;
87
89
  }
@@ -91,8 +91,8 @@ function routePathToAlias(routePath) {
91
91
  .split("/")
92
92
  .filter(Boolean)
93
93
  .map((seg) => seg
94
- .replace(/\{(.+?)\}/g, (_match, name) => name.replace(/[^a-z0-9]/gi, " "))
95
- .replace(/[-_\s]([a-z])/g, (_match, c) => c.toUpperCase())
94
+ .replace(/\{(?<name>.+?)\}/g, (_match, name) => name.replace(/[^a-z0-9]/gi, " "))
95
+ .replace(/[-_\s](?<letter>[a-z])/g, (_match, c) => c.toUpperCase())
96
96
  .replace(/^[a-z]/, (c) => c.toUpperCase())
97
97
  .replace(/[^a-z0-9]/gi, ""))
98
98
  .join("") + "Context");
@@ -3,6 +3,7 @@ import { TypeCoder } from "./type-coder.js";
3
3
  import { Requirement } from "./requirement.js";
4
4
  import type { Script } from "./script.js";
5
5
  export declare class SchemaTypeCoder extends TypeCoder {
6
+ protected child(requirement: Requirement): SchemaTypeCoder;
6
7
  names(): Generator<string>;
7
8
  jsdoc(): string;
8
9
  additionalPropertiesType(script: Script): ts.TypeNode;
@@ -18,5 +19,5 @@ export declare class SchemaTypeCoder extends TypeCoder {
18
19
  writeEnum(requirement: Requirement): ts.TypeNode;
19
20
  modulePath(): string;
20
21
  writeCode(script: Script): ts.TypeNode;
21
- private writeSchema;
22
+ protected writeSchema(script: Script): ts.TypeNode;
22
23
  }
@@ -6,6 +6,9 @@ import { pathJoin } from "./forward-slash-path.js";
6
6
  import { buildJsDoc } from "./jsdoc.js";
7
7
  import { Requirement } from "./requirement.js";
8
8
  export class SchemaTypeCoder extends TypeCoder {
9
+ child(requirement) {
10
+ return new SchemaTypeCoder(requirement, this.version);
11
+ }
9
12
  names() {
10
13
  return super.names(this.requirement.refUrl?.split("/").at(-1));
11
14
  }
@@ -20,7 +23,7 @@ export class SchemaTypeCoder extends TypeCoder {
20
23
  Object.values(properties ?? {}).some((property) => property.type !== additionalProperties.type)))) {
21
24
  return unknownType();
22
25
  }
23
- return new SchemaTypeCoder(this.requirement.get("additionalProperties"), this.version).write(script);
26
+ return this.child(this.requirement.get("additionalProperties")).write(script);
24
27
  }
25
28
  objectSchema(script) {
26
29
  const data = this.requirement.data;
@@ -28,7 +31,7 @@ export class SchemaTypeCoder extends TypeCoder {
28
31
  const property = this.requirement.get("properties").get(name);
29
32
  const isRequired = data.required?.includes(name) ||
30
33
  property.data.required === true;
31
- return typeProperty(name, new SchemaTypeCoder(property, this.version).write(script), !isRequired, property.data);
34
+ return typeProperty(name, this.child(property).write(script), !isRequired, property.data);
32
35
  });
33
36
  if (data.additionalProperties) {
34
37
  members.push(ts.factory.createIndexSignature(undefined, [
@@ -48,7 +51,7 @@ export class SchemaTypeCoder extends TypeCoder {
48
51
  const items = this.requirement.get(tupleKey);
49
52
  const members = items
50
53
  .map((item, index) => {
51
- const type = new SchemaTypeCoder(item, this.version).write(script);
54
+ const type = this.child(item).write(script);
52
55
  return Number(index) < (data.minItems ?? 0)
53
56
  ? type
54
57
  : ts.factory.createOptionalTypeNode(type);
@@ -58,18 +61,14 @@ export class SchemaTypeCoder extends TypeCoder {
58
61
  const rest = this.requirement.get(restKey);
59
62
  if (rest?.data !== false &&
60
63
  (data.maxItems === undefined || data.maxItems > members.length)) {
61
- const restType = rest
62
- ? new SchemaTypeCoder(rest, this.version).write(script)
63
- : unknownType();
64
+ const restType = rest ? this.child(rest).write(script) : unknownType();
64
65
  members.push(ts.factory.createRestTypeNode(ts.factory.createArrayTypeNode(restType)));
65
66
  }
66
67
  return ts.factory.createTupleTypeNode(members);
67
68
  }
68
69
  const items = this.requirement.get("items");
69
70
  return typeReference("Array", [
70
- items
71
- ? new SchemaTypeCoder(items, this.version).write(script)
72
- : unknownType(),
71
+ items ? this.child(items).write(script) : unknownType(),
73
72
  ]);
74
73
  }
75
74
  writePrimitive(value) {
@@ -123,7 +122,7 @@ export class SchemaTypeCoder extends TypeCoder {
123
122
  const { discriminator } = this.requirement.data;
124
123
  const types = items.map((_item, index) => {
125
124
  const branch = this.requirement.get(key).get(index);
126
- const type = new SchemaTypeCoder(branch, this.version).write(script);
125
+ const type = this.child(branch).write(script);
127
126
  const values = !allOf && branch.refUrl && discriminator?.propertyName
128
127
  ? Object.entries(discriminator.mapping ?? {})
129
128
  .filter(([, ref]) => ref === branch.refUrl)
@@ -142,7 +141,7 @@ export class SchemaTypeCoder extends TypeCoder {
142
141
  if (!allOf) {
143
142
  const { discriminator } = this.requirement.data;
144
143
  if (discriminator?.defaultMapping) {
145
- types.push(new SchemaTypeCoder(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification), this.version).write(script));
144
+ types.push(this.child(new Requirement({ $ref: discriminator.defaultMapping }, "", this.requirement.specification)).write(script));
146
145
  }
147
146
  }
148
147
  return allOf
@@ -175,7 +174,7 @@ export class SchemaTypeCoder extends TypeCoder {
175
174
  .data;
176
175
  if (itemSchema) {
177
176
  return typeReference("AsyncIterable", [
178
- new SchemaTypeCoder(this.requirement.get("itemSchema"), this.version).write(script),
177
+ this.child(this.requirement.get("itemSchema")).write(script),
179
178
  ]);
180
179
  }
181
180
  if (allOf ?? anyOf ?? oneOf) {
package/dist/script.d.ts CHANGED
@@ -12,6 +12,7 @@ export type ModuleReference = string | {
12
12
  context: true;
13
13
  };
14
14
  interface ExternalImportEntry {
15
+ exportedName?: string;
15
16
  isDefault?: boolean;
16
17
  isType: boolean;
17
18
  modulePath: ModuleReference;
@@ -21,6 +22,7 @@ export declare class Script {
21
22
  path: string;
22
23
  repository: Repository;
23
24
  comments: string[];
25
+ contextRoutePath?: string;
24
26
  exports: Map<string, ExportStatement>;
25
27
  versions: Map<string, Map<string, ExportStatement>>;
26
28
  versionBuilders: Map<string, (versions: Map<string, ts.TypeNode>) => ts.Statement[]>;
package/dist/script.js CHANGED
@@ -9,6 +9,7 @@ export class Script {
9
9
  path;
10
10
  repository;
11
11
  comments = [];
12
+ contextRoutePath;
12
13
  exports = new Map();
13
14
  versions = new Map();
14
15
  versionBuilders = new Map();
@@ -124,8 +125,22 @@ export class Script {
124
125
  return this.import(coder, isType, true);
125
126
  }
126
127
  importExternal(name, modulePath, isType = false) {
127
- this.externalImport.set(name, { isType, modulePath });
128
- return name;
128
+ const existing = [...this.externalImport].find(([, entry]) => (entry.modulePath === modulePath ||
129
+ (typeof entry.modulePath !== "string" &&
130
+ typeof modulePath !== "string")) &&
131
+ entry.isType === isType &&
132
+ entry.exportedName === name);
133
+ if (existing)
134
+ return existing[0];
135
+ let local = name;
136
+ let suffix = 2;
137
+ while (this.reservedNames.has(local) ||
138
+ this.exports.has(local) ||
139
+ this.imports.has(local) ||
140
+ this.externalImport.has(local))
141
+ local = name + suffix++;
142
+ this.externalImport.set(local, { isType, modulePath, exportedName: name });
143
+ return local;
129
144
  }
130
145
  importExternalType(name, path) {
131
146
  return this.importExternal(name, path, true);
@@ -194,7 +209,7 @@ export class Script {
194
209
  pathRelative(pathDirname(this.path), "routes/_.context.ts"));
195
210
  return importDeclaration(name, modulePath.startsWith(".") || typeof entry.modulePath === "string"
196
211
  ? modulePath
197
- : `./${modulePath}`, entry.isType, entry.isDefault);
212
+ : `./${modulePath}`, entry.isType, entry.isDefault, entry.exportedName ?? name);
198
213
  });
199
214
  }
200
215
  importStatements() {
@@ -28,3 +28,4 @@ export type { ResponseBuilder } from "./response-builder.js";
28
28
  export type { ResponseBuilderFactory } from "./response-builder-factory.js";
29
29
  export type { WideOperationArgument } from "./wide-operation-argument.js";
30
30
  export type { WideResponseBuilder } from "./wide-response-builder.js";
31
+ export type { MultipartFile } from "./multipart-file.js";
@@ -0,0 +1,7 @@
1
+ /** An in-memory multipart upload. Filenames and content types are client supplied. */
2
+ export interface MultipartFile {
3
+ data: Uint8Array;
4
+ filename: string;
5
+ contentType: string;
6
+ size: number;
7
+ }
@@ -10,6 +10,7 @@ const directory = await mkdtemp(path.join(tmpdir(), "counterfact-generator-"));
10
10
  try {
11
11
  const specPath = path.join(directory, "openapi.yaml");
12
12
  const outputPath = path.join(directory, "generated");
13
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- This example reads/writes fixed relative filenames beneath its own mkdtemp directory.
13
14
  await writeFile(
14
15
  specPath,
15
16
  `openapi: 3.0.3
@@ -32,6 +33,7 @@ paths:
32
33
  }).generate();
33
34
 
34
35
  assert.match(
36
+ // eslint-disable-next-line security/detect-non-literal-fs-filename -- This example reads/writes fixed relative filenames beneath its own mkdtemp directory.
35
37
  await readFile(path.join(outputPath, "routes", "health.ts"), "utf8"),
36
38
  /export const GET/u,
37
39
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "1.1.0",
3
+ "version": "1.3.0",
4
4
  "description": "Generate Counterfact route scaffolds and OpenAPI-derived TypeScript contracts.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -53,7 +53,7 @@
53
53
  },
54
54
  "dependencies": {
55
55
  "@counterfact/openapi": "0.1.7",
56
- "@counterfact/types": "0.2.0",
56
+ "@counterfact/types": "0.3.0",
57
57
  "chokidar": "6.0.0",
58
58
  "debug": "4.4.3",
59
59
  "prettier": "3.9.10",
package/src/README.md CHANGED
@@ -31,26 +31,26 @@ Both writers serialize helper updates without rewriting each other's exports.
31
31
 
32
32
  ## Files
33
33
 
34
- | File | Description |
35
- | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
- | `code-generator.ts` | Top-level `CodeGenerator` class; orchestrates the full generate pipeline (reads the OpenAPI spec, iterates over paths/operations, drives the `Repository` to write output files) and file watching via `EventTarget` |
37
- | `specification.ts` | `Specification` class: loads and parses an OpenAPI document and provides cached `Requirement` lookup via JSON Pointer |
38
- | `requirement.ts` | `Requirement` class: wraps a single OpenAPI schema object with its URL and resolves `$ref` pointers |
39
- | `repository.ts` | `Repository` class: manages all output `Script` instances, deduplicates them, and coordinates async export resolution |
40
- | `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
41
- | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
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 |
44
- | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
45
- | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
46
- | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
47
- | `parameter-export-type-coder.ts` | `ParameterExportTypeCoder`: generates and exports the type for a single request parameter |
48
- | `responses-type-coder.ts` | `ResponsesTypeCoder`: generates the response builder factory type covering all HTTP status codes for an operation |
49
- | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
50
- | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
51
- | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
52
- | `ast.ts` | TypeScript AST construction and printing helpers |
53
- | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
34
+ | File | Description |
35
+ | -------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | `code-generator.ts` | Top-level `CodeGenerator` class; orchestrates the full generate pipeline (reads the OpenAPI spec, iterates over paths/operations, drives the `Repository` to write output files; `generateSchemas()` writes only the component schema types) and file watching via `EventTarget` |
37
+ | `specification.ts` | `Specification` class: loads and parses an OpenAPI document and provides cached `Requirement` lookup via JSON Pointer |
38
+ | `requirement.ts` | `Requirement` class: wraps a single OpenAPI schema object with its URL and resolves `$ref` pointers |
39
+ | `repository.ts` | `Repository` class: manages all output `Script` instances, deduplicates them, and coordinates async export resolution |
40
+ | `script.ts` | `Script` class: manages code generation for a single output file — imports, exports, deduplication, and Prettier formatting |
41
+ | `coder.ts` | Abstract `Coder` base class: defines the Template Method pattern used by all code-generating components |
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 |
44
+ | `operation-coder.ts` | `OperationCoder`: generates the route handler function for an OpenAPI operation |
45
+ | `operation-type-coder.ts` | `OperationTypeCoder`: generates the TypeScript type for a route handler, including parameters and response builder |
46
+ | `parameters-type-coder.ts` | `ParametersTypeCoder`: generates the typed object for path/query/header parameters of an operation |
47
+ | `parameter-export-type-coder.ts` | `ParameterExportTypeCoder`: generates and exports the type for a single request parameter |
48
+ | `responses-type-coder.ts` | `ResponsesTypeCoder`: generates the response builder factory type covering all HTTP status codes for an operation |
49
+ | `response-type-coder.ts` | `ResponseTypeCoder`: generates the type for a single HTTP response, including headers, content, and named examples |
50
+ | `schema-type-coder.ts` | `SchemaTypeCoder`: converts an OpenAPI schema definition to a TypeScript type (objects, arrays, unions, enums) |
51
+ | `schema-coder.ts` | `SchemaCoder`: generates a JSON Schema representation of an OpenAPI schema for use in runtime validation |
52
+ | `ast.ts` | TypeScript AST construction and printing helpers |
53
+ | `read-only-comments.ts` | Standard warning comments inserted into generated type files to discourage manual edits |
54
54
 
55
55
  ## Architecture
56
56