@counterfact/generator 1.2.0 → 2.0.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 +55 -0
- package/dist/adopt-spellings.d.ts +15 -0
- package/dist/adopt-spellings.js +48 -0
- package/dist/case-safe-paths.d.ts +21 -0
- package/dist/case-safe-paths.js +57 -0
- package/dist/central-types.d.ts +2 -1
- package/dist/central-types.js +2 -2
- package/dist/client-multipart-schema-type-coder.d.ts +16 -0
- package/dist/client-multipart-schema-type-coder.js +78 -0
- package/dist/client-response-schemas.d.ts +29 -0
- package/dist/client-response-schemas.js +120 -0
- package/dist/client-security.d.ts +10 -0
- package/dist/client-security.js +49 -0
- package/dist/code-generator.d.ts +22 -4
- package/dist/code-generator.js +51 -57
- package/dist/generate-client.d.ts +3 -0
- package/dist/generate-client.js +418 -0
- package/dist/generate-versioned-client.d.ts +12 -0
- package/dist/generate-versioned-client.js +103 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/migrate-route-layout.d.ts +8 -0
- package/dist/migrate-route-layout.js +448 -0
- package/dist/named-client-operations.d.ts +19 -0
- package/dist/named-client-operations.js +96 -0
- package/dist/operation-coder.js +3 -3
- package/dist/operation-type-coder.d.ts +9 -3
- package/dist/operation-type-coder.js +43 -33
- package/dist/path-operations.d.ts +2 -0
- package/dist/path-operations.js +31 -0
- package/dist/prune.d.ts +1 -1
- package/dist/prune.js +10 -3
- package/dist/repository.d.ts +30 -1
- package/dist/repository.js +224 -34
- package/dist/requirement.js +3 -1
- package/dist/route-file-layout.d.ts +32 -0
- package/dist/route-file-layout.js +152 -0
- package/dist/scenario-file-generator.js +27 -7
- package/dist/script.d.ts +2 -0
- package/dist/script.js +16 -4
- package/dist/standalone-client-validators.d.ts +2 -0
- package/dist/standalone-client-validators.js +85 -0
- package/dist/swagger2-client.d.ts +31 -0
- package/dist/swagger2-client.js +92 -0
- package/examples/generate-routes.mjs +2 -0
- package/package.json +4 -3
- package/src/README.md +21 -20
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,60 @@
|
|
|
1
1
|
# @counterfact/generator
|
|
2
2
|
|
|
3
|
+
## 2.0.0
|
|
4
|
+
|
|
5
|
+
### Major Changes
|
|
6
|
+
|
|
7
|
+
- 7cf6324: Coalesce case-variant generated paths using the spelling that sorts first, independent of declaration order, while preserving CamelCase and exact OpenAPI URLs. Only routes that share a file use case-keyed method exports and route metadata; other routes keep the ordinary layout, and generated types share the canonical module. Generation migrates supported authored handlers and middleware with a backup and rejects ambiguous migrations.
|
|
8
|
+
|
|
9
|
+
### Minor Changes
|
|
10
|
+
|
|
11
|
+
- 0bc24a0: Generate Fetch clients for Swagger 2.0 in normal and client-only generation.
|
|
12
|
+
The fluent client and named SDK use Swagger response schemas for validation
|
|
13
|
+
and support legacy array encodings, form fields, file bodies, and Basic
|
|
14
|
+
authentication.
|
|
15
|
+
- 6ea99b0: OpenAPI 3.x type generation now includes a Fetch client under `client/`. Use
|
|
16
|
+
`--generate-client` to generate only the client. Reuse route prefixes with
|
|
17
|
+
`segment()` and send requests once all required inputs are present. Validated
|
|
18
|
+
responses narrow by matched status. Responses outside the contract reject with
|
|
19
|
+
an error. Response validators are compiled during generation.
|
|
20
|
+
|
|
21
|
+
Generated clients apply OpenAPI security requirements and support per-request
|
|
22
|
+
authentication, credentials, redirect handling, and cancellation.
|
|
23
|
+
|
|
24
|
+
Completed fluent requests can call `stream()` to read declared byte responses
|
|
25
|
+
as they arrive.
|
|
26
|
+
|
|
27
|
+
Use `createSdk()` for named operations grouped by path segment or OpenAPI tag.
|
|
28
|
+
The named SDK shares request handling and validated response types with the fluent client.
|
|
29
|
+
|
|
30
|
+
- de2bd09: Accept typed OpenAPI 3.x multipart objects in the fluent client and named SDK.
|
|
31
|
+
File fields accept File, Blob, or Uint8Array.
|
|
32
|
+
- 31b46b0: Generate one Fetch client entry point per versioned API group. Fluent clients select the request and response types from the configured URL prefix in the route path, such as `route("/v2/greeting")`. Named SDKs select the contract with `version()`.
|
|
33
|
+
|
|
34
|
+
Import the root fluent client to call every configured API from one route function. Import a specific group or version to include only its contracts in your application.
|
|
35
|
+
|
|
36
|
+
### Patch Changes
|
|
37
|
+
|
|
38
|
+
- Updated dependencies [0bc24a0]
|
|
39
|
+
- Updated dependencies [6ea99b0]
|
|
40
|
+
- @counterfact/types@0.4.0
|
|
41
|
+
|
|
42
|
+
## 1.3.0
|
|
43
|
+
|
|
44
|
+
### Minor Changes
|
|
45
|
+
|
|
46
|
+
- 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.
|
|
47
|
+
|
|
48
|
+
`CodeGenerator` gains `generateSchemas()` and `Repository` gains `writeSchemas()` for the same behavior.
|
|
49
|
+
|
|
50
|
+
## 1.2.1
|
|
51
|
+
|
|
52
|
+
### Patch Changes
|
|
53
|
+
|
|
54
|
+
- 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.
|
|
55
|
+
- 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.
|
|
56
|
+
- 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.
|
|
57
|
+
|
|
3
58
|
## 1.2.0
|
|
4
59
|
|
|
5
60
|
### Minor Changes
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Renames existing files and directories under `root` whose names differ from
|
|
3
|
+
* `paths` only by case, so the next write keeps the chosen spelling.
|
|
4
|
+
*
|
|
5
|
+
* On a case-insensitive file system, writing `A.ts` over an existing `a.ts`
|
|
6
|
+
* keeps the old name. Imports would then disagree with the file name, and
|
|
7
|
+
* pruning would remove the file that was just written.
|
|
8
|
+
*
|
|
9
|
+
* An entry is left alone when the chosen spelling already exists beside it,
|
|
10
|
+
* because on a case-sensitive file system the two are distinct files.
|
|
11
|
+
*
|
|
12
|
+
* @param root - Directory that `paths` are relative to.
|
|
13
|
+
* @param paths - Forward-slash relative paths, spelled as they will be written.
|
|
14
|
+
*/
|
|
15
|
+
export declare function adoptSpellings(root: string, paths: Iterable<string>): Promise<void>;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import fs from "node:fs/promises";
|
|
2
|
+
import nodePath from "node:path";
|
|
3
|
+
/* eslint-disable security/detect-non-literal-fs-filename -- only renames entries below a generator-owned destination directory. */
|
|
4
|
+
/**
|
|
5
|
+
* Renames existing files and directories under `root` whose names differ from
|
|
6
|
+
* `paths` only by case, so the next write keeps the chosen spelling.
|
|
7
|
+
*
|
|
8
|
+
* On a case-insensitive file system, writing `A.ts` over an existing `a.ts`
|
|
9
|
+
* keeps the old name. Imports would then disagree with the file name, and
|
|
10
|
+
* pruning would remove the file that was just written.
|
|
11
|
+
*
|
|
12
|
+
* An entry is left alone when the chosen spelling already exists beside it,
|
|
13
|
+
* because on a case-sensitive file system the two are distinct files.
|
|
14
|
+
*
|
|
15
|
+
* @param root - Directory that `paths` are relative to.
|
|
16
|
+
* @param paths - Forward-slash relative paths, spelled as they will be written.
|
|
17
|
+
*/
|
|
18
|
+
export async function adoptSpellings(root, paths) {
|
|
19
|
+
const listings = new Map();
|
|
20
|
+
const list = async (directory) => {
|
|
21
|
+
if (!listings.has(directory)) {
|
|
22
|
+
listings.set(directory, await fs.readdir(directory).catch((error) => {
|
|
23
|
+
if (error.code === "ENOENT" || error.code === "ENOTDIR")
|
|
24
|
+
return [];
|
|
25
|
+
throw error;
|
|
26
|
+
}));
|
|
27
|
+
}
|
|
28
|
+
return listings.get(directory);
|
|
29
|
+
};
|
|
30
|
+
for (const path of [...new Set(paths)].sort()) {
|
|
31
|
+
let directory = root;
|
|
32
|
+
for (const segment of path.split("/")) {
|
|
33
|
+
const names = await list(directory);
|
|
34
|
+
if (!names.includes(segment)) {
|
|
35
|
+
const index = names.findIndex((name) => name.toLowerCase() === segment.toLowerCase());
|
|
36
|
+
if (index !== -1) {
|
|
37
|
+
// A case-only rename is a no-op on some file systems, so go through
|
|
38
|
+
// a temporary name.
|
|
39
|
+
const temporary = nodePath.join(directory, `.${segment}.${process.pid}.case-rename`);
|
|
40
|
+
await fs.rename(nodePath.join(directory, names.at(index)), temporary);
|
|
41
|
+
await fs.rename(temporary, nodePath.join(directory, segment));
|
|
42
|
+
names.splice(index, 1, segment);
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
directory = nodePath.join(directory, segment);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps repository paths to output paths that stay distinct on
|
|
3
|
+
* case-insensitive file systems (the default on macOS and Windows).
|
|
4
|
+
*
|
|
5
|
+
* OpenAPI names are case-sensitive, so a document can contain both
|
|
6
|
+
* `/Companies/{id}` and `/companies/{id}`, or schemas named `OutputType` and
|
|
7
|
+
* `OutPutType`. Written as-is, those paths would share directories under
|
|
8
|
+
* different spellings, or overwrite each other.
|
|
9
|
+
*
|
|
10
|
+
* - Directories whose names differ only by case are merged under one
|
|
11
|
+
* spelling.
|
|
12
|
+
* - A file whose name differs only by case from another file in the same
|
|
13
|
+
* directory gets the next free numeric suffix (`OutputType_2.ts`). Suffixes
|
|
14
|
+
* skip names that another input path already uses, so a file without a
|
|
15
|
+
* case-insensitive twin always keeps its name.
|
|
16
|
+
*
|
|
17
|
+
* Paths without a case-insensitive twin map to themselves. The first
|
|
18
|
+
* spelling in code-unit order wins, so the result does not depend on the
|
|
19
|
+
* order in which paths are discovered.
|
|
20
|
+
*/
|
|
21
|
+
export declare function caseSafeOutputPaths(paths: Iterable<string>): Map<string, string>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Maps repository paths to output paths that stay distinct on
|
|
3
|
+
* case-insensitive file systems (the default on macOS and Windows).
|
|
4
|
+
*
|
|
5
|
+
* OpenAPI names are case-sensitive, so a document can contain both
|
|
6
|
+
* `/Companies/{id}` and `/companies/{id}`, or schemas named `OutputType` and
|
|
7
|
+
* `OutPutType`. Written as-is, those paths would share directories under
|
|
8
|
+
* different spellings, or overwrite each other.
|
|
9
|
+
*
|
|
10
|
+
* - Directories whose names differ only by case are merged under one
|
|
11
|
+
* spelling.
|
|
12
|
+
* - A file whose name differs only by case from another file in the same
|
|
13
|
+
* directory gets the next free numeric suffix (`OutputType_2.ts`). Suffixes
|
|
14
|
+
* skip names that another input path already uses, so a file without a
|
|
15
|
+
* case-insensitive twin always keeps its name.
|
|
16
|
+
*
|
|
17
|
+
* Paths without a case-insensitive twin map to themselves. The first
|
|
18
|
+
* spelling in code-unit order wins, so the result does not depend on the
|
|
19
|
+
* order in which paths are discovered.
|
|
20
|
+
*/
|
|
21
|
+
export function caseSafeOutputPaths(paths) {
|
|
22
|
+
const directories = new Map();
|
|
23
|
+
const entries = [...new Set(paths)].sort().map((path) => {
|
|
24
|
+
const segments = path.split("/");
|
|
25
|
+
const fileName = segments.pop();
|
|
26
|
+
let directory = "";
|
|
27
|
+
for (const segment of segments) {
|
|
28
|
+
const candidate = directory === "" ? segment : `${directory}/${segment}`;
|
|
29
|
+
const key = candidate.toLowerCase();
|
|
30
|
+
if (!directories.has(key))
|
|
31
|
+
directories.set(key, candidate);
|
|
32
|
+
directory = directories.get(key);
|
|
33
|
+
}
|
|
34
|
+
return { fileName, path, prefix: directory === "" ? "" : `${directory}/` };
|
|
35
|
+
});
|
|
36
|
+
// Reserve every natural name first, so a suffixed file never displaces a
|
|
37
|
+
// file that has no case-insensitive twin.
|
|
38
|
+
const reserved = new Set(entries.map(({ fileName, prefix }) => `${prefix}${fileName}`.toLowerCase()));
|
|
39
|
+
const taken = new Set();
|
|
40
|
+
const outputPaths = new Map();
|
|
41
|
+
const isFree = (candidate) => !taken.has(candidate.toLowerCase()) &&
|
|
42
|
+
!reserved.has(candidate.toLowerCase());
|
|
43
|
+
for (const { fileName, path, prefix } of entries) {
|
|
44
|
+
const extensionStart = fileName.indexOf(".", 1);
|
|
45
|
+
const stem = extensionStart === -1 ? fileName : fileName.slice(0, extensionStart);
|
|
46
|
+
const extension = extensionStart === -1 ? "" : fileName.slice(extensionStart);
|
|
47
|
+
let outputPath = `${prefix}${fileName}`;
|
|
48
|
+
for (let suffix = 2; taken.has(outputPath.toLowerCase()); suffix += 1) {
|
|
49
|
+
const candidate = `${prefix}${stem}_${suffix}${extension}`;
|
|
50
|
+
if (isFree(candidate))
|
|
51
|
+
outputPath = candidate;
|
|
52
|
+
}
|
|
53
|
+
taken.add(outputPath.toLowerCase());
|
|
54
|
+
outputPaths.set(path, outputPath);
|
|
55
|
+
}
|
|
56
|
+
return outputPaths;
|
|
57
|
+
}
|
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) => {
|
|
@@ -0,0 +1,16 @@
|
|
|
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
|
+
/** Model file inputs directly without changing the JSON representation of a shared schema. */
|
|
6
|
+
export declare class ClientMultipartSchemaTypeCoder extends SchemaTypeCoder {
|
|
7
|
+
private readonly position;
|
|
8
|
+
private readonly legacyStrings;
|
|
9
|
+
private readonly encoding?;
|
|
10
|
+
constructor(requirement: Requirement, version?: string, position?: "root" | "part" | "nested", legacyStrings?: boolean, encoding?: Requirement | undefined);
|
|
11
|
+
protected child(requirement: Requirement): SchemaTypeCoder;
|
|
12
|
+
get id(): string;
|
|
13
|
+
delegate(): Promise<ClientMultipartSchemaTypeCoder>;
|
|
14
|
+
modulePath(): string;
|
|
15
|
+
protected writeSchema(script: Script): ts.TypeNode;
|
|
16
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { typeReference, unionType } from "./ast.js";
|
|
2
|
+
import { SchemaTypeCoder } from "./schema-type-coder.js";
|
|
3
|
+
/** Model file inputs directly without changing the JSON representation of a shared schema. */
|
|
4
|
+
export class ClientMultipartSchemaTypeCoder extends SchemaTypeCoder {
|
|
5
|
+
position;
|
|
6
|
+
legacyStrings;
|
|
7
|
+
encoding;
|
|
8
|
+
constructor(requirement, version = "", position = "root", legacyStrings = false, encoding) {
|
|
9
|
+
super(requirement, version);
|
|
10
|
+
this.position = position;
|
|
11
|
+
this.legacyStrings = legacyStrings;
|
|
12
|
+
this.encoding = encoding;
|
|
13
|
+
}
|
|
14
|
+
child(requirement) {
|
|
15
|
+
const properties = this.requirement.get("properties");
|
|
16
|
+
const property = properties !== undefined && requirement.parent?.url === properties.url;
|
|
17
|
+
const position = property
|
|
18
|
+
? this.position === "root"
|
|
19
|
+
? "part"
|
|
20
|
+
: "nested"
|
|
21
|
+
: this.position;
|
|
22
|
+
if (property && this.position === "root" && this.encoding) {
|
|
23
|
+
const name = requirement.unescapeJsonPointer(requirement.url.slice(properties.url.length + 1));
|
|
24
|
+
const contentType = this.encoding.get(name)?.get("contentType")?.data;
|
|
25
|
+
if (typeof contentType === "string" &&
|
|
26
|
+
contentType.split(",").every((type) => {
|
|
27
|
+
const essence = type.split(";")[0]?.trim().toLowerCase();
|
|
28
|
+
return essence === "application/json" || essence?.endsWith("+json");
|
|
29
|
+
}))
|
|
30
|
+
return new SchemaTypeCoder(requirement, this.version);
|
|
31
|
+
}
|
|
32
|
+
return new ClientMultipartSchemaTypeCoder(requirement, this.version, position, this.legacyStrings, position === "root" ? this.encoding : undefined);
|
|
33
|
+
}
|
|
34
|
+
get id() {
|
|
35
|
+
return `${super.id}:${this.position}:${this.legacyStrings}:${this.encoding?.url ?? ""}`;
|
|
36
|
+
}
|
|
37
|
+
async delegate() {
|
|
38
|
+
return this.requirement.isReference
|
|
39
|
+
? new ClientMultipartSchemaTypeCoder(this.requirement.reference(), this.version, this.position, this.legacyStrings, this.encoding)
|
|
40
|
+
: this;
|
|
41
|
+
}
|
|
42
|
+
modulePath() {
|
|
43
|
+
return super.modulePath().replace("types/", "types/multipart/");
|
|
44
|
+
}
|
|
45
|
+
writeSchema(script) {
|
|
46
|
+
const raw = this.requirement.get("type")?.data;
|
|
47
|
+
const types = Array.isArray(raw) ? raw : [raw];
|
|
48
|
+
const binaryString = types.includes("string") &&
|
|
49
|
+
this.requirement.get("format")?.data === "binary";
|
|
50
|
+
const data = this.requirement.data;
|
|
51
|
+
const openapi = this.requirement.specification?.getRequirement("#/openapi")?.data;
|
|
52
|
+
const emptyRawPart = this.position === "part" &&
|
|
53
|
+
typeof openapi === "string" &&
|
|
54
|
+
/^3\.[1-9]\d*\./u.test(openapi) &&
|
|
55
|
+
data !== null &&
|
|
56
|
+
typeof data === "object" &&
|
|
57
|
+
Object.keys(data).every((key) => ["title", "description", "$comment"].includes(key));
|
|
58
|
+
const rawBinary = raw === undefined &&
|
|
59
|
+
(emptyRawPart ||
|
|
60
|
+
typeof this.requirement.get("contentMediaType")?.data === "string") &&
|
|
61
|
+
!["contentEncoding", "properties", "items", "additionalProperties"].some((keyword) => this.requirement.has(keyword));
|
|
62
|
+
if (!(binaryString || rawBinary || types.includes("file")) ||
|
|
63
|
+
["allOf", "anyOf", "oneOf", "enum", "const"].some((keyword) => this.requirement.has(keyword))) {
|
|
64
|
+
return super.writeSchema(script);
|
|
65
|
+
}
|
|
66
|
+
const alternatives = types.filter((type) => type !== undefined &&
|
|
67
|
+
type !== "file" &&
|
|
68
|
+
(type !== "string" || !binaryString));
|
|
69
|
+
return unionType([
|
|
70
|
+
typeReference("Blob"),
|
|
71
|
+
typeReference("Uint8Array"),
|
|
72
|
+
...(this.legacyStrings && (binaryString || types.includes("file"))
|
|
73
|
+
? [this.writeType(script, "string")]
|
|
74
|
+
: []),
|
|
75
|
+
...alternatives.map((type) => this.writeType(script, type)),
|
|
76
|
+
]);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { Requirement } from "./requirement.js";
|
|
2
|
+
import type { Specification } from "./specification.js";
|
|
3
|
+
/** Collect response schemas and their bundled references in one schema resource. */
|
|
4
|
+
export declare class ClientResponseSchemas {
|
|
5
|
+
private readonly specification;
|
|
6
|
+
private readonly definitions;
|
|
7
|
+
private readonly validators;
|
|
8
|
+
private readonly keys;
|
|
9
|
+
private readonly draft;
|
|
10
|
+
private readonly resource;
|
|
11
|
+
constructor(specification: Specification);
|
|
12
|
+
add(schema: Requirement): string;
|
|
13
|
+
private addDefinition;
|
|
14
|
+
output(): {
|
|
15
|
+
draft: "7" | "2020-12";
|
|
16
|
+
validators: {
|
|
17
|
+
[k: string]: string;
|
|
18
|
+
};
|
|
19
|
+
schema: {
|
|
20
|
+
$id: string;
|
|
21
|
+
$defs: {
|
|
22
|
+
[k: string]: unknown;
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
} | undefined;
|
|
26
|
+
private reference;
|
|
27
|
+
private pointer;
|
|
28
|
+
private visit;
|
|
29
|
+
}
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
import { isSwagger2 } from "./swagger2-client.js";
|
|
2
|
+
const schemaMaps = new Set([
|
|
3
|
+
"$defs",
|
|
4
|
+
"definitions",
|
|
5
|
+
"properties",
|
|
6
|
+
"patternProperties",
|
|
7
|
+
"dependentSchemas",
|
|
8
|
+
"dependencies",
|
|
9
|
+
]);
|
|
10
|
+
const subschemas = new Set([
|
|
11
|
+
"additionalItems",
|
|
12
|
+
"additionalProperties",
|
|
13
|
+
"allOf",
|
|
14
|
+
"anyOf",
|
|
15
|
+
"contains",
|
|
16
|
+
"contentSchema",
|
|
17
|
+
"else",
|
|
18
|
+
"if",
|
|
19
|
+
"items",
|
|
20
|
+
"not",
|
|
21
|
+
"oneOf",
|
|
22
|
+
"prefixItems",
|
|
23
|
+
"propertyNames",
|
|
24
|
+
"then",
|
|
25
|
+
"unevaluatedItems",
|
|
26
|
+
"unevaluatedProperties",
|
|
27
|
+
]);
|
|
28
|
+
/** Collect response schemas and their bundled references in one schema resource. */
|
|
29
|
+
export class ClientResponseSchemas {
|
|
30
|
+
specification;
|
|
31
|
+
definitions = new Map();
|
|
32
|
+
validators = new Set();
|
|
33
|
+
keys = new Map();
|
|
34
|
+
draft;
|
|
35
|
+
resource = "https://counterfact.invalid/client-response-schemas";
|
|
36
|
+
constructor(specification) {
|
|
37
|
+
this.specification = specification;
|
|
38
|
+
const version = String(specification.getRequirement("#/openapi")?.data);
|
|
39
|
+
this.draft =
|
|
40
|
+
isSwagger2(specification) || version.startsWith("3.0.") ? "7" : "2020-12";
|
|
41
|
+
}
|
|
42
|
+
add(schema) {
|
|
43
|
+
const key = this.addDefinition(schema);
|
|
44
|
+
this.validators.add(key);
|
|
45
|
+
return key;
|
|
46
|
+
}
|
|
47
|
+
addDefinition(schema) {
|
|
48
|
+
const previous = this.keys.get(schema.data);
|
|
49
|
+
if (previous !== undefined)
|
|
50
|
+
return previous;
|
|
51
|
+
const key = `schema${this.keys.size}`;
|
|
52
|
+
// Allocate the key before following references so recursive schemas can point back to it.
|
|
53
|
+
this.keys.set(schema.data, key);
|
|
54
|
+
this.definitions.set(key, this.visit(schema.data, false));
|
|
55
|
+
return key;
|
|
56
|
+
}
|
|
57
|
+
output() {
|
|
58
|
+
if (this.definitions.size === 0)
|
|
59
|
+
return undefined;
|
|
60
|
+
return {
|
|
61
|
+
draft: this.draft,
|
|
62
|
+
validators: Object.fromEntries([...this.validators].map((key) => [key, this.pointer(key)])),
|
|
63
|
+
schema: {
|
|
64
|
+
$id: this.resource,
|
|
65
|
+
$defs: Object.fromEntries(this.definitions),
|
|
66
|
+
},
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
reference(pointer) {
|
|
70
|
+
if (!pointer.startsWith("#/"))
|
|
71
|
+
return undefined;
|
|
72
|
+
const target = this.specification.getRequirement(pointer);
|
|
73
|
+
return target && this.pointer(this.addDefinition(target));
|
|
74
|
+
}
|
|
75
|
+
pointer(key) {
|
|
76
|
+
return this.resource + "#/$defs/" + key;
|
|
77
|
+
}
|
|
78
|
+
visit(schema, nestedResource) {
|
|
79
|
+
if (Array.isArray(schema)) {
|
|
80
|
+
return schema.map((child) => this.visit(child, nestedResource));
|
|
81
|
+
}
|
|
82
|
+
if (typeof schema !== "object" || schema === null)
|
|
83
|
+
return schema;
|
|
84
|
+
const entries = Object.entries(schema);
|
|
85
|
+
const localResource = nestedResource || entries.some(([key]) => key === "$id");
|
|
86
|
+
const keywords = new Map(entries);
|
|
87
|
+
return Object.fromEntries(entries.flatMap(([key, value]) => {
|
|
88
|
+
// Swagger 2.0 and OpenAPI 3.0 express exclusive limits as booleans beside the limit.
|
|
89
|
+
if (this.draft === "7" && typeof value === "boolean") {
|
|
90
|
+
const limit = key === "exclusiveMinimum"
|
|
91
|
+
? keywords.get("minimum")
|
|
92
|
+
: key === "exclusiveMaximum"
|
|
93
|
+
? keywords.get("maximum")
|
|
94
|
+
: undefined;
|
|
95
|
+
if (key === "exclusiveMinimum" || key === "exclusiveMaximum") {
|
|
96
|
+
return value && typeof limit === "number" ? [[key, limit]] : [];
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (key === "$ref" && typeof value === "string" && !localResource) {
|
|
100
|
+
return [[key, this.reference(value) ?? value]];
|
|
101
|
+
}
|
|
102
|
+
if (schemaMaps.has(key) &&
|
|
103
|
+
typeof value === "object" &&
|
|
104
|
+
value !== null) {
|
|
105
|
+
return [
|
|
106
|
+
[
|
|
107
|
+
key,
|
|
108
|
+
Object.fromEntries(Object.entries(value).map(([name, child]) => [
|
|
109
|
+
name,
|
|
110
|
+
this.visit(child, localResource),
|
|
111
|
+
])),
|
|
112
|
+
],
|
|
113
|
+
];
|
|
114
|
+
}
|
|
115
|
+
return [
|
|
116
|
+
[key, subschemas.has(key) ? this.visit(value, localResource) : value],
|
|
117
|
+
];
|
|
118
|
+
}));
|
|
119
|
+
}
|
|
120
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { ClientSecurityScheme } from "@counterfact/types/client-route";
|
|
2
|
+
import type { Requirement } from "./requirement.js";
|
|
3
|
+
import type { Specification } from "./specification.js";
|
|
4
|
+
export declare function clientSecuritySchemes(specification: Specification): {
|
|
5
|
+
name: string;
|
|
6
|
+
scheme: ClientSecurityScheme;
|
|
7
|
+
}[];
|
|
8
|
+
export declare function clientSecurityRequirements(operation: Requirement): {
|
|
9
|
+
[k: string]: string[];
|
|
10
|
+
}[] | undefined;
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { isSwagger2 } from "./swagger2-client.js";
|
|
2
|
+
export function clientSecuritySchemes(specification) {
|
|
3
|
+
return (specification
|
|
4
|
+
.getRequirement(isSwagger2(specification)
|
|
5
|
+
? "#/securityDefinitions"
|
|
6
|
+
: "#/components/securitySchemes")
|
|
7
|
+
?.flatMap((scheme, name) => {
|
|
8
|
+
const type = scheme.get("type")?.data;
|
|
9
|
+
const http = scheme.get("scheme")?.data;
|
|
10
|
+
if (type === "basic" ||
|
|
11
|
+
(type === "http" &&
|
|
12
|
+
typeof http === "string" &&
|
|
13
|
+
http.toLowerCase() === "basic")) {
|
|
14
|
+
return [{ name, scheme: { type: "basic" } }];
|
|
15
|
+
}
|
|
16
|
+
if (type === "oauth2" ||
|
|
17
|
+
type === "openIdConnect" ||
|
|
18
|
+
(type === "http" &&
|
|
19
|
+
typeof http === "string" &&
|
|
20
|
+
http.toLowerCase() === "bearer")) {
|
|
21
|
+
return [{ name, scheme: { type: "bearer" } }];
|
|
22
|
+
}
|
|
23
|
+
const location = scheme.get("in")?.data;
|
|
24
|
+
const wireName = scheme.get("name")?.data;
|
|
25
|
+
if (type === "apiKey" &&
|
|
26
|
+
typeof wireName === "string" &&
|
|
27
|
+
(location === "header" ||
|
|
28
|
+
location === "query" ||
|
|
29
|
+
location === "cookie")) {
|
|
30
|
+
return [
|
|
31
|
+
{
|
|
32
|
+
name,
|
|
33
|
+
scheme: { type: "apiKey", location, name: wireName },
|
|
34
|
+
},
|
|
35
|
+
];
|
|
36
|
+
}
|
|
37
|
+
return [];
|
|
38
|
+
}) ?? []);
|
|
39
|
+
}
|
|
40
|
+
export function clientSecurityRequirements(operation) {
|
|
41
|
+
const security = operation.get("security") ??
|
|
42
|
+
operation.specification?.getRequirement("#/security");
|
|
43
|
+
return security?.map((requirement) => Object.fromEntries(requirement.map((scopes, name) => [
|
|
44
|
+
name,
|
|
45
|
+
Array.isArray(scopes.data)
|
|
46
|
+
? scopes.data.filter((scope) => typeof scope === "string")
|
|
47
|
+
: [],
|
|
48
|
+
])));
|
|
49
|
+
}
|
package/dist/code-generator.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { ClientGroupingOptions } from "./named-client-operations.js";
|
|
1
2
|
import { Repository } from "./repository.js";
|
|
2
3
|
/**
|
|
3
4
|
* Orchestrates the code-generation pipeline and optional file-system watching.
|
|
@@ -13,7 +14,7 @@ export declare class CodeGenerator extends EventTarget {
|
|
|
13
14
|
private readonly overlays;
|
|
14
15
|
private readonly generateOptions;
|
|
15
16
|
private watcher;
|
|
16
|
-
constructor(openApiPath: string, destination: string, generateOptions: {
|
|
17
|
+
constructor(openApiPath: string, destination: string, generateOptions: ClientGroupingOptions & {
|
|
17
18
|
prune?: boolean;
|
|
18
19
|
routes?: boolean;
|
|
19
20
|
types?: boolean;
|
|
@@ -41,20 +42,37 @@ export declare class CodeGenerator extends EventTarget {
|
|
|
41
42
|
*
|
|
42
43
|
* Loads the OpenAPI spec from `openapiPath`, optionally prunes defunct route
|
|
43
44
|
* files, registers all path operations as {@link OperationCoder} exports, and
|
|
44
|
-
* writes the resulting TypeScript files to `destination`.
|
|
45
|
+
* writes the resulting TypeScript files to `destination`. Type generation
|
|
46
|
+
* also writes a Fetch client.
|
|
45
47
|
*
|
|
46
48
|
* @param repository - Injectable repository instance; defaults to a fresh one
|
|
47
49
|
* (primarily useful in tests).
|
|
48
50
|
*/
|
|
49
|
-
generate(repository?: Repository): Promise<void>;
|
|
51
|
+
generate(repository?: Repository, deferWrite?: boolean): Promise<void>;
|
|
52
|
+
/** Write the complete shared route layout once all versions have registered. */
|
|
53
|
+
finishGeneration(repository: Repository): Promise<void>;
|
|
54
|
+
/**
|
|
55
|
+
* Writes only the schema types, directly into `destination`
|
|
56
|
+
* (or `destination/<version>` for a versioned spec), and nothing else.
|
|
57
|
+
*
|
|
58
|
+
* Unlike {@link generate}, this creates no `.cache`, routes, scenarios,
|
|
59
|
+
* helper types or central `types/index.ts`.
|
|
60
|
+
*
|
|
61
|
+
* @param repository - Injectable repository instance; defaults to a fresh one.
|
|
62
|
+
* @returns The written file paths, relative to `destination`.
|
|
63
|
+
*/
|
|
64
|
+
generateSchemas(repository?: Repository): Promise<string[]>;
|
|
65
|
+
/** Generate a standalone Fetch client for this spec. */
|
|
66
|
+
generateClient(): Promise<string[]>;
|
|
50
67
|
/**
|
|
51
68
|
* Starts watching the OpenAPI document and any overlay files for changes.
|
|
52
69
|
*
|
|
53
70
|
* Has no effect when neither source is watchable (for example, an HTTP
|
|
54
71
|
* OpenAPI source with no local overlays).
|
|
55
72
|
* Resolves once the watcher is ready.
|
|
73
|
+
* A caller may supply regeneration for a whole group of versioned sources.
|
|
56
74
|
*/
|
|
57
|
-
watch(): Promise<void>;
|
|
75
|
+
watch(regenerate?: () => Promise<void>): Promise<void>;
|
|
58
76
|
/** Closes the file-system watcher. */
|
|
59
77
|
stopWatching(): Promise<void>;
|
|
60
78
|
}
|