@wirecat/cli-base 0.107.0 → 0.108.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 +87 -0
- package/README.md +2 -1
- package/dist/codegen/fake.d.ts +64 -0
- package/dist/codegen/fake.js +341 -0
- package/dist/codegen/index.d.ts +11 -4
- package/dist/codegen/index.js +10 -3
- package/dist/codegen/manifest.d.ts +4 -1
- package/dist/codegen/manifest.js +69 -2
- package/dist/codegen/merge.d.ts +37 -0
- package/dist/codegen/merge.js +257 -0
- package/dist/codegen/model.d.ts +94 -0
- package/dist/codegen/openapi.d.ts +5 -1
- package/dist/codegen/openapi.js +102 -10
- package/dist/codegen/pagination.d.ts +14 -0
- package/dist/codegen/pagination.js +129 -0
- package/dist/codegen/patch.d.ts +28 -0
- package/dist/codegen/patch.js +75 -0
- package/dist/codegen/pipeline.d.ts +52 -1
- package/dist/codegen/pipeline.js +198 -4
- package/dist/codegen/swagger.d.ts +7 -0
- package/dist/codegen/swagger.js +39 -0
- package/dist/credentials.d.ts +2 -2
- package/dist/credentials.js +17 -3
- package/dist/dev/conformance.d.ts +0 -2
- package/dist/dev/conformance.js +3 -9
- package/dist/dev/main.js +5 -1
- package/dist/dev/ready.d.ts +30 -0
- package/dist/dev/ready.js +249 -0
- package/dist/dev/slow-tests.d.ts +1 -0
- package/dist/http/fetch.js +21 -1
- package/dist/standards/audit.js +2 -1
- package/dist/standards/errors.js +6 -0
- package/dist/standards/index.d.ts +1 -0
- package/dist/standards/index.js +1 -0
- package/dist/standards/monthly.d.ts +5 -0
- package/dist/standards/monthly.js +12 -0
- package/docs/standards/ci.md +4 -2
- package/docs/standards/kit-surface.md +138 -0
- package/docs/standards/new-cli.md +14 -7
- package/package.json +11 -1
package/dist/codegen/openapi.js
CHANGED
|
@@ -61,7 +61,7 @@ export class OpenApiError extends Error {
|
|
|
61
61
|
this.problems = problems;
|
|
62
62
|
}
|
|
63
63
|
}
|
|
64
|
-
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
64
|
+
export const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
65
65
|
const EFFECT_BY_METHOD = {
|
|
66
66
|
GET: "read",
|
|
67
67
|
HEAD: "read",
|
|
@@ -70,6 +70,12 @@ const EFFECT_BY_METHOD = {
|
|
|
70
70
|
PATCH: "write",
|
|
71
71
|
DELETE: "destructive",
|
|
72
72
|
};
|
|
73
|
+
const JSON_VARIANT = /^application\/([\w.-]+\+)?json\s*(;|$)/i;
|
|
74
|
+
/** `application/json`, else a JSON variant: `application/hal+json`, `application/json; charset=utf-8`. */
|
|
75
|
+
const jsonContent = (content) => content[JSON_TYPE] ?? Object.entries(content).find(([type]) => JSON_VARIANT.test(type))?.[1];
|
|
76
|
+
const SCHEME_TYPES = new Set(["apiKey", "http", "oauth2", "openIdConnect", "mutualTLS"]);
|
|
77
|
+
const FLOWS = ["implicit", "password", "clientCredentials", "authorizationCode"];
|
|
78
|
+
const strings = (source, keys) => Object.fromEntries(keys.flatMap((key) => (typeof source[key] === "string" ? [[key, source[key]]] : [])));
|
|
73
79
|
/** `{type: "null"}` or `type: ["null"]`: JSON Schema 2020-12's own way to say "only null". */
|
|
74
80
|
const isNullOnly = (source) => isObject(source) &&
|
|
75
81
|
(source.type === "null" ||
|
|
@@ -425,7 +431,8 @@ class Adapter {
|
|
|
425
431
|
const schemaOf = (type) => (isObject(content[type]) ? content[type].schema : undefined);
|
|
426
432
|
const carriesFile = JSON.stringify(schemaOf(MULTIPART) ?? {}).includes('"format":"binary"');
|
|
427
433
|
const offered = Object.keys(content);
|
|
428
|
-
const
|
|
434
|
+
const json = offered.find((candidate) => candidate === JSON_TYPE) ?? offered.find((candidate) => JSON_VARIANT.test(candidate));
|
|
435
|
+
const type = carriesFile ? MULTIPART : (json ?? [MULTIPART, FORM].find((candidate) => offered.includes(candidate)));
|
|
429
436
|
const body = { confidence: "contract", required: source.required === true };
|
|
430
437
|
if (offered.length === 0)
|
|
431
438
|
return body;
|
|
@@ -433,7 +440,8 @@ class Adapter {
|
|
|
433
440
|
this.problems.push(`${where}: a body must be JSON, multipart or a form, found ${offered.join(", ")}`);
|
|
434
441
|
return body;
|
|
435
442
|
}
|
|
436
|
-
|
|
443
|
+
// Only a charset may be dropped: `application/merge-patch+json` must travel as itself.
|
|
444
|
+
if (type.split(";")[0]?.trim().toLowerCase() !== JSON_TYPE)
|
|
437
445
|
body.contentType = type;
|
|
438
446
|
const schema = schemaOf(type);
|
|
439
447
|
if (schema === undefined)
|
|
@@ -444,17 +452,89 @@ class Adapter {
|
|
|
444
452
|
return body;
|
|
445
453
|
}
|
|
446
454
|
/**
|
|
447
|
-
*
|
|
448
|
-
* is passed through as it is. Nothing at run time
|
|
455
|
+
* The first 2xx answer with JSON (HubSpot creates with 201, Yandex Disk with 201 or 202). Only an inline answer has a
|
|
456
|
+
* shape to check; a file, plain text or a `$ref` to a shared response is passed through as it is. Nothing at run time
|
|
457
|
+
* validates an answer yet.
|
|
449
458
|
*/
|
|
450
459
|
#response(source, where) {
|
|
451
|
-
const
|
|
452
|
-
|
|
460
|
+
const responses = isObject(source.responses) ? source.responses : {};
|
|
461
|
+
for (const code of Object.keys(responses)
|
|
462
|
+
.filter((code) => /^2(\d\d|XX)$/i.test(code))
|
|
463
|
+
.sort()) {
|
|
464
|
+
const answer = responses[code];
|
|
465
|
+
const json = isObject(answer) && isObject(answer.content) ? jsonContent(answer.content) : undefined;
|
|
466
|
+
if (isObject(json) && json.schema !== undefined)
|
|
467
|
+
return this.schema(json.schema, `${where}.responses.${code}`);
|
|
468
|
+
}
|
|
469
|
+
return undefined;
|
|
470
|
+
}
|
|
471
|
+
security(source, where) {
|
|
472
|
+
if (source === undefined)
|
|
453
473
|
return undefined;
|
|
454
|
-
|
|
455
|
-
|
|
474
|
+
if (!Array.isArray(source) || !source.every(isObject)) {
|
|
475
|
+
this.problems.push(`${where}: security must be a list of requirements`);
|
|
456
476
|
return undefined;
|
|
457
|
-
|
|
477
|
+
}
|
|
478
|
+
return source.map((requirement) => Object.fromEntries(Object.entries(requirement).map(([name, scopes]) => [name, Array.isArray(scopes) ? scopes.map(String) : []])));
|
|
479
|
+
}
|
|
480
|
+
securitySchemes() {
|
|
481
|
+
const components = isObject(this.document.components) ? this.document.components : {};
|
|
482
|
+
if (!isObject(components.securitySchemes))
|
|
483
|
+
return undefined;
|
|
484
|
+
const schemes = {};
|
|
485
|
+
for (const [name, source] of Object.entries(components.securitySchemes)) {
|
|
486
|
+
const where = `#/components/securitySchemes/${name}`;
|
|
487
|
+
if (isObject(source) && source.$ref !== undefined) {
|
|
488
|
+
this.problems.push(`${where}: a $ref security scheme is not supported; write the scheme in place`);
|
|
489
|
+
continue;
|
|
490
|
+
}
|
|
491
|
+
if (!isObject(source) || !SCHEME_TYPES.has(source.type)) {
|
|
492
|
+
this.problems.push(`${where}: unsupported security scheme ${JSON.stringify(isObject(source) ? source.type : source)}`);
|
|
493
|
+
continue;
|
|
494
|
+
}
|
|
495
|
+
const scheme = {
|
|
496
|
+
...strings(source, ["description", "name", "in", "scheme", "bearerFormat", "openIdConnectUrl"]),
|
|
497
|
+
type: source.type,
|
|
498
|
+
};
|
|
499
|
+
if (isObject(source.flows)) {
|
|
500
|
+
const flows = source.flows;
|
|
501
|
+
scheme.flows = Object.fromEntries(FLOWS.flatMap((flow) => {
|
|
502
|
+
const one = flows[flow];
|
|
503
|
+
if (!isObject(one))
|
|
504
|
+
return [];
|
|
505
|
+
const scopes = isObject(one.scopes)
|
|
506
|
+
? Object.fromEntries(Object.entries(one.scopes).map(([k, v]) => [k, String(v)]))
|
|
507
|
+
: {};
|
|
508
|
+
return [[flow, { ...strings(one, ["authorizationUrl", "tokenUrl", "refreshUrl"]), scopes }]];
|
|
509
|
+
}));
|
|
510
|
+
}
|
|
511
|
+
schemes[name] = scheme;
|
|
512
|
+
}
|
|
513
|
+
return schemes;
|
|
514
|
+
}
|
|
515
|
+
servers() {
|
|
516
|
+
if (!Array.isArray(this.document.servers))
|
|
517
|
+
return undefined;
|
|
518
|
+
return this.document.servers.flatMap((source) => {
|
|
519
|
+
if (!isObject(source) || typeof source.url !== "string")
|
|
520
|
+
return [];
|
|
521
|
+
const server = { url: source.url, ...strings(source, ["description"]) };
|
|
522
|
+
if (isObject(source.variables)) {
|
|
523
|
+
server.variables = Object.fromEntries(Object.entries(source.variables).flatMap(([name, variable]) => isObject(variable) && variable.default !== undefined
|
|
524
|
+
? [
|
|
525
|
+
[
|
|
526
|
+
name,
|
|
527
|
+
{
|
|
528
|
+
default: String(variable.default),
|
|
529
|
+
...(Array.isArray(variable.enum) ? { enum: variable.enum.map(String) } : {}),
|
|
530
|
+
...strings(variable, ["description"]),
|
|
531
|
+
},
|
|
532
|
+
],
|
|
533
|
+
]
|
|
534
|
+
: []));
|
|
535
|
+
}
|
|
536
|
+
return [server];
|
|
537
|
+
});
|
|
458
538
|
}
|
|
459
539
|
operations() {
|
|
460
540
|
const operations = [];
|
|
@@ -491,6 +571,9 @@ class Adapter {
|
|
|
491
571
|
effect: EFFECT_BY_METHOD[verb],
|
|
492
572
|
source: { location: pointer },
|
|
493
573
|
};
|
|
574
|
+
const security = this.security(source.security, `${pointer}.security`);
|
|
575
|
+
if (security)
|
|
576
|
+
operation.security = security;
|
|
494
577
|
if (typeof source.summary === "string")
|
|
495
578
|
operation.summary = source.summary;
|
|
496
579
|
if (typeof source.description === "string")
|
|
@@ -516,6 +599,12 @@ export const adaptOpenApi = (document, source = {}) => {
|
|
|
516
599
|
const adapter = new Adapter(document);
|
|
517
600
|
const schemas = adapter.components();
|
|
518
601
|
const operations = adapter.operations();
|
|
602
|
+
// Meta's spec repeats one server on every path group.
|
|
603
|
+
const servers = adapter
|
|
604
|
+
.servers()
|
|
605
|
+
?.filter((one, index, all) => all.findIndex((other) => other.url === one.url) === index);
|
|
606
|
+
const securitySchemes = adapter.securitySchemes();
|
|
607
|
+
const security = adapter.security(document.security, "#/security");
|
|
519
608
|
if (operations.length === 0)
|
|
520
609
|
adapter.problems.push("the document has no operations");
|
|
521
610
|
if (adapter.problems.length > 0)
|
|
@@ -525,5 +614,8 @@ export const adaptOpenApi = (document, source = {}) => {
|
|
|
525
614
|
source: { kind: "openapi", ...(typeof info.version === "string" ? { version: info.version } : {}), ...source },
|
|
526
615
|
schemas,
|
|
527
616
|
operations,
|
|
617
|
+
...(servers?.length ? { servers } : {}),
|
|
618
|
+
...(securitySchemes ? { securitySchemes } : {}),
|
|
619
|
+
...(security ? { security } : {}),
|
|
528
620
|
};
|
|
529
621
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finds how a read pages from the names its request and answer use: a cursor (`after` → `paging.next.after`,
|
|
3
|
+
* `start_cursor` → `next_cursor`), an offset (`offset` with `_embedded.items`), a page number, or a link to the next
|
|
4
|
+
* page. A name it does not know detects nothing; an override then says how the operation pages.
|
|
5
|
+
*/
|
|
6
|
+
import type { ApiOperation, ApiSchema, PageParameter, Pagination, SchemaNode } from "./model.js";
|
|
7
|
+
type Typed = PageParameter & {
|
|
8
|
+
type: SchemaNode["type"];
|
|
9
|
+
};
|
|
10
|
+
export declare const requestParameters: (operation: ApiOperation, schemas: ReadonlyMap<string, ApiSchema>) => Typed[];
|
|
11
|
+
/** The answer's fields as dotted paths, for an override's check. */
|
|
12
|
+
export declare const answerPaths: (operation: ApiOperation, schemas: ReadonlyMap<string, ApiSchema>) => Set<string>;
|
|
13
|
+
export declare const detectPagination: (operation: ApiOperation, schemas: ReadonlyMap<string, ApiSchema>) => Pagination | undefined;
|
|
14
|
+
export {};
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const CURSORS = ["after", "cursor", "start_cursor", "page_token", "pageToken", "starting_after", "continuation"];
|
|
2
|
+
// Not `cursor`: an answer that echoes the request's cursor back would read as the next one.
|
|
3
|
+
const NEXT_CURSORS = ["next_cursor", "nextCursor", "next_page_token", "nextPageToken", "next_page_cursor"];
|
|
4
|
+
const LIMITS = ["limit", "page_size", "pageSize", "per_page", "perPage", "count", "max_results", "maxResults"];
|
|
5
|
+
const ITEMS = ["results", "items", "data", "entries", "records", "values"];
|
|
6
|
+
// Not `count`: as often the number of items on this page, after which an executor would stop.
|
|
7
|
+
const TOTALS = ["total", "total_count", "totalCount"];
|
|
8
|
+
const LINKS = ["next", "links.next", "_links.next.href", "paging.next.link", "next_url", "nextUrl"];
|
|
9
|
+
const DEPTH = 3;
|
|
10
|
+
/** Every field of an answer down to `DEPTH`, through references and inheritance; a union's members are not guessed. */
|
|
11
|
+
const fieldsOf = (root, schemas) => {
|
|
12
|
+
const found = [];
|
|
13
|
+
const walk = (node, prefix, depth, seen) => {
|
|
14
|
+
if (node.type === "ref") {
|
|
15
|
+
const target = schemas.get(node.ref);
|
|
16
|
+
if (target && !seen.has(node.ref))
|
|
17
|
+
walk(target.schema, prefix, depth, new Set([...seen, node.ref]));
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (node.type === "allOf") {
|
|
21
|
+
for (const member of node.of)
|
|
22
|
+
walk(member, prefix, depth, seen);
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
if (node.type !== "object" || depth === DEPTH)
|
|
26
|
+
return;
|
|
27
|
+
for (const [name, property] of Object.entries(node.properties)) {
|
|
28
|
+
const path = prefix ? `${prefix}.${name}` : name;
|
|
29
|
+
found.push({ path, node: property });
|
|
30
|
+
walk(property, path, depth + 1, seen);
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
walk(root, "", 0, new Set());
|
|
34
|
+
return found;
|
|
35
|
+
};
|
|
36
|
+
const resolve = (node, schemas) => {
|
|
37
|
+
for (let at = node, hops = 0; hops < 10; hops++) {
|
|
38
|
+
if (at.type !== "ref")
|
|
39
|
+
return at;
|
|
40
|
+
const target = schemas.get(at.ref);
|
|
41
|
+
if (!target)
|
|
42
|
+
return at;
|
|
43
|
+
at = target.schema;
|
|
44
|
+
}
|
|
45
|
+
return node;
|
|
46
|
+
};
|
|
47
|
+
const lastName = (path) => path.slice(path.lastIndexOf(".") + 1);
|
|
48
|
+
export const requestParameters = (operation, schemas) => [
|
|
49
|
+
...operation.parameters
|
|
50
|
+
.filter((parameter) => parameter.in === "query")
|
|
51
|
+
.map((parameter) => ({
|
|
52
|
+
in: "query",
|
|
53
|
+
name: parameter.name,
|
|
54
|
+
type: resolve(parameter.schema, schemas).type,
|
|
55
|
+
})),
|
|
56
|
+
...(operation.requestBody?.schema
|
|
57
|
+
? fieldsOf(operation.requestBody.schema, schemas)
|
|
58
|
+
.filter((field) => !field.path.includes("."))
|
|
59
|
+
.map((field) => ({ in: "body", name: field.path, type: resolve(field.node, schemas).type }))
|
|
60
|
+
: []),
|
|
61
|
+
];
|
|
62
|
+
/** The answer's fields as dotted paths, for an override's check. */
|
|
63
|
+
export const answerPaths = (operation, schemas) => new Set(operation.response?.schema ? fieldsOf(operation.response.schema, schemas).map((field) => field.path) : []);
|
|
64
|
+
export const detectPagination = (operation, schemas) => {
|
|
65
|
+
if (operation.effect !== "read" || !operation.response?.schema)
|
|
66
|
+
return undefined;
|
|
67
|
+
const answer = fieldsOf(operation.response.schema, schemas);
|
|
68
|
+
const typed = (path) => answer.find((field) => field.path === path);
|
|
69
|
+
const kind = (field) => resolve(field.node, schemas).type;
|
|
70
|
+
const request = requestParameters(operation, schemas);
|
|
71
|
+
// A `start` date or a `page` id is not a position: only a number counts as an offset, a page or a limit.
|
|
72
|
+
const named = (names, types) => {
|
|
73
|
+
const found = names
|
|
74
|
+
.map((name) => request.find((parameter) => parameter.name === name && types.includes(parameter.type)))
|
|
75
|
+
.find(Boolean);
|
|
76
|
+
return found && { in: found.in, name: found.name };
|
|
77
|
+
};
|
|
78
|
+
const NUMBER = ["integer", "number"];
|
|
79
|
+
const limit = named(LIMITS, NUMBER);
|
|
80
|
+
const optional = (key, value) => (value === undefined ? {} : { [key]: value });
|
|
81
|
+
const arrays = answer.filter((field) => kind(field) === "array");
|
|
82
|
+
const items = ITEMS.map((name) => arrays.find((field) => lastName(field.path) === name)).find(Boolean) ??
|
|
83
|
+
(arrays.length === 1 && !arrays[0]?.path.includes(".") ? arrays[0] : undefined);
|
|
84
|
+
const sibling = (names) => {
|
|
85
|
+
const parent = items?.path.includes(".") ? items.path.slice(0, items.path.lastIndexOf(".") + 1) : "";
|
|
86
|
+
return names
|
|
87
|
+
.map((name) => typed(`${parent}${name}`))
|
|
88
|
+
.find((field) => field !== undefined && ["integer", "number"].includes(kind(field)))?.path;
|
|
89
|
+
};
|
|
90
|
+
const cursor = named(CURSORS, ["string"]);
|
|
91
|
+
if (cursor) {
|
|
92
|
+
const strings = answer.filter((field) => kind(field) === "string");
|
|
93
|
+
const next = strings.find((field) => field.path.endsWith(`next.${cursor.name}`)) ??
|
|
94
|
+
NEXT_CURSORS.map((name) => strings.find((field) => lastName(field.path) === name)).find(Boolean);
|
|
95
|
+
if (next) {
|
|
96
|
+
const hasMore = answer.find((field) => ["has_more", "hasMore"].includes(lastName(field.path)) && kind(field) === "boolean");
|
|
97
|
+
return {
|
|
98
|
+
style: "cursor",
|
|
99
|
+
cursor,
|
|
100
|
+
next: next.path,
|
|
101
|
+
...optional("items", items?.path),
|
|
102
|
+
...optional("hasMore", hasMore?.path),
|
|
103
|
+
...optional("limit", limit),
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
const offset = named(["offset", "skip", "start"], NUMBER);
|
|
108
|
+
if (offset && items)
|
|
109
|
+
return {
|
|
110
|
+
style: "offset",
|
|
111
|
+
offset,
|
|
112
|
+
...optional("limit", limit),
|
|
113
|
+
items: items.path,
|
|
114
|
+
...optional("total", sibling(TOTALS)),
|
|
115
|
+
};
|
|
116
|
+
const page = named(["page", "page_number", "pageNumber"], NUMBER);
|
|
117
|
+
if (page && items)
|
|
118
|
+
return {
|
|
119
|
+
style: "page",
|
|
120
|
+
page,
|
|
121
|
+
...optional("limit", limit),
|
|
122
|
+
items: items.path,
|
|
123
|
+
...optional("total", sibling(TOTALS)),
|
|
124
|
+
};
|
|
125
|
+
const link = LINKS.map((path) => typed(path)).find((field) => field !== undefined && kind(field) === "string");
|
|
126
|
+
if (link)
|
|
127
|
+
return { style: "link", next: link.path, ...optional("items", items?.path) };
|
|
128
|
+
return undefined;
|
|
129
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
type Json = Record<string, unknown>;
|
|
2
|
+
export interface SpecPatch {
|
|
3
|
+
/**
|
|
4
|
+
* A JSON pointer: `/components/schemas/Void`, `/paths/~1x/get/parameters/0/name`. Its parent must exist; the value is
|
|
5
|
+
* set or replaced, and `-` appends to an array.
|
|
6
|
+
*/
|
|
7
|
+
pointer: string;
|
|
8
|
+
value: unknown;
|
|
9
|
+
reason: string;
|
|
10
|
+
}
|
|
11
|
+
export interface PatchSpecOptions {
|
|
12
|
+
patches?: readonly SpecPatch[];
|
|
13
|
+
/**
|
|
14
|
+
* The reason for giving every schema the document references but does not define an "anything" stub, as HubSpot's
|
|
15
|
+
* associations v4 needs for `Void`.
|
|
16
|
+
*/
|
|
17
|
+
stubMissingSchemas?: string;
|
|
18
|
+
}
|
|
19
|
+
export interface PatchedSpec {
|
|
20
|
+
document: Json;
|
|
21
|
+
applied: {
|
|
22
|
+
pointer: string;
|
|
23
|
+
reason: string;
|
|
24
|
+
}[];
|
|
25
|
+
}
|
|
26
|
+
/** Returns a patched copy; the caller's document is left as it is. Throws `OpenApiError` naming every patch that misses. */
|
|
27
|
+
export declare const patchSpec: (document: unknown, options: PatchSpecOptions) => PatchedSpec;
|
|
28
|
+
export {};
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Corrections to a source document before it is adapted, each with its reason, in place of a hand-written
|
|
3
|
+
* `scripts/<service>-spec.ts` per CLI. The returned `applied` list belongs in the CLI's provenance or coverage page.
|
|
4
|
+
*/
|
|
5
|
+
import { isObject, OpenApiError } from "./openapi.js";
|
|
6
|
+
const decode = (segment) => segment.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
7
|
+
const encode = (segment) => segment.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
8
|
+
const SCHEMA_REF = "#/components/schemas/";
|
|
9
|
+
// A pointer through these would change every object in the process, not the document.
|
|
10
|
+
const UNSAFE = new Set(["__proto__", "constructor", "prototype"]);
|
|
11
|
+
const child = (node, segment) => {
|
|
12
|
+
if (Array.isArray(node))
|
|
13
|
+
return /^\d+$/.test(segment) ? node[Number(segment)] : undefined;
|
|
14
|
+
return isObject(node) && Object.hasOwn(node, segment) ? node[segment] : undefined;
|
|
15
|
+
};
|
|
16
|
+
const refs = (node, found) => {
|
|
17
|
+
if (Array.isArray(node))
|
|
18
|
+
for (const item of node)
|
|
19
|
+
refs(item, found);
|
|
20
|
+
else if (isObject(node)) {
|
|
21
|
+
if (typeof node.$ref === "string" && node.$ref.startsWith(SCHEMA_REF))
|
|
22
|
+
found.add(decode(decodeURIComponent(node.$ref.slice(SCHEMA_REF.length))));
|
|
23
|
+
for (const value of Object.values(node))
|
|
24
|
+
refs(value, found);
|
|
25
|
+
}
|
|
26
|
+
return found;
|
|
27
|
+
};
|
|
28
|
+
/** Returns a patched copy; the caller's document is left as it is. Throws `OpenApiError` naming every patch that misses. */
|
|
29
|
+
export const patchSpec = (document, options) => {
|
|
30
|
+
if (!isObject(document))
|
|
31
|
+
throw new OpenApiError(["not an OpenAPI document"]);
|
|
32
|
+
const copy = structuredClone(document);
|
|
33
|
+
const applied = [];
|
|
34
|
+
const problems = [];
|
|
35
|
+
for (const { pointer, value, reason } of options.patches ?? []) {
|
|
36
|
+
if (!pointer.startsWith("/")) {
|
|
37
|
+
problems.push(`patch "${pointer}": a pointer starts with "/"; replacing the whole document is not supported`);
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const path = pointer.split("/").slice(1).map(decode);
|
|
41
|
+
const key = path.pop();
|
|
42
|
+
const parent = path.reduce(child, copy);
|
|
43
|
+
if (UNSAFE.has(key) || path.some((segment) => UNSAFE.has(segment))) {
|
|
44
|
+
problems.push(`patch ${pointer}: __proto__, constructor and prototype are not document keys`);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (Array.isArray(parent) && (key === "-" || /^\d+$/.test(key))) {
|
|
48
|
+
parent[key === "-" ? parent.length : Number(key)] = structuredClone(value);
|
|
49
|
+
}
|
|
50
|
+
else if (isObject(parent))
|
|
51
|
+
parent[key] = structuredClone(value);
|
|
52
|
+
else {
|
|
53
|
+
problems.push(`patch ${pointer}: its parent is not in the document`);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
applied.push({ pointer, reason });
|
|
57
|
+
}
|
|
58
|
+
if (options.stubMissingSchemas) {
|
|
59
|
+
if (!isObject(copy.components))
|
|
60
|
+
copy.components = {};
|
|
61
|
+
const components = copy.components;
|
|
62
|
+
if (!isObject(components.schemas))
|
|
63
|
+
components.schemas = {};
|
|
64
|
+
const schemas = components.schemas;
|
|
65
|
+
for (const id of [...refs(copy, new Set())].sort()) {
|
|
66
|
+
if (Object.hasOwn(schemas, id))
|
|
67
|
+
continue;
|
|
68
|
+
schemas[id] = { description: options.stubMissingSchemas };
|
|
69
|
+
applied.push({ pointer: `/components/schemas/${encode(id)}`, reason: options.stubMissingSchemas });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
if (problems.length > 0)
|
|
73
|
+
throw new OpenApiError(problems);
|
|
74
|
+
return { document: copy, applied };
|
|
75
|
+
};
|
|
@@ -1,13 +1,64 @@
|
|
|
1
|
-
import type { ApiModel, CodeGenerator, GeneratedArtifact, Override } from "./model.js";
|
|
1
|
+
import type { ApiModel, ApiOperation, CodeGenerator, GeneratedArtifact, Override, Pagination, SecurityRequirement, SecurityScheme } from "./model.js";
|
|
2
2
|
export declare class CodegenError extends Error {
|
|
3
3
|
readonly problems: readonly string[];
|
|
4
4
|
constructor(problems: readonly string[]);
|
|
5
5
|
}
|
|
6
|
+
export declare const READING_POST_REASON = "a POST to a \u2026/search or \u2026/query path only reads (readingPosts rule)";
|
|
7
|
+
/**
|
|
8
|
+
* Command names for a source whose operation ids make poor ones: HubSpot's `get-/crm/v3/objects/contacts_getPage`.
|
|
9
|
+
* `commands` wins; with `fromPath` the rest are named from the path and the method; otherwise from the id.
|
|
10
|
+
*/
|
|
11
|
+
export interface CommandNames {
|
|
12
|
+
/** Operation id → command, kebab case: `{ "get-/crm/v3/objects/contacts_getPage": "contacts-list" }`. */
|
|
13
|
+
commands?: Readonly<Record<string, string>>;
|
|
14
|
+
fromPath?: boolean;
|
|
15
|
+
/** A path segment → its word in a command; `""` leaves it out: `{ "0-3": "deals", crm: "", objects: "" }`. */
|
|
16
|
+
segments?: Readonly<Record<string, string>>;
|
|
17
|
+
}
|
|
18
|
+
export declare const applyNames: (model: ApiModel, names: CommandNames) => ApiModel;
|
|
19
|
+
/** Each read's pagination, detected unless an override set it, or said with `null` that the read does not page. */
|
|
20
|
+
export declare const applyPagination: (model: ApiModel, overrides: Readonly<Record<string, {
|
|
21
|
+
pagination?: Pagination | null;
|
|
22
|
+
reason: string;
|
|
23
|
+
}>>, detect: boolean) => ApiModel;
|
|
6
24
|
export declare const applyOverrides: (model: ApiModel, overrides: Readonly<Record<string, Override>>) => ApiModel;
|
|
25
|
+
/**
|
|
26
|
+
* Which calls the CLI's own permission keys guard, so denying `files.delete` also holds over the raw `api` group:
|
|
27
|
+
* `<group>.delete` for every destructive operation and for every flag in `deletingFlags` an operation takes (cli-core
|
|
28
|
+
* checks the key when the flag is `true`); `<group>.share` for the operations in `shares`.
|
|
29
|
+
*/
|
|
30
|
+
export interface PermissionRule {
|
|
31
|
+
/** `files`, or one per operation (a tag, a spec's prefix). */
|
|
32
|
+
group: string | ((operation: ApiOperation) => string);
|
|
33
|
+
/**
|
|
34
|
+
* Top-level body fields and query parameters that delete or overwrite when `true`: `archived`, `in_trash` (Notion),
|
|
35
|
+
* `permanently`, `overwrite` (Yandex Disk).
|
|
36
|
+
*/
|
|
37
|
+
deletingFlags?: readonly string[];
|
|
38
|
+
/** Operation ids that make something public, as a share link does: neither a plain write nor a delete. */
|
|
39
|
+
shares?: readonly string[];
|
|
40
|
+
}
|
|
41
|
+
export declare const applyPermissionRule: (model: ApiModel, rule: PermissionRule) => ApiModel;
|
|
42
|
+
/**
|
|
43
|
+
* Sign-in the source does not describe, or describes wrongly: Yandex Disk's Swagger 1.2 has no scheme, and its header
|
|
44
|
+
* is `Authorization: OAuth <token>`, which `{ type: "http", scheme: "OAuth" }` says. Replaces the source's own.
|
|
45
|
+
*/
|
|
46
|
+
export interface AuthOverride {
|
|
47
|
+
securitySchemes: Readonly<Record<string, SecurityScheme>>;
|
|
48
|
+
security: readonly SecurityRequirement[];
|
|
49
|
+
reason: string;
|
|
50
|
+
}
|
|
7
51
|
/** Everything that would otherwise make an operation vanish or turn into a guess. */
|
|
8
52
|
export declare const validateModel: (model: ApiModel) => void;
|
|
9
53
|
export interface GenerateOptions {
|
|
10
54
|
overrides?: Readonly<Record<string, Override>>;
|
|
55
|
+
/** Treat a POST to a `…/search` or `…/query` path as a read; an override still wins. */
|
|
56
|
+
readingPosts?: boolean;
|
|
57
|
+
/** Detect how each read pages; an override's `pagination` wins either way. */
|
|
58
|
+
pagination?: boolean;
|
|
59
|
+
names?: CommandNames;
|
|
60
|
+
permissions?: PermissionRule;
|
|
61
|
+
auth?: AuthOverride;
|
|
11
62
|
/** Lines under "GENERATED. DO NOT EDIT." — the source and the command. Nothing that changes by itself. */
|
|
12
63
|
banner: readonly string[];
|
|
13
64
|
}
|