@docs-sdk-dev/openapi 0.0.0-stage → 0.0.3
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/LICENSE +21 -0
- package/README.md +10 -2
- package/dist/index.d.ts +195 -0
- package/dist/index.js +492 -0
- package/package.json +31 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Lenso contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Docs SDK OpenAPI Provider
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
`@docs-sdk-dev/openapi` reads an OpenAPI 3 document in JSON or YAML (`.yaml`, `.yml`) and turns it into Docs SDK entities and reference pages. It depends on Core, the TypeScript compiler (its JSON parser keeps source positions) and `yaml` (the same for YAML), not on a web framework.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { apiReference } from "@docs-sdk-dev/openapi"
|
|
7
|
+
|
|
8
|
+
const api = apiReference({ id: "api", scope: "reference", spec: "content/api/components.openapi.json" }, read)
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Each operation becomes a page with Overview, Parameters, Request body and Responses sections, an `api:<scope>/<operationId>` entity, and `schema:<scope>/<Name>` and `field:<scope>/<Name>#<field>` entities for the schemas it uses, each with the line range it was declared on. Operations need an `operationId`. Schema references may point into the same file (`#/components/schemas/<Name>`), into another project file (`shared.yaml#/components/schemas/<Name>`), or at a whole file holding one schema (`models/Tag.yaml`), relative to the referring file; each schema records its own source file. Parameters, responses and request bodies may refer to `#/components/parameters|responses|requestBodies/<Name>` here or in another file. Text the pages write inside sections (table headers, Yes/No, required/optional, Example, the Authentication line) follows `context.locale`: English and French are built in, a regional locale uses its language, others use English, and `apiReference({ text: { fr: { required: "Obligatoire" } } })` replaces single strings. Section titles are named in the collection's template config. `oneOf`, `anyOf`, `allOf`, enums, `const` and `nullable` show in field types, and an `allOf` schema lists the fields it inherits. URLs, paths outside the project and other references are reported with `DOCS_OPENAPI_REF`, and malformed documents with `DOCS_OPENAPI_INVALID`.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { type Context, type EntityInput, type ReadSource } from "@docs-sdk-dev/core";
|
|
2
|
+
export declare const extractor: {
|
|
3
|
+
name: string;
|
|
4
|
+
version: string;
|
|
5
|
+
};
|
|
6
|
+
export interface LineRange {
|
|
7
|
+
start: number;
|
|
8
|
+
end: number;
|
|
9
|
+
}
|
|
10
|
+
/** `source` and `revision` name the file the field is declared in: a field inherited through `allOf` may come from another file. */
|
|
11
|
+
export interface Field {
|
|
12
|
+
name: string;
|
|
13
|
+
type: string;
|
|
14
|
+
required: boolean;
|
|
15
|
+
description: string;
|
|
16
|
+
deprecated?: true;
|
|
17
|
+
source: string;
|
|
18
|
+
revision: string;
|
|
19
|
+
range: LineRange;
|
|
20
|
+
}
|
|
21
|
+
/** `source` and `revision` name the file the schema is declared in, which may be another file the spec refers to. */
|
|
22
|
+
export interface Schema {
|
|
23
|
+
name: string;
|
|
24
|
+
source: string;
|
|
25
|
+
revision: string;
|
|
26
|
+
type: string;
|
|
27
|
+
fields: Field[];
|
|
28
|
+
range: LineRange;
|
|
29
|
+
}
|
|
30
|
+
/** `deprecated` is present only when the spec marks it, so unmarked facts keep their data and revisions. */
|
|
31
|
+
export interface Parameter {
|
|
32
|
+
name: string;
|
|
33
|
+
in: string;
|
|
34
|
+
type: string;
|
|
35
|
+
required: boolean;
|
|
36
|
+
description: string;
|
|
37
|
+
deprecated?: true;
|
|
38
|
+
}
|
|
39
|
+
/** A named example payload. `name` is the key in `examples`, or `example` for the single `example` field. */
|
|
40
|
+
export interface Example {
|
|
41
|
+
name: string;
|
|
42
|
+
summary?: string;
|
|
43
|
+
value: unknown;
|
|
44
|
+
}
|
|
45
|
+
export interface Response {
|
|
46
|
+
status: string;
|
|
47
|
+
description: string;
|
|
48
|
+
schema?: string;
|
|
49
|
+
examples?: Example[];
|
|
50
|
+
}
|
|
51
|
+
/** A security scheme an operation requires. `label` describes it for readers, e.g. "HTTP bearer" or "API key in header `X-Key`". */
|
|
52
|
+
export interface SecurityScheme {
|
|
53
|
+
name: string;
|
|
54
|
+
type: string;
|
|
55
|
+
label: string;
|
|
56
|
+
scopes: string[];
|
|
57
|
+
}
|
|
58
|
+
export interface ApiOperation {
|
|
59
|
+
operationId: string;
|
|
60
|
+
method: string;
|
|
61
|
+
path: string;
|
|
62
|
+
summary: string;
|
|
63
|
+
description: string;
|
|
64
|
+
deprecated?: true;
|
|
65
|
+
/** The operation's tags, in spec order; absent when it has none. */
|
|
66
|
+
tags?: string[];
|
|
67
|
+
/**
|
|
68
|
+
* How to authenticate, when the spec says: any one of the alternatives, each needing all of its schemes. An empty
|
|
69
|
+
* list means the operation needs none. Absent when neither the operation nor the document declares `security`.
|
|
70
|
+
*/
|
|
71
|
+
security?: SecurityScheme[][];
|
|
72
|
+
parameters: Parameter[];
|
|
73
|
+
requestBody?: {
|
|
74
|
+
required: boolean;
|
|
75
|
+
contentType: string;
|
|
76
|
+
schema: string;
|
|
77
|
+
examples?: Example[];
|
|
78
|
+
};
|
|
79
|
+
responses: Response[];
|
|
80
|
+
range: LineRange;
|
|
81
|
+
/** Components the operation reached through `$ref` (parameters, responses, request bodies), with where each is declared. */
|
|
82
|
+
components: {
|
|
83
|
+
source: string;
|
|
84
|
+
revision: string;
|
|
85
|
+
pointer: string;
|
|
86
|
+
range: LineRange;
|
|
87
|
+
}[];
|
|
88
|
+
}
|
|
89
|
+
export interface ApiSpec {
|
|
90
|
+
source: string;
|
|
91
|
+
revision: string;
|
|
92
|
+
title: string;
|
|
93
|
+
version: string;
|
|
94
|
+
operations: ApiOperation[];
|
|
95
|
+
schemas: Schema[];
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Read an OpenAPI 3 document in JSON, or in YAML when the source ends in `.yaml` or `.yml`. Operations keep document
|
|
99
|
+
* order. Schema references resolve to schema names: `#/components/schemas/<Name>` in the same file, the same pointer in
|
|
100
|
+
* another project file (`schemas.yaml#/components/schemas/<Name>`), or a whole file that is one schema
|
|
101
|
+
* (`schemas/Pet.yaml`, named after the file). Paths are relative to the file holding the reference, and each schema
|
|
102
|
+
* records the file it came from. Parameters, responses and request bodies may likewise refer to
|
|
103
|
+
* `#/components/{parameters,responses,requestBodies}/<Name>`, here or in another file. Two different schemas with one
|
|
104
|
+
* name, and other references, are reported rather than guessed.
|
|
105
|
+
*/
|
|
106
|
+
export declare function extractOpenApi(read: ReadSource, source: string): Promise<ApiSpec>;
|
|
107
|
+
/** Schema names an operation refers to, without array markers. */
|
|
108
|
+
export declare const schemasOf: (operation: ApiOperation) => string[];
|
|
109
|
+
/** Entities for one operation and the schemas it uses. IDs: api:<scope>/<operationId>, schema:<scope>/<Name>, field:<scope>/<Name>#<field>. */
|
|
110
|
+
export declare function apiEntities(spec: ApiSpec, operation: ApiOperation, options: {
|
|
111
|
+
scope: string;
|
|
112
|
+
context?: Context;
|
|
113
|
+
}): {
|
|
114
|
+
id: string;
|
|
115
|
+
schemas: string[];
|
|
116
|
+
entities: EntityInput<unknown>[];
|
|
117
|
+
};
|
|
118
|
+
/**
|
|
119
|
+
* The text API pages write inside sections, per locale. Section titles are not here: a collection's template config
|
|
120
|
+
* names them (`sections.parameters.title`), like any template's.
|
|
121
|
+
*/
|
|
122
|
+
export declare const englishApiText: {
|
|
123
|
+
name: string;
|
|
124
|
+
in: string;
|
|
125
|
+
type: string;
|
|
126
|
+
required: string;
|
|
127
|
+
description: string;
|
|
128
|
+
field: string;
|
|
129
|
+
status: string;
|
|
130
|
+
body: string;
|
|
131
|
+
yes: string;
|
|
132
|
+
no: string;
|
|
133
|
+
requiredBody: string;
|
|
134
|
+
optionalBody: string;
|
|
135
|
+
example: string;
|
|
136
|
+
deprecated: string;
|
|
137
|
+
authentication: string;
|
|
138
|
+
none: string;
|
|
139
|
+
and: string;
|
|
140
|
+
or: string;
|
|
141
|
+
scopes: string;
|
|
142
|
+
};
|
|
143
|
+
export type ApiText = typeof englishApiText;
|
|
144
|
+
/** The text for a locale: project overrides, then built-in text for the locale or its language, then English. */
|
|
145
|
+
export declare function apiTextFor(locale: string | undefined, overrides?: Record<string, Partial<ApiText>>): ApiText;
|
|
146
|
+
/**
|
|
147
|
+
* One reference page per operation, in document order. Page IDs are the kebab-case operationId; titles are the
|
|
148
|
+
* operation summary. Entries carry the api, schema and field entities, so pages, search and contracts share them.
|
|
149
|
+
*/
|
|
150
|
+
export declare function apiReference(options: {
|
|
151
|
+
id: string;
|
|
152
|
+
scope: string;
|
|
153
|
+
spec: string;
|
|
154
|
+
source?: string;
|
|
155
|
+
templateConfig?: string;
|
|
156
|
+
context?: Context;
|
|
157
|
+
/**
|
|
158
|
+
* Only the operations with any of these tags. Declaring one collection per tag, each with its own scope, gives each
|
|
159
|
+
* tag its own navigation group. Every tag listed must match an operation.
|
|
160
|
+
*/
|
|
161
|
+
tags?: readonly string[];
|
|
162
|
+
/** With `tags`, also the operations that have no tags, so a group such as "Other" can hold them. */
|
|
163
|
+
untagged?: boolean;
|
|
164
|
+
/** The scope of entity IDs (api:, schema:, field:), when collections of one spec share them; defaults to `scope`. */
|
|
165
|
+
entityScope?: string;
|
|
166
|
+
/** Replacements for the text API pages write, by locale or language, such as `{ fr: { required: "Obligatoire" } }`. */
|
|
167
|
+
text?: Record<string, Partial<ApiText>>;
|
|
168
|
+
}, read: ReadSource): import("@docs-sdk-dev/core").Collection<{
|
|
169
|
+
spec: ApiSpec;
|
|
170
|
+
operation: ApiOperation;
|
|
171
|
+
scope: string;
|
|
172
|
+
api: string;
|
|
173
|
+
schemas: string[];
|
|
174
|
+
text: {
|
|
175
|
+
name: string;
|
|
176
|
+
in: string;
|
|
177
|
+
type: string;
|
|
178
|
+
required: string;
|
|
179
|
+
description: string;
|
|
180
|
+
field: string;
|
|
181
|
+
status: string;
|
|
182
|
+
body: string;
|
|
183
|
+
yes: string;
|
|
184
|
+
no: string;
|
|
185
|
+
requiredBody: string;
|
|
186
|
+
optionalBody: string;
|
|
187
|
+
example: string;
|
|
188
|
+
deprecated: string;
|
|
189
|
+
authentication: string;
|
|
190
|
+
none: string;
|
|
191
|
+
and: string;
|
|
192
|
+
or: string;
|
|
193
|
+
scopes: string;
|
|
194
|
+
};
|
|
195
|
+
}>;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
import { posix } from "node:path";
|
|
3
|
+
import ts from "typescript";
|
|
4
|
+
import { isMap, isScalar, isSeq, LineCounter, parseDocument } from "yaml";
|
|
5
|
+
import { defineCollection, defineTemplate, DocsError, inlineCode, markdown } from "@docs-sdk-dev/core";
|
|
6
|
+
const { version } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
7
|
+
export const extractor = { name: "@docs-sdk-dev/openapi", version };
|
|
8
|
+
const deprecated = (value) => value.deprecated === true ? { deprecated: true } : {};
|
|
9
|
+
const methods = ["get", "put", "post", "delete", "patch", "head", "options", "trace"];
|
|
10
|
+
const escapeKey = (key) => key.replaceAll("~", "~0").replaceAll("/", "~1");
|
|
11
|
+
/** JSON pointer (`/paths/~1components/get`) → 1-based line range of the value, from TypeScript's JSON parser. */
|
|
12
|
+
function jsonRanges(source, text) {
|
|
13
|
+
const file = ts.parseJsonText(source, text);
|
|
14
|
+
const map = new Map();
|
|
15
|
+
const line = (position) => file.getLineAndCharacterOfPosition(position).line + 1;
|
|
16
|
+
function visit(node, pointer) {
|
|
17
|
+
map.set(pointer, { start: line(node.getStart(file)), end: line(node.getEnd()) });
|
|
18
|
+
if (ts.isObjectLiteralExpression(node))
|
|
19
|
+
for (const property of node.properties) {
|
|
20
|
+
if (ts.isPropertyAssignment(property) && (ts.isStringLiteral(property.name) || ts.isIdentifier(property.name)))
|
|
21
|
+
visit(property.initializer, `${pointer}/${escapeKey(property.name.text)}`);
|
|
22
|
+
}
|
|
23
|
+
else if (ts.isArrayLiteralExpression(node))
|
|
24
|
+
node.elements.forEach((element, index) => visit(element, `${pointer}/${index}`));
|
|
25
|
+
}
|
|
26
|
+
const root = file.statements[0]?.expression;
|
|
27
|
+
if (root)
|
|
28
|
+
visit(root, "");
|
|
29
|
+
return map;
|
|
30
|
+
}
|
|
31
|
+
/** The same pointer map for YAML. A mapping value's range starts at its key, matching where a reader looks for it. */
|
|
32
|
+
function yamlRanges(root, counter) {
|
|
33
|
+
const map = new Map();
|
|
34
|
+
const line = (offset) => counter.linePos(offset).line;
|
|
35
|
+
// A block value's end offset sits after its trailing newline; step back so the range ends on its last line.
|
|
36
|
+
const range = (start, end) => ({ start: line(start), end: line(Math.max(start, end - 1)) });
|
|
37
|
+
function visit(node, pointer, start) {
|
|
38
|
+
const own = node?.range;
|
|
39
|
+
if (own)
|
|
40
|
+
map.set(pointer, range(start ?? own[0], own[1]));
|
|
41
|
+
if (isMap(node))
|
|
42
|
+
for (const pair of node.items) {
|
|
43
|
+
const key = isScalar(pair.key) ? pair.key.value : pair.key;
|
|
44
|
+
if (typeof key !== "string" && typeof key !== "number")
|
|
45
|
+
continue;
|
|
46
|
+
visit(pair.value, `${pointer}/${escapeKey(String(key))}`, isScalar(pair.key) ? pair.key.range?.[0] : undefined);
|
|
47
|
+
}
|
|
48
|
+
else if (isSeq(node))
|
|
49
|
+
node.items.forEach((item, index) => visit(item, `${pointer}/${index}`));
|
|
50
|
+
}
|
|
51
|
+
visit(root, "");
|
|
52
|
+
return map;
|
|
53
|
+
}
|
|
54
|
+
/** `.yaml` and `.yml` sources are YAML; everything else is JSON. */
|
|
55
|
+
function parseSpec(source, text) {
|
|
56
|
+
if (/\.ya?ml$/i.test(source)) {
|
|
57
|
+
const counter = new LineCounter();
|
|
58
|
+
const document = parseDocument(text, { lineCounter: counter, prettyErrors: false, uniqueKeys: true });
|
|
59
|
+
const [error] = document.errors;
|
|
60
|
+
if (error)
|
|
61
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", `Expected an OpenAPI document in YAML: ${error.message}`, { source, line: counter.linePos(error.pos[0]).line });
|
|
62
|
+
const spec = document.toJS({ maxAliasCount: 100 });
|
|
63
|
+
if (!spec || typeof spec !== "object" || Array.isArray(spec))
|
|
64
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", "Expected an OpenAPI document: the YAML root is not a mapping.", { source });
|
|
65
|
+
return { spec: spec, lines: yamlRanges(document.contents, counter) };
|
|
66
|
+
}
|
|
67
|
+
let spec;
|
|
68
|
+
try {
|
|
69
|
+
spec = JSON.parse(text);
|
|
70
|
+
}
|
|
71
|
+
catch (error) {
|
|
72
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", `Expected an OpenAPI document in JSON: ${error.message}`, { source });
|
|
73
|
+
}
|
|
74
|
+
return { spec, lines: jsonRanges(source, text) };
|
|
75
|
+
}
|
|
76
|
+
const unescapeKey = (key) => key.replaceAll("~1", "/").replaceAll("~0", "~");
|
|
77
|
+
const valueAt = (file, pointer) => pointer.split("/").slice(1).map(unescapeKey).reduce((value, key) => value?.[key], file.spec);
|
|
78
|
+
/** A relative file reference resolved against the file containing it. URLs, absolute paths and paths leaving the project are refused. */
|
|
79
|
+
function referencedFile(from, path) {
|
|
80
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("/"))
|
|
81
|
+
return undefined;
|
|
82
|
+
const resolved = posix.normalize(posix.join(posix.dirname(from), path));
|
|
83
|
+
return resolved === ".." || resolved.startsWith("../") ? undefined : resolved;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Read an OpenAPI 3 document in JSON, or in YAML when the source ends in `.yaml` or `.yml`. Operations keep document
|
|
87
|
+
* order. Schema references resolve to schema names: `#/components/schemas/<Name>` in the same file, the same pointer in
|
|
88
|
+
* another project file (`schemas.yaml#/components/schemas/<Name>`), or a whole file that is one schema
|
|
89
|
+
* (`schemas/Pet.yaml`, named after the file). Paths are relative to the file holding the reference, and each schema
|
|
90
|
+
* records the file it came from. Parameters, responses and request bodies may likewise refer to
|
|
91
|
+
* `#/components/{parameters,responses,requestBodies}/<Name>`, here or in another file. Two different schemas with one
|
|
92
|
+
* name, and other references, are reported rather than guessed.
|
|
93
|
+
*/
|
|
94
|
+
export async function extractOpenApi(read, source) {
|
|
95
|
+
const files = new Map();
|
|
96
|
+
const failed = new Map();
|
|
97
|
+
const load = async (path) => {
|
|
98
|
+
const { text, revision } = await read(path);
|
|
99
|
+
const file = { source: path, revision, ...parseSpec(path, text) };
|
|
100
|
+
files.set(path, file);
|
|
101
|
+
return file;
|
|
102
|
+
};
|
|
103
|
+
const root = await load(source);
|
|
104
|
+
const spec = root.spec;
|
|
105
|
+
if (typeof spec.openapi !== "string" || !spec.openapi.startsWith("3."))
|
|
106
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", "Expected an OpenAPI 3 document with an openapi version field.", { source });
|
|
107
|
+
// Load every project file the documents refer to, transitively, so resolution below stays synchronous. A file that
|
|
108
|
+
// cannot be loaded is reported only if a schema reference actually reaches it.
|
|
109
|
+
const pending = [root];
|
|
110
|
+
while (pending.length) {
|
|
111
|
+
const file = pending.pop();
|
|
112
|
+
const paths = [];
|
|
113
|
+
const walk = (value) => {
|
|
114
|
+
if (Array.isArray(value))
|
|
115
|
+
value.forEach(walk);
|
|
116
|
+
else if (value && typeof value === "object")
|
|
117
|
+
for (const [key, item] of Object.entries(value)) {
|
|
118
|
+
if (key !== "$ref")
|
|
119
|
+
walk(item);
|
|
120
|
+
else if (typeof item === "string" && !item.startsWith("#")) {
|
|
121
|
+
const path = referencedFile(file.source, item.split("#")[0]);
|
|
122
|
+
if (path)
|
|
123
|
+
paths.push(path);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
walk(file.spec);
|
|
128
|
+
for (const path of paths)
|
|
129
|
+
if (!files.has(path) && !failed.has(path)) {
|
|
130
|
+
try {
|
|
131
|
+
pending.push(await load(path));
|
|
132
|
+
}
|
|
133
|
+
catch (error) {
|
|
134
|
+
failed.set(path, error.message);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
const named = new Map();
|
|
139
|
+
const order = [];
|
|
140
|
+
const register = (name, file, pointer, at) => {
|
|
141
|
+
const existing = named.get(name);
|
|
142
|
+
if (!existing) {
|
|
143
|
+
named.set(name, { file, pointer });
|
|
144
|
+
order.push(name);
|
|
145
|
+
}
|
|
146
|
+
else if (existing.file !== file || existing.pointer !== pointer)
|
|
147
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Two different schemas are named ${name}: ${existing.file.source}#${existing.pointer} `
|
|
148
|
+
+ `and ${file.source}#${pointer}.`, at);
|
|
149
|
+
return name;
|
|
150
|
+
};
|
|
151
|
+
for (const name of Object.keys(spec.components?.schemas ?? {}))
|
|
152
|
+
register(name, root, `/components/schemas/${escapeKey(name)}`, { source, line: 1 });
|
|
153
|
+
const rangeIn = (file, pointer) => file.lines.get(pointer) ?? { start: 1, end: 1 };
|
|
154
|
+
const at = (pointer) => rangeIn(root, pointer);
|
|
155
|
+
/** The file and pointer a `$ref` names, relative to the file holding it. */
|
|
156
|
+
function follow(ref, file, pointer) {
|
|
157
|
+
const location = { source: file.source, line: rangeIn(file, pointer).start };
|
|
158
|
+
const hash = ref.indexOf("#");
|
|
159
|
+
const path = hash === -1 ? ref : ref.slice(0, hash);
|
|
160
|
+
const fragment = hash === -1 ? "" : ref.slice(hash + 1);
|
|
161
|
+
let target = file;
|
|
162
|
+
if (path) {
|
|
163
|
+
const resolved = referencedFile(file.source, path);
|
|
164
|
+
if (!resolved)
|
|
165
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Only references to files inside the project are supported, not ${ref}.`, location);
|
|
166
|
+
const loaded = files.get(resolved);
|
|
167
|
+
if (!loaded)
|
|
168
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Cannot read ${resolved} for ${ref}: ${failed.get(resolved)}`, location);
|
|
169
|
+
target = loaded;
|
|
170
|
+
}
|
|
171
|
+
return { target, path, fragment, location };
|
|
172
|
+
}
|
|
173
|
+
/** A parameter, response or request body, following `$ref` to `#/components/<kind>/<Name>` here or in another file. */
|
|
174
|
+
let reached = [];
|
|
175
|
+
function component(value, pointer, file, kind) {
|
|
176
|
+
for (let depth = 0; typeof value?.$ref === "string"; depth++) {
|
|
177
|
+
const ref = value.$ref;
|
|
178
|
+
const { target, fragment, location } = follow(ref, file, pointer);
|
|
179
|
+
if (depth > 16 || !new RegExp(`^/components/${kind}/[^/]+$`).test(fragment))
|
|
180
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Expected a reference to #/components/${kind}/<Name>, not ${ref}.`, location);
|
|
181
|
+
const next = valueAt(target, fragment);
|
|
182
|
+
if (!next || typeof next !== "object")
|
|
183
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Unknown ${kind} ${ref}.`, location);
|
|
184
|
+
value = next;
|
|
185
|
+
pointer = fragment;
|
|
186
|
+
file = target;
|
|
187
|
+
if (!reached.some(item => item.source === file.source && item.pointer === pointer))
|
|
188
|
+
reached.push({ source: file.source, revision: file.revision, pointer, range: rangeIn(file, pointer) });
|
|
189
|
+
}
|
|
190
|
+
return { value, pointer, file };
|
|
191
|
+
}
|
|
192
|
+
function typeOf(schema, pointer, file = root) {
|
|
193
|
+
if (!schema)
|
|
194
|
+
return "unknown";
|
|
195
|
+
if (typeof schema.$ref === "string") {
|
|
196
|
+
const ref = schema.$ref;
|
|
197
|
+
const { target, path, fragment, location } = follow(ref, file, pointer);
|
|
198
|
+
const match = /^\/components\/schemas\/([^/]+)$/.exec(fragment);
|
|
199
|
+
if (!match && (fragment || !path))
|
|
200
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Only schema references (#/components/schemas/<Name>, or a whole file) are supported, not ${ref}.`, location);
|
|
201
|
+
const value = valueAt(target, fragment);
|
|
202
|
+
if (!value || typeof value !== "object")
|
|
203
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Unknown schema ${ref}.`, location);
|
|
204
|
+
const name = match ? unescapeKey(match[1]) : posix.basename(target.source).replace(/\.(?:json|ya?ml)$/i, "");
|
|
205
|
+
return register(name, target, fragment, location);
|
|
206
|
+
}
|
|
207
|
+
const wrap = (type) => /[ |&]/.test(type) ? `(${type})` : type;
|
|
208
|
+
const members = (key) => schema[key].map((member, index) => wrap(typeOf(member, `${pointer}/${key}/${index}`, file)));
|
|
209
|
+
let type;
|
|
210
|
+
if (Array.isArray(schema.allOf) && schema.allOf.length)
|
|
211
|
+
type = members("allOf").join(" & ");
|
|
212
|
+
else if (Array.isArray(schema.oneOf) && schema.oneOf.length)
|
|
213
|
+
type = members("oneOf").join(" | ");
|
|
214
|
+
else if (Array.isArray(schema.anyOf) && schema.anyOf.length)
|
|
215
|
+
type = members("anyOf").join(" | ");
|
|
216
|
+
else if (Array.isArray(schema.enum) && schema.enum.length)
|
|
217
|
+
type = schema.enum.map(value => JSON.stringify(value)).join(" | ");
|
|
218
|
+
else if ("const" in schema)
|
|
219
|
+
type = JSON.stringify(schema.const);
|
|
220
|
+
else if (schema.type === "array")
|
|
221
|
+
type = `${wrap(typeOf(schema.items, `${pointer}/items`, file))}[]`;
|
|
222
|
+
else
|
|
223
|
+
type = typeof schema.type === "string" ? schema.type : Array.isArray(schema.type) ? schema.type.join(" | ") : "object";
|
|
224
|
+
// OpenAPI 3.0 marks optional null with `nullable`; 3.1 lists "null" in `type`, which the line above already shows.
|
|
225
|
+
return schema.nullable === true && !/(^|\| )null($| \|)/.test(type) ? `${type} | null` : type;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* A schema's fields: those inherited through `allOf` members (references followed, in order), then its own, each
|
|
229
|
+
* followed by the fields of an inline object it holds. A later declaration of the same name replaces an earlier one in
|
|
230
|
+
* place; a field is required if any level requires it, and a nested field if its own object requires it.
|
|
231
|
+
*/
|
|
232
|
+
function fieldsOf(schema, pointer, file, depth = 0) {
|
|
233
|
+
if (depth > 16)
|
|
234
|
+
throw new DocsError("DOCS_OPENAPI_REF", "allOf nests or refers to itself too deeply.", { source: file.source, line: rangeIn(file, pointer).start });
|
|
235
|
+
const fields = new Map();
|
|
236
|
+
for (const [index, member] of (schema.allOf ?? []).entries()) {
|
|
237
|
+
let value = member, at = `${pointer}/allOf/${index}`, from = file;
|
|
238
|
+
if (typeof member.$ref === "string") {
|
|
239
|
+
typeOf(member, at, file);
|
|
240
|
+
const { target, fragment } = follow(member.$ref, file, at);
|
|
241
|
+
value = valueAt(target, fragment);
|
|
242
|
+
at = fragment;
|
|
243
|
+
from = target;
|
|
244
|
+
}
|
|
245
|
+
for (const field of fieldsOf(value, at, from, depth + 1))
|
|
246
|
+
fields.set(field.name, field);
|
|
247
|
+
}
|
|
248
|
+
for (const [name, property] of Object.entries(schema.properties ?? {})) {
|
|
249
|
+
const at = `${pointer}/properties/${escapeKey(name)}`;
|
|
250
|
+
fields.set(name, { name, type: typeOf(property, at, file), required: false, description: property.description ?? "",
|
|
251
|
+
...deprecated(property), source: file.source, revision: file.revision, range: rangeIn(file, at) });
|
|
252
|
+
// An inline object has no schema page of its own, so its fields follow the parent as `name.inner`, or
|
|
253
|
+
// `name[].inner` for an array of inline objects. Referenced schemas keep their own entity and table instead.
|
|
254
|
+
const inline = (value) => !!value && typeof value.$ref !== "string" && (!!value.properties || !!value.allOf);
|
|
255
|
+
const nested = inline(property) ? { value: property, at, prefix: `${name}.` }
|
|
256
|
+
: property.type === "array" && inline(property.items) ? { value: property.items, at: `${at}/items`, prefix: `${name}[].` } : undefined;
|
|
257
|
+
if (nested)
|
|
258
|
+
for (const field of fieldsOf(nested.value, nested.at, file, depth + 1))
|
|
259
|
+
fields.set(nested.prefix + field.name, { ...field, name: nested.prefix + field.name });
|
|
260
|
+
}
|
|
261
|
+
const required = new Set(schema.required ?? []);
|
|
262
|
+
return [...fields.values()].map(field => required.has(field.name) ? { ...field, required: true } : field);
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* A media type's examples: `example`, then each of `examples` in order (references to `#/components/examples/<Name>`
|
|
266
|
+
* followed). Examples that only name an `externalValue` are left out; the provider reads project files, not URLs.
|
|
267
|
+
*/
|
|
268
|
+
function examplesOf(media, pointer, file) {
|
|
269
|
+
const examples = "example" in media ? [{ name: "example", value: media.example }] : [];
|
|
270
|
+
for (const [name, value] of Object.entries(media.examples ?? {})) {
|
|
271
|
+
const { value: example } = component(value, `${pointer}/examples/${escapeKey(name)}`, file, "examples");
|
|
272
|
+
if ("value" in example)
|
|
273
|
+
examples.push({ name, ...typeof example.summary === "string" ? { summary: example.summary } : {}, value: example.value });
|
|
274
|
+
}
|
|
275
|
+
return examples.length ? { examples } : {};
|
|
276
|
+
}
|
|
277
|
+
/** Security requirements, with each scheme looked up in `components.securitySchemes` (references followed). */
|
|
278
|
+
function securityOf(requirements, pointer) {
|
|
279
|
+
if (!Array.isArray(requirements))
|
|
280
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", "Expected security to be a list of requirements.", { source, line: at(pointer).start });
|
|
281
|
+
return requirements.map((requirement, index) => Object.entries(requirement ?? {}).map(([name, scopes]) => {
|
|
282
|
+
const declared = spec.components?.securitySchemes?.[name];
|
|
283
|
+
if (!declared)
|
|
284
|
+
throw new DocsError("DOCS_OPENAPI_REF", `Unknown security scheme ${name}.`, { source, line: at(`${pointer}/${index}`).start });
|
|
285
|
+
const { value: scheme } = component(declared, `/components/securitySchemes/${escapeKey(name)}`, root, "securitySchemes");
|
|
286
|
+
const type = String(scheme.type ?? "unknown");
|
|
287
|
+
const label = type === "http" ? `HTTP ${scheme.scheme ?? ""}`.trim()
|
|
288
|
+
: type === "apiKey" ? `API key in ${scheme.in} ${inlineCode(scheme.name)}`
|
|
289
|
+
: type === "oauth2" ? "OAuth 2" : type === "openIdConnect" ? "OpenID Connect" : type === "mutualTLS" ? "Mutual TLS" : type;
|
|
290
|
+
return { name, type, label, scopes: Array.isArray(scopes) ? scopes.map(String) : [] };
|
|
291
|
+
}));
|
|
292
|
+
}
|
|
293
|
+
const operations = [];
|
|
294
|
+
for (const [path, item] of Object.entries(spec.paths ?? {})) {
|
|
295
|
+
for (const method of methods) {
|
|
296
|
+
const operation = item[method];
|
|
297
|
+
if (!operation)
|
|
298
|
+
continue;
|
|
299
|
+
const pointer = `/paths/${escapeKey(path)}/${method}`;
|
|
300
|
+
if (typeof operation.operationId !== "string" || !operation.operationId)
|
|
301
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", `${method.toUpperCase()} ${path} needs an operationId for a stable identity.`, { source, line: at(pointer).start });
|
|
302
|
+
reached = [];
|
|
303
|
+
const parameters = [
|
|
304
|
+
...(item.parameters ?? []).map((value, index) => component(value, `/paths/${escapeKey(path)}/parameters/${index}`, root, "parameters")),
|
|
305
|
+
...(operation.parameters ?? []).map((value, index) => component(value, `${pointer}/parameters/${index}`, root, "parameters")),
|
|
306
|
+
];
|
|
307
|
+
const body = operation.requestBody ? component(operation.requestBody, `${pointer}/requestBody`, root, "requestBodies") : undefined;
|
|
308
|
+
const [contentType, media] = Object.entries(body?.value.content ?? {})[0] ?? [];
|
|
309
|
+
operations.push({
|
|
310
|
+
operationId: operation.operationId, method: method.toUpperCase(), path,
|
|
311
|
+
summary: operation.summary ?? "", description: operation.description ?? "", ...deprecated(operation),
|
|
312
|
+
...Array.isArray(operation.tags) && operation.tags.length ? { tags: operation.tags.map(String) } : {},
|
|
313
|
+
...("security" in operation ? { security: securityOf(operation.security, `${pointer}/security`) }
|
|
314
|
+
: "security" in spec ? { security: securityOf(spec.security, "/security") } : {}),
|
|
315
|
+
parameters: parameters.map(({ value, pointer, file }) => ({
|
|
316
|
+
name: value.name, in: value.in, type: typeOf(value.schema, `${pointer}/schema`, file),
|
|
317
|
+
required: value.required === true, description: value.description ?? "", ...deprecated(value)
|
|
318
|
+
})),
|
|
319
|
+
...(body && contentType ? { requestBody: { required: body.value.required === true, contentType,
|
|
320
|
+
schema: typeOf(media.schema, `${body.pointer}/content/${escapeKey(contentType)}/schema`, body.file),
|
|
321
|
+
...examplesOf(media, `${body.pointer}/content/${escapeKey(contentType)}`, body.file) } } : {}),
|
|
322
|
+
responses: Object.entries(operation.responses ?? {}).map(([status, value]) => {
|
|
323
|
+
const response = component(value, `${pointer}/responses/${escapeKey(status)}`, root, "responses");
|
|
324
|
+
const [type, content] = Object.entries(response.value.content ?? {})[0] ?? [];
|
|
325
|
+
return { status, description: response.value.description ?? "",
|
|
326
|
+
...(type ? { schema: typeOf(content.schema, `${response.pointer}/content/${escapeKey(type)}/schema`, response.file),
|
|
327
|
+
...examplesOf(content, `${response.pointer}/content/${escapeKey(type)}`, response.file) } : {}) };
|
|
328
|
+
}),
|
|
329
|
+
range: at(pointer),
|
|
330
|
+
components: reached,
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
// Fields can reach schemas in further files, which join the end of `order` and are read in turn.
|
|
335
|
+
const schemas = [];
|
|
336
|
+
for (let index = 0; index < order.length; index++) {
|
|
337
|
+
const name = order[index];
|
|
338
|
+
const { file, pointer } = named.get(name);
|
|
339
|
+
const schema = valueAt(file, pointer);
|
|
340
|
+
// A schema composed with allOf is the object its members describe together; its fields say what that object holds.
|
|
341
|
+
const type = Array.isArray(schema.allOf) && schema.allOf.length ? "object" : typeOf({ ...schema, $ref: undefined }, pointer, file);
|
|
342
|
+
schemas.push({ name, source: file.source, revision: file.revision, type, range: rangeIn(file, pointer), fields: fieldsOf(schema, pointer, file) });
|
|
343
|
+
}
|
|
344
|
+
return { source, revision: root.revision, title: spec.info?.title ?? source, version: spec.info?.version ?? "", operations, schemas };
|
|
345
|
+
}
|
|
346
|
+
/** Schema names an operation refers to, without array markers. */
|
|
347
|
+
export const schemasOf = (operation) => [...new Set([operation.requestBody?.schema, ...operation.responses.map(response => response.schema)]
|
|
348
|
+
.filter((name) => !!name).map(name => name.replace(/(\[\])+$/, "")))];
|
|
349
|
+
/** Entities for one operation and the schemas it uses. IDs: api:<scope>/<operationId>, schema:<scope>/<Name>, field:<scope>/<Name>#<field>. */
|
|
350
|
+
export function apiEntities(spec, operation, options) {
|
|
351
|
+
const context = options.context ?? {};
|
|
352
|
+
const at = (range, symbol, file = spec) => ({ source: file.source, revision: file.revision, symbol, range, extractor, evidence: "extracted" });
|
|
353
|
+
const schemaId = (name) => `schema:${options.scope}/${name}`;
|
|
354
|
+
const known = new Map(spec.schemas.map(schema => [schema.name, schema]));
|
|
355
|
+
const used = schemasOf(operation).filter(name => known.has(name));
|
|
356
|
+
const { range, components, ...data } = operation;
|
|
357
|
+
const id = `api:${options.scope}/${operation.operationId}`;
|
|
358
|
+
const entities = [{
|
|
359
|
+
id, type: "api", context, data, provenance: [at(range, `${operation.method} ${operation.path}`),
|
|
360
|
+
...components.map(item => at(item.range, `#${item.pointer}`, item))],
|
|
361
|
+
relations: [
|
|
362
|
+
...(operation.requestBody && known.has(operation.requestBody.schema.replace(/(\[\])+$/, ""))
|
|
363
|
+
? [{ type: "requires", target: schemaId(operation.requestBody.schema.replace(/(\[\])+$/, "")), evidence: "extracted" }] : []),
|
|
364
|
+
...used.filter(name => name !== operation.requestBody?.schema.replace(/(\[\])+$/, ""))
|
|
365
|
+
.map(name => ({ type: "references", target: schemaId(name), evidence: "extracted" })),
|
|
366
|
+
],
|
|
367
|
+
}];
|
|
368
|
+
for (const name of used) {
|
|
369
|
+
const schema = known.get(name);
|
|
370
|
+
entities.push({ id: schemaId(name), type: "schema", context, provenance: [at(schema.range, name, schema)],
|
|
371
|
+
data: { name, type: schema.type, required: schema.fields.filter(field => field.required).map(field => field.name) },
|
|
372
|
+
relations: schema.fields.map((field, order) => ({ type: "contains", target: `field:${options.scope}/${name}#${field.name}`,
|
|
373
|
+
evidence: "extracted", order })) });
|
|
374
|
+
for (const { range: fieldRange, source, revision, ...field } of schema.fields)
|
|
375
|
+
entities.push({ id: `field:${options.scope}/${name}#${field.name}`, type: "field", context, data: field,
|
|
376
|
+
provenance: [at(fieldRange, `${name}.${field.name}`, { source, revision })] });
|
|
377
|
+
}
|
|
378
|
+
return { id, schemas: used.map(schemaId), entities };
|
|
379
|
+
}
|
|
380
|
+
const cell = (text) => text.replaceAll("|", "\\|").replaceAll("\n", " ");
|
|
381
|
+
const table = (head, rows) => [`| ${head.join(" | ")} |`, `| ${head.map(() => "---").join(" | ")} |`, ...rows.map(row => `| ${row.map(cell).join(" | ")} |`)].join("\n");
|
|
382
|
+
const kebab = (text) => text.replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
|
|
383
|
+
/** The schema a body type names, looking through array markers (`Component[]` → `Component`). */
|
|
384
|
+
const schemaNamed = (spec, type) => spec.schemas.find(schema => schema.name === type.replace(/(\[\])+$/, ""));
|
|
385
|
+
/**
|
|
386
|
+
* The text API pages write inside sections, per locale. Section titles are not here: a collection's template config
|
|
387
|
+
* names them (`sections.parameters.title`), like any template's.
|
|
388
|
+
*/
|
|
389
|
+
export const englishApiText = {
|
|
390
|
+
name: "Name", in: "In", type: "Type", required: "Required", description: "Description", field: "Field", status: "Status",
|
|
391
|
+
body: "Body", yes: "Yes", no: "No", requiredBody: "required", optionalBody: "optional", example: "Example",
|
|
392
|
+
deprecated: "Deprecated.", authentication: "Authentication:", none: "none", and: "and", or: "or", scopes: "scopes",
|
|
393
|
+
};
|
|
394
|
+
const builtInApiText = {
|
|
395
|
+
en: englishApiText,
|
|
396
|
+
fr: {
|
|
397
|
+
name: "Nom", in: "Emplacement", type: "Type", required: "Requis", description: "Description", field: "Champ", status: "Statut",
|
|
398
|
+
body: "Corps", yes: "Oui", no: "Non", requiredBody: "requis", optionalBody: "facultatif", example: "Exemple",
|
|
399
|
+
deprecated: "Obsolète.", authentication: "Authentification :", none: "aucune", and: "et", or: "ou", scopes: "portées",
|
|
400
|
+
},
|
|
401
|
+
};
|
|
402
|
+
/** The text for a locale: project overrides, then built-in text for the locale or its language, then English. */
|
|
403
|
+
export function apiTextFor(locale, overrides = {}) {
|
|
404
|
+
for (const [key, values] of Object.entries(overrides))
|
|
405
|
+
for (const name of Object.keys(values))
|
|
406
|
+
if (!Object.hasOwn(englishApiText, name))
|
|
407
|
+
throw new DocsError("DOCS_TEMPLATE_INVALID_CONFIG", `text.${key}.${name} is not text API pages write.`, { field: `text.${key}.${name}` });
|
|
408
|
+
const language = locale?.split("-")[0];
|
|
409
|
+
const base = (locale && builtInApiText[locale]) || (language && builtInApiText[language]) || englishApiText;
|
|
410
|
+
return { ...base, ...(language ? overrides[language] : {}), ...(locale ? overrides[locale] : {}) };
|
|
411
|
+
}
|
|
412
|
+
const describe = (item, text) => item.deprecated ? [`**${text.deprecated}**`, item.description].filter(Boolean).join(" ") : item.description;
|
|
413
|
+
const fieldTable = (schema, text) => table([text.field, text.type, text.required, text.description], schema.fields.map(field => [inlineCode(field.name), inlineCode(field.type), field.required ? text.yes : text.no, describe(field, text)]));
|
|
414
|
+
/** A fenced block longer than any backtick run inside it. JSON values print as JSON; strings print as written. */
|
|
415
|
+
function codeBlock(code, language) {
|
|
416
|
+
const fence = "`".repeat(Math.max(3, ...[...code.matchAll(/`+/g)].map(match => match[0].length + 1)));
|
|
417
|
+
return `${fence}${language}\n${code}\n${fence}`;
|
|
418
|
+
}
|
|
419
|
+
const exampleBlocks = (examples, text, status) => (examples ?? []).flatMap(example => [
|
|
420
|
+
`${text.example}${status ? ` ${inlineCode(status)}` : ""}${example.name === "example" ? "" : ` ${inlineCode(example.name)}`}${example.summary ? ` (${example.summary.replace(/\.$/, "")})` : ""}:`,
|
|
421
|
+
typeof example.value === "string" ? codeBlock(example.value, "text") : codeBlock(JSON.stringify(example.value, null, 2), "json")
|
|
422
|
+
]);
|
|
423
|
+
/** "Authentication: `a` (HTTP bearer) and `b` (…), or `c` (…)." An empty alternative means the call may also be anonymous. */
|
|
424
|
+
function authentication(security, text) {
|
|
425
|
+
if (!security.length)
|
|
426
|
+
return `${text.authentication} ${text.none}.`;
|
|
427
|
+
const scheme = (item) => `${inlineCode(item.name)} (${item.label}${item.scopes.length ? `, ${text.scopes} ${item.scopes.map(scope => inlineCode(scope)).join(", ")}` : ""})`;
|
|
428
|
+
const options = security.map(alternative => alternative.length ? alternative.map(scheme).join(` ${text.and} `) : text.none);
|
|
429
|
+
return `${text.authentication} ${options.join(`, ${text.or} `)}.`;
|
|
430
|
+
}
|
|
431
|
+
const template = defineTemplate({
|
|
432
|
+
id: "api-reference", source: "@docs-sdk-dev/openapi", revision: version,
|
|
433
|
+
sections: [
|
|
434
|
+
{ id: "overview", required: true, build: ({ data }) => ({
|
|
435
|
+
...markdown([data.operation.deprecated ? `**${data.text.deprecated}**` : "", data.operation.description || data.operation.summary, "```http\n" + `${data.operation.method} ${data.operation.path}` + "\n```",
|
|
436
|
+
data.operation.security ? authentication(data.operation.security, data.text) : ""]
|
|
437
|
+
.filter(Boolean).join("\n\n"), data.spec.source), derivedFrom: [data.api]
|
|
438
|
+
}) },
|
|
439
|
+
{ id: "parameters", title: "Parameters", build: ({ data: { operation, spec, api, text } }) => operation.parameters.length ? {
|
|
440
|
+
...markdown(table([text.name, text.in, text.type, text.required, text.description], operation.parameters.map(parameter => [inlineCode(parameter.name), parameter.in, inlineCode(parameter.type), parameter.required ? text.yes : text.no, describe(parameter, text)])), spec.source),
|
|
441
|
+
derivedFrom: [api]
|
|
442
|
+
} : null },
|
|
443
|
+
{ id: "request", title: "Request body", build: ({ data }) => {
|
|
444
|
+
const body = data.operation.requestBody;
|
|
445
|
+
if (!body)
|
|
446
|
+
return null;
|
|
447
|
+
const schema = schemaNamed(data.spec, body.schema);
|
|
448
|
+
const lines = [`${inlineCode(body.contentType)}, ${body.required ? data.text.requiredBody : data.text.optionalBody}: ${inlineCode(body.schema)}.`];
|
|
449
|
+
if (schema?.fields.length)
|
|
450
|
+
lines.push(fieldTable(schema, data.text));
|
|
451
|
+
lines.push(...exampleBlocks(body.examples, data.text));
|
|
452
|
+
return { ...markdown(lines.join("\n\n"), data.spec.source), derivedFrom: [data.api, ...schema ? [`schema:${data.scope}/${schema.name}`] : []] };
|
|
453
|
+
} },
|
|
454
|
+
{ id: "responses", title: "Responses", required: true, build: ({ data }) => {
|
|
455
|
+
// Each response body schema with fields gets one table, in first-use order, so readers see what a response holds.
|
|
456
|
+
const bodies = [...new Set(data.operation.responses.flatMap(response => response.schema ? [response.schema] : []))]
|
|
457
|
+
.map(name => schemaNamed(data.spec, name)).filter((schema, index, all) => !!schema?.fields.length && all.findIndex(other => other?.name === schema.name) === index);
|
|
458
|
+
return {
|
|
459
|
+
...markdown([table([data.text.status, data.text.description, data.text.body], data.operation.responses.map(response => [inlineCode(response.status), response.description, response.schema ? inlineCode(response.schema) : ""])),
|
|
460
|
+
...bodies.flatMap(schema => [`${inlineCode(schema.name)}:`, fieldTable(schema, data.text)]),
|
|
461
|
+
...data.operation.responses.flatMap(response => exampleBlocks(response.examples, data.text, response.status))].join("\n\n"), data.spec.source),
|
|
462
|
+
derivedFrom: [data.api, ...data.schemas]
|
|
463
|
+
};
|
|
464
|
+
} },
|
|
465
|
+
],
|
|
466
|
+
});
|
|
467
|
+
/**
|
|
468
|
+
* One reference page per operation, in document order. Page IDs are the kebab-case operationId; titles are the
|
|
469
|
+
* operation summary. Entries carry the api, schema and field entities, so pages, search and contracts share them.
|
|
470
|
+
*/
|
|
471
|
+
export function apiReference(options, read) {
|
|
472
|
+
// Pages are written in the language of the collection's context; check overrides when the project loads.
|
|
473
|
+
const text = apiTextFor(options.context?.locale, options.text);
|
|
474
|
+
return defineCollection({
|
|
475
|
+
id: options.id, scope: options.scope, template, templateConfig: options.templateConfig, source: options.source ?? options.spec,
|
|
476
|
+
async load() {
|
|
477
|
+
const spec = await extractOpenApi(read, options.spec);
|
|
478
|
+
const wanted = options.tags && new Set(options.tags);
|
|
479
|
+
for (const tag of wanted ?? [])
|
|
480
|
+
if (!spec.operations.some(operation => operation.tags?.includes(tag)))
|
|
481
|
+
throw new DocsError("DOCS_OPENAPI_INVALID", `No operation in ${options.spec} has the tag ${tag}.`, { source: options.spec, field: "tags" });
|
|
482
|
+
const operations = wanted ? spec.operations.filter(operation => operation.tags?.some(tag => wanted.has(tag))
|
|
483
|
+
|| options.untagged && !operation.tags) : spec.operations;
|
|
484
|
+
return operations.map(operation => {
|
|
485
|
+
const extracted = apiEntities(spec, operation, { scope: options.entityScope ?? options.scope, context: options.context });
|
|
486
|
+
return { id: kebab(operation.operationId), title: operation.summary || operation.operationId, source: options.spec,
|
|
487
|
+
...(options.context && Object.keys(options.context).length ? { dimensions: options.context } : {}),
|
|
488
|
+
data: { spec, operation, scope: options.entityScope ?? options.scope, api: extracted.id, schemas: extracted.schemas, text }, entities: extracted.entities };
|
|
489
|
+
});
|
|
490
|
+
},
|
|
491
|
+
});
|
|
492
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,33 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@docs-sdk-dev/openapi",
|
|
3
|
-
"version": "0.0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.0.3",
|
|
4
|
+
"description": "Framework-independent OpenAPI provider and API reference preset for Docs SDK",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"engines": {
|
|
8
|
+
"node": ">=22.12.0"
|
|
9
|
+
},
|
|
10
|
+
"repository": {
|
|
11
|
+
"type": "git",
|
|
12
|
+
"url": "git+https://github.com/LioRael/docs-sdk.git",
|
|
13
|
+
"directory": "packages/openapi"
|
|
14
|
+
},
|
|
15
|
+
"publishConfig": {
|
|
16
|
+
"access": "public"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist/*.js",
|
|
20
|
+
"dist/*.d.ts"
|
|
21
|
+
],
|
|
22
|
+
"exports": {
|
|
23
|
+
".": {
|
|
24
|
+
"types": "./dist/index.d.ts",
|
|
25
|
+
"default": "./dist/index.js"
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@docs-sdk-dev/core": "0.0.3",
|
|
30
|
+
"typescript": "6.0.3",
|
|
31
|
+
"yaml": "2.9.1"
|
|
32
|
+
}
|
|
33
|
+
}
|