@webpieces/openapi-generator 0.4.829 → 0.4.830
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/README.md +47 -1
- package/package.json +3 -3
- package/src/cli/OpenApiCli.d.ts +5 -0
- package/src/cli/OpenApiCli.js +27 -1
- package/src/cli/OpenApiCli.js.map +1 -1
- package/src/generate/DocumentSelection.d.ts +8 -0
- package/src/generate/DocumentSelection.js +14 -4
- package/src/generate/DocumentSelection.js.map +1 -1
- package/src/generate/GenerationInputs.d.ts +34 -3
- package/src/generate/GenerationInputs.js +33 -2
- package/src/generate/GenerationInputs.js.map +1 -1
- package/src/generate/OpenApiGenerator.d.ts +43 -4
- package/src/generate/OpenApiGenerator.js +142 -10
- package/src/generate/OpenApiGenerator.js.map +1 -1
- package/src/generate/SchemaPlacement.d.ts +82 -0
- package/src/generate/SchemaPlacement.js +126 -0
- package/src/generate/SchemaPlacement.js.map +1 -0
- package/src/generate/SchemaRenderer.d.ts +27 -2
- package/src/generate/SchemaRenderer.js +57 -11
- package/src/generate/SchemaRenderer.js.map +1 -1
- package/src/generate/UpstreamComponents.d.ts +43 -0
- package/src/generate/UpstreamComponents.js +68 -0
- package/src/generate/UpstreamComponents.js.map +1 -0
- package/src/index.d.ts +6 -2
- package/src/index.js +16 -1
- package/src/index.js.map +1 -1
- package/src/load/ComponentsLocator.d.ts +44 -0
- package/src/load/ComponentsLocator.js +127 -0
- package/src/load/ComponentsLocator.js.map +1 -0
- package/src/load/InputsLoader.d.ts +14 -1
- package/src/load/InputsLoader.js +79 -1
- package/src/load/InputsLoader.js.map +1 -1
- package/src/manifest/ManifestLoader.d.ts +10 -2
- package/src/manifest/ManifestLoader.js +53 -3
- package/src/manifest/ManifestLoader.js.map +1 -1
- package/src/manifest/OpenApiManifest.d.ts +17 -0
- package/src/manifest/OpenApiManifest.js +21 -1
- package/src/manifest/OpenApiManifest.js.map +1 -1
|
@@ -7,8 +7,28 @@ const OpenApiGenerationError_1 = require("../OpenApiGenerationError");
|
|
|
7
7
|
const GenerationInputs_1 = require("./GenerationInputs");
|
|
8
8
|
const DocumentSelection_1 = require("./DocumentSelection");
|
|
9
9
|
const OperationRenderer_1 = require("./OperationRenderer");
|
|
10
|
+
const SchemaPlacement_1 = require("./SchemaPlacement");
|
|
10
11
|
const SchemaRenderer_1 = require("./SchemaRenderer");
|
|
11
12
|
const SecurityDeriver_1 = require("./SecurityDeriver");
|
|
13
|
+
/** One rendered document, and the renderer that built its schemas — what it defined and referenced. */
|
|
14
|
+
class RenderedDocument {
|
|
15
|
+
document;
|
|
16
|
+
schemas;
|
|
17
|
+
constructor(document, schemas) {
|
|
18
|
+
this.document = document;
|
|
19
|
+
this.schemas = schemas;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** The suffix of a split document's self-contained sibling: `public-openapi.bundled.json`. */
|
|
23
|
+
const BUNDLED_SUFFIX = '.bundled';
|
|
24
|
+
/** The document a DTO library publishes, without its extension (#1058). */
|
|
25
|
+
const COMPONENTS_DOCUMENT = 'components.openapi';
|
|
26
|
+
/** Every cure for a type reached in a package that publishes no components document. */
|
|
27
|
+
const PUBLISH_COMPONENTS_CURE = 'Move each type into a DTO library that publishes a components document — as a `…Dto` string ' +
|
|
28
|
+
'enum when it is a string-literal union — or make its package publish one: a "kind": ' +
|
|
29
|
+
'"components" openapi.manifest.json naming its entry files, rendered by wp-openapi into the ' +
|
|
30
|
+
"directory the package is packed from. A document references another package's schema; it " +
|
|
31
|
+
'never copies one in.';
|
|
12
32
|
/** The OpenAPI version this generator writes. See the class doc for why 3.1 and not 3.0. */
|
|
13
33
|
const OPENAPI_VERSION = '3.1.0';
|
|
14
34
|
/**
|
|
@@ -58,14 +78,69 @@ class OpenApiGenerator {
|
|
|
58
78
|
if (contracts.length === 0) {
|
|
59
79
|
continue;
|
|
60
80
|
}
|
|
61
|
-
|
|
81
|
+
if (selection.inlinesEveryPackage) {
|
|
82
|
+
documents.push(new GenerationInputs_1.GeneratedDocument(selection.fileName, this.bundled(inputs, contracts, selection)));
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
this.refuseCollisions(this.collisionsOf(inputs, contracts), inputs.manifestPath);
|
|
86
|
+
const split = this.render(inputs, contracts, selection, new SchemaPlacement_1.SplitPlacement(inputs.homePackage));
|
|
87
|
+
this.refuseUnpublished(split.schemas, this.mergedTypes(inputs), inputs.upstream, selection.fileName, inputs.manifestPath);
|
|
88
|
+
documents.push(new GenerationInputs_1.GeneratedDocument(selection.fileName, split.document));
|
|
89
|
+
documents.push(new GenerationInputs_1.GeneratedDocument(`${selection.fileName}${BUNDLED_SUFFIX}`, this.bundled(inputs, contracts, selection)));
|
|
62
90
|
}
|
|
63
91
|
return new GenerationInputs_1.GeneratedDocuments(documents);
|
|
64
92
|
}
|
|
93
|
+
/**
|
|
94
|
+
* A DTO library's COMPONENTS-ONLY document (#1058): `openapi`, `info`, `x-webpieces-id` and
|
|
95
|
+
* `components.schemas` — every type the library exports and declares, with every OTHER package's
|
|
96
|
+
* type a `$ref` into that package's own components document, so a chain of DTO libraries is a
|
|
97
|
+
* chain of documents of any depth.
|
|
98
|
+
*
|
|
99
|
+
* `info.version` is the PACKAGE version. The package-qualified URI downstream documents reference
|
|
100
|
+
* it by (`@scope/pkg/components.openapi.json`) is stated as `x-webpieces-id`, because OpenAPI 3.1's
|
|
101
|
+
* root object admits no `$id` — a 3.1 validator rejects one — and the document must validate on its
|
|
102
|
+
* own.
|
|
103
|
+
*/
|
|
104
|
+
components(inputs) {
|
|
105
|
+
const model = inputs.model;
|
|
106
|
+
const where = inputs.manifestPath;
|
|
107
|
+
this.refuseCollisions(model.collisions, where);
|
|
108
|
+
const schemas = new SchemaRenderer_1.SchemaRenderer(model.types, new SchemaPlacement_1.SplitPlacement(model.packageName));
|
|
109
|
+
for (const key of model.exported) {
|
|
110
|
+
schemas.define(key);
|
|
111
|
+
}
|
|
112
|
+
const rendered = schemas.components();
|
|
113
|
+
this.refuseUnmapped(schemas.unmapped(), COMPONENTS_DOCUMENT, where);
|
|
114
|
+
this.refuseUnpublished(schemas, model.types, inputs.upstream, COMPONENTS_DOCUMENT, where);
|
|
115
|
+
if (rendered.isEmpty()) {
|
|
116
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${model.packageName}'s entries export no type with a schema`, where, 'Name the entry files that export the library\'s DTOs and enums — usually "src/index.ts".');
|
|
117
|
+
}
|
|
118
|
+
return new GenerationInputs_1.GeneratedDocument(COMPONENTS_DOCUMENT, new JsonObject_1.JsonObject()
|
|
119
|
+
.set('openapi', OPENAPI_VERSION)
|
|
120
|
+
.set('info', new JsonObject_1.JsonObject()
|
|
121
|
+
.set('title', inputs.manifest.title)
|
|
122
|
+
.set('version', model.packageVersion))
|
|
123
|
+
.set('x-webpieces-id', SchemaPlacement_1.ComponentsReference.documentUri(model.packageName))
|
|
124
|
+
.set('components', new JsonObject_1.JsonObject().set('schemas', rendered)));
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* The SELF-CONTAINED form of a document: every reached schema defined locally, whichever package
|
|
128
|
+
* declares it — the `*.bundled.json` sibling of a split document, and the MCP projection.
|
|
129
|
+
*
|
|
130
|
+
* Two passes, because a schema's NAME depends on which other schemas the document reaches: the
|
|
131
|
+
* first renders with every type under its unique model key just to learn the reached set, and the
|
|
132
|
+
* second renders with the names {@link BundledNames} assigns from it. Rendering is a pure walk of
|
|
133
|
+
* the model, so the second pass reaches exactly what the first did.
|
|
134
|
+
*/
|
|
135
|
+
bundled(inputs, contracts, selection) {
|
|
136
|
+
const discovery = this.render(inputs, contracts, selection, new SchemaPlacement_1.DiscoveryPlacement());
|
|
137
|
+
const names = SchemaPlacement_1.BundledNames.assign(discovery.schemas.reachedTypes(), this.mergedTypes(inputs), inputs.homePackage);
|
|
138
|
+
return this.render(inputs, contracts, selection, new SchemaPlacement_1.BundledPlacement(names)).document;
|
|
139
|
+
}
|
|
65
140
|
/** ONE document, from the operations this selection accepts and nothing else. */
|
|
66
|
-
render(inputs, contracts, selection) {
|
|
141
|
+
render(inputs, contracts, selection, placement) {
|
|
67
142
|
const types = this.mergedTypes(inputs);
|
|
68
|
-
const schemas = new SchemaRenderer_1.SchemaRenderer(types);
|
|
143
|
+
const schemas = new SchemaRenderer_1.SchemaRenderer(types, placement);
|
|
69
144
|
const operations = new OperationRenderer_1.OperationRenderer(schemas, selection.includeMcpExtensions, selection.internalNotice);
|
|
70
145
|
const apiKey = this.singleApiKey(inputs, contracts, selection);
|
|
71
146
|
const schemeNames = inputs.manifest.securitySchemeNames;
|
|
@@ -83,14 +158,14 @@ class OpenApiGenerator {
|
|
|
83
158
|
// DTO's fields — and an unmapped field can only be found by that walk. A guard that ran
|
|
84
159
|
// before it would see only the top-level request and response refs and miss every one.
|
|
85
160
|
const renderedSchemas = schemas.components().orUndefined();
|
|
86
|
-
this.
|
|
161
|
+
this.refuseUnmapped(schemas.unmapped(), selection.fileName, inputs.manifestPath);
|
|
87
162
|
const components = new JsonObject_1.JsonObject()
|
|
88
163
|
.set('schemas', renderedSchemas)
|
|
89
164
|
.set('securitySchemes', apiKey === undefined
|
|
90
165
|
? undefined
|
|
91
166
|
: this.security.schemes(apiKey, schemeNames, inputs.manifestPath))
|
|
92
167
|
.set('headers', this.headers(inputs));
|
|
93
|
-
|
|
168
|
+
const document = new JsonObject_1.JsonObject()
|
|
94
169
|
.set('openapi', OPENAPI_VERSION)
|
|
95
170
|
.set('info', this.info(inputs, selection))
|
|
96
171
|
.set('servers', this.servers(inputs))
|
|
@@ -99,6 +174,61 @@ class OpenApiGenerator {
|
|
|
99
174
|
.set('paths', paths)
|
|
100
175
|
.set('webhooks', webhooks.orUndefined())
|
|
101
176
|
.set('components', components.orUndefined());
|
|
177
|
+
return new RenderedDocument(document, schemas);
|
|
178
|
+
}
|
|
179
|
+
/** Same-named, different declarations in one package, across every contract a document reads. */
|
|
180
|
+
collisionsOf(inputs, contracts) {
|
|
181
|
+
const models = contracts.map((each) => each.model);
|
|
182
|
+
const all = inputs.errorType === undefined ? models : models.concat([inputs.errorType]);
|
|
183
|
+
return all.flatMap((model) => Array.from(model.collisions));
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Two DIFFERENT declarations of one name in one package. A document defines each of its
|
|
187
|
+
* package's schemas under its bare name, so one of the two would be published as the other's
|
|
188
|
+
* shape. (Two packages' same-named types are not this: each is defined in its own package's
|
|
189
|
+
* document — #1058's `LocalizedDescriptionsDto` case.)
|
|
190
|
+
*/
|
|
191
|
+
refuseCollisions(collisions, where) {
|
|
192
|
+
if (collisions.length === 0) {
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${collisions.length} name(s) are declared twice in one package, so one document would ` +
|
|
196
|
+
'publish two different types under one name', where, 'Rename one declaration of each. Within one package a schema name is one type.', collisions.map((each) => `${each.name} (${each.packageName ?? 'no package'}): ${each.firstLocation} and ${each.secondLocation}`));
|
|
197
|
+
}
|
|
198
|
+
/**
|
|
199
|
+
* FAIL CLOSED (#1058): every type this document references in another package must be a schema
|
|
200
|
+
* of that package's published components document. A package that publishes none is refused —
|
|
201
|
+
* naming the type, its package and the fix — rather than copied in, because silent copying is
|
|
202
|
+
* exactly the duplication this replaces. A document that exists but lacks the schema is stale.
|
|
203
|
+
*/
|
|
204
|
+
refuseUnpublished(schemas, types, upstream, fileName, where) {
|
|
205
|
+
const unpublished = [];
|
|
206
|
+
const stale = [];
|
|
207
|
+
for (const key of Array.from(schemas.externalTypes()).sort()) {
|
|
208
|
+
const type = types.get(key);
|
|
209
|
+
const owner = type.packageName;
|
|
210
|
+
const declared = `${type.name} — declared in ${owner ?? 'no package'} (${type.location})`;
|
|
211
|
+
if (owner === undefined) {
|
|
212
|
+
unpublished.push(`${declared}: its file belongs to no package, so no document can own its schema`);
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const published = upstream.publishedBy(owner);
|
|
216
|
+
if (published === undefined) {
|
|
217
|
+
const reason = upstream.missingFor(owner)?.reason ?? 'it was never located';
|
|
218
|
+
unpublished.push(`${declared}: ${owner} publishes no components document — ${reason}`);
|
|
219
|
+
}
|
|
220
|
+
else if (!published.schemaNames.has(type.name)) {
|
|
221
|
+
stale.push(`${declared}: ${published.documentPath} has no schema '${type.name}'`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
if (unpublished.length > 0) {
|
|
225
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${unpublished.length} type(s) ${fileName} reaches are declared in a package that ` +
|
|
226
|
+
'publishes no components document', where, PUBLISH_COMPONENTS_CURE, unpublished);
|
|
227
|
+
}
|
|
228
|
+
if (stale.length > 0) {
|
|
229
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${stale.length} type(s) ${fileName} references are missing from their package's components document`, where, 'Regenerate the upstream components document with wp-openapi before this one — it is ' +
|
|
230
|
+
'older than its source.', stale);
|
|
231
|
+
}
|
|
102
232
|
}
|
|
103
233
|
/**
|
|
104
234
|
* A webhook is served by the PARTNER, so neither our failure envelope nor the header we stamp on
|
|
@@ -140,9 +270,10 @@ class OpenApiGenerator {
|
|
|
140
270
|
return endpoint.path.replace(/^\/+/, '');
|
|
141
271
|
}
|
|
142
272
|
/**
|
|
143
|
-
* Every named type from every contract, merged
|
|
273
|
+
* Every named type from every contract, merged by MODEL KEY — which carries the declaring
|
|
274
|
+
* package, so two packages' same-named types never meet here (#1058).
|
|
144
275
|
*
|
|
145
|
-
* Two contracts declaring DIFFERENT types under one
|
|
276
|
+
* Two contracts declaring DIFFERENT types under one key is a hard failure, not a first-wins
|
|
146
277
|
* merge: `components.schemas` is keyed by name, so one of the two would be published as the
|
|
147
278
|
* other's shape, and the operation referring to it would be quietly wrong.
|
|
148
279
|
*/
|
|
@@ -156,7 +287,7 @@ class OpenApiGenerator {
|
|
|
156
287
|
const existing = merged.get(name);
|
|
157
288
|
if (existing !== undefined &&
|
|
158
289
|
this.signature(existing) !== this.signature(incoming)) {
|
|
159
|
-
throw new OpenApiGenerationError_1.OpenApiGenerationError(`two different types are both named '${name}'`, `${model.contractName} (${inputs.manifestPath})`, 'Rename one of them. `components.schemas` is keyed by name, so one shape ' +
|
|
290
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`two different types are both named '${incoming.name}'`, `${model.contractName} (${inputs.manifestPath})`, 'Rename one of them. `components.schemas` is keyed by name, so one shape ' +
|
|
160
291
|
'would be published as the other.');
|
|
161
292
|
}
|
|
162
293
|
merged.set(name, incoming);
|
|
@@ -269,6 +400,7 @@ class OpenApiGenerator {
|
|
|
269
400
|
}
|
|
270
401
|
// Rendering the reference is what puts the error body into `components.schemas`, so the
|
|
271
402
|
// published shape is the compiler's answer about that TS type and not a hand-copied one.
|
|
403
|
+
// The model key of a type its own file declares is its bare name (`DocumentedType.keyOf`).
|
|
272
404
|
return schemas.type(api_doc_model_1.TypeRef.ref(errors.type), '#/components/schemas/error');
|
|
273
405
|
}
|
|
274
406
|
/** `components.headers`, one entry per declared response header. */
|
|
@@ -293,12 +425,12 @@ class OpenApiGenerator {
|
|
|
293
425
|
* The guard. An unmapped field is a published partner-facing field with no shape, and there is
|
|
294
426
|
* deliberately no flag to switch this off — the cure is at the contract, by naming the type.
|
|
295
427
|
*/
|
|
296
|
-
|
|
428
|
+
refuseUnmapped(unmapped, fileName, manifestPath) {
|
|
297
429
|
if (unmapped.length === 0) {
|
|
298
430
|
return;
|
|
299
431
|
}
|
|
300
432
|
const pointers = unmapped.map((field) => `${field.pointer} (${field.typeText})`);
|
|
301
|
-
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${unmapped.length} field(s) in ${
|
|
433
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`${unmapped.length} field(s) in ${fileName} have no schema it can state`, manifestPath, 'Give each one a type a document can carry — a named DTO, an array of one, a ' +
|
|
302
434
|
'string-literal union, or Record<string, X>. An untyped field publishes as "anything".', pointers);
|
|
303
435
|
}
|
|
304
436
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenApiGenerator.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/OpenApiGenerator.ts"],"names":[],"mappings":";;;AAAA,4DAOkC;AAClC,mDAA2D;AAC3D,sEAAmE;AAEnE,yDAK4B;AAC5B,2DAAwD;AACxD,2DAA0E;AAC1E,qDAAiE;AACjE,uDAAoD;AAEpD,4FAA4F;AAC5F,MAAM,eAAe,GAAG,OAAO,CAAC;AAEhC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,MAAa,gBAAgB;IACR,QAAQ,GAAG,IAAI,iCAAe,EAAE,CAAC;IAElD;;;;;;;OAOG;IACH,QAAQ,CAAC,MAAwB;QAC7B,MAAM,SAAS,GAAwB,EAAE,CAAC;QAC1C,KAAK,MAAM,SAAS,IAAI,qCAAiB,CAAC,GAAG,EAAE,EAAE,CAAC;YAC9C,MAAM,SAAS,GAAG,MAAM,CAAC,SAAS,CAAC,MAAM,CAAC,CAAC,IAAmB,EAAE,EAAE,CAC9D,SAAS,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CACxC,CAAC;YACF,IAAI,SAAS,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBACzB,SAAS;YACb,CAAC;YACD,SAAS,CAAC,IAAI,CACV,IAAI,oCAAiB,CACjB,SAAS,CAAC,QAAQ,EAClB,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,EAAE,SAAS,CAAC,CAC5C,CACJ,CAAC;QACN,CAAC;QACD,OAAO,IAAI,qCAAkB,CAAC,SAAS,CAAC,CAAC;IAC7C,CAAC;IAED,iFAAiF;IACzE,MAAM,CACV,MAAwB,EACxB,SAAmC,EACnC,SAA4B;QAE5B,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC;QACvC,MAAM,OAAO,GAAG,IAAI,+BAAc,CAAC,KAAK,CAAC,CAAC;QAC1C,M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AAC,WAAW,EAAE,CAAC;IAC9B,CAAC;IAED;;;OAGG;IACK,oBAAoB,CACxB,QAAkC,EAClC,MAAwB,EACxB,SAA4B;QAE5B,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACX,CAAC;QACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CACzB,CAAC,KAAoB,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,QAAQ,GAAG,CACnE,CAAC;QACF,MAAM,IAAI,+CAAsB,CAC5B,GAAG,QAAQ,CAAC,MAAM,gBAAgB,SAAS,CAAC,QAAQ,8BAA8B,EAClF,MAAM,CAAC,YAAY,EACnB,8EAA8E;YAC1E,uFAAuF,EAC3F,QAAQ,CACX,CAAC;IACN,CAAC;CACJ;AApYD,4CAoYC","sourcesContent":["import {\n ApiDocModel,\n DocumentedApiKey,\n DocumentedEndpoint,\n DocumentedField,\n DocumentedType,\n TypeRef,\n} from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\nimport { ServerEntry } from '../manifest/OpenApiManifest';\nimport {\n ContractModel,\n GeneratedDocument,\n GeneratedDocuments,\n GenerationInputs,\n} from './GenerationInputs';\nimport { DocumentSelection } from './DocumentSelection';\nimport { OperationRenderer, ResponseContract } from './OperationRenderer';\nimport { SchemaRenderer, UnmappedField } from './SchemaRenderer';\nimport { SecurityDeriver } from './SecurityDeriver';\n\n/** The OpenAPI version this generator writes. See the class doc for why 3.1 and not 3.0. */\nconst OPENAPI_VERSION = '3.1.0';\n\n/**\n * {@link GenerationInputs} -> one OpenAPI 3.1.0 document per `@ApiType` some contract declares.\n *\n * ## 3.1, because it is what the model can state HONESTLY\n *\n * `type: [T, \"null\"]` instead of a `nullable` keyword; a `description` legal beside a `$ref`; a\n * top-level `webhooks:` block. Each of those is a fact the model holds that 3.0 would have forced\n * this renderer to drop or to lie about. 3.1's schema dialect is also JSON Schema 2020-12, which is\n * what MCP `tools/list` speaks.\n *\n * ## ONE render function, called once per document\n *\n * ```\n * ApiDocModel --> render(selection) --+--> full-private-openapi.json SVC_TO_SVC contracts\n * +--> public-openapi.json EXTERNAL_CUSTOMER contracts, minus hidden methods\n * +--> mcp-openapi.json MCP contracts\n * ```\n *\n * `components.schemas` is built by walking OUTWARD from the operations the selection accepted, so an\n * unselected operation's DTOs are never constructed. See {@link DocumentSelection} for why that\n * asymmetry — a bug emits nothing, rather than shipping an unreleased feature's schemas with only\n * its URL removed — decides the whole design.\n *\n * ## It REFUSES to write an unmapped field\n *\n * An unmapped type renders as an empty schema, which in JSON Schema means \"anything\". Publishing one\n * is a green build handing a partner a field with no shape, so the guard names the JSON pointer of\n * every one and exits non-zero. There is deliberately NO flag to switch it off: the cure is at the\n * contract, by naming the type.\n */\nexport class OpenApiGenerator {\n private readonly security = new SecurityDeriver();\n\n /**\n * ONE document per `@ApiType` some contract declares, and no others.\n *\n * A document nobody asked for is not written empty — it is not written. That is the ONE\n * conditional in the whole pipeline, and it lives here rather than in three places: no contract\n * declaring `MCP` means no `mcp-openapi.json`, with no second \"is it empty?\" rule to keep in step\n * with the first.\n */\n generate(inputs: GenerationInputs): GeneratedDocuments {\n const documents: GeneratedDocument[] = [];\n for (const selection of DocumentSelection.all()) {\n const contracts = inputs.contracts.filter((each: ContractModel) =>\n selection.acceptsContract(each.model),\n );\n if (contracts.length === 0) {\n continue;\n }\n documents.push(\n new GeneratedDocument(\n selection.fileName,\n this.render(inputs, contracts, selection),\n ),\n );\n }\n return new GeneratedDocuments(documents);\n }\n\n /** ONE document, from the operations this selection accepts and nothing else. */\n private render(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): JsonObject {\n const types = this.mergedTypes(inputs);\n const schemas = new SchemaRenderer(types);\n const operations = new OperationRenderer(\n schemas,\n selection.includeMcpExtensions,\n selection.internalNotice,\n );\n const apiKey = this.singleApiKey(inputs, contracts, selection);\n const schemeNames = inputs.manifest.securitySchemeNames;\n const hoisted =\n apiKey !== undefined && this.everyOperationIsCovered(contracts, selection)\n ? this.security.requirement(schemeNames)\n : undefined;\n\n const contract = new ResponseContract(\n this.errorResponses(inputs),\n this.errorSchemaRef(inputs, schemas),\n this.headerRefs(inputs),\n );\n\n const paths = new JsonObject();\n const webhooks = new JsonObject();\n const tags = new JsonObject();\n for (const contractModel of contracts) {\n this.renderContract(\n contractModel,\n selection,\n operations,\n contract,\n this.webhookContract(),\n hoisted === undefined ? this.security.requirement(schemeNames) : undefined,\n paths,\n webhooks,\n tags,\n );\n }\n\n // The schemas are built HERE, after the operations, because building them is what walks a\n // DTO's fields — and an unmapped field can only be found by that walk. A guard that ran\n // before it would see only the top-level request and response refs and miss every one.\n const renderedSchemas = schemas.components().orUndefined();\n this.refuseUnmappedFields(schemas.unmapped(), inputs, selection);\n\n const components = new JsonObject()\n .set('schemas', renderedSchemas)\n .set(\n 'securitySchemes',\n apiKey === undefined\n ? undefined\n : this.security.schemes(apiKey, schemeNames, inputs.manifestPath),\n )\n .set('headers', this.headers(inputs));\n\n return new JsonObject()\n .set('openapi', OPENAPI_VERSION)\n .set('info', this.info(inputs, selection))\n .set('servers', this.servers(inputs))\n .set('tags', this.tagList(tags))\n .set('security', hoisted === undefined ? undefined : hoisted.slice())\n .set('paths', paths)\n .set('webhooks', webhooks.orUndefined())\n .set('components', components.orUndefined());\n }\n\n /**\n * A webhook is served by the PARTNER, so neither our failure envelope nor the header we stamp on\n * our own responses is true of it. Publishing either would document their server, not ours.\n */\n private webhookContract(): ResponseContract {\n return new ResponseContract(new Map<string, string>(), undefined, undefined);\n }\n\n /** One contract's ACCEPTED endpoints, into `paths` or into `webhooks`. */\n private renderContract(\n contractModel: ContractModel,\n selection: DocumentSelection,\n operations: OperationRenderer,\n contract: ResponseContract,\n webhookContract: ResponseContract,\n perOperationSecurity: readonly JsonValue[] | undefined,\n paths: JsonObject,\n webhooks: JsonObject,\n tags: JsonObject,\n ): void {\n const model = contractModel.model;\n const tag = contractModel.entry.tag;\n for (const endpoint of model.endpoints) {\n if (!selection.acceptsEndpoint(endpoint)) {\n continue;\n }\n // A tag is added only by an operation that survived, so a document never advertises a\n // section of its sidebar that turns out to be empty.\n tags.set(tag, this.tagProse(model) ?? '');\n if (contractModel.entry.isWebhook()) {\n webhooks.set(\n this.eventName(endpoint),\n new JsonObject().set(\n 'post',\n operations.webhook(endpoint, model.contractName, tag, webhookContract),\n ),\n );\n continue;\n }\n const url = `${model.basePath}${endpoint.path}`;\n const existing = paths.get(url);\n const item = existing instanceof JsonObject ? existing : new JsonObject();\n item.set(\n endpoint.httpMethod.toLowerCase(),\n operations.operation(\n endpoint,\n model.contractName,\n tag,\n contract,\n endpoint.auth?.apiKey === undefined ? undefined : perOperationSecurity,\n ),\n );\n paths.set(url, item);\n }\n }\n\n /**\n * A webhook is keyed by the EVENT NAME, with the `@ApiPath` base deliberately NOT prepended.\n *\n * There is no url of ours here — the partner hosts the endpoint, at whatever path they choose —\n * so publishing `/our-base/delivered` would document a route that exists nowhere. What we are\n * naming is the event we will send.\n */\n private eventName(endpoint: DocumentedEndpoint): string {\n return endpoint.path.replace(/^\\/+/, '');\n }\n\n /**\n * Every named type from every contract, merged.\n *\n * Two contracts declaring DIFFERENT types under one name is a hard failure, not a first-wins\n * merge: `components.schemas` is keyed by name, so one of the two would be published as the\n * other's shape, and the operation referring to it would be quietly wrong.\n */\n private mergedTypes(inputs: GenerationInputs): ReadonlyMap<string, DocumentedType> {\n const merged = new Map<string, DocumentedType>();\n const sources = inputs.contracts.map((each: ContractModel) => each.model);\n const all = inputs.errorType === undefined ? sources : sources.concat([inputs.errorType]);\n for (const model of all) {\n for (const name of Array.from(model.types.keys())) {\n const incoming = model.types.get(name)!;\n const existing = merged.get(name);\n if (\n existing !== undefined &&\n this.signature(existing) !== this.signature(incoming)\n ) {\n throw new OpenApiGenerationError(\n `two different types are both named '${name}'`,\n `${model.contractName} (${inputs.manifestPath})`,\n 'Rename one of them. `components.schemas` is keyed by name, so one shape ' +\n 'would be published as the other.',\n );\n }\n merged.set(name, incoming);\n }\n }\n return merged;\n }\n\n /** Enough of a type's shape to tell two same-named types apart without comparing prose. */\n private signature(type: DocumentedType): string {\n const fields = type.fields.map((field: DocumentedField) => field.name).join(',');\n return `${fields}|${type.enumValues.join(',')}|${type.unionRefNames.join(',')}`;\n }\n\n /**\n * The ONE api-key regime this document publishes.\n *\n * Two regimes in one document is a hard failure: `securitySchemeNames` is a single ordered list,\n * so there is no honest way to say which regime a given name belongs to, and a document that\n * guessed would publish one regime's header names under the other's scheme keys.\n */\n private singleApiKey(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): DocumentedApiKey | undefined {\n let found: DocumentedApiKey | undefined;\n for (const endpoint of this.selectedEndpoints(contracts, selection)) {\n const apiKey = endpoint.auth?.apiKey;\n if (apiKey === undefined) {\n continue;\n }\n if (found !== undefined && found.regime !== apiKey.regime) {\n throw new OpenApiGenerationError(\n `the ${selection.fileName} document mixes the api-key regimes ` +\n `'${found.regime}' ` +\n `and '${apiKey.regime}'`,\n inputs.manifestPath,\n 'Publish one regime per document — split the manifest, or move the ' +\n \"other regime's contract out of `apis`.\",\n );\n }\n found = apiKey;\n }\n return found;\n }\n\n /**\n * True when EVERY selected operation demands the credential, which is what licenses hoisting the\n * requirement to the document. A document that mixes credentialled and uncredentialled routes\n * stamps it per-operation instead — hoisting there would tell a partner that a public endpoint\n * needs a key.\n *\n * Judged per DOCUMENT, over the operations that document actually contains, because that is the\n * only question the document's own `security` block answers.\n */\n private everyOperationIsCovered(\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): boolean {\n const served = this.selectedEndpoints(contracts, selection);\n return (\n served.length > 0 &&\n served.every((e: DocumentedEndpoint) => e.auth?.apiKey !== undefined)\n );\n }\n\n /**\n * The endpoints this selection accepts that are routes on OUR server. A webhook is somebody\n * else's route, so it never counts toward our security requirement or our regime.\n */\n private selectedEndpoints(\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): readonly DocumentedEndpoint[] {\n const served: DocumentedEndpoint[] = [];\n for (const contract of contracts) {\n if (contract.entry.isWebhook()) {\n continue;\n }\n for (const endpoint of contract.model.endpoints) {\n if (selection.acceptsEndpoint(endpoint)) {\n served.push(endpoint);\n }\n }\n }\n return served;\n }\n\n /** `info`, whose `description` is the ONE piece of prose that differs between the documents. */\n private info(inputs: GenerationInputs, selection: DocumentSelection): JsonObject {\n return new JsonObject()\n .set('title', inputs.manifest.title)\n .set('version', inputs.manifest.version)\n .set('description', selection.description(inputs.description));\n }\n\n private servers(inputs: GenerationInputs): readonly JsonValue[] | undefined {\n if (inputs.manifest.servers.length === 0) {\n return undefined;\n }\n return inputs.manifest.servers.map((server: ServerEntry) =>\n new JsonObject().set('url', server.url).set('description', server.description),\n );\n }\n\n /**\n * `tags[]` in MANIFEST ORDER, because that order IS the published sidebar — one of the two\n * orders in this document that carries meaning and is therefore NOT sorted.\n */\n private tagList(tags: JsonObject): readonly JsonValue[] | undefined {\n const list: JsonValue[] = [];\n for (const name of tags.keys()) {\n const prose = tags.get(name);\n list.push(\n new JsonObject()\n .set('name', name)\n .set('description', prose === '' ? undefined : prose),\n );\n }\n return list.length === 0 ? undefined : list;\n }\n\n private tagProse(model: ApiDocModel): string | undefined {\n return model.description.trim() === '' ? undefined : model.description;\n }\n\n private errorResponses(inputs: GenerationInputs): ReadonlyMap<string, string> {\n const responses = new Map<string, string>();\n for (const response of inputs.manifest.errors?.responses ?? []) {\n responses.set(response.status, response.description);\n }\n return responses;\n }\n\n private errorSchemaRef(\n inputs: GenerationInputs,\n schemas: SchemaRenderer,\n ): JsonObject | undefined {\n const errors = inputs.manifest.errors;\n if (errors === undefined || inputs.errorType === undefined) {\n return undefined;\n }\n // Rendering the reference is what puts the error body into `components.schemas`, so the\n // published shape is the compiler's answer about that TS type and not a hand-copied one.\n return schemas.type(TypeRef.ref(errors.type), '#/components/schemas/error');\n }\n\n /** `components.headers`, one entry per declared response header. */\n private headers(inputs: GenerationInputs): JsonObject | undefined {\n const headers = new JsonObject();\n for (const header of inputs.responseHeaders) {\n headers.set(\n header.headerName,\n new JsonObject()\n .set('description', header.description)\n .set('schema', new JsonObject().set('type', 'string')),\n );\n }\n return headers.orUndefined();\n }\n\n /** The `$ref`s every SUCCESS response carries at those headers. */\n private headerRefs(inputs: GenerationInputs): JsonObject | undefined {\n const refs = new JsonObject();\n for (const header of inputs.responseHeaders) {\n refs.set(\n header.headerName,\n new JsonObject().set('$ref', `#/components/headers/${header.headerName}`),\n );\n }\n return refs.orUndefined();\n }\n\n /**\n * The guard. An unmapped field is a published partner-facing field with no shape, and there is\n * deliberately no flag to switch this off — the cure is at the contract, by naming the type.\n */\n private refuseUnmappedFields(\n unmapped: readonly UnmappedField[],\n inputs: GenerationInputs,\n selection: DocumentSelection,\n ): void {\n if (unmapped.length === 0) {\n return;\n }\n const pointers = unmapped.map(\n (field: UnmappedField) => `${field.pointer} (${field.typeText})`,\n );\n throw new OpenApiGenerationError(\n `${unmapped.length} field(s) in ${selection.fileName} have no schema it can state`,\n inputs.manifestPath,\n 'Give each one a type a document can carry — a named DTO, an array of one, a ' +\n 'string-literal union, or Record<string, X>. An untyped field publishes as \"anything\".',\n pointers,\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"OpenApiGenerator.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/OpenApiGenerator.ts"],"names":[],"mappings":";;;AAAA,4DAQkC;AAClC,mDAA2D;AAC3D,sEAAmE;AAEnE,yDAM4B;AAC5B,2DAAwD;AACxD,2DAA0E;AAC1E,uDAO2B;AAC3B,qDAAiE;AACjE,uDAAoD;AAGpD,uGAAuG;AACvG,MAAM,gBAAgB;IAEL;IACA;IAFb,YACa,QAAoB,EACpB,OAAuB;QADvB,aAAQ,GAAR,QAAQ,CAAY;QACpB,YAAO,GAAP,OAAO,CAAgB;IACjC,C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AAC;QACN,CAAC;QACD,OAAO,OAAO,CAAC,WAAW,EAAE,CAAC;IACjC,CAAC;IAED,mEAAmE;IAC3D,UAAU,CAAC,MAAwB;QACvC,MAAM,IAAI,GAAG,IAAI,uBAAU,EAAE,CAAC;QAC9B,KAAK,MAAM,MAAM,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;YAC1C,IAAI,CAAC,GAAG,CACJ,MAAM,CAAC,UAAU,EACjB,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,wBAAwB,MAAM,CAAC,UAAU,EAAE,CAAC,CAC5E,CAAC;QACN,CAAC;QACD,OAAO,IAAI,CAAC,WAAW,EAAE,CAAC;IAC9B,CAAC;IAED;;;OAGG;IACK,cAAc,CAClB,QAAkC,EAClC,QAAgB,EAChB,YAAoB;QAEpB,IAAI,QAAQ,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YACxB,OAAO;QACX,CAAC;QACD,MAAM,QAAQ,GAAG,QAAQ,CAAC,GAAG,CACzB,CAAC,KAAoB,EAAE,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,KAAK,KAAK,CAAC,QAAQ,GAAG,CACnE,CAAC;QACF,MAAM,IAAI,+CAAsB,CAC5B,GAAG,QAAQ,CAAC,MAAM,gBAAgB,QAAQ,8BAA8B,EACxE,YAAY,EACZ,8EAA8E;YAC1E,uFAAuF,EAC3F,QAAQ,CACX,CAAC;IACN,CAAC;CACJ;AAtjBD,4CAsjBC","sourcesContent":["import {\n ApiDocModel,\n DocumentedApiKey,\n DocumentedEndpoint,\n DocumentedField,\n DocumentedType,\n TypeNameCollision,\n TypeRef,\n} from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\nimport { ServerEntry } from '../manifest/OpenApiManifest';\nimport {\n ComponentsInputs,\n ContractModel,\n GeneratedDocument,\n GeneratedDocuments,\n GenerationInputs,\n} from './GenerationInputs';\nimport { DocumentSelection } from './DocumentSelection';\nimport { OperationRenderer, ResponseContract } from './OperationRenderer';\nimport {\n BundledNames,\n BundledPlacement,\n ComponentsReference,\n DiscoveryPlacement,\n SchemaPlacement,\n SplitPlacement,\n} from './SchemaPlacement';\nimport { SchemaRenderer, UnmappedField } from './SchemaRenderer';\nimport { SecurityDeriver } from './SecurityDeriver';\nimport { UpstreamComponentsIndex } from './UpstreamComponents';\n\n/** One rendered document, and the renderer that built its schemas — what it defined and referenced. */\nclass RenderedDocument {\n constructor(\n readonly document: JsonObject,\n readonly schemas: SchemaRenderer,\n ) {}\n}\n\n/** The suffix of a split document's self-contained sibling: `public-openapi.bundled.json`. */\nconst BUNDLED_SUFFIX = '.bundled';\n\n/** The document a DTO library publishes, without its extension (#1058). */\nconst COMPONENTS_DOCUMENT = 'components.openapi';\n\n/** Every cure for a type reached in a package that publishes no components document. */\nconst PUBLISH_COMPONENTS_CURE =\n 'Move each type into a DTO library that publishes a components document — as a `…Dto` string ' +\n 'enum when it is a string-literal union — or make its package publish one: a \"kind\": ' +\n '\"components\" openapi.manifest.json naming its entry files, rendered by wp-openapi into the ' +\n \"directory the package is packed from. A document references another package's schema; it \" +\n 'never copies one in.';\n\n/** The OpenAPI version this generator writes. See the class doc for why 3.1 and not 3.0. */\nconst OPENAPI_VERSION = '3.1.0';\n\n/**\n * {@link GenerationInputs} -> one OpenAPI 3.1.0 document per `@ApiType` some contract declares.\n *\n * ## 3.1, because it is what the model can state HONESTLY\n *\n * `type: [T, \"null\"]` instead of a `nullable` keyword; a `description` legal beside a `$ref`; a\n * top-level `webhooks:` block. Each of those is a fact the model holds that 3.0 would have forced\n * this renderer to drop or to lie about. 3.1's schema dialect is also JSON Schema 2020-12, which is\n * what MCP `tools/list` speaks.\n *\n * ## ONE render function, called once per document\n *\n * ```\n * ApiDocModel --> render(selection) --+--> full-private-openapi.json SVC_TO_SVC contracts\n * +--> public-openapi.json EXTERNAL_CUSTOMER contracts, minus hidden methods\n * +--> mcp-openapi.json MCP contracts\n * ```\n *\n * `components.schemas` is built by walking OUTWARD from the operations the selection accepted, so an\n * unselected operation's DTOs are never constructed. See {@link DocumentSelection} for why that\n * asymmetry — a bug emits nothing, rather than shipping an unreleased feature's schemas with only\n * its URL removed — decides the whole design.\n *\n * ## It REFUSES to write an unmapped field\n *\n * An unmapped type renders as an empty schema, which in JSON Schema means \"anything\". Publishing one\n * is a green build handing a partner a field with no shape, so the guard names the JSON pointer of\n * every one and exits non-zero. There is deliberately NO flag to switch it off: the cure is at the\n * contract, by naming the type.\n */\nexport class OpenApiGenerator {\n private readonly security = new SecurityDeriver();\n\n /**\n * ONE document per `@ApiType` some contract declares, and no others.\n *\n * A document nobody asked for is not written empty — it is not written. That is the ONE\n * conditional in the whole pipeline, and it lives here rather than in three places: no contract\n * declaring `MCP` means no `mcp-openapi.json`, with no second \"is it empty?\" rule to keep in step\n * with the first.\n */\n generate(inputs: GenerationInputs): GeneratedDocuments {\n const documents: GeneratedDocument[] = [];\n for (const selection of DocumentSelection.all()) {\n const contracts = inputs.contracts.filter((each: ContractModel) =>\n selection.acceptsContract(each.model),\n );\n if (contracts.length === 0) {\n continue;\n }\n if (selection.inlinesEveryPackage) {\n documents.push(\n new GeneratedDocument(\n selection.fileName,\n this.bundled(inputs, contracts, selection),\n ),\n );\n continue;\n }\n this.refuseCollisions(this.collisionsOf(inputs, contracts), inputs.manifestPath);\n const split = this.render(\n inputs,\n contracts,\n selection,\n new SplitPlacement(inputs.homePackage),\n );\n this.refuseUnpublished(\n split.schemas,\n this.mergedTypes(inputs),\n inputs.upstream,\n selection.fileName,\n inputs.manifestPath,\n );\n documents.push(new GeneratedDocument(selection.fileName, split.document));\n documents.push(\n new GeneratedDocument(\n `${selection.fileName}${BUNDLED_SUFFIX}`,\n this.bundled(inputs, contracts, selection),\n ),\n );\n }\n return new GeneratedDocuments(documents);\n }\n\n /**\n * A DTO library's COMPONENTS-ONLY document (#1058): `openapi`, `info`, `x-webpieces-id` and\n * `components.schemas` — every type the library exports and declares, with every OTHER package's\n * type a `$ref` into that package's own components document, so a chain of DTO libraries is a\n * chain of documents of any depth.\n *\n * `info.version` is the PACKAGE version. The package-qualified URI downstream documents reference\n * it by (`@scope/pkg/components.openapi.json`) is stated as `x-webpieces-id`, because OpenAPI 3.1's\n * root object admits no `$id` — a 3.1 validator rejects one — and the document must validate on its\n * own.\n */\n components(inputs: ComponentsInputs): GeneratedDocument {\n const model = inputs.model;\n const where = inputs.manifestPath;\n this.refuseCollisions(model.collisions, where);\n const schemas = new SchemaRenderer(model.types, new SplitPlacement(model.packageName));\n for (const key of model.exported) {\n schemas.define(key);\n }\n const rendered = schemas.components();\n this.refuseUnmapped(schemas.unmapped(), COMPONENTS_DOCUMENT, where);\n this.refuseUnpublished(schemas, model.types, inputs.upstream, COMPONENTS_DOCUMENT, where);\n if (rendered.isEmpty()) {\n throw new OpenApiGenerationError(\n `${model.packageName}'s entries export no type with a schema`,\n where,\n 'Name the entry files that export the library\\'s DTOs and enums — usually \"src/index.ts\".',\n );\n }\n return new GeneratedDocument(\n COMPONENTS_DOCUMENT,\n new JsonObject()\n .set('openapi', OPENAPI_VERSION)\n .set(\n 'info',\n new JsonObject()\n .set('title', inputs.manifest.title)\n .set('version', model.packageVersion),\n )\n .set('x-webpieces-id', ComponentsReference.documentUri(model.packageName))\n .set('components', new JsonObject().set('schemas', rendered)),\n );\n }\n\n /**\n * The SELF-CONTAINED form of a document: every reached schema defined locally, whichever package\n * declares it — the `*.bundled.json` sibling of a split document, and the MCP projection.\n *\n * Two passes, because a schema's NAME depends on which other schemas the document reaches: the\n * first renders with every type under its unique model key just to learn the reached set, and the\n * second renders with the names {@link BundledNames} assigns from it. Rendering is a pure walk of\n * the model, so the second pass reaches exactly what the first did.\n */\n private bundled(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): JsonObject {\n const discovery = this.render(inputs, contracts, selection, new DiscoveryPlacement());\n const names = BundledNames.assign(\n discovery.schemas.reachedTypes(),\n this.mergedTypes(inputs),\n inputs.homePackage,\n );\n return this.render(inputs, contracts, selection, new BundledPlacement(names)).document;\n }\n\n /** ONE document, from the operations this selection accepts and nothing else. */\n private render(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n placement: SchemaPlacement,\n ): RenderedDocument {\n const types = this.mergedTypes(inputs);\n const schemas = new SchemaRenderer(types, placement);\n const operations = new OperationRenderer(\n schemas,\n selection.includeMcpExtensions,\n selection.internalNotice,\n );\n const apiKey = this.singleApiKey(inputs, contracts, selection);\n const schemeNames = inputs.manifest.securitySchemeNames;\n const hoisted =\n apiKey !== undefined && this.everyOperationIsCovered(contracts, selection)\n ? this.security.requirement(schemeNames)\n : undefined;\n\n const contract = new ResponseContract(\n this.errorResponses(inputs),\n this.errorSchemaRef(inputs, schemas),\n this.headerRefs(inputs),\n );\n\n const paths = new JsonObject();\n const webhooks = new JsonObject();\n const tags = new JsonObject();\n for (const contractModel of contracts) {\n this.renderContract(\n contractModel,\n selection,\n operations,\n contract,\n this.webhookContract(),\n hoisted === undefined ? this.security.requirement(schemeNames) : undefined,\n paths,\n webhooks,\n tags,\n );\n }\n\n // The schemas are built HERE, after the operations, because building them is what walks a\n // DTO's fields — and an unmapped field can only be found by that walk. A guard that ran\n // before it would see only the top-level request and response refs and miss every one.\n const renderedSchemas = schemas.components().orUndefined();\n this.refuseUnmapped(schemas.unmapped(), selection.fileName, inputs.manifestPath);\n\n const components = new JsonObject()\n .set('schemas', renderedSchemas)\n .set(\n 'securitySchemes',\n apiKey === undefined\n ? undefined\n : this.security.schemes(apiKey, schemeNames, inputs.manifestPath),\n )\n .set('headers', this.headers(inputs));\n\n const document = new JsonObject()\n .set('openapi', OPENAPI_VERSION)\n .set('info', this.info(inputs, selection))\n .set('servers', this.servers(inputs))\n .set('tags', this.tagList(tags))\n .set('security', hoisted === undefined ? undefined : hoisted.slice())\n .set('paths', paths)\n .set('webhooks', webhooks.orUndefined())\n .set('components', components.orUndefined());\n return new RenderedDocument(document, schemas);\n }\n\n /** Same-named, different declarations in one package, across every contract a document reads. */\n private collisionsOf(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n ): readonly TypeNameCollision[] {\n const models = contracts.map((each: ContractModel) => each.model);\n const all = inputs.errorType === undefined ? models : models.concat([inputs.errorType]);\n return all.flatMap((model: ApiDocModel) => Array.from(model.collisions));\n }\n\n /**\n * Two DIFFERENT declarations of one name in one package. A document defines each of its\n * package's schemas under its bare name, so one of the two would be published as the other's\n * shape. (Two packages' same-named types are not this: each is defined in its own package's\n * document — #1058's `LocalizedDescriptionsDto` case.)\n */\n private refuseCollisions(collisions: readonly TypeNameCollision[], where: string): void {\n if (collisions.length === 0) {\n return;\n }\n throw new OpenApiGenerationError(\n `${collisions.length} name(s) are declared twice in one package, so one document would ` +\n 'publish two different types under one name',\n where,\n 'Rename one declaration of each. Within one package a schema name is one type.',\n collisions.map(\n (each: TypeNameCollision) =>\n `${each.name} (${each.packageName ?? 'no package'}): ${each.firstLocation} and ${each.secondLocation}`,\n ),\n );\n }\n\n /**\n * FAIL CLOSED (#1058): every type this document references in another package must be a schema\n * of that package's published components document. A package that publishes none is refused —\n * naming the type, its package and the fix — rather than copied in, because silent copying is\n * exactly the duplication this replaces. A document that exists but lacks the schema is stale.\n */\n private refuseUnpublished(\n schemas: SchemaRenderer,\n types: ReadonlyMap<string, DocumentedType>,\n upstream: UpstreamComponentsIndex,\n fileName: string,\n where: string,\n ): void {\n const unpublished: string[] = [];\n const stale: string[] = [];\n for (const key of Array.from(schemas.externalTypes()).sort()) {\n const type = types.get(key)!;\n const owner = type.packageName;\n const declared = `${type.name} — declared in ${owner ?? 'no package'} (${type.location})`;\n if (owner === undefined) {\n unpublished.push(`${declared}: its file belongs to no package, so no document can own its schema`);\n continue;\n }\n const published = upstream.publishedBy(owner);\n if (published === undefined) {\n const reason = upstream.missingFor(owner)?.reason ?? 'it was never located';\n unpublished.push(`${declared}: ${owner} publishes no components document — ${reason}`);\n } else if (!published.schemaNames.has(type.name)) {\n stale.push(`${declared}: ${published.documentPath} has no schema '${type.name}'`);\n }\n }\n if (unpublished.length > 0) {\n throw new OpenApiGenerationError(\n `${unpublished.length} type(s) ${fileName} reaches are declared in a package that ` +\n 'publishes no components document',\n where,\n PUBLISH_COMPONENTS_CURE,\n unpublished,\n );\n }\n if (stale.length > 0) {\n throw new OpenApiGenerationError(\n `${stale.length} type(s) ${fileName} references are missing from their package's components document`,\n where,\n 'Regenerate the upstream components document with wp-openapi before this one — it is ' +\n 'older than its source.',\n stale,\n );\n }\n }\n\n /**\n * A webhook is served by the PARTNER, so neither our failure envelope nor the header we stamp on\n * our own responses is true of it. Publishing either would document their server, not ours.\n */\n private webhookContract(): ResponseContract {\n return new ResponseContract(new Map<string, string>(), undefined, undefined);\n }\n\n /** One contract's ACCEPTED endpoints, into `paths` or into `webhooks`. */\n private renderContract(\n contractModel: ContractModel,\n selection: DocumentSelection,\n operations: OperationRenderer,\n contract: ResponseContract,\n webhookContract: ResponseContract,\n perOperationSecurity: readonly JsonValue[] | undefined,\n paths: JsonObject,\n webhooks: JsonObject,\n tags: JsonObject,\n ): void {\n const model = contractModel.model;\n const tag = contractModel.entry.tag;\n for (const endpoint of model.endpoints) {\n if (!selection.acceptsEndpoint(endpoint)) {\n continue;\n }\n // A tag is added only by an operation that survived, so a document never advertises a\n // section of its sidebar that turns out to be empty.\n tags.set(tag, this.tagProse(model) ?? '');\n if (contractModel.entry.isWebhook()) {\n webhooks.set(\n this.eventName(endpoint),\n new JsonObject().set(\n 'post',\n operations.webhook(endpoint, model.contractName, tag, webhookContract),\n ),\n );\n continue;\n }\n const url = `${model.basePath}${endpoint.path}`;\n const existing = paths.get(url);\n const item = existing instanceof JsonObject ? existing : new JsonObject();\n item.set(\n endpoint.httpMethod.toLowerCase(),\n operations.operation(\n endpoint,\n model.contractName,\n tag,\n contract,\n endpoint.auth?.apiKey === undefined ? undefined : perOperationSecurity,\n ),\n );\n paths.set(url, item);\n }\n }\n\n /**\n * A webhook is keyed by the EVENT NAME, with the `@ApiPath` base deliberately NOT prepended.\n *\n * There is no url of ours here — the partner hosts the endpoint, at whatever path they choose —\n * so publishing `/our-base/delivered` would document a route that exists nowhere. What we are\n * naming is the event we will send.\n */\n private eventName(endpoint: DocumentedEndpoint): string {\n return endpoint.path.replace(/^\\/+/, '');\n }\n\n /**\n * Every named type from every contract, merged by MODEL KEY — which carries the declaring\n * package, so two packages' same-named types never meet here (#1058).\n *\n * Two contracts declaring DIFFERENT types under one key is a hard failure, not a first-wins\n * merge: `components.schemas` is keyed by name, so one of the two would be published as the\n * other's shape, and the operation referring to it would be quietly wrong.\n */\n private mergedTypes(inputs: GenerationInputs): ReadonlyMap<string, DocumentedType> {\n const merged = new Map<string, DocumentedType>();\n const sources = inputs.contracts.map((each: ContractModel) => each.model);\n const all = inputs.errorType === undefined ? sources : sources.concat([inputs.errorType]);\n for (const model of all) {\n for (const name of Array.from(model.types.keys())) {\n const incoming = model.types.get(name)!;\n const existing = merged.get(name);\n if (\n existing !== undefined &&\n this.signature(existing) !== this.signature(incoming)\n ) {\n throw new OpenApiGenerationError(\n `two different types are both named '${incoming.name}'`,\n `${model.contractName} (${inputs.manifestPath})`,\n 'Rename one of them. `components.schemas` is keyed by name, so one shape ' +\n 'would be published as the other.',\n );\n }\n merged.set(name, incoming);\n }\n }\n return merged;\n }\n\n /** Enough of a type's shape to tell two same-named types apart without comparing prose. */\n private signature(type: DocumentedType): string {\n const fields = type.fields.map((field: DocumentedField) => field.name).join(',');\n return `${fields}|${type.enumValues.join(',')}|${type.unionRefNames.join(',')}`;\n }\n\n /**\n * The ONE api-key regime this document publishes.\n *\n * Two regimes in one document is a hard failure: `securitySchemeNames` is a single ordered list,\n * so there is no honest way to say which regime a given name belongs to, and a document that\n * guessed would publish one regime's header names under the other's scheme keys.\n */\n private singleApiKey(\n inputs: GenerationInputs,\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): DocumentedApiKey | undefined {\n let found: DocumentedApiKey | undefined;\n for (const endpoint of this.selectedEndpoints(contracts, selection)) {\n const apiKey = endpoint.auth?.apiKey;\n if (apiKey === undefined) {\n continue;\n }\n if (found !== undefined && found.regime !== apiKey.regime) {\n throw new OpenApiGenerationError(\n `the ${selection.fileName} document mixes the api-key regimes ` +\n `'${found.regime}' ` +\n `and '${apiKey.regime}'`,\n inputs.manifestPath,\n 'Publish one regime per document — split the manifest, or move the ' +\n \"other regime's contract out of `apis`.\",\n );\n }\n found = apiKey;\n }\n return found;\n }\n\n /**\n * True when EVERY selected operation demands the credential, which is what licenses hoisting the\n * requirement to the document. A document that mixes credentialled and uncredentialled routes\n * stamps it per-operation instead — hoisting there would tell a partner that a public endpoint\n * needs a key.\n *\n * Judged per DOCUMENT, over the operations that document actually contains, because that is the\n * only question the document's own `security` block answers.\n */\n private everyOperationIsCovered(\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): boolean {\n const served = this.selectedEndpoints(contracts, selection);\n return (\n served.length > 0 &&\n served.every((e: DocumentedEndpoint) => e.auth?.apiKey !== undefined)\n );\n }\n\n /**\n * The endpoints this selection accepts that are routes on OUR server. A webhook is somebody\n * else's route, so it never counts toward our security requirement or our regime.\n */\n private selectedEndpoints(\n contracts: readonly ContractModel[],\n selection: DocumentSelection,\n ): readonly DocumentedEndpoint[] {\n const served: DocumentedEndpoint[] = [];\n for (const contract of contracts) {\n if (contract.entry.isWebhook()) {\n continue;\n }\n for (const endpoint of contract.model.endpoints) {\n if (selection.acceptsEndpoint(endpoint)) {\n served.push(endpoint);\n }\n }\n }\n return served;\n }\n\n /** `info`, whose `description` is the ONE piece of prose that differs between the documents. */\n private info(inputs: GenerationInputs, selection: DocumentSelection): JsonObject {\n return new JsonObject()\n .set('title', inputs.manifest.title)\n .set('version', inputs.manifest.version)\n .set('description', selection.description(inputs.description));\n }\n\n private servers(inputs: GenerationInputs): readonly JsonValue[] | undefined {\n if (inputs.manifest.servers.length === 0) {\n return undefined;\n }\n return inputs.manifest.servers.map((server: ServerEntry) =>\n new JsonObject().set('url', server.url).set('description', server.description),\n );\n }\n\n /**\n * `tags[]` in MANIFEST ORDER, because that order IS the published sidebar — one of the two\n * orders in this document that carries meaning and is therefore NOT sorted.\n */\n private tagList(tags: JsonObject): readonly JsonValue[] | undefined {\n const list: JsonValue[] = [];\n for (const name of tags.keys()) {\n const prose = tags.get(name);\n list.push(\n new JsonObject()\n .set('name', name)\n .set('description', prose === '' ? undefined : prose),\n );\n }\n return list.length === 0 ? undefined : list;\n }\n\n private tagProse(model: ApiDocModel): string | undefined {\n return model.description.trim() === '' ? undefined : model.description;\n }\n\n private errorResponses(inputs: GenerationInputs): ReadonlyMap<string, string> {\n const responses = new Map<string, string>();\n for (const response of inputs.manifest.errors?.responses ?? []) {\n responses.set(response.status, response.description);\n }\n return responses;\n }\n\n private errorSchemaRef(\n inputs: GenerationInputs,\n schemas: SchemaRenderer,\n ): JsonObject | undefined {\n const errors = inputs.manifest.errors;\n if (errors === undefined || inputs.errorType === undefined) {\n return undefined;\n }\n // Rendering the reference is what puts the error body into `components.schemas`, so the\n // published shape is the compiler's answer about that TS type and not a hand-copied one.\n // The model key of a type its own file declares is its bare name (`DocumentedType.keyOf`).\n return schemas.type(TypeRef.ref(errors.type), '#/components/schemas/error');\n }\n\n /** `components.headers`, one entry per declared response header. */\n private headers(inputs: GenerationInputs): JsonObject | undefined {\n const headers = new JsonObject();\n for (const header of inputs.responseHeaders) {\n headers.set(\n header.headerName,\n new JsonObject()\n .set('description', header.description)\n .set('schema', new JsonObject().set('type', 'string')),\n );\n }\n return headers.orUndefined();\n }\n\n /** The `$ref`s every SUCCESS response carries at those headers. */\n private headerRefs(inputs: GenerationInputs): JsonObject | undefined {\n const refs = new JsonObject();\n for (const header of inputs.responseHeaders) {\n refs.set(\n header.headerName,\n new JsonObject().set('$ref', `#/components/headers/${header.headerName}`),\n );\n }\n return refs.orUndefined();\n }\n\n /**\n * The guard. An unmapped field is a published partner-facing field with no shape, and there is\n * deliberately no flag to switch this off — the cure is at the contract, by naming the type.\n */\n private refuseUnmapped(\n unmapped: readonly UnmappedField[],\n fileName: string,\n manifestPath: string,\n ): void {\n if (unmapped.length === 0) {\n return;\n }\n const pointers = unmapped.map(\n (field: UnmappedField) => `${field.pointer} (${field.typeText})`,\n );\n throw new OpenApiGenerationError(\n `${unmapped.length} field(s) in ${fileName} have no schema it can state`,\n manifestPath,\n 'Give each one a type a document can carry — a named DTO, an array of one, a ' +\n 'string-literal union, or Record<string, X>. An untyped field publishes as \"anything\".',\n pointers,\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { DocumentedType } from '@webpieces/api-doc-model';
|
|
2
|
+
/**
|
|
3
|
+
* WHERE a named type's schema lives, from the point of view of ONE document being rendered (#1058).
|
|
4
|
+
*
|
|
5
|
+
* The model keys every type by its declaring package (`DocumentedType.keyOf`); a placement turns that
|
|
6
|
+
* into the two facts a renderer needs — whether the schema is defined in THIS document's
|
|
7
|
+
* `components.schemas` (and under what name), or referenced in another package's document — so the
|
|
8
|
+
* three output forms are one renderer with three placements, not three renderers that could drift:
|
|
9
|
+
*
|
|
10
|
+
* | placement | used for | other packages' types |
|
|
11
|
+
* |---|---|---|
|
|
12
|
+
* | {@link SplitPlacement} | `full-private-openapi.json`, `public-openapi.json`, `components.openapi.json` | `$ref` into `<package>/components.openapi.json` |
|
|
13
|
+
* | {@link BundledPlacement} | `*.bundled.json`, `mcp-openapi.json` | defined locally, renamed only on a name clash |
|
|
14
|
+
* | {@link DiscoveryPlacement} | the first pass of a bundled render | defined locally under their unique key |
|
|
15
|
+
*/
|
|
16
|
+
export interface SchemaPlacement {
|
|
17
|
+
/** True when `type` is defined in this document's own `components.schemas`. */
|
|
18
|
+
isLocal(key: string, type: DocumentedType): boolean;
|
|
19
|
+
/** The `components.schemas` key a LOCAL type is defined under. */
|
|
20
|
+
localName(key: string, type: DocumentedType): string;
|
|
21
|
+
/** The `$ref` value a reference to `type` is written as. */
|
|
22
|
+
pointer(key: string, type: DocumentedType): string;
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The package-qualified reference into a package's components document — decision 3 of #1058:
|
|
26
|
+
* `@scope/pkg/components.openapi.json#/components/schemas/X`, resolved by the same package lookup
|
|
27
|
+
* `McpToolCatalog.fromPackages` uses rather than by a `dist/` path.
|
|
28
|
+
*/
|
|
29
|
+
export declare class ComponentsReference {
|
|
30
|
+
static documentUri(packageName: string): string;
|
|
31
|
+
static to(packageName: string, schemaName: string): string;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* The SPLIT form: a schema is defined in the document of the package that declares it, and every
|
|
35
|
+
* other package's schema is a `$ref` into that package's `components.openapi.json`. One owner per
|
|
36
|
+
* schema — which is what removes both the duplicate copies and the name collisions of a flat namespace.
|
|
37
|
+
*/
|
|
38
|
+
export declare class SplitPlacement implements SchemaPlacement {
|
|
39
|
+
/** The package this document is published by. */
|
|
40
|
+
private readonly homePackage;
|
|
41
|
+
constructor(
|
|
42
|
+
/** The package this document is published by. */
|
|
43
|
+
homePackage: string | undefined);
|
|
44
|
+
isLocal(_key: string, type: DocumentedType): boolean;
|
|
45
|
+
localName(_key: string, type: DocumentedType): string;
|
|
46
|
+
pointer(key: string, type: DocumentedType): string;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The BUNDLED form: every schema is defined locally, so the document has no external reference and
|
|
50
|
+
* validates on its own. Names are assigned by {@link BundledNames}.
|
|
51
|
+
*/
|
|
52
|
+
export declare class BundledPlacement implements SchemaPlacement {
|
|
53
|
+
private readonly names;
|
|
54
|
+
constructor(names: ReadonlyMap<string, string>);
|
|
55
|
+
isLocal(): boolean;
|
|
56
|
+
localName(key: string, type: DocumentedType): string;
|
|
57
|
+
pointer(key: string, type: DocumentedType): string;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* The first pass of a bundled render, run only to learn WHICH types the document reaches: every type
|
|
61
|
+
* is local under its unique model key, so nothing can collide before the names are chosen.
|
|
62
|
+
*/
|
|
63
|
+
export declare class DiscoveryPlacement implements SchemaPlacement {
|
|
64
|
+
isLocal(): boolean;
|
|
65
|
+
localName(key: string): string;
|
|
66
|
+
pointer(key: string): string;
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* The `components.schemas` names of a BUNDLED document.
|
|
70
|
+
*
|
|
71
|
+
* Every type keeps its own name unless two packages' types of ONE name are both reached — the
|
|
72
|
+
* `LocalizedDescriptionsDto` case of #1058, which the split form keeps apart by keeping them in two
|
|
73
|
+
* documents. A bundled document has one namespace, so then the home package's type keeps the bare
|
|
74
|
+
* name and every other package's is qualified by its package (`myorg.lang-api-dtos.X`, in the
|
|
75
|
+
* characters a components key may hold). Renaming only on a clash keeps every ordinary bundled
|
|
76
|
+
* document identical to the split one wherever the split one defines the schema itself.
|
|
77
|
+
*/
|
|
78
|
+
export declare class BundledNames {
|
|
79
|
+
static assign(reached: Iterable<string>, types: ReadonlyMap<string, DocumentedType>, homePackage: string | undefined): ReadonlyMap<string, string>;
|
|
80
|
+
/** `@myorg/lang-api-dtos` + `X` → `myorg.lang-api-dtos.X` — `^[a-zA-Z0-9.\-_]+$`, as 3.1 requires. */
|
|
81
|
+
private static qualified;
|
|
82
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.BundledNames = exports.DiscoveryPlacement = exports.BundledPlacement = exports.SplitPlacement = exports.ComponentsReference = void 0;
|
|
4
|
+
const core_util_1 = require("@webpieces/core-util");
|
|
5
|
+
const LOCAL_POINTER = '#/components/schemas/';
|
|
6
|
+
/**
|
|
7
|
+
* The package-qualified reference into a package's components document — decision 3 of #1058:
|
|
8
|
+
* `@scope/pkg/components.openapi.json#/components/schemas/X`, resolved by the same package lookup
|
|
9
|
+
* `McpToolCatalog.fromPackages` uses rather than by a `dist/` path.
|
|
10
|
+
*/
|
|
11
|
+
class ComponentsReference {
|
|
12
|
+
// webpieces-disable no-function-outside-class -- static helper on the class that owns the URI form
|
|
13
|
+
static documentUri(packageName) {
|
|
14
|
+
return `${packageName}/${core_util_1.GeneratedApiDocsLayout.COMPONENTS_FILE}`;
|
|
15
|
+
}
|
|
16
|
+
// webpieces-disable no-function-outside-class -- static helper on the class that owns the URI form
|
|
17
|
+
static to(packageName, schemaName) {
|
|
18
|
+
return `${ComponentsReference.documentUri(packageName)}#/components/schemas/${schemaName}`;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.ComponentsReference = ComponentsReference;
|
|
22
|
+
/**
|
|
23
|
+
* The SPLIT form: a schema is defined in the document of the package that declares it, and every
|
|
24
|
+
* other package's schema is a `$ref` into that package's `components.openapi.json`. One owner per
|
|
25
|
+
* schema — which is what removes both the duplicate copies and the name collisions of a flat namespace.
|
|
26
|
+
*/
|
|
27
|
+
class SplitPlacement {
|
|
28
|
+
homePackage;
|
|
29
|
+
constructor(
|
|
30
|
+
/** The package this document is published by. */
|
|
31
|
+
homePackage) {
|
|
32
|
+
this.homePackage = homePackage;
|
|
33
|
+
}
|
|
34
|
+
isLocal(_key, type) {
|
|
35
|
+
return type.packageName === this.homePackage;
|
|
36
|
+
}
|
|
37
|
+
localName(_key, type) {
|
|
38
|
+
return type.name;
|
|
39
|
+
}
|
|
40
|
+
pointer(key, type) {
|
|
41
|
+
if (this.isLocal(key, type)) {
|
|
42
|
+
return `${LOCAL_POINTER}${type.name}`;
|
|
43
|
+
}
|
|
44
|
+
return ComponentsReference.to(type.packageName ?? '<no package>', type.name);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
exports.SplitPlacement = SplitPlacement;
|
|
48
|
+
/**
|
|
49
|
+
* The BUNDLED form: every schema is defined locally, so the document has no external reference and
|
|
50
|
+
* validates on its own. Names are assigned by {@link BundledNames}.
|
|
51
|
+
*/
|
|
52
|
+
class BundledPlacement {
|
|
53
|
+
names;
|
|
54
|
+
constructor(names) {
|
|
55
|
+
this.names = names;
|
|
56
|
+
}
|
|
57
|
+
isLocal() {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
localName(key, type) {
|
|
61
|
+
return this.names.get(key) ?? type.name;
|
|
62
|
+
}
|
|
63
|
+
pointer(key, type) {
|
|
64
|
+
return `${LOCAL_POINTER}${this.localName(key, type)}`;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
exports.BundledPlacement = BundledPlacement;
|
|
68
|
+
/**
|
|
69
|
+
* The first pass of a bundled render, run only to learn WHICH types the document reaches: every type
|
|
70
|
+
* is local under its unique model key, so nothing can collide before the names are chosen.
|
|
71
|
+
*/
|
|
72
|
+
class DiscoveryPlacement {
|
|
73
|
+
isLocal() {
|
|
74
|
+
return true;
|
|
75
|
+
}
|
|
76
|
+
localName(key) {
|
|
77
|
+
return key;
|
|
78
|
+
}
|
|
79
|
+
pointer(key) {
|
|
80
|
+
return `${LOCAL_POINTER}${key}`;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
exports.DiscoveryPlacement = DiscoveryPlacement;
|
|
84
|
+
/**
|
|
85
|
+
* The `components.schemas` names of a BUNDLED document.
|
|
86
|
+
*
|
|
87
|
+
* Every type keeps its own name unless two packages' types of ONE name are both reached — the
|
|
88
|
+
* `LocalizedDescriptionsDto` case of #1058, which the split form keeps apart by keeping them in two
|
|
89
|
+
* documents. A bundled document has one namespace, so then the home package's type keeps the bare
|
|
90
|
+
* name and every other package's is qualified by its package (`myorg.lang-api-dtos.X`, in the
|
|
91
|
+
* characters a components key may hold). Renaming only on a clash keeps every ordinary bundled
|
|
92
|
+
* document identical to the split one wherever the split one defines the schema itself.
|
|
93
|
+
*/
|
|
94
|
+
class BundledNames {
|
|
95
|
+
// webpieces-disable no-function-outside-class -- static factory of this class
|
|
96
|
+
static assign(reached, types, homePackage) {
|
|
97
|
+
const byName = new Map();
|
|
98
|
+
for (const key of reached) {
|
|
99
|
+
const type = types.get(key);
|
|
100
|
+
if (type === undefined) {
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
const group = byName.get(type.name) ?? [];
|
|
104
|
+
group.push(key);
|
|
105
|
+
byName.set(type.name, group);
|
|
106
|
+
}
|
|
107
|
+
const names = new Map();
|
|
108
|
+
for (const name of byName.keys()) {
|
|
109
|
+
const keys = byName.get(name);
|
|
110
|
+
for (const key of keys) {
|
|
111
|
+
const type = types.get(key);
|
|
112
|
+
const keepsBareName = keys.length === 1 || type.packageName === homePackage;
|
|
113
|
+
names.set(key, keepsBareName ? name : BundledNames.qualified(type.packageName, name));
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return names;
|
|
117
|
+
}
|
|
118
|
+
/** `@myorg/lang-api-dtos` + `X` → `myorg.lang-api-dtos.X` — `^[a-zA-Z0-9.\-_]+$`, as 3.1 requires. */
|
|
119
|
+
// webpieces-disable no-function-outside-class -- private static helper of this class
|
|
120
|
+
static qualified(packageName, name) {
|
|
121
|
+
const owner = (packageName ?? 'no-package').replace(/^@/, '').replace(/\//g, '.');
|
|
122
|
+
return `${owner}.${name}`.replace(/[^A-Za-z0-9.\-_]/g, '_');
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
exports.BundledNames = BundledNames;
|
|
126
|
+
//# sourceMappingURL=SchemaPlacement.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"SchemaPlacement.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/SchemaPlacement.ts"],"names":[],"mappings":";;;AACA,oDAA8D;AAyB9D,MAAM,aAAa,GAAG,uBAAuB,CAAC;AAE9C;;;;GAIG;AACH,MAAa,mBAAmB;IAC5B,mGAAmG;IACnG,MAAM,CAAC,WAAW,CAAC,WAAmB;QAClC,OAAO,GAAG,WAAW,IAAI,kCAAsB,CAAC,eAAe,EAAE,CAAC;IACtE,CAAC;IAED,mGAAmG;IACnG,MAAM,CAAC,EAAE,CAAC,WAAmB,EAAE,UAAkB;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,CAAC,IAAI,CAAC,CAAC,CAAC,YAAY,CAAC,SAAS,CAAC,IAAI,CAAC,WAAW,EAAE,IAAI,CAAC,CACxE,CAAC;YACN,CAAC;QACL,CAAC;QACD,OAAO,KAAK,CAAC;IACjB,CAAC;IAED,sGAAsG;IACtG,qFAAqF;IAC7E,MAAM,CAAC,SAAS,CAAC,WAA+B,EAAE,IAAY;QAClE,MAAM,KAAK,GAAG,CAAC,WAAW,IAAI,YAAY,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;QAClF,OAAO,GAAG,KAAK,IAAI,IAAI,EAAE,CAAC,OAAO,CAAC,mBAAmB,EAAE,GAAG,CAAC,CAAC;IAChE,CAAC;CACJ;AAtCD,oCAsCC","sourcesContent":["import { DocumentedType } from '@webpieces/api-doc-model';\nimport { GeneratedApiDocsLayout } from '@webpieces/core-util';\n\n/**\n * WHERE a named type's schema lives, from the point of view of ONE document being rendered (#1058).\n *\n * The model keys every type by its declaring package (`DocumentedType.keyOf`); a placement turns that\n * into the two facts a renderer needs — whether the schema is defined in THIS document's\n * `components.schemas` (and under what name), or referenced in another package's document — so the\n * three output forms are one renderer with three placements, not three renderers that could drift:\n *\n * | placement | used for | other packages' types |\n * |---|---|---|\n * | {@link SplitPlacement} | `full-private-openapi.json`, `public-openapi.json`, `components.openapi.json` | `$ref` into `<package>/components.openapi.json` |\n * | {@link BundledPlacement} | `*.bundled.json`, `mcp-openapi.json` | defined locally, renamed only on a name clash |\n * | {@link DiscoveryPlacement} | the first pass of a bundled render | defined locally under their unique key |\n */\nexport interface SchemaPlacement {\n /** True when `type` is defined in this document's own `components.schemas`. */\n isLocal(key: string, type: DocumentedType): boolean;\n /** The `components.schemas` key a LOCAL type is defined under. */\n localName(key: string, type: DocumentedType): string;\n /** The `$ref` value a reference to `type` is written as. */\n pointer(key: string, type: DocumentedType): string;\n}\n\nconst LOCAL_POINTER = '#/components/schemas/';\n\n/**\n * The package-qualified reference into a package's components document — decision 3 of #1058:\n * `@scope/pkg/components.openapi.json#/components/schemas/X`, resolved by the same package lookup\n * `McpToolCatalog.fromPackages` uses rather than by a `dist/` path.\n */\nexport class ComponentsReference {\n // webpieces-disable no-function-outside-class -- static helper on the class that owns the URI form\n static documentUri(packageName: string): string {\n return `${packageName}/${GeneratedApiDocsLayout.COMPONENTS_FILE}`;\n }\n\n // webpieces-disable no-function-outside-class -- static helper on the class that owns the URI form\n static to(packageName: string, schemaName: string): string {\n return `${ComponentsReference.documentUri(packageName)}#/components/schemas/${schemaName}`;\n }\n}\n\n/**\n * The SPLIT form: a schema is defined in the document of the package that declares it, and every\n * other package's schema is a `$ref` into that package's `components.openapi.json`. One owner per\n * schema — which is what removes both the duplicate copies and the name collisions of a flat namespace.\n */\nexport class SplitPlacement implements SchemaPlacement {\n constructor(\n /** The package this document is published by. */\n private readonly homePackage: string | undefined,\n ) {}\n\n isLocal(_key: string, type: DocumentedType): boolean {\n return type.packageName === this.homePackage;\n }\n\n localName(_key: string, type: DocumentedType): string {\n return type.name;\n }\n\n pointer(key: string, type: DocumentedType): string {\n if (this.isLocal(key, type)) {\n return `${LOCAL_POINTER}${type.name}`;\n }\n return ComponentsReference.to(type.packageName ?? '<no package>', type.name);\n }\n}\n\n/**\n * The BUNDLED form: every schema is defined locally, so the document has no external reference and\n * validates on its own. Names are assigned by {@link BundledNames}.\n */\nexport class BundledPlacement implements SchemaPlacement {\n constructor(private readonly names: ReadonlyMap<string, string>) {}\n\n isLocal(): boolean {\n return true;\n }\n\n localName(key: string, type: DocumentedType): string {\n return this.names.get(key) ?? type.name;\n }\n\n pointer(key: string, type: DocumentedType): string {\n return `${LOCAL_POINTER}${this.localName(key, type)}`;\n }\n}\n\n/**\n * The first pass of a bundled render, run only to learn WHICH types the document reaches: every type\n * is local under its unique model key, so nothing can collide before the names are chosen.\n */\nexport class DiscoveryPlacement implements SchemaPlacement {\n isLocal(): boolean {\n return true;\n }\n\n localName(key: string): string {\n return key;\n }\n\n pointer(key: string): string {\n return `${LOCAL_POINTER}${key}`;\n }\n}\n\n/**\n * The `components.schemas` names of a BUNDLED document.\n *\n * Every type keeps its own name unless two packages' types of ONE name are both reached — the\n * `LocalizedDescriptionsDto` case of #1058, which the split form keeps apart by keeping them in two\n * documents. A bundled document has one namespace, so then the home package's type keeps the bare\n * name and every other package's is qualified by its package (`myorg.lang-api-dtos.X`, in the\n * characters a components key may hold). Renaming only on a clash keeps every ordinary bundled\n * document identical to the split one wherever the split one defines the schema itself.\n */\nexport class BundledNames {\n // webpieces-disable no-function-outside-class -- static factory of this class\n static assign(\n reached: Iterable<string>,\n types: ReadonlyMap<string, DocumentedType>,\n homePackage: string | undefined,\n ): ReadonlyMap<string, string> {\n const byName = new Map<string, string[]>();\n for (const key of reached) {\n const type = types.get(key);\n if (type === undefined) {\n continue;\n }\n const group = byName.get(type.name) ?? [];\n group.push(key);\n byName.set(type.name, group);\n }\n const names = new Map<string, string>();\n for (const name of byName.keys()) {\n const keys = byName.get(name)!;\n for (const key of keys) {\n const type = types.get(key)!;\n const keepsBareName = keys.length === 1 || type.packageName === homePackage;\n names.set(\n key,\n keepsBareName ? name : BundledNames.qualified(type.packageName, name),\n );\n }\n }\n return names;\n }\n\n /** `@myorg/lang-api-dtos` + `X` → `myorg.lang-api-dtos.X` — `^[a-zA-Z0-9.\\-_]+$`, as 3.1 requires. */\n // webpieces-disable no-function-outside-class -- private static helper of this class\n private static qualified(packageName: string | undefined, name: string): string {\n const owner = (packageName ?? 'no-package').replace(/^@/, '').replace(/\\//g, '.');\n return `${owner}.${name}`.replace(/[^A-Za-z0-9.\\-_]/g, '_');\n }\n}\n"]}
|