@counterfact/generator 1.1.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,21 @@
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
+
3
19
  ## 1.1.0
4
20
 
5
21
  ### Minor Changes
@@ -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
+ }
@@ -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,7 +5,7 @@ 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
10
  import { toForwardSlashPath, pathRelative, pathDirname, } from "./forward-slash-path.js";
11
11
  import { writeHelperTypes } from "./scenario-file-generator.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");
@@ -157,6 +157,7 @@ export class Repository {
157
157
  }
158
158
  await ensureDirectoryExists(contextFilePath);
159
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. */"),
160
161
  ts.factory.createConstructorDeclaration(undefined, [parameter("$", typeReference("Context$"))], ts.factory.createBlock([
161
162
  ts.factory.createExpressionStatement(ts.factory.createVoidExpression(ts.factory.createIdentifier("$"))),
162
163
  ], true)),
@@ -473,8 +474,8 @@ export class Repository {
473
474
  * @param destination - Output root directory.
474
475
  * @param path - Repository-relative path of the script being generated.
475
476
  */
476
- findContextPath(destination, path) {
477
- 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));
478
479
  }
479
480
  /**
480
481
  * Walks up the directory tree from `path` to find the nearest
@@ -483,23 +484,26 @@ export class Repository {
483
484
  * @param destination - Output root directory.
484
485
  * @param path - Repository-relative path to start from.
485
486
  */
486
- nearestContextFile(destination, path) {
487
- const parts = pathDirname(path)
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, "")
488
491
  .split("/")
489
492
  .filter((part) => part !== ".");
490
493
  const pathsIndex = parts[0] === "types" ? parts.indexOf("paths") : -1;
491
- const directory = pathsIndex === 1 || pathsIndex === 2
494
+ let directory = pathsIndex === 1 || pathsIndex === 2
492
495
  ? ["routes", ...parts.slice(pathsIndex + 1)].join("/")
493
496
  : 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;
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);
501
505
  }
502
- return this.nearestContextFile(destination, nodePath.join(path, ".."));
506
+ return nodePath.join(destination, "routes", "_.context.ts");
503
507
  }
504
508
  }
505
509
  function renameTypeRoot(type, name) {
@@ -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
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@counterfact/generator",
3
- "version": "1.1.0",
3
+ "version": "1.2.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",