@counterfact/generator 1.2.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 +16 -0
- package/dist/central-types.d.ts +2 -1
- package/dist/central-types.js +2 -2
- package/dist/code-generator.d.ts +13 -1
- package/dist/code-generator.js +23 -2
- package/dist/operation-coder.js +2 -2
- package/dist/operation-type-coder.d.ts +3 -3
- package/dist/operation-type-coder.js +26 -28
- package/dist/repository.d.ts +15 -0
- package/dist/repository.js +45 -6
- package/dist/requirement.js +3 -1
- package/dist/scenario-file-generator.js +2 -2
- package/examples/generate-routes.mjs +2 -0
- package/package.json +1 -1
- package/src/README.md +20 -20
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,21 @@
|
|
|
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
|
+
|
|
3
19
|
## 1.2.0
|
|
4
20
|
|
|
5
21
|
### Minor Changes
|
package/dist/central-types.d.ts
CHANGED
|
@@ -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 {};
|
package/dist/central-types.js
CHANGED
|
@@ -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
|
|
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) => {
|
package/dist/code-generator.d.ts
CHANGED
|
@@ -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
|
}
|
package/dist/code-generator.js
CHANGED
|
@@ -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
|
|
204
|
+
void regenerate().then(() => {
|
|
184
205
|
this.dispatchEvent(new Event("generate"));
|
|
185
206
|
return true;
|
|
186
207
|
}, () => {
|
package/dist/operation-coder.js
CHANGED
|
@@ -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.
|
|
46
|
-
|
|
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
|
|
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
|
|
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
|
|
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;
|
|
@@ -199,7 +199,7 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
199
199
|
return new Requirement([...map.values()], this.requirement.url, this.requirement.specification);
|
|
200
200
|
}
|
|
201
201
|
/**
|
|
202
|
-
* Builds the
|
|
202
|
+
* Builds the dollar-argument type body and sets
|
|
203
203
|
* up all required shared-type imports on `script`.
|
|
204
204
|
*
|
|
205
205
|
* This helper is reused by both {@link writeCode} (non-versioned) and
|
|
@@ -211,7 +211,6 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
211
211
|
*/
|
|
212
212
|
buildDollarArgType(script, baseName, modulePath) {
|
|
213
213
|
const xType = script.importSharedType("WideOperationArgument");
|
|
214
|
-
script.importSharedType("OmitValueWhenNever");
|
|
215
214
|
script.importSharedType("COUNTERFACT_RESPONSE");
|
|
216
215
|
script.contextRoutePath = normalizeOpenApiPath(this.requirement.url.split("/").at(-2).replaceAll("~1", "/"));
|
|
217
216
|
const contextTypeImportName = script.importExternalType("Context", {
|
|
@@ -232,17 +231,14 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
232
231
|
const bodyTypes = legacyBody
|
|
233
232
|
? [new SchemaTypeCoder(legacyBody, this.version).write(script)]
|
|
234
233
|
: [];
|
|
234
|
+
const requestBody = this.requirement.get("requestBody");
|
|
235
235
|
const seenBodySchemas = new Set();
|
|
236
236
|
for (const mediaType of [
|
|
237
237
|
"application/json",
|
|
238
238
|
"application/x-www-form-urlencoded",
|
|
239
239
|
"multipart/form-data",
|
|
240
240
|
]) {
|
|
241
|
-
const schema =
|
|
242
|
-
.get("requestBody")
|
|
243
|
-
?.get("content")
|
|
244
|
-
?.get(mediaType)
|
|
245
|
-
?.get("schema");
|
|
241
|
+
const schema = requestBody?.get("content")?.get(mediaType)?.get("schema");
|
|
246
242
|
if (schema) {
|
|
247
243
|
const Coder = mediaType === "multipart/form-data"
|
|
248
244
|
? MultipartSchemaTypeCoder
|
|
@@ -254,6 +250,11 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
254
250
|
}
|
|
255
251
|
}
|
|
256
252
|
}
|
|
253
|
+
if (requestBody &&
|
|
254
|
+
bodyTypes.length > 0 &&
|
|
255
|
+
requestBody.get("required")?.data !== true) {
|
|
256
|
+
bodyTypes.push(ts.factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword));
|
|
257
|
+
}
|
|
257
258
|
const bodyType = bodyTypes.length === 0 ? neverType() : unionType(bodyTypes);
|
|
258
259
|
const openApi2MediaTypes = (this.requirement.get("produces")?.data ??
|
|
259
260
|
this.requirement.specification?.rootRequirement?.get("produces")
|
|
@@ -278,24 +279,22 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
278
279
|
: neverType();
|
|
279
280
|
const querystringTypeName = this.exportParameterType(script, "querystring", querystringType, baseName, modulePath);
|
|
280
281
|
const versionLiteralType = this.version !== "" ? literalType(this.version) : neverType();
|
|
281
|
-
return
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
]),
|
|
298
|
-
]);
|
|
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));
|
|
299
298
|
}
|
|
300
299
|
exportDeclarations(script, name) {
|
|
301
300
|
if (this.version === "")
|
|
@@ -318,7 +317,6 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
318
317
|
writeCode(script) {
|
|
319
318
|
script.comments = READ_ONLY_COMMENTS;
|
|
320
319
|
script.importSharedType("WideOperationArgument");
|
|
321
|
-
script.importSharedType("OmitValueWhenNever");
|
|
322
320
|
script.importSharedType("MaybePromise");
|
|
323
321
|
script.importSharedType("COUNTERFACT_RESPONSE");
|
|
324
322
|
const arg = this.buildDollarArgType(script, this.getOperationBaseName(), this.modulePath());
|
|
@@ -334,7 +332,7 @@ export class OperationTypeCoder extends TypeCoder {
|
|
|
334
332
|
* `script.importType(this)` so that the type is written to the per-version
|
|
335
333
|
* file and an import is added to the calling script.
|
|
336
334
|
*
|
|
337
|
-
* Only the
|
|
335
|
+
* Only the dollar-argument type body is emitted — the
|
|
338
336
|
* function-wrapper `($: Versioned<…>) => MaybePromise<COUNTERFACT_RESPONSE>`
|
|
339
337
|
* is assembled by the shared script's `versionsTypeStatements()`.
|
|
340
338
|
*/
|
|
@@ -389,7 +387,7 @@ export class VersionedArgTypeCoder extends OperationTypeCoder {
|
|
|
389
387
|
return typeReference(script.importType(this));
|
|
390
388
|
}
|
|
391
389
|
/**
|
|
392
|
-
* Generates the
|
|
390
|
+
* Generates the dollar-argument type and writes
|
|
393
391
|
* it to the per-version script.
|
|
394
392
|
*/
|
|
395
393
|
writeCode(script) {
|
package/dist/repository.d.ts
CHANGED
|
@@ -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.
|
package/dist/repository.js
CHANGED
|
@@ -7,7 +7,7 @@ import createDebug from "debug";
|
|
|
7
7
|
import ts from "typescript";
|
|
8
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";
|
|
@@ -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.
|
|
@@ -418,12 +457,12 @@ export class Repository {
|
|
|
418
457
|
const scanner = ts.createScanner(ts.ScriptTarget.Latest, false, ts.LanguageVariant.Standard, existing);
|
|
419
458
|
scanner.setTextPos(position);
|
|
420
459
|
let end = position;
|
|
421
|
-
for (let
|
|
422
|
-
if (
|
|
460
|
+
for (let syntaxKind = scanner.scan(); syntaxKind !== ts.SyntaxKind.EndOfFileToken; syntaxKind = scanner.scan()) {
|
|
461
|
+
if (syntaxKind === ts.SyntaxKind.NewLineTrivia)
|
|
423
462
|
return scanner.getTextPos();
|
|
424
|
-
if (
|
|
425
|
-
|
|
426
|
-
|
|
463
|
+
if (syntaxKind !== ts.SyntaxKind.WhitespaceTrivia &&
|
|
464
|
+
syntaxKind !== ts.SyntaxKind.SingleLineCommentTrivia &&
|
|
465
|
+
syntaxKind !== ts.SyntaxKind.MultiLineCommentTrivia)
|
|
427
466
|
break;
|
|
428
467
|
end = scanner.getTextPos();
|
|
429
468
|
}
|
package/dist/requirement.js
CHANGED
|
@@ -81,7 +81,9 @@ export class Requirement {
|
|
|
81
81
|
return undefined;
|
|
82
82
|
}
|
|
83
83
|
const objectData = this.data;
|
|
84
|
-
const child = new Requirement(
|
|
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(/\{(
|
|
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");
|
|
@@ -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
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
|
|