@webpieces/openapi-generator 0.4.921 → 0.4.923
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 +46 -5
- package/package.json +3 -3
- package/src/generate/GenerationInputs.d.ts +7 -3
- package/src/generate/GenerationInputs.js +7 -3
- package/src/generate/GenerationInputs.js.map +1 -1
- package/src/generate/OpenApiGenerator.d.ts +9 -0
- package/src/generate/OpenApiGenerator.js +41 -7
- package/src/generate/OpenApiGenerator.js.map +1 -1
- package/src/generate/OperationRenderer.d.ts +27 -7
- package/src/generate/OperationRenderer.js +34 -7
- package/src/generate/OperationRenderer.js.map +1 -1
- package/src/generate/SecurityDeriver.js +5 -3
- package/src/generate/SecurityDeriver.js.map +1 -1
- package/src/index.d.ts +1 -2
- package/src/index.js +2 -3
- package/src/index.js.map +1 -1
- package/src/load/InputsLoader.d.ts +0 -1
- package/src/load/InputsLoader.js +9 -3
- package/src/load/InputsLoader.js.map +1 -1
- package/src/manifest/JsonReader.d.ts +2 -0
- package/src/manifest/JsonReader.js +12 -0
- package/src/manifest/JsonReader.js.map +1 -1
- package/src/manifest/ManifestLoader.d.ts +5 -0
- package/src/manifest/ManifestLoader.js +39 -5
- package/src/manifest/ManifestLoader.js.map +1 -1
- package/src/manifest/OpenApiManifest.d.ts +56 -10
- package/src/manifest/OpenApiManifest.js +50 -11
- package/src/manifest/OpenApiManifest.js.map +1 -1
- package/src/load/ExportedConstantFolder.d.ts +0 -21
- package/src/load/ExportedConstantFolder.js +0 -57
- package/src/load/ExportedConstantFolder.js.map +0 -1
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.OperationRenderer = exports.ResponseContract = void 0;
|
|
4
4
|
const core_util_1 = require("@webpieces/core-util");
|
|
5
5
|
const JsonObject_1 = require("../json/JsonObject");
|
|
6
|
+
const OpenApiManifest_1 = require("../manifest/OpenApiManifest");
|
|
6
7
|
/** What a webhook's `void` return means on the wire, said once. */
|
|
7
8
|
const ACKNOWLEDGE = 'Return any 2xx to acknowledge delivery. The body is ignored.';
|
|
8
9
|
/** `Promise<void>` on the wire, said once. */
|
|
@@ -12,11 +13,15 @@ class ResponseContract {
|
|
|
12
13
|
errorSchemaRef;
|
|
13
14
|
headers;
|
|
14
15
|
constructor(
|
|
15
|
-
/**
|
|
16
|
+
/** The manifest's `errors.responses`, in declared order. */
|
|
16
17
|
errors,
|
|
17
18
|
/** `$ref` at the error body schema, when the manifest declared one. */
|
|
18
19
|
errorSchemaRef,
|
|
19
|
-
/**
|
|
20
|
+
/**
|
|
21
|
+
* Header name -> its `components.headers` `$ref`, on the success response AND on every
|
|
22
|
+
* failure listed for the operation (#1270). The server stamps the header on every response,
|
|
23
|
+
* and the failing one is the response a partner most needs to quote back.
|
|
24
|
+
*/
|
|
20
25
|
headers) {
|
|
21
26
|
this.errors = errors;
|
|
22
27
|
this.errorSchemaRef = errorSchemaRef;
|
|
@@ -50,14 +55,29 @@ class OperationRenderer {
|
|
|
50
55
|
schemas;
|
|
51
56
|
includeMcp;
|
|
52
57
|
includeTrigger;
|
|
58
|
+
operationIds;
|
|
53
59
|
constructor(schemas,
|
|
54
60
|
/** True only for the MCP document — see {@link withMcp}. */
|
|
55
61
|
includeMcp,
|
|
56
62
|
/** True only for the private document — see {@link triggerSentence}. */
|
|
57
|
-
includeTrigger
|
|
63
|
+
includeTrigger,
|
|
64
|
+
/** The manifest's `operationIds` — see {@link operationIdOf}. */
|
|
65
|
+
operationIds) {
|
|
58
66
|
this.schemas = schemas;
|
|
59
67
|
this.includeMcp = includeMcp;
|
|
60
68
|
this.includeTrigger = includeTrigger;
|
|
69
|
+
this.operationIds = operationIds;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* The published `operationId`, in the manifest's chosen style (#1270).
|
|
73
|
+
*
|
|
74
|
+
* Public because the generator checks uniqueness with the SAME function before rendering: a
|
|
75
|
+
* second spelling of the id there could pass a collision this one then publishes.
|
|
76
|
+
*/
|
|
77
|
+
operationIdOf(endpoint, contractName) {
|
|
78
|
+
return this.operationIds === OpenApiManifest_1.OperationIdStyle.METHOD
|
|
79
|
+
? endpoint.methodName
|
|
80
|
+
: `${contractName}_${endpoint.methodName}`;
|
|
61
81
|
}
|
|
62
82
|
/** An ordinary served route. */
|
|
63
83
|
operation(endpoint, contractName, tag, contract, security) {
|
|
@@ -83,7 +103,7 @@ class OperationRenderer {
|
|
|
83
103
|
}
|
|
84
104
|
common(endpoint, contractName, tag, contract) {
|
|
85
105
|
return new JsonObject_1.JsonObject()
|
|
86
|
-
.set('operationId',
|
|
106
|
+
.set('operationId', this.operationIdOf(endpoint, contractName))
|
|
87
107
|
.set('x-webpieces-authentication', endpoint.auth?.methods.map((method) => new JsonObject_1.JsonObject().set('kind', method.kind).set('arguments', method.argumentTexts)))
|
|
88
108
|
.set('summary', endpoint.methodName)
|
|
89
109
|
.set('description', this.describe(endpoint))
|
|
@@ -222,8 +242,13 @@ class OperationRenderer {
|
|
|
222
242
|
responses(endpoint, contractName, contract) {
|
|
223
243
|
const responses = new JsonObject_1.JsonObject();
|
|
224
244
|
responses.set('200', this.success(endpoint, contractName, contract));
|
|
225
|
-
for (const
|
|
226
|
-
|
|
245
|
+
for (const error of contract.errors) {
|
|
246
|
+
// A failure only an AUTHENTICATED operation can have (a 401) is not one a public
|
|
247
|
+
// endpoint can return, so it is not documented there.
|
|
248
|
+
if (error.requiresAuth && this.isPublic(endpoint)) {
|
|
249
|
+
continue;
|
|
250
|
+
}
|
|
251
|
+
responses.set(error.status, this.failure(error.description, contract));
|
|
227
252
|
}
|
|
228
253
|
return responses;
|
|
229
254
|
}
|
|
@@ -238,7 +263,9 @@ class OperationRenderer {
|
|
|
238
263
|
return response.set('content', new JsonObject_1.JsonObject().set('application/json', new JsonObject_1.JsonObject().set('schema', this.schemas.type(endpoint.response, pointer))));
|
|
239
264
|
}
|
|
240
265
|
failure(description, contract) {
|
|
241
|
-
const response = new JsonObject_1.JsonObject()
|
|
266
|
+
const response = new JsonObject_1.JsonObject()
|
|
267
|
+
.set('description', description)
|
|
268
|
+
.set('headers', contract.headers);
|
|
242
269
|
if (contract.errorSchemaRef === undefined) {
|
|
243
270
|
return response;
|
|
244
271
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OperationRenderer.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/OperationRenderer.ts"],"names":[],"mappings":";;;AACA,oDAU8B;AAC9B,mDAA2D;AAG3D,mEAAmE;AACnE,MAAM,WAAW,GAAG,8DAA8D,CAAC;AAEnF,8CAA8C;AAE9C,4FAA4F;AAC5F,MAAa,gBAAgB;IAGZ;IAEA;IAEA;IANb;IACI,wFAAwF;IAC/E,MAAmC;IAC5C,uEAAuE;IAC9D,cAAsC;IAC/C,iFAAiF;IACxE,OAA+B;QAJ/B,WAAM,GAAN,MAAM,CAA6B;QAEnC,mBAAc,GAAd,cAAc,CAAwB;QAEtC,YAAO,GAAP,OAAO,CAAwB;IACzC,CAAC;CACP;AATD,4CASC;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAa,iBAAiB;IAEL;IAEA;IAEA;IALrB,YACqB,OAAuB;IACxC,4DAA4D;IAC3C,UAAmB;IACpC,wEAAwE;IACvD,cAAuB;QAJvB,YAAO,GAAP,OAAO,CAAgB;QAEvB,eAAU,GAAV,UAAU,CAAS;QAEnB,mBAAc,GAAd,cAAc,CAAS;IACzC,CAAC;IAEJ,gCAAgC;IAChC,SAAS,CACL,QAA4B,EAC5B,YAAoB,EACpB,GAAW,EACX,QAA0B,EAC1B,QAA0C;QAE1C,MAAM,SAAS,GAAG,IAAI,CAAC,MAAM,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,EAAE,QAAQ,CAAC,CAAC;QACrE,wFAAwF;QACxF,2FAA2F;QAC3F,8EAA8E;QAC9E,MAAM,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC,QAAQ,CAA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AAE,CAAC,GAAG,CAAC,aAAa,EAAE,WAAW,CAAC,CAAC;QAClE,IAAI,QAAQ,CAAC,cAAc,KAAK,SAAS,EAAE,CAAC;YACxC,OAAO,QAAQ,CAAC;QACpB,CAAC;QACD,OAAO,QAAQ,CAAC,GAAG,CACf,SAAS,EACT,IAAI,uBAAU,EAAE,CAAC,GAAG,CAChB,kBAAkB,EAClB,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,CAAC,CAC1D,CACJ,CAAC;IACN,CAAC;IAED,mGAAmG;IAC3F,MAAM,CAAC,QAA6B;QACxC,OAAO,CACH,QAAQ,KAAK,SAAS;YACtB,CAAC,QAAQ,CAAC,IAAI,KAAK,WAAW,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS,CAAC,CACtE,CAAC;IACN,CAAC;IAEO,KAAK,CAAC,IAAwB;QAClC,OAAO,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;IACvE,CAAC;CACJ;AA9QD,8CA8QC","sourcesContent":["import { DocumentedAuthMethod, DocumentedEndpoint, TypeRef } from '@webpieces/api-doc-model';\nimport {\n CLOUDTASKS,\n CRON,\n EXTERNAL,\n mcpHintsForOperation,\n POST,\n READ,\n RPC,\n WRITE,\n WRITE_IDEMPOTENT,\n} from '@webpieces/core-util';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { SchemaRenderer } from './SchemaRenderer';\n\n/** What a webhook's `void` return means on the wire, said once. */\nconst ACKNOWLEDGE = 'Return any 2xx to acknowledge delivery. The body is ignored.';\n\n/** `Promise<void>` on the wire, said once. */\n\n/** The response document, and the responses a document-wide failure contract adds to it. */\nexport class ResponseContract {\n constructor(\n /** Status -> description, from the manifest's `errors.responses`, in declared order. */\n readonly errors: ReadonlyMap<string, string>,\n /** `$ref` at the error body schema, when the manifest declared one. */\n readonly errorSchemaRef: JsonObject | undefined,\n /** Header name -> its `components.headers` `$ref`, on every success response. */\n readonly headers: JsonObject | undefined,\n ) {}\n}\n\n/**\n * ONE {@link DocumentedEndpoint} -> one OpenAPI Operation Object.\n *\n * ## `summary` is the operation NAME, never a sentence\n *\n * A docs theme titles the endpoint's page from `summary` and puts `description` in the body. Writing\n * the first sentence of the prose into `summary` therefore produces a sidebar of sentences and a page\n * whose heading repeats its own first line. The method name is what a reader is looking for, and it\n * is also what the generated client calls the method, so the two agree by construction.\n *\n * ## The MCP extensions ride HERE, on the operation\n *\n * `x-mcp-tool`, `x-mcp-hints`, `x-mcp-description` and `x-mcp-auth` are stamped on every operation\n * carrying the tool decorator, hidden or not: an internal endpoint that is an agent tool is a\n * legitimate agent tool, and requiring it to be published to partners in order to be one would be\n * exactly the wrong coupling.\n *\n * They are stamped on the BASE, which every published document is derived from, and\n * {@link DocumentDeriver} STRIPS them from the customer document. Stamping-then-stripping rather than\n * rendering the customer document without them is the same choice the whole deriver rests on: one\n * render of one operation, so two documents holding it cannot disagree about anything else in it.\n */\nexport class OperationRenderer {\n constructor(\n private readonly schemas: SchemaRenderer,\n /** True only for the MCP document — see {@link withMcp}. */\n private readonly includeMcp: boolean,\n /** True only for the private document — see {@link triggerSentence}. */\n private readonly includeTrigger: boolean,\n ) {}\n\n /** An ordinary served route. */\n operation(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n security: readonly JsonValue[] | undefined,\n ): JsonObject {\n const operation = this.common(endpoint, contractName, tag, contract);\n // An endpoint that authenticates NOBODY says so explicitly: `security: []` is OpenAPI's\n // spelling of \"no credential required\", and leaving the key off instead means \"inherit the\n // document's\", which is a different statement that happens to coincide today.\n const explicit = this.isPublic(endpoint) ? [] : security;\n operation.set('security', explicit === undefined ? undefined : explicit.slice());\n return this.withMcp(operation, endpoint);\n }\n\n /**\n * A call WE make to a PARTNER's server.\n *\n * It carries `x-webpieces-webhook: true`, which is the one fact about it a document cannot state\n * any other way. It gets no trigger sentence and no security at all, because neither is true of\n * it: nothing of ours triggers it and nothing of ours authenticates it — our api key must never\n * be published as a guard on somebody else's endpoint.\n */\n webhook(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n ): JsonObject {\n const operation = this.common(endpoint, contractName, tag, contract);\n return this.withMcp(operation.set('x-webpieces-webhook', true), endpoint);\n }\n\n private common(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n ): JsonObject {\n return new JsonObject()\n .set('operationId', `${contractName}_${endpoint.methodName}`)\n .set('x-webpieces-authentication', endpoint.auth?.methods.map((method: DocumentedAuthMethod) => new JsonObject().set('kind', method.kind).set('arguments', method.argumentTexts)))\n .set('summary', endpoint.methodName)\n .set('description', this.describe(endpoint))\n .set('tags', [tag])\n .set('requestBody', this.requestBody(endpoint, contractName))\n .set('responses', this.responses(endpoint, contractName, contract));\n }\n\n /**\n * The JSDoc body, plus the sentences that are DERIVED rather than written.\n *\n * The retry sentence comes from the endpoint's declared `operation`, which every integration\n * wants to know and most APIs state nowhere. It is a SENTENCE and not a vendor extension because\n * Swagger UI and most themes do not render `x-` extensions and no standard generator reads\n * `x-webpieces-*`: an extension would be invisible to the human and unread by the machine. The\n * mapping it is derived from is published once, in `info.description`, so the rule is stated and\n * not only its consequences.\n */\n private describe(endpoint: DocumentedEndpoint): string | undefined {\n const parts: string[] = [];\n const body = this.prose(endpoint.description);\n if (body !== undefined) {\n parts.push(body);\n }\n parts.push(this.retrySentence(endpoint));\n if (this.includeTrigger) {\n parts.push(this.triggerSentence(endpoint));\n }\n if (endpoint.openWorld) {\n parts.push(\n 'Reaches beyond this service: it may act on an external system, so its effects ' +\n 'are not all visible here.',\n );\n }\n return parts.join('\\n\\n');\n }\n\n /**\n * WHAT FIRES this endpoint, in the private document only.\n *\n * A customer calls what they are given a url for; whether ours runs off a queue or a clock is our\n * business and would only invite a question they cannot act on. It is a SENTENCE and not\n * `x-webpieces-trigger` for the same reason the retry sentence is: Swagger UI and most themes do\n * not render `x-` extensions, and no standard generator reads `x-webpieces-*`, so an extension is\n * invisible to the human and unread by the machine.\n */\n private triggerSentence(endpoint: DocumentedEndpoint): string {\n if (endpoint.kind === CLOUDTASKS) {\n return 'Triggered by a queued task, delivered asynchronously.';\n }\n if (endpoint.kind === CRON) {\n return 'Triggered on a schedule, not by a caller.';\n }\n if (endpoint.kind === EXTERNAL) {\n const caller = endpoint.options.calledBy;\n return caller === undefined\n ? 'Triggered by an outside system.'\n : `Triggered by an outside system: ${caller}.`;\n }\n return endpoint.kind === RPC\n ? 'Triggered by a direct call.'\n : `Triggered by: ${endpoint.kind}.`;\n }\n\n /** An endpoint whose declared credential is \"none\", said out loud rather than left absent. */\n private isPublic(endpoint: DocumentedEndpoint): boolean {\n return endpoint.auth?.publicReason !== undefined;\n }\n\n private retrySentence(endpoint: DocumentedEndpoint): string {\n if (endpoint.operation === READ) {\n return 'Safe to retry: this operation is read-only and idempotent.';\n }\n if (endpoint.operation === WRITE_IDEMPOTENT) {\n return 'Safe to retry: this operation changes state but is idempotent.';\n }\n return 'NOT safe to retry: this operation changes state and is not idempotent.';\n }\n\n /**\n * The MCP extensions, stamped only on the document that has an agent for a reader.\n *\n * ## The three side-effect hints are COMPUTED, never declared\n *\n * `mcpHintsForOperation` in `@webpieces/core-util` is the one place the mapping from\n * `READ | WRITE_IDEMPOTENT | WRITE` to `readOnlyHint` / `destructiveHint` / `idempotentHint`\n * lives, and this calls it rather than reimplementing it. The endpoint's `operation` already\n * states whether repeating the call is safe; a hand-declared hint would be a second answer to a\n * question the contract has answered, and the two could disagree. `openWorldHint` is the only one\n * a human declares, because it is a judgement about the world rather than a consequence of the\n * operation.\n *\n * ## There is no separate MCP description\n *\n * The agent reads the operation's `description` — the method's JSDoc — byte-identical to what the\n * partner reads. `x-mcp-description` appears ONLY when the author wrote an explicit `@mcp` JSDoc\n * tag, which is a deliberate act rather than a second copy of the same paragraph.\n */\n private withMcp(operation: JsonObject, endpoint: DocumentedEndpoint): JsonObject {\n if (!this.includeMcp || endpoint.mcpTool === undefined) {\n return operation;\n }\n const hints = mcpHintsForOperation(this.operationOf(endpoint), endpoint.openWorld);\n return operation\n .set('x-mcp-tool', endpoint.mcpTool.name)\n .set(\n 'x-mcp-hints',\n new JsonObject()\n .set('readOnlyHint', hints.readOnlyHint)\n .set('destructiveHint', hints.destructiveHint)\n .set('idempotentHint', hints.idempotentHint)\n .set('openWorldHint', hints.openWorldHint),\n )\n .set('x-mcp-description', this.prose(endpoint.mcpDescription))\n .set('x-webpieces-authorization', endpoint.authorizationText);\n }\n\n /**\n * The endpoint's operation as the REAL exported constant.\n *\n * The model carries it as a string, verbatim from the source, because the model invents no\n * taxonomy. Matching it back to the constant here — rather than casting — is what makes a rename\n * of `WRITE_IDEMPOTENT` in `core-util` a compile error in this file.\n */\n private operationOf(\n endpoint: DocumentedEndpoint,\n ): typeof READ | typeof WRITE_IDEMPOTENT | typeof WRITE {\n if (endpoint.operation === READ) {\n return READ;\n }\n return endpoint.operation === WRITE_IDEMPOTENT ? WRITE_IDEMPOTENT : WRITE;\n }\n\n /**\n * The request DTO as a body. Only for `POST`: OpenAPI gives a `GET` body no defined semantics and\n * most tooling drops it, so publishing one would document a request no generated client sends.\n */\n private requestBody(\n endpoint: DocumentedEndpoint,\n contractName: string,\n ): JsonObject | undefined {\n if (endpoint.httpMethod !== 'POST' || endpoint.request === undefined) {\n return undefined;\n }\n const pointer = `#/paths/${contractName}_${endpoint.methodName}/requestBody`;\n const media = endpoint.options.formPost\n ? 'application/x-www-form-urlencoded'\n : 'application/json';\n return new JsonObject()\n .set('required', true)\n .set(\n 'content',\n new JsonObject().set(\n media,\n new JsonObject().set('schema', this.schemas.type(endpoint.request, pointer)),\n ),\n );\n }\n\n private responses(\n endpoint: DocumentedEndpoint,\n contractName: string,\n contract: ResponseContract,\n ): JsonObject {\n const responses = new JsonObject();\n responses.set('200', this.success(endpoint, contractName, contract));\n for (const status of Array.from(contract.errors.keys())) {\n responses.set(status, this.failure(contract.errors.get(status)!, contract));\n }\n return responses;\n }\n\n private success(\n endpoint: DocumentedEndpoint,\n contractName: string,\n contract: ResponseContract,\n ): JsonObject {\n const response = new JsonObject()\n .set('description', this.isVoid(endpoint.response) ? ACKNOWLEDGE : 'Success.')\n .set('headers', contract.headers);\n if (this.isVoid(endpoint.response)) {\n return response;\n }\n const pointer = `#/paths/${contractName}_${endpoint.methodName}/responses/200`;\n return response.set(\n 'content',\n new JsonObject().set(\n 'application/json',\n new JsonObject().set('schema', this.schemas.type(endpoint.response!, pointer)),\n ),\n );\n }\n\n private failure(description: string, contract: ResponseContract): JsonObject {\n const response = new JsonObject().set('description', description);\n if (contract.errorSchemaRef === undefined) {\n return response;\n }\n return response.set(\n 'content',\n new JsonObject().set(\n 'application/json',\n new JsonObject().set('schema', contract.errorSchemaRef),\n ),\n );\n }\n\n /** `Promise<void>` reaches the model as the `unknown` primitive — there is no body to document. */\n private isVoid(response: TypeRef | undefined): boolean {\n return (\n response === undefined ||\n (response.kind === 'primitive' && response.primitive === 'unknown')\n );\n }\n\n private prose(text: string | undefined): string | undefined {\n return text === undefined || text.trim() === '' ? undefined : text;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"OperationRenderer.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/OperationRenderer.ts"],"names":[],"mappings":";;;AACA,oDAU8B;AAC9B,mDAA2D;AAC3D,iEAAmF;AAGnF,mEAAmE;AACnE,MAAM,WAAW,GAAG,8DAA8D,CAAC;AAEnF,8CAA8C;AAE9C,4FAA4F;AAC5F,MAAa,gBAAgB;IAGZ;IAEA;IAMA;IAVb;IACI,4DAA4D;IACnD,MAAqC;IAC9C,uEAAuE;IAC9D,cAAsC;IAC/C;;;;OAIG;IACM,OAA+B;QAR/B,WAAM,GAAN,MAAM,CAA+B;QAErC,mBAAc,GAAd,cAAc,CAAwB;QAMtC,YAAO,GAAP,OAAO,CAAw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,EAAE,CAAC,GAAG,CAChB,kBAAkB,EAClB,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC,cAAc,CAAC,CAC1D,CACJ,CAAC;IACN,CAAC;IAED,mGAAmG;IAC3F,MAAM,CAAC,QAA6B;QACxC,OAAO,CACH,QAAQ,KAAK,SAAS;YACtB,CAAC,QAAQ,CAAC,IAAI,KAAK,WAAW,IAAI,QAAQ,CAAC,SAAS,KAAK,SAAS,CAAC,CACtE,CAAC;IACN,CAAC;IAEO,KAAK,CAAC,IAAwB;QAClC,OAAO,IAAI,KAAK,SAAS,IAAI,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,IAAI,CAAC;IACvE,CAAC;CACJ;AAnSD,8CAmSC","sourcesContent":["import { DocumentedAuthMethod, DocumentedEndpoint, TypeRef } from '@webpieces/api-doc-model';\nimport {\n CLOUDTASKS,\n CRON,\n EXTERNAL,\n mcpHintsForOperation,\n POST,\n READ,\n RPC,\n WRITE,\n WRITE_IDEMPOTENT,\n} from '@webpieces/core-util';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { ErrorResponseEntry, OperationIdStyle } from '../manifest/OpenApiManifest';\nimport { SchemaRenderer } from './SchemaRenderer';\n\n/** What a webhook's `void` return means on the wire, said once. */\nconst ACKNOWLEDGE = 'Return any 2xx to acknowledge delivery. The body is ignored.';\n\n/** `Promise<void>` on the wire, said once. */\n\n/** The response document, and the responses a document-wide failure contract adds to it. */\nexport class ResponseContract {\n constructor(\n /** The manifest's `errors.responses`, in declared order. */\n readonly errors: readonly ErrorResponseEntry[],\n /** `$ref` at the error body schema, when the manifest declared one. */\n readonly errorSchemaRef: JsonObject | undefined,\n /**\n * Header name -> its `components.headers` `$ref`, on the success response AND on every\n * failure listed for the operation (#1270). The server stamps the header on every response,\n * and the failing one is the response a partner most needs to quote back.\n */\n readonly headers: JsonObject | undefined,\n ) {}\n}\n\n/**\n * ONE {@link DocumentedEndpoint} -> one OpenAPI Operation Object.\n *\n * ## `summary` is the operation NAME, never a sentence\n *\n * A docs theme titles the endpoint's page from `summary` and puts `description` in the body. Writing\n * the first sentence of the prose into `summary` therefore produces a sidebar of sentences and a page\n * whose heading repeats its own first line. The method name is what a reader is looking for, and it\n * is also what the generated client calls the method, so the two agree by construction.\n *\n * ## The MCP extensions ride HERE, on the operation\n *\n * `x-mcp-tool`, `x-mcp-hints`, `x-mcp-description` and `x-mcp-auth` are stamped on every operation\n * carrying the tool decorator, hidden or not: an internal endpoint that is an agent tool is a\n * legitimate agent tool, and requiring it to be published to partners in order to be one would be\n * exactly the wrong coupling.\n *\n * They are stamped on the BASE, which every published document is derived from, and\n * {@link DocumentDeriver} STRIPS them from the customer document. Stamping-then-stripping rather than\n * rendering the customer document without them is the same choice the whole deriver rests on: one\n * render of one operation, so two documents holding it cannot disagree about anything else in it.\n */\nexport class OperationRenderer {\n constructor(\n private readonly schemas: SchemaRenderer,\n /** True only for the MCP document — see {@link withMcp}. */\n private readonly includeMcp: boolean,\n /** True only for the private document — see {@link triggerSentence}. */\n private readonly includeTrigger: boolean,\n /** The manifest's `operationIds` — see {@link operationIdOf}. */\n private readonly operationIds: OperationIdStyle,\n ) {}\n\n /**\n * The published `operationId`, in the manifest's chosen style (#1270).\n *\n * Public because the generator checks uniqueness with the SAME function before rendering: a\n * second spelling of the id there could pass a collision this one then publishes.\n */\n operationIdOf(endpoint: DocumentedEndpoint, contractName: string): string {\n return this.operationIds === OperationIdStyle.METHOD\n ? endpoint.methodName\n : `${contractName}_${endpoint.methodName}`;\n }\n\n /** An ordinary served route. */\n operation(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n security: readonly JsonValue[] | undefined,\n ): JsonObject {\n const operation = this.common(endpoint, contractName, tag, contract);\n // An endpoint that authenticates NOBODY says so explicitly: `security: []` is OpenAPI's\n // spelling of \"no credential required\", and leaving the key off instead means \"inherit the\n // document's\", which is a different statement that happens to coincide today.\n const explicit = this.isPublic(endpoint) ? [] : security;\n operation.set('security', explicit === undefined ? undefined : explicit.slice());\n return this.withMcp(operation, endpoint);\n }\n\n /**\n * A call WE make to a PARTNER's server.\n *\n * It carries `x-webpieces-webhook: true`, which is the one fact about it a document cannot state\n * any other way. It gets no trigger sentence and no security at all, because neither is true of\n * it: nothing of ours triggers it and nothing of ours authenticates it — our api key must never\n * be published as a guard on somebody else's endpoint.\n */\n webhook(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n ): JsonObject {\n const operation = this.common(endpoint, contractName, tag, contract);\n return this.withMcp(operation.set('x-webpieces-webhook', true), endpoint);\n }\n\n private common(\n endpoint: DocumentedEndpoint,\n contractName: string,\n tag: string,\n contract: ResponseContract,\n ): JsonObject {\n return new JsonObject()\n .set('operationId', this.operationIdOf(endpoint, contractName))\n .set('x-webpieces-authentication', endpoint.auth?.methods.map((method: DocumentedAuthMethod) => new JsonObject().set('kind', method.kind).set('arguments', method.argumentTexts)))\n .set('summary', endpoint.methodName)\n .set('description', this.describe(endpoint))\n .set('tags', [tag])\n .set('requestBody', this.requestBody(endpoint, contractName))\n .set('responses', this.responses(endpoint, contractName, contract));\n }\n\n /**\n * The JSDoc body, plus the sentences that are DERIVED rather than written.\n *\n * The retry sentence comes from the endpoint's declared `operation`, which every integration\n * wants to know and most APIs state nowhere. It is a SENTENCE and not a vendor extension because\n * Swagger UI and most themes do not render `x-` extensions and no standard generator reads\n * `x-webpieces-*`: an extension would be invisible to the human and unread by the machine. The\n * mapping it is derived from is published once, in `info.description`, so the rule is stated and\n * not only its consequences.\n */\n private describe(endpoint: DocumentedEndpoint): string | undefined {\n const parts: string[] = [];\n const body = this.prose(endpoint.description);\n if (body !== undefined) {\n parts.push(body);\n }\n parts.push(this.retrySentence(endpoint));\n if (this.includeTrigger) {\n parts.push(this.triggerSentence(endpoint));\n }\n if (endpoint.openWorld) {\n parts.push(\n 'Reaches beyond this service: it may act on an external system, so its effects ' +\n 'are not all visible here.',\n );\n }\n return parts.join('\\n\\n');\n }\n\n /**\n * WHAT FIRES this endpoint, in the private document only.\n *\n * A customer calls what they are given a url for; whether ours runs off a queue or a clock is our\n * business and would only invite a question they cannot act on. It is a SENTENCE and not\n * `x-webpieces-trigger` for the same reason the retry sentence is: Swagger UI and most themes do\n * not render `x-` extensions, and no standard generator reads `x-webpieces-*`, so an extension is\n * invisible to the human and unread by the machine.\n */\n private triggerSentence(endpoint: DocumentedEndpoint): string {\n if (endpoint.kind === CLOUDTASKS) {\n return 'Triggered by a queued task, delivered asynchronously.';\n }\n if (endpoint.kind === CRON) {\n return 'Triggered on a schedule, not by a caller.';\n }\n if (endpoint.kind === EXTERNAL) {\n const caller = endpoint.options.calledBy;\n return caller === undefined\n ? 'Triggered by an outside system.'\n : `Triggered by an outside system: ${caller}.`;\n }\n return endpoint.kind === RPC\n ? 'Triggered by a direct call.'\n : `Triggered by: ${endpoint.kind}.`;\n }\n\n /** An endpoint whose declared credential is \"none\", said out loud rather than left absent. */\n private isPublic(endpoint: DocumentedEndpoint): boolean {\n return endpoint.auth?.publicReason !== undefined;\n }\n\n private retrySentence(endpoint: DocumentedEndpoint): string {\n if (endpoint.operation === READ) {\n return 'Safe to retry: this operation is read-only and idempotent.';\n }\n if (endpoint.operation === WRITE_IDEMPOTENT) {\n return 'Safe to retry: this operation changes state but is idempotent.';\n }\n return 'NOT safe to retry: this operation changes state and is not idempotent.';\n }\n\n /**\n * The MCP extensions, stamped only on the document that has an agent for a reader.\n *\n * ## The three side-effect hints are COMPUTED, never declared\n *\n * `mcpHintsForOperation` in `@webpieces/core-util` is the one place the mapping from\n * `READ | WRITE_IDEMPOTENT | WRITE` to `readOnlyHint` / `destructiveHint` / `idempotentHint`\n * lives, and this calls it rather than reimplementing it. The endpoint's `operation` already\n * states whether repeating the call is safe; a hand-declared hint would be a second answer to a\n * question the contract has answered, and the two could disagree. `openWorldHint` is the only one\n * a human declares, because it is a judgement about the world rather than a consequence of the\n * operation.\n *\n * ## There is no separate MCP description\n *\n * The agent reads the operation's `description` — the method's JSDoc — byte-identical to what the\n * partner reads. `x-mcp-description` appears ONLY when the author wrote an explicit `@mcp` JSDoc\n * tag, which is a deliberate act rather than a second copy of the same paragraph.\n */\n private withMcp(operation: JsonObject, endpoint: DocumentedEndpoint): JsonObject {\n if (!this.includeMcp || endpoint.mcpTool === undefined) {\n return operation;\n }\n const hints = mcpHintsForOperation(this.operationOf(endpoint), endpoint.openWorld);\n return operation\n .set('x-mcp-tool', endpoint.mcpTool.name)\n .set(\n 'x-mcp-hints',\n new JsonObject()\n .set('readOnlyHint', hints.readOnlyHint)\n .set('destructiveHint', hints.destructiveHint)\n .set('idempotentHint', hints.idempotentHint)\n .set('openWorldHint', hints.openWorldHint),\n )\n .set('x-mcp-description', this.prose(endpoint.mcpDescription))\n .set('x-webpieces-authorization', endpoint.authorizationText);\n }\n\n /**\n * The endpoint's operation as the REAL exported constant.\n *\n * The model carries it as a string, verbatim from the source, because the model invents no\n * taxonomy. Matching it back to the constant here — rather than casting — is what makes a rename\n * of `WRITE_IDEMPOTENT` in `core-util` a compile error in this file.\n */\n private operationOf(\n endpoint: DocumentedEndpoint,\n ): typeof READ | typeof WRITE_IDEMPOTENT | typeof WRITE {\n if (endpoint.operation === READ) {\n return READ;\n }\n return endpoint.operation === WRITE_IDEMPOTENT ? WRITE_IDEMPOTENT : WRITE;\n }\n\n /**\n * The request DTO as a body. Only for `POST`: OpenAPI gives a `GET` body no defined semantics and\n * most tooling drops it, so publishing one would document a request no generated client sends.\n */\n private requestBody(\n endpoint: DocumentedEndpoint,\n contractName: string,\n ): JsonObject | undefined {\n if (endpoint.httpMethod !== 'POST' || endpoint.request === undefined) {\n return undefined;\n }\n const pointer = `#/paths/${contractName}_${endpoint.methodName}/requestBody`;\n const media = endpoint.options.formPost\n ? 'application/x-www-form-urlencoded'\n : 'application/json';\n return new JsonObject()\n .set('required', true)\n .set(\n 'content',\n new JsonObject().set(\n media,\n new JsonObject().set('schema', this.schemas.type(endpoint.request, pointer)),\n ),\n );\n }\n\n private responses(\n endpoint: DocumentedEndpoint,\n contractName: string,\n contract: ResponseContract,\n ): JsonObject {\n const responses = new JsonObject();\n responses.set('200', this.success(endpoint, contractName, contract));\n for (const error of contract.errors) {\n // A failure only an AUTHENTICATED operation can have (a 401) is not one a public\n // endpoint can return, so it is not documented there.\n if (error.requiresAuth && this.isPublic(endpoint)) {\n continue;\n }\n responses.set(error.status, this.failure(error.description, contract));\n }\n return responses;\n }\n\n private success(\n endpoint: DocumentedEndpoint,\n contractName: string,\n contract: ResponseContract,\n ): JsonObject {\n const response = new JsonObject()\n .set('description', this.isVoid(endpoint.response) ? ACKNOWLEDGE : 'Success.')\n .set('headers', contract.headers);\n if (this.isVoid(endpoint.response)) {\n return response;\n }\n const pointer = `#/paths/${contractName}_${endpoint.methodName}/responses/200`;\n return response.set(\n 'content',\n new JsonObject().set(\n 'application/json',\n new JsonObject().set('schema', this.schemas.type(endpoint.response!, pointer)),\n ),\n );\n }\n\n private failure(description: string, contract: ResponseContract): JsonObject {\n const response = new JsonObject()\n .set('description', description)\n .set('headers', contract.headers);\n if (contract.errorSchemaRef === undefined) {\n return response;\n }\n return response.set(\n 'content',\n new JsonObject().set(\n 'application/json',\n new JsonObject().set('schema', contract.errorSchemaRef),\n ),\n );\n }\n\n /** `Promise<void>` reaches the model as the `unknown` primitive — there is no body to document. */\n private isVoid(response: TypeRef | undefined): boolean {\n return (\n response === undefined ||\n (response.kind === 'primitive' && response.primitive === 'unknown')\n );\n }\n\n private prose(text: string | undefined): string | undefined {\n return text === undefined || text.trim() === '' ? undefined : text;\n }\n}\n"]}
|
|
@@ -102,11 +102,13 @@ class SecurityDeriver {
|
|
|
102
102
|
.set('description', credential.description);
|
|
103
103
|
}
|
|
104
104
|
if (credential.location !== 'header') {
|
|
105
|
-
throw new OpenApiGenerationError_1.OpenApiGenerationError(`unknown api-key credential location '${credential.location}'`, manifestPath, "A credential rides `in: 'header'` with
|
|
105
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`unknown api-key credential location '${credential.location}'`, manifestPath, "A credential rides `in: 'header'` with its ContextKey, or `in: 'bearer'`.");
|
|
106
106
|
}
|
|
107
|
+
// The extractor reads the name off the credential's ContextKey and refuses, quoting the key,
|
|
108
|
+
// when it cannot — so a model reaching here without one was built by hand, not extracted.
|
|
107
109
|
if (credential.name === undefined) {
|
|
108
|
-
throw new OpenApiGenerationError_1.OpenApiGenerationError('a header api-key credential
|
|
109
|
-
|
|
110
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError('a header api-key credential reached the generator with no resolved header name', manifestPath, "Declare it as `{ in: 'header', key: MyKeys.API_KEY }` and let the extractor read the " +
|
|
111
|
+
"header name off that ContextKey's httpHeader.");
|
|
110
112
|
}
|
|
111
113
|
return new JsonObject_1.JsonObject()
|
|
112
114
|
.set('type', 'apiKey')
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SecurityDeriver.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/SecurityDeriver.ts"],"names":[],"mappings":";;;AACA,mDAA2D;AAC3D,sEAAmE;AAEnE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,eAAe;IACxB,SAAS,CAAC,IAAgC,EAAE,iBAAmD;QAC3F,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,CAAC;QAC9B,IAAI,CAAC,OAAO,EAAE,MAAM;YAAE,OAAO,SAAS,CAAC;QACvC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,iBAAiB,CAAC;QACnF,MAAM,YAAY,GAAgB,EAAE,CAAC;QACrC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC3B,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC3B,IA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M,CAAC;iBACnB,GAAG,CAAC,QAAQ,EAAE,QAAQ,CAAC;iBACvB,GAAG,CAAC,aAAa,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;QACpD,CAAC;QACD,IAAI,UAAU,CAAC,QAAQ,KAAK,QAAQ,EAAE,CAAC;YACnC,MAAM,IAAI,+CAAsB,CAC5B,wCAAwC,UAAU,CAAC,QAAQ,GAAG,EAC9D,YAAY,EACZ,mEAAmE,CACtE,CAAC;QACN,CAAC;QACD,IAAI,UAAU,CAAC,IAAI,KAAK,SAAS,EAAE,CAAC;YAChC,MAAM,IAAI,+CAAsB,CAC5B,qDAAqD,EACrD,YAAY,EACZ,gFAAgF;gBAC5E,sCAAsC,CAC7C,CAAC;QACN,CAAC;QACD,OAAO,IAAI,uBAAU,EAAE;aAClB,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC;aACrB,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC;aACnB,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC;aAC5B,GAAG,CAAC,aAAa,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IACpD,CAAC;IAED,8FAA8F;IAC9F,WAAW,CAAC,WAA8B;QACtC,MAAM,KAAK,GAAG,IAAI,uBAAU,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,WAAW,EAAE,CAAC;YAC7B,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;CACJ;AA1GD,0CA0GC","sourcesContent":["import { DocumentedAuth, DocumentedApiKey, DocumentedApiKeyCredential, DocumentedEndpoint } from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\n\n/**\n * `components.securitySchemes` and the `security` requirement, DERIVED from the contract's own\n * `apiKey(regime, credentials)`. The manifest contributes the published KEYS and nothing else.\n *\n * ## Why the schemes are not in the manifest\n *\n * A `components.securitySchemes` block in a JSON file would be a second copy of header names the\n * running server never reads — and nothing could contradict it. Deriving them from the decorator\n * means the published document and the hook that enforces the credential are the same declaration,\n * so the document cannot say `x-api-key` while the server checks `x-partner-key`. The manifest keeps\n * the KEYS because a scheme key is partner-visible naming, which is a product decision.\n *\n * ## ONE requirement object holding every scheme, never a list of one-key objects\n *\n * OpenAPI's `security` is a list of ALTERNATIVES, and each alternative is an object whose keys must\n * ALL be satisfied. So:\n *\n * ```\n * [{ PartnerApiKey: [], PartnerOrg: [] }] // AND — present both. What a real regime means.\n * [{ PartnerApiKey: [] }, { PartnerOrg: [] }] // OR — \"either header alone suffices\". A lie.\n * ```\n *\n * The second form is the dangerous default because it is what \"a list of credentials\" reads like,\n * and NO BUILD COULD CONTRADICT IT: the document would be well-formed, the tooling green, and a\n * partner told they may skip the organization header. Hence one object, always.\n */\nexport class SecurityDeriver {\n operation(auth: DocumentedAuth | undefined, apiKeyRequirement: readonly JsonValue[] | undefined): readonly JsonValue[] | undefined {\n const methods = auth?.methods;\n if (!methods?.length) return undefined;\n if (methods.length === 1 && methods[0].kind === 'apikey') return apiKeyRequirement;\n const alternatives: JsonValue[] = [];\n for (const method of methods) {\n if (method.kind === 'apikey') {\n if (!apiKeyRequirement) throw new Error('Mixed credentials require an explicit API-key security requirement.');\n alternatives.push(...apiKeyRequirement);\n } else {\n const name = this.builtinName(method.kind);\n // Vendor signatures do not declare their wire headers. Keep the complete canonical\n // authentication extension rather than inventing a header or publishing a subset.\n if (!name) return undefined;\n alternatives.push(new JsonObject().set(name, []));\n }\n }\n return alternatives;\n }\n\n addBuiltinSchemes(schemes: JsonObject, endpoints: readonly DocumentedEndpoint[]): JsonObject {\n const added = new Set<string>();\n for (const endpoint of endpoints) for (const method of endpoint.auth?.methods ?? []) {\n const name = this.builtinName(method.kind);\n if (!name || added.has(name)) continue;\n if (schemes.has(name)) throw new Error(`securitySchemeNames reserves '${name}' for framework credentials; choose another API-key scheme name.`);\n added.add(name);\n schemes.set(name, new JsonObject().set('type', 'http').set('scheme', method.kind === 'shared-secret' ? 'Webpieces' : 'bearer'));\n }\n return schemes;\n }\n\n private builtinName(kind: string): string | undefined {\n switch (kind) {\n case 'jwt': return 'WebpiecesJwt';\n case 'oidc': return 'WebpiecesOidc';\n case 'shared-secret': return 'WebpiecesSharedSecret';\n default: return undefined;\n }\n }\n\n /** Every scheme, keyed by the manifest's published names, in declaration order. */\n schemes(\n apiKey: DocumentedApiKey,\n schemeNames: readonly string[],\n manifestPath: string,\n ): JsonObject {\n if (schemeNames.length !== apiKey.credentials.length) {\n throw new OpenApiGenerationError(\n `securitySchemeNames has ${schemeNames.length} name(s) but the '${apiKey.regime}' ` +\n `regime declares ${apiKey.credentials.length} credential(s)`,\n manifestPath,\n 'Give exactly one published scheme name per credential, in the order the ' +\n 'contract declares them. The names are partner-visible; the credentials are not ' +\n 'the manifest to choose.',\n );\n }\n const schemes = new JsonObject();\n for (let i = 0; i < schemeNames.length; i++) {\n schemes.set(schemeNames[i]!, this.scheme(apiKey.credentials[i]!, manifestPath));\n }\n return schemes;\n }\n\n /**\n * ONE credential -> ONE scheme. The two shapes are STRUCTURALLY different documents, which is\n * exactly why `ApiKeyCredential` is a union in the framework rather than one optional field.\n */\n private scheme(credential: DocumentedApiKeyCredential, manifestPath: string): JsonObject {\n if (credential.location === 'bearer') {\n return new JsonObject()\n .set('type', 'http')\n .set('scheme', 'bearer')\n .set('description', credential.description);\n }\n if (credential.location !== 'header') {\n throw new OpenApiGenerationError(\n `unknown api-key credential location '${credential.location}'`,\n manifestPath,\n \"A credential rides `in: 'header'` with a name, or `in: 'bearer'`.\",\n );\n }\n if (credential.name === undefined) {\n throw new OpenApiGenerationError(\n 'a header api-key credential declares no header name',\n manifestPath,\n \"Write `{ in: 'header', name: 'x-api-key' }`; a header credential with no name \" +\n 'is unusable and cannot be published.',\n );\n }\n return new JsonObject()\n .set('type', 'apiKey')\n .set('in', 'header')\n .set('name', credential.name)\n .set('description', credential.description);\n }\n\n /** The ONE AND-ed requirement — see the class doc for why it is one object and not a list. */\n requirement(schemeNames: readonly string[]): readonly JsonValue[] {\n const anded = new JsonObject();\n for (const name of schemeNames) {\n anded.set(name, []);\n }\n return [anded];\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SecurityDeriver.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/SecurityDeriver.ts"],"names":[],"mappings":";;;AACA,mDAA2D;AAC3D,sEAAmE;AAEnE;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,MAAa,eAAe;IACxB,SAAS,CAAC,IAAgC,EAAE,iBAAmD;QAC3F,MAAM,OAAO,GAAG,IAAI,EAAE,OAAO,CAAC;QAC9B,IAAI,CAAC,OAAO,EAAE,MAAM;YAAE,OAAO,SAAS,CAAC;QACvC,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC,IAAI,OAAO,CAAC,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ;YAAE,OAAO,iBAAiB,CAAC;QACnF,MAAM,YAAY,GAAgB,EAAE,CAAC;QACrC,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;YAC3B,IAAI,MAAM,CAAC,IAAI,KAAK,QAAQ,EAAE,CAAC;gBAC3B,IAAI,CAAC,iBAAiB;oBAAE,MAAM,IAAI,KAAK,CAAC,qEAAqE,CAAC,CAAC;gBAC/G,YAAY,CAAC,IAAI,CAAC,GAAG,iBAAiB,CAAC,CAAC;YAC5C,CAAC;iBAAM,CAAC;gBACJ,MAAM,IAAI,GAAG,IAAI,CAAC,WAAW,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;gBAC3C,mFAAmF;gBACnF,kFAAkF;gBAClF,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,CAAC;gBAC5B,YAAY,CAAC,IAAI,CAAC,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,CA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gFAAgF,EAChF,YAAY,EACZ,uFAAuF;gBACnF,+CAA+C,CACtD,CAAC;QACN,CAAC;QACD,OAAO,IAAI,uBAAU,EAAE;aAClB,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC;aACrB,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC;aACnB,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,IAAI,CAAC;aAC5B,GAAG,CAAC,aAAa,EAAE,UAAU,CAAC,WAAW,CAAC,CAAC;IACpD,CAAC;IAED,8FAA8F;IAC9F,WAAW,CAAC,WAA8B;QACtC,MAAM,KAAK,GAAG,IAAI,uBAAU,EAAE,CAAC;QAC/B,KAAK,MAAM,IAAI,IAAI,WAAW,EAAE,CAAC;YAC7B,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACxB,CAAC;QACD,OAAO,CAAC,KAAK,CAAC,CAAC;IACnB,CAAC;CACJ;AA5GD,0CA4GC","sourcesContent":["import { DocumentedAuth, DocumentedApiKey, DocumentedApiKeyCredential, DocumentedEndpoint } from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\n\n/**\n * `components.securitySchemes` and the `security` requirement, DERIVED from the contract's own\n * `apiKey(regime, credentials)`. The manifest contributes the published KEYS and nothing else.\n *\n * ## Why the schemes are not in the manifest\n *\n * A `components.securitySchemes` block in a JSON file would be a second copy of header names the\n * running server never reads — and nothing could contradict it. Deriving them from the decorator\n * means the published document and the hook that enforces the credential are the same declaration,\n * so the document cannot say `x-api-key` while the server checks `x-partner-key`. The manifest keeps\n * the KEYS because a scheme key is partner-visible naming, which is a product decision.\n *\n * ## ONE requirement object holding every scheme, never a list of one-key objects\n *\n * OpenAPI's `security` is a list of ALTERNATIVES, and each alternative is an object whose keys must\n * ALL be satisfied. So:\n *\n * ```\n * [{ PartnerApiKey: [], PartnerOrg: [] }] // AND — present both. What a real regime means.\n * [{ PartnerApiKey: [] }, { PartnerOrg: [] }] // OR — \"either header alone suffices\". A lie.\n * ```\n *\n * The second form is the dangerous default because it is what \"a list of credentials\" reads like,\n * and NO BUILD COULD CONTRADICT IT: the document would be well-formed, the tooling green, and a\n * partner told they may skip the organization header. Hence one object, always.\n */\nexport class SecurityDeriver {\n operation(auth: DocumentedAuth | undefined, apiKeyRequirement: readonly JsonValue[] | undefined): readonly JsonValue[] | undefined {\n const methods = auth?.methods;\n if (!methods?.length) return undefined;\n if (methods.length === 1 && methods[0].kind === 'apikey') return apiKeyRequirement;\n const alternatives: JsonValue[] = [];\n for (const method of methods) {\n if (method.kind === 'apikey') {\n if (!apiKeyRequirement) throw new Error('Mixed credentials require an explicit API-key security requirement.');\n alternatives.push(...apiKeyRequirement);\n } else {\n const name = this.builtinName(method.kind);\n // Vendor signatures do not declare their wire headers. Keep the complete canonical\n // authentication extension rather than inventing a header or publishing a subset.\n if (!name) return undefined;\n alternatives.push(new JsonObject().set(name, []));\n }\n }\n return alternatives;\n }\n\n addBuiltinSchemes(schemes: JsonObject, endpoints: readonly DocumentedEndpoint[]): JsonObject {\n const added = new Set<string>();\n for (const endpoint of endpoints) for (const method of endpoint.auth?.methods ?? []) {\n const name = this.builtinName(method.kind);\n if (!name || added.has(name)) continue;\n if (schemes.has(name)) throw new Error(`securitySchemeNames reserves '${name}' for framework credentials; choose another API-key scheme name.`);\n added.add(name);\n schemes.set(name, new JsonObject().set('type', 'http').set('scheme', method.kind === 'shared-secret' ? 'Webpieces' : 'bearer'));\n }\n return schemes;\n }\n\n private builtinName(kind: string): string | undefined {\n switch (kind) {\n case 'jwt': return 'WebpiecesJwt';\n case 'oidc': return 'WebpiecesOidc';\n case 'shared-secret': return 'WebpiecesSharedSecret';\n default: return undefined;\n }\n }\n\n /** Every scheme, keyed by the manifest's published names, in declaration order. */\n schemes(\n apiKey: DocumentedApiKey,\n schemeNames: readonly string[],\n manifestPath: string,\n ): JsonObject {\n if (schemeNames.length !== apiKey.credentials.length) {\n throw new OpenApiGenerationError(\n `securitySchemeNames has ${schemeNames.length} name(s) but the '${apiKey.regime}' ` +\n `regime declares ${apiKey.credentials.length} credential(s)`,\n manifestPath,\n 'Give exactly one published scheme name per credential, in the order the ' +\n 'contract declares them. The names are partner-visible; the credentials are not ' +\n 'the manifest to choose.',\n );\n }\n const schemes = new JsonObject();\n for (let i = 0; i < schemeNames.length; i++) {\n schemes.set(schemeNames[i]!, this.scheme(apiKey.credentials[i]!, manifestPath));\n }\n return schemes;\n }\n\n /**\n * ONE credential -> ONE scheme. The two shapes are STRUCTURALLY different documents, which is\n * exactly why `ApiKeyCredential` is a union in the framework rather than one optional field.\n */\n private scheme(credential: DocumentedApiKeyCredential, manifestPath: string): JsonObject {\n if (credential.location === 'bearer') {\n return new JsonObject()\n .set('type', 'http')\n .set('scheme', 'bearer')\n .set('description', credential.description);\n }\n if (credential.location !== 'header') {\n throw new OpenApiGenerationError(\n `unknown api-key credential location '${credential.location}'`,\n manifestPath,\n \"A credential rides `in: 'header'` with its ContextKey, or `in: 'bearer'`.\",\n );\n }\n // The extractor reads the name off the credential's ContextKey and refuses, quoting the key,\n // when it cannot — so a model reaching here without one was built by hand, not extracted.\n if (credential.name === undefined) {\n throw new OpenApiGenerationError(\n 'a header api-key credential reached the generator with no resolved header name',\n manifestPath,\n \"Declare it as `{ in: 'header', key: MyKeys.API_KEY }` and let the extractor read the \" +\n \"header name off that ContextKey's httpHeader.\",\n );\n }\n return new JsonObject()\n .set('type', 'apiKey')\n .set('in', 'header')\n .set('name', credential.name)\n .set('description', credential.description);\n }\n\n /** The ONE AND-ed requirement — see the class doc for why it is one object and not a list. */\n requirement(schemeNames: readonly string[]): readonly JsonValue[] {\n const anded = new JsonObject();\n for (const name of schemeNames) {\n anded.set(name, []);\n }\n return [anded];\n }\n}\n"]}
|
package/src/index.d.ts
CHANGED
|
@@ -14,7 +14,7 @@ export type { JsonValue } from './json/JsonObject';
|
|
|
14
14
|
export { JsonWriter } from './json/JsonWriter';
|
|
15
15
|
export { YamlWriter } from './json/YamlWriter';
|
|
16
16
|
export { YamlReader } from './json/YamlReader';
|
|
17
|
-
export { ApiEntry, ComponentsManifest, ErrorResponseEntry, ErrorsEntry, OpenApiManifest, ResponseHeaderEntry, ServerEntry, } from './manifest/OpenApiManifest';
|
|
17
|
+
export { ApiEntry, ComponentsManifest, ErrorResponseEntry, ErrorsEntry, OpenApiManifest, OperationIdStyle, ResponseHeaderEntry, ServerEntry, } from './manifest/OpenApiManifest';
|
|
18
18
|
export { JsonReader } from './manifest/JsonReader';
|
|
19
19
|
export { ManifestLoader } from './manifest/ManifestLoader';
|
|
20
20
|
export { ComponentsInputs, ContractModel, GeneratedDocument, GeneratedDocuments, GenerationInputs, ResolvedResponseHeader, } from './generate/GenerationInputs';
|
|
@@ -27,7 +27,6 @@ export type { SchemaPlacement } from './generate/SchemaPlacement';
|
|
|
27
27
|
export { MissingComponents, PublishedComponents, UpstreamComponentsIndex, } from './generate/UpstreamComponents';
|
|
28
28
|
export { ComponentsLocator, LocatedComponents } from './load/ComponentsLocator';
|
|
29
29
|
export { SecurityDeriver } from './generate/SecurityDeriver';
|
|
30
|
-
export { ExportedConstantFolder } from './load/ExportedConstantFolder';
|
|
31
30
|
export { ForeignFailure } from './load/ForeignFailure';
|
|
32
31
|
export { InputsLoader } from './load/InputsLoader';
|
|
33
32
|
export { ArtifactWriter, GeneratedArtifact } from './emit/ArtifactWriter';
|
package/src/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.WpOpenApiMain = exports.USAGE = exports.OpenApiCli = exports.CliResult = exports.GeneratedArtifact = exports.ArtifactWriter = exports.InputsLoader = exports.ForeignFailure = exports.
|
|
3
|
+
exports.WpOpenApiMain = exports.USAGE = exports.OpenApiCli = exports.CliResult = exports.GeneratedArtifact = exports.ArtifactWriter = exports.InputsLoader = exports.ForeignFailure = exports.SecurityDeriver = exports.LocatedComponents = exports.ComponentsLocator = exports.UpstreamComponentsIndex = exports.PublishedComponents = exports.MissingComponents = exports.SplitPlacement = exports.DiscoveryPlacement = exports.ComponentsReference = exports.BundledPlacement = exports.BundledNames = exports.UnmappedField = exports.SchemaRenderer = exports.ResponseContract = exports.OperationRenderer = exports.OpenApiGenerator = exports.OPERATION_SEMANTICS = exports.INTERNAL_ONLY_LINE = exports.DocumentSelection = exports.ResolvedResponseHeader = exports.GenerationInputs = exports.GeneratedDocuments = exports.GeneratedDocument = exports.ContractModel = exports.ComponentsInputs = exports.ManifestLoader = exports.JsonReader = exports.ServerEntry = exports.ResponseHeaderEntry = exports.OperationIdStyle = exports.OpenApiManifest = exports.ErrorsEntry = exports.ErrorResponseEntry = exports.ComponentsManifest = exports.ApiEntry = exports.YamlReader = exports.YamlWriter = exports.JsonWriter = exports.JsonObject = exports.OpenApiGenerationError = void 0;
|
|
4
4
|
/**
|
|
5
5
|
* `@webpieces/openapi-generator` — render an `ApiDocModel` to OpenAPI 3.1.0.
|
|
6
6
|
*
|
|
@@ -27,6 +27,7 @@ Object.defineProperty(exports, "ComponentsManifest", { enumerable: true, get: fu
|
|
|
27
27
|
Object.defineProperty(exports, "ErrorResponseEntry", { enumerable: true, get: function () { return OpenApiManifest_1.ErrorResponseEntry; } });
|
|
28
28
|
Object.defineProperty(exports, "ErrorsEntry", { enumerable: true, get: function () { return OpenApiManifest_1.ErrorsEntry; } });
|
|
29
29
|
Object.defineProperty(exports, "OpenApiManifest", { enumerable: true, get: function () { return OpenApiManifest_1.OpenApiManifest; } });
|
|
30
|
+
Object.defineProperty(exports, "OperationIdStyle", { enumerable: true, get: function () { return OpenApiManifest_1.OperationIdStyle; } });
|
|
30
31
|
Object.defineProperty(exports, "ResponseHeaderEntry", { enumerable: true, get: function () { return OpenApiManifest_1.ResponseHeaderEntry; } });
|
|
31
32
|
Object.defineProperty(exports, "ServerEntry", { enumerable: true, get: function () { return OpenApiManifest_1.ServerEntry; } });
|
|
32
33
|
var JsonReader_1 = require("./manifest/JsonReader");
|
|
@@ -67,8 +68,6 @@ Object.defineProperty(exports, "ComponentsLocator", { enumerable: true, get: fun
|
|
|
67
68
|
Object.defineProperty(exports, "LocatedComponents", { enumerable: true, get: function () { return ComponentsLocator_1.LocatedComponents; } });
|
|
68
69
|
var SecurityDeriver_1 = require("./generate/SecurityDeriver");
|
|
69
70
|
Object.defineProperty(exports, "SecurityDeriver", { enumerable: true, get: function () { return SecurityDeriver_1.SecurityDeriver; } });
|
|
70
|
-
var ExportedConstantFolder_1 = require("./load/ExportedConstantFolder");
|
|
71
|
-
Object.defineProperty(exports, "ExportedConstantFolder", { enumerable: true, get: function () { return ExportedConstantFolder_1.ExportedConstantFolder; } });
|
|
72
71
|
var ForeignFailure_1 = require("./load/ForeignFailure");
|
|
73
72
|
Object.defineProperty(exports, "ForeignFailure", { enumerable: true, get: function () { return ForeignFailure_1.ForeignFailure; } });
|
|
74
73
|
var InputsLoader_1 = require("./load/InputsLoader");
|
package/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/docs/openapi-generator/src/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;GASG;AACH,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AAEnB,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AACnB,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AACnB,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AACnB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../../packages/docs/openapi-generator/src/index.ts"],"names":[],"mappings":";;;AAAA;;;;;;;;;GASG;AACH,mEAAkE;AAAzD,gIAAA,sBAAsB,OAAA;AAC/B,gDAA+C;AAAtC,wGAAA,UAAU,OAAA;AAEnB,gDAA+C;AAAtC,wGAAA,UAAU,OAAA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AAA,cAAc,OAAA;AACvB,oDAAmD;AAA1C,4GAAA,YAAY,OAAA;AACrB,wDAA0E;AAAjE,gHAAA,cAAc,OAAA;AAAE,mHAAA,iBAAiB,OAAA;AAE1C,+CAAgE;AAAvD,uGAAA,SAAS,OAAA;AAAE,wGAAA,UAAU,OAAA;AAAE,mGAAA,KAAK,OAAA;AACrC,qDAAoD;AAA3C,8GAAA,aAAa,OAAA","sourcesContent":["/**\n * `@webpieces/openapi-generator` — render an `ApiDocModel` to OpenAPI 3.1.0.\n *\n * ONE generation pass produces TWO documents: the CANONICAL internal one, which carries every\n * operation including hidden ones plus the `x-mcp-*` extensions, and the CUSTOMER one, from which a\n * hidden endpoint is absent entirely. They are byte-identical when nothing is hidden, which is the\n * property that makes hiding reviewable — see `responsibilities.md`.\n *\n * It ships the `wp-openapi` bin, and depends on `typescript` and `@webpieces/api-doc-model` alone.\n */\nexport { OpenApiGenerationError } from './OpenApiGenerationError';\nexport { JsonObject } from './json/JsonObject';\nexport type { JsonValue } from './json/JsonObject';\nexport { JsonWriter } from './json/JsonWriter';\nexport { YamlWriter } from './json/YamlWriter';\nexport { YamlReader } from './json/YamlReader';\nexport {\n ApiEntry,\n ComponentsManifest,\n ErrorResponseEntry,\n ErrorsEntry,\n OpenApiManifest,\n OperationIdStyle,\n ResponseHeaderEntry,\n ServerEntry,\n} from './manifest/OpenApiManifest';\nexport { JsonReader } from './manifest/JsonReader';\nexport { ManifestLoader } from './manifest/ManifestLoader';\nexport {\n ComponentsInputs,\n ContractModel,\n GeneratedDocument,\n GeneratedDocuments,\n GenerationInputs,\n ResolvedResponseHeader,\n} from './generate/GenerationInputs';\nexport {\n DocumentSelection,\n INTERNAL_ONLY_LINE,\n OPERATION_SEMANTICS,\n} from './generate/DocumentSelection';\nexport { OpenApiGenerator } from './generate/OpenApiGenerator';\nexport { OperationRenderer, ResponseContract } from './generate/OperationRenderer';\nexport { SchemaRenderer, UnmappedField } from './generate/SchemaRenderer';\nexport {\n BundledNames,\n BundledPlacement,\n ComponentsReference,\n DiscoveryPlacement,\n SplitPlacement,\n} from './generate/SchemaPlacement';\nexport type { SchemaPlacement } from './generate/SchemaPlacement';\nexport {\n MissingComponents,\n PublishedComponents,\n UpstreamComponentsIndex,\n} from './generate/UpstreamComponents';\nexport { ComponentsLocator, LocatedComponents } from './load/ComponentsLocator';\nexport { SecurityDeriver } from './generate/SecurityDeriver';\nexport { ForeignFailure } from './load/ForeignFailure';\nexport { InputsLoader } from './load/InputsLoader';\nexport { ArtifactWriter, GeneratedArtifact } from './emit/ArtifactWriter';\nexport type { OutputFormat } from './emit/ArtifactWriter';\nexport { CliResult, OpenApiCli, USAGE } from './cli/OpenApiCli';\nexport { WpOpenApiMain } from './cli/WpOpenApiMain';\n"]}
|
|
@@ -9,7 +9,6 @@ import { ComponentsInputs, GenerationInputs } from '../generate/GenerationInputs
|
|
|
9
9
|
*/
|
|
10
10
|
export declare class InputsLoader {
|
|
11
11
|
private readonly manifests;
|
|
12
|
-
private readonly constants;
|
|
13
12
|
private extractor;
|
|
14
13
|
private readonly packages;
|
|
15
14
|
private readonly locator;
|
package/src/load/InputsLoader.js
CHANGED
|
@@ -12,7 +12,6 @@ const ManifestLoader_1 = require("../manifest/ManifestLoader");
|
|
|
12
12
|
const GenerationInputs_1 = require("../generate/GenerationInputs");
|
|
13
13
|
const UpstreamComponents_1 = require("../generate/UpstreamComponents");
|
|
14
14
|
const ComponentsLocator_1 = require("./ComponentsLocator");
|
|
15
|
-
const ExportedConstantFolder_1 = require("./ExportedConstantFolder");
|
|
16
15
|
const ForeignFailure_1 = require("./ForeignFailure");
|
|
17
16
|
/** A `path/to/File.ts:12:5` location's FILE. */
|
|
18
17
|
const LINE_AND_COLUMN = /:\d+:\d+$/;
|
|
@@ -44,7 +43,6 @@ const FALLBACK_OPTIONS = {
|
|
|
44
43
|
*/
|
|
45
44
|
class InputsLoader {
|
|
46
45
|
manifests = new ManifestLoader_1.ManifestLoader();
|
|
47
|
-
constants = new ExportedConstantFolder_1.ExportedConstantFolder();
|
|
48
46
|
extractor = new api_doc_model_1.ApiDocExtractor();
|
|
49
47
|
packages = new api_doc_model_1.PackageOfFile();
|
|
50
48
|
locator = new ComponentsLocator_1.ComponentsLocator();
|
|
@@ -207,7 +205,15 @@ class InputsLoader {
|
|
|
207
205
|
responseHeaders(manifestPath, manifest) {
|
|
208
206
|
return manifest.responseHeaders.map((header) => {
|
|
209
207
|
const file = this.manifests.resolve(manifestPath, header.entry);
|
|
210
|
-
|
|
208
|
+
this.mustExist(file, header.entry, manifestPath);
|
|
209
|
+
// eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package
|
|
210
|
+
try {
|
|
211
|
+
return new GenerationInputs_1.ResolvedResponseHeader(this.extractor.extractContextKeyHeader(file, header.contextKey, api_doc_model_1.ContextKeyHeaderSlot.RESPONSE, this.options), header.description, header.required);
|
|
212
|
+
}
|
|
213
|
+
catch (err) {
|
|
214
|
+
//const error = toError(err);
|
|
215
|
+
throw this.rethrow(err, file);
|
|
216
|
+
}
|
|
211
217
|
});
|
|
212
218
|
}
|
|
213
219
|
description(manifestPath, manifest) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"InputsLoader.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/load/InputsLoader.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,uDAAiC;AACjC,4DAMkC;AAClC,oDAAqE;AACrE,sEAAmE;AACnE,+DAA4D;AAE5D,mEAKsC;AACtC,uEAIwC;AACxC,2DAAwD;AACxD,qEAAkE;AAClE,qDAAkD;AAElD,gDAAgD;AAChD,MAAM,eAAe,GAAG,WAAW,CAAC;AAEpC;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAuB;IACzC,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM;IAC9B,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ;IAC9B,gBAAgB,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C,CACjD,CAAC;IACN,CAAC;IAEO,eAAe,CACnB,YAAoB,EACpB,QAAyB;QAEzB,OAAO,QAAQ,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC,MAA2B,EAAE,EAAE;YAChE,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;YAChE,OAAO,IAAI,yCAAsB,CAC7B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,IAAI,EAAE,MAAM,CAAC,YAAY,CAAC,EAC9C,MAAM,CAAC,WAAW,CACrB,CAAC;QACN,CAAC,CAAC,CAAC;IACP,CAAC;IAEO,WAAW,CAAC,YAAoB,EAAE,QAAyB;QAC/D,IAAI,QAAQ,CAAC,eAAe,KAAK,SAAS,EAAE,CAAC;YACzC,OAAO,SAAS,CAAC;QACrB,CAAC;QACD,MAAM,IAAI,GAAG,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,YAAY,EAAE,QAAQ,CAAC,eAAe,CAAC,CAAC;QAC5E,IAAI,CAAC,SAAS,CAAC,IAAI,EAAE,QAAQ,CAAC,eAAe,EAAE,YAAY,CAAC,CAAC;QAC7D,OAAO,EAAE,CAAC,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAC,IAAI,EAAE,CAAC;IAChD,CAAC;IAEO,SAAS,CAAC,IAAY,EAAE,QAAgB,EAAE,YAAoB;QAClE,IAAI,CAAC,EAAE,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE,CAAC;YACvB,MAAM,IAAI,+CAAsB,CAC5B,uBAAuB,QAAQ,yBAAyB,EACxD,YAAY,EACZ,sEAAsE,IAAI,GAAG,CAChF,CAAC;QACN,CAAC;IACL,CAAC;CACJ;AA7OD,oCA6OC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as ts from 'typescript';\nimport {\n ApiComponentsModel,\n ApiDocExtractor,\n DocumentedType,\n PackageOfFile,\n SchemaNames,\n} from '@webpieces/api-doc-model';\nimport { EXTERNAL_CUSTOMER, SVC_TO_SVC } from '@webpieces/core-util';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\nimport { ManifestLoader } from '../manifest/ManifestLoader';\nimport { ApiEntry, OpenApiManifest, ResponseHeaderEntry } from '../manifest/OpenApiManifest';\nimport {\n ComponentsInputs,\n ContractModel,\n GenerationInputs,\n ResolvedResponseHeader,\n} from '../generate/GenerationInputs';\nimport {\n MissingComponents,\n PublishedComponents,\n UpstreamComponentsIndex,\n} from '../generate/UpstreamComponents';\nimport { ComponentsLocator } from './ComponentsLocator';\nimport { ExportedConstantFolder } from './ExportedConstantFolder';\nimport { ForeignFailure } from './ForeignFailure';\n\n/** A `path/to/File.ts:12:5` location's FILE. */\nconst LINE_AND_COLUMN = /:\\d+:\\d+$/;\n\n/**\n * The compiler options the contracts are read with, when the project has no `tsconfig.json` of its\n * own to inherit from (see {@link InputsLoader.compilerOptions}).\n *\n * Decorators must be enabled or a contract does not parse at all, and `skipLibCheck` is on because\n * this is an EXTRACTION pass, not a type-check: the app's own build is what decides whether the\n * contract compiles, and duplicating that judgement here would make `wp-openapi` fail for reasons\n * that have nothing to do with the document.\n */\nconst FALLBACK_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.CommonJS,\n moduleResolution: ts.ModuleResolutionKind.Node10,\n experimentalDecorators: true,\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n};\n\n/**\n * Read everything from disk, ONCE, into {@link GenerationInputs}.\n *\n * Every path in the manifest is resolved against the MANIFEST's own directory, never against the\n * process's cwd. A document whose contents depended on where `wp-openapi` was invoked from would be\n * a different document per caller, and the committed golden would go red depending on which\n * directory a build happened to run in.\n */\nexport class InputsLoader {\n private readonly manifests = new ManifestLoader();\n private readonly constants = new ExportedConstantFolder();\n private extractor = new ApiDocExtractor();\n private readonly packages = new PackageOfFile();\n private readonly locator = new ComponentsLocator();\n private options: ts.CompilerOptions = FALLBACK_OPTIONS;\n\n /** True when `manifestPath` is a DTO library's `\"kind\": \"components\"` manifest. */\n isComponents(manifestPath: string): boolean {\n return this.manifests.isComponents(manifestPath);\n }\n\n load(manifestPath: string): GenerationInputs {\n const manifest = this.manifests.load(manifestPath);\n this.extractor = new ApiDocExtractor(new SchemaNames(manifest.schemaNames));\n this.options = this.compilerOptions(manifestPath);\n const contracts = this.contracts(manifestPath, manifest);\n const errorType = this.errorType(manifestPath, manifest);\n const homePackage = this.packages.of(manifestPath)?.name;\n // Only the SPLIT documents reference other packages' components documents. A contract that\n // feeds nothing but the MCP projection inlines every schema, so it requires no DTO library to\n // publish one (#1058) — and it is not asked to.\n const split = contracts\n .filter(\n (contract: ContractModel) =>\n contract.model.apiTypes.includes(SVC_TO_SVC) ||\n contract.model.apiTypes.includes(EXTERNAL_CUSTOMER),\n )\n .map((contract: ContractModel) => contract.model.types);\n const reached = errorType === undefined ? split : split.concat([errorType.types]);\n return new GenerationInputs(\n manifestPath,\n manifest,\n contracts,\n errorType,\n this.responseHeaders(manifestPath, manifest),\n this.description(manifestPath, manifest),\n homePackage,\n this.upstream(manifestPath, homePackage, reached),\n );\n }\n\n /** A DTO library's components manifest, its exported types, and the libraries THEY reach. */\n loadComponents(manifestPath: string): ComponentsInputs {\n const manifest = this.manifests.loadComponents(manifestPath);\n this.extractor = new ApiDocExtractor(new SchemaNames(manifest.schemaNames));\n this.options = this.compilerOptions(manifestPath);\n const files = manifest.entries.map((entry: string) => {\n const file = this.manifests.resolve(manifestPath, entry);\n this.mustExist(file, entry, manifestPath);\n return file;\n });\n const model = this.extractComponents(files, manifestPath);\n const manifestPackage = this.packages.of(manifestPath)?.name;\n if (manifestPackage !== model.packageName) {\n throw new OpenApiGenerationError(\n `the entries belong to ${model.packageName}, and the manifest to ${manifestPackage ?? 'no package'}`,\n manifestPath,\n \"Keep a DTO library's manifest beside its own package.json, naming that library's entry files.\",\n );\n }\n return new ComponentsInputs(\n manifestPath,\n manifest,\n model,\n this.upstream(manifestPath, model.packageName, [model.types]),\n );\n }\n\n private extractComponents(files: readonly string[], manifestPath: string): ApiComponentsModel {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractComponents(files, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, files[0] ?? manifestPath);\n }\n }\n\n /**\n * The components document of EVERY OTHER package these types are declared in, located once each\n * by {@link ComponentsLocator}. A package that publishes none is recorded, not refused, here: the\n * generator refuses only when a document it renders actually reaches one of its types.\n */\n private upstream(\n manifestPath: string,\n homePackage: string | undefined,\n typeMaps: readonly ReadonlyMap<string, DocumentedType>[],\n ): UpstreamComponentsIndex {\n const declaredIn = new Map<string, string>();\n for (const types of typeMaps) {\n for (const type of types.values()) {\n if (type.packageName === undefined || type.packageName === homePackage) {\n continue;\n }\n if (!declaredIn.has(type.packageName)) {\n declaredIn.set(type.packageName, type.location.replace(LINE_AND_COLUMN, ''));\n }\n }\n }\n const published = new Map<string, PublishedComponents>();\n const missing = new Map<string, MissingComponents>();\n for (const packageName of Array.from(declaredIn.keys()).sort()) {\n const located = this.locator.locate(\n packageName,\n path.dirname(manifestPath),\n this.packages.of(declaredIn.get(packageName)!)?.directory,\n );\n if (located.published !== undefined) {\n published.set(packageName, located.published);\n } else {\n missing.set(packageName, located.missing!);\n }\n }\n return new UpstreamComponentsIndex(published, missing);\n }\n\n /**\n * The nearest `tsconfig.json` at or above the MANIFEST, with the extraction flags forced on.\n *\n * A contract imports its decorators from `@webpieces/core-util`, and a path mapping or a\n * `baseUrl` is what makes that name resolve. Reading the project's own tsconfig is therefore not\n * a convenience — without it the checker cannot see that `POST` is the string `'POST'`, and the\n * constant folder does the right thing and REFUSES rather than guessing a verb. Falling back to\n * a fixed set of options is for a caller with no tsconfig at all, which is a legal thing to be.\n *\n * The flags below are forced over whatever the project says because they are about THIS read and\n * not about the project's build: decorators must parse, nothing may be emitted, and a library\n * type error in `node_modules` is the project's business, not a reason to refuse a document.\n */\n private compilerOptions(manifestPath: string): ts.CompilerOptions {\n const configFile = ts.findConfigFile(path.dirname(manifestPath), (file: string) =>\n ts.sys.fileExists(file),\n );\n if (configFile === undefined) {\n return FALLBACK_OPTIONS;\n }\n const read = ts.readConfigFile(configFile, (file: string) => ts.sys.readFile(file));\n if (read.error !== undefined || read.config === undefined) {\n return FALLBACK_OPTIONS;\n }\n const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, path.dirname(configFile));\n const options = parsed.options;\n options.noEmit = true;\n options.skipLibCheck = true;\n options.experimentalDecorators = true;\n options.composite = false;\n options.declaration = false;\n return options;\n }\n\n private contracts(manifestPath: string, manifest: OpenApiManifest): readonly ContractModel[] {\n return manifest.apis.map((entry: ApiEntry) => {\n const file = this.manifests.resolve(manifestPath, entry.entry);\n this.mustExist(file, entry.entry, manifestPath);\n return new ContractModel(entry, this.extract(file), file);\n });\n }\n\n /**\n * The extractor's own failure is re-thrown as THIS package's one error type, carrying the\n * extractor's location and cure. The alternative — letting `ApiDocExtractionError` out — would\n * give `wp-openapi` two failure types that its top-level handler had to know about, and only one\n * of them would be documented on this package's surface.\n */\n private extract(file: string): ReturnType<ApiDocExtractor['extractFile']> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractFile(file, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, file);\n }\n }\n\n private errorType(\n manifestPath: string,\n manifest: OpenApiManifest,\n ): ReturnType<ApiDocExtractor['extractType']> | undefined {\n const errors = manifest.errors;\n if (errors === undefined) {\n return undefined;\n }\n const file = this.manifests.resolve(manifestPath, errors.entry);\n this.mustExist(file, errors.entry, manifestPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractType(file, errors.type, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, file);\n }\n }\n\n // webpieces-disable no-any-unknown -- a caught value; ForeignFailure is what narrows it\n private rethrow(err: unknown, file: string): OpenApiGenerationError {\n if (err instanceof OpenApiGenerationError) {\n return err;\n }\n return ForeignFailure.of(err).asGenerationError(\n file,\n 'Fix the contract this document is read from.',\n );\n }\n\n private responseHeaders(\n manifestPath: string,\n manifest: OpenApiManifest,\n ): readonly ResolvedResponseHeader[] {\n return manifest.responseHeaders.map((header: ResponseHeaderEntry) => {\n const file = this.manifests.resolve(manifestPath, header.entry);\n return new ResolvedResponseHeader(\n this.constants.fold(file, header.nameConstant),\n header.description,\n );\n });\n }\n\n private description(manifestPath: string, manifest: OpenApiManifest): string | undefined {\n if (manifest.descriptionFile === undefined) {\n return undefined;\n }\n const file = this.manifests.resolve(manifestPath, manifest.descriptionFile);\n this.mustExist(file, manifest.descriptionFile, manifestPath);\n return fs.readFileSync(file, 'utf8').trim();\n }\n\n private mustExist(file: string, declared: string, manifestPath: string): void {\n if (!fs.existsSync(file)) {\n throw new OpenApiGenerationError(\n `the manifest names '${declared}', which does not exist`,\n manifestPath,\n `Paths are relative to the manifest's own directory. Expected it at ${file}.`,\n );\n }\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"InputsLoader.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/load/InputsLoader.ts"],"names":[],"mappings":";;;;AAAA,oDAA8B;AAC9B,wDAAkC;AAClC,uDAAiC;AACjC,4DAOkC;AAClC,oDAAqE;AACrE,sEAAmE;AACnE,+DAA4D;AAE5D,mEAKsC;AACtC,uEAIwC;AACxC,2DAAwD;AACxD,qDAAkD;AAElD,gDAAgD;AAChD,MAAM,eAAe,GAAG,WAAW,CAAC;AAEpC;;;;;;;;GAQG;AACH,MAAM,gBAAgB,GAAuB;IACzC,MAAM,EAAE,EAAE,CAAC,YAAY,CAAC,MAAM;IAC9B,MAAM,EAAE,EAAE,CAAC,UAAU,CAAC,QAAQ;IAC9B,gBAAgB,EAAE,EAAE,CAAC,oBAAoB,CAA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AsB,CAC5B,uBAAuB,QAAQ,yBAAyB,EACxD,YAAY,EACZ,sEAAsE,IAAI,GAAG,CAChF,CAAC;QACN,CAAC;IACL,CAAC;CACJ;AAzPD,oCAyPC","sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport * as ts from 'typescript';\nimport {\n ApiComponentsModel,\n ApiDocExtractor,\n ContextKeyHeaderSlot,\n DocumentedType,\n PackageOfFile,\n SchemaNames,\n} from '@webpieces/api-doc-model';\nimport { EXTERNAL_CUSTOMER, SVC_TO_SVC } from '@webpieces/core-util';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\nimport { ManifestLoader } from '../manifest/ManifestLoader';\nimport { ApiEntry, OpenApiManifest, ResponseHeaderEntry } from '../manifest/OpenApiManifest';\nimport {\n ComponentsInputs,\n ContractModel,\n GenerationInputs,\n ResolvedResponseHeader,\n} from '../generate/GenerationInputs';\nimport {\n MissingComponents,\n PublishedComponents,\n UpstreamComponentsIndex,\n} from '../generate/UpstreamComponents';\nimport { ComponentsLocator } from './ComponentsLocator';\nimport { ForeignFailure } from './ForeignFailure';\n\n/** A `path/to/File.ts:12:5` location's FILE. */\nconst LINE_AND_COLUMN = /:\\d+:\\d+$/;\n\n/**\n * The compiler options the contracts are read with, when the project has no `tsconfig.json` of its\n * own to inherit from (see {@link InputsLoader.compilerOptions}).\n *\n * Decorators must be enabled or a contract does not parse at all, and `skipLibCheck` is on because\n * this is an EXTRACTION pass, not a type-check: the app's own build is what decides whether the\n * contract compiles, and duplicating that judgement here would make `wp-openapi` fail for reasons\n * that have nothing to do with the document.\n */\nconst FALLBACK_OPTIONS: ts.CompilerOptions = {\n target: ts.ScriptTarget.ES2022,\n module: ts.ModuleKind.CommonJS,\n moduleResolution: ts.ModuleResolutionKind.Node10,\n experimentalDecorators: true,\n strict: true,\n noEmit: true,\n skipLibCheck: true,\n};\n\n/**\n * Read everything from disk, ONCE, into {@link GenerationInputs}.\n *\n * Every path in the manifest is resolved against the MANIFEST's own directory, never against the\n * process's cwd. A document whose contents depended on where `wp-openapi` was invoked from would be\n * a different document per caller, and the committed golden would go red depending on which\n * directory a build happened to run in.\n */\nexport class InputsLoader {\n private readonly manifests = new ManifestLoader();\n private extractor = new ApiDocExtractor();\n private readonly packages = new PackageOfFile();\n private readonly locator = new ComponentsLocator();\n private options: ts.CompilerOptions = FALLBACK_OPTIONS;\n\n /** True when `manifestPath` is a DTO library's `\"kind\": \"components\"` manifest. */\n isComponents(manifestPath: string): boolean {\n return this.manifests.isComponents(manifestPath);\n }\n\n load(manifestPath: string): GenerationInputs {\n const manifest = this.manifests.load(manifestPath);\n this.extractor = new ApiDocExtractor(new SchemaNames(manifest.schemaNames));\n this.options = this.compilerOptions(manifestPath);\n const contracts = this.contracts(manifestPath, manifest);\n const errorType = this.errorType(manifestPath, manifest);\n const homePackage = this.packages.of(manifestPath)?.name;\n // Only the SPLIT documents reference other packages' components documents. A contract that\n // feeds nothing but the MCP projection inlines every schema, so it requires no DTO library to\n // publish one (#1058) — and it is not asked to.\n const split = contracts\n .filter(\n (contract: ContractModel) =>\n contract.model.apiTypes.includes(SVC_TO_SVC) ||\n contract.model.apiTypes.includes(EXTERNAL_CUSTOMER),\n )\n .map((contract: ContractModel) => contract.model.types);\n const reached = errorType === undefined ? split : split.concat([errorType.types]);\n return new GenerationInputs(\n manifestPath,\n manifest,\n contracts,\n errorType,\n this.responseHeaders(manifestPath, manifest),\n this.description(manifestPath, manifest),\n homePackage,\n this.upstream(manifestPath, homePackage, reached),\n );\n }\n\n /** A DTO library's components manifest, its exported types, and the libraries THEY reach. */\n loadComponents(manifestPath: string): ComponentsInputs {\n const manifest = this.manifests.loadComponents(manifestPath);\n this.extractor = new ApiDocExtractor(new SchemaNames(manifest.schemaNames));\n this.options = this.compilerOptions(manifestPath);\n const files = manifest.entries.map((entry: string) => {\n const file = this.manifests.resolve(manifestPath, entry);\n this.mustExist(file, entry, manifestPath);\n return file;\n });\n const model = this.extractComponents(files, manifestPath);\n const manifestPackage = this.packages.of(manifestPath)?.name;\n if (manifestPackage !== model.packageName) {\n throw new OpenApiGenerationError(\n `the entries belong to ${model.packageName}, and the manifest to ${manifestPackage ?? 'no package'}`,\n manifestPath,\n \"Keep a DTO library's manifest beside its own package.json, naming that library's entry files.\",\n );\n }\n return new ComponentsInputs(\n manifestPath,\n manifest,\n model,\n this.upstream(manifestPath, model.packageName, [model.types]),\n );\n }\n\n private extractComponents(files: readonly string[], manifestPath: string): ApiComponentsModel {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractComponents(files, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, files[0] ?? manifestPath);\n }\n }\n\n /**\n * The components document of EVERY OTHER package these types are declared in, located once each\n * by {@link ComponentsLocator}. A package that publishes none is recorded, not refused, here: the\n * generator refuses only when a document it renders actually reaches one of its types.\n */\n private upstream(\n manifestPath: string,\n homePackage: string | undefined,\n typeMaps: readonly ReadonlyMap<string, DocumentedType>[],\n ): UpstreamComponentsIndex {\n const declaredIn = new Map<string, string>();\n for (const types of typeMaps) {\n for (const type of types.values()) {\n if (type.packageName === undefined || type.packageName === homePackage) {\n continue;\n }\n if (!declaredIn.has(type.packageName)) {\n declaredIn.set(type.packageName, type.location.replace(LINE_AND_COLUMN, ''));\n }\n }\n }\n const published = new Map<string, PublishedComponents>();\n const missing = new Map<string, MissingComponents>();\n for (const packageName of Array.from(declaredIn.keys()).sort()) {\n const located = this.locator.locate(\n packageName,\n path.dirname(manifestPath),\n this.packages.of(declaredIn.get(packageName)!)?.directory,\n );\n if (located.published !== undefined) {\n published.set(packageName, located.published);\n } else {\n missing.set(packageName, located.missing!);\n }\n }\n return new UpstreamComponentsIndex(published, missing);\n }\n\n /**\n * The nearest `tsconfig.json` at or above the MANIFEST, with the extraction flags forced on.\n *\n * A contract imports its decorators from `@webpieces/core-util`, and a path mapping or a\n * `baseUrl` is what makes that name resolve. Reading the project's own tsconfig is therefore not\n * a convenience — without it the checker cannot see that `POST` is the string `'POST'`, and the\n * constant folder does the right thing and REFUSES rather than guessing a verb. Falling back to\n * a fixed set of options is for a caller with no tsconfig at all, which is a legal thing to be.\n *\n * The flags below are forced over whatever the project says because they are about THIS read and\n * not about the project's build: decorators must parse, nothing may be emitted, and a library\n * type error in `node_modules` is the project's business, not a reason to refuse a document.\n */\n private compilerOptions(manifestPath: string): ts.CompilerOptions {\n const configFile = ts.findConfigFile(path.dirname(manifestPath), (file: string) =>\n ts.sys.fileExists(file),\n );\n if (configFile === undefined) {\n return FALLBACK_OPTIONS;\n }\n const read = ts.readConfigFile(configFile, (file: string) => ts.sys.readFile(file));\n if (read.error !== undefined || read.config === undefined) {\n return FALLBACK_OPTIONS;\n }\n const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, path.dirname(configFile));\n const options = parsed.options;\n options.noEmit = true;\n options.skipLibCheck = true;\n options.experimentalDecorators = true;\n options.composite = false;\n options.declaration = false;\n return options;\n }\n\n private contracts(manifestPath: string, manifest: OpenApiManifest): readonly ContractModel[] {\n return manifest.apis.map((entry: ApiEntry) => {\n const file = this.manifests.resolve(manifestPath, entry.entry);\n this.mustExist(file, entry.entry, manifestPath);\n return new ContractModel(entry, this.extract(file), file);\n });\n }\n\n /**\n * The extractor's own failure is re-thrown as THIS package's one error type, carrying the\n * extractor's location and cure. The alternative — letting `ApiDocExtractionError` out — would\n * give `wp-openapi` two failure types that its top-level handler had to know about, and only one\n * of them would be documented on this package's surface.\n */\n private extract(file: string): ReturnType<ApiDocExtractor['extractFile']> {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractFile(file, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, file);\n }\n }\n\n private errorType(\n manifestPath: string,\n manifest: OpenApiManifest,\n ): ReturnType<ApiDocExtractor['extractType']> | undefined {\n const errors = manifest.errors;\n if (errors === undefined) {\n return undefined;\n }\n const file = this.manifests.resolve(manifestPath, errors.entry);\n this.mustExist(file, errors.entry, manifestPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return this.extractor.extractType(file, errors.type, this.options);\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, file);\n }\n }\n\n // webpieces-disable no-any-unknown -- a caught value; ForeignFailure is what narrows it\n private rethrow(err: unknown, file: string): OpenApiGenerationError {\n if (err instanceof OpenApiGenerationError) {\n return err;\n }\n return ForeignFailure.of(err).asGenerationError(\n file,\n 'Fix the contract this document is read from.',\n );\n }\n\n private responseHeaders(\n manifestPath: string,\n manifest: OpenApiManifest,\n ): readonly ResolvedResponseHeader[] {\n return manifest.responseHeaders.map((header: ResponseHeaderEntry) => {\n const file = this.manifests.resolve(manifestPath, header.entry);\n this.mustExist(file, header.entry, manifestPath);\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package\n try {\n return new ResolvedResponseHeader(\n this.extractor.extractContextKeyHeader(\n file,\n header.contextKey,\n ContextKeyHeaderSlot.RESPONSE,\n this.options,\n ),\n header.description,\n header.required,\n );\n } catch (err: unknown) {\n //const error = toError(err);\n throw this.rethrow(err, file);\n }\n });\n }\n\n private description(manifestPath: string, manifest: OpenApiManifest): string | undefined {\n if (manifest.descriptionFile === undefined) {\n return undefined;\n }\n const file = this.manifests.resolve(manifestPath, manifest.descriptionFile);\n this.mustExist(file, manifest.descriptionFile, manifestPath);\n return fs.readFileSync(file, 'utf8').trim();\n }\n\n private mustExist(file: string, declared: string, manifestPath: string): void {\n if (!fs.existsSync(file)) {\n throw new OpenApiGenerationError(\n `the manifest names '${declared}', which does not exist`,\n manifestPath,\n `Paths are relative to the manifest's own directory. Expected it at ${file}.`,\n );\n }\n }\n}\n"]}
|
|
@@ -28,6 +28,8 @@ export declare class JsonReader {
|
|
|
28
28
|
/** A required, non-empty string. */
|
|
29
29
|
string(field: string): string;
|
|
30
30
|
optionalString(field: string): string | undefined;
|
|
31
|
+
/** A boolean, or undefined when the field is absent. Anything else present is refused. */
|
|
32
|
+
optionalBoolean(field: string): boolean | undefined;
|
|
31
33
|
/** An array of strings, empty when the field is absent. */
|
|
32
34
|
strings(field: string): readonly string[];
|
|
33
35
|
/** A nested object, or undefined when the field is absent. */
|
|
@@ -72,6 +72,18 @@ class JsonReader {
|
|
|
72
72
|
const value = this.entries.get(field);
|
|
73
73
|
return typeof value === 'string' && value !== '' ? value : undefined;
|
|
74
74
|
}
|
|
75
|
+
/** A boolean, or undefined when the field is absent. Anything else present is refused. */
|
|
76
|
+
optionalBoolean(field) {
|
|
77
|
+
// webpieces-disable no-any-unknown -- the raw entry, narrowed below
|
|
78
|
+
const value = this.entries.get(field);
|
|
79
|
+
if (value === undefined) {
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
82
|
+
if (typeof value !== 'boolean') {
|
|
83
|
+
throw new OpenApiGenerationError_1.OpenApiGenerationError(`'${field}' is not a boolean`, this.where, `Write "${field}" as true or false, or leave it out.`);
|
|
84
|
+
}
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
75
87
|
/** An array of strings, empty when the field is absent. */
|
|
76
88
|
strings(field) {
|
|
77
89
|
// webpieces-disable no-any-unknown -- the raw entry, narrowed below
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"JsonReader.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/manifest/JsonReader.ts"],"names":[],"mappings":";;;AAAA,sEAAmE;AAEnE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,UAAU;IAGE;IAER;IAJb;IACI,sJAAsJ;IACrI,OAAqC;IACtD,mFAAmF;IAC1E,KAAa;QAFL,YAAO,GAAP,OAAO,CAA8B;QAE7C,UAAK,GAAL,KAAK,CAAQ;IACvB,CAAC;IAEJ,0BAA0B;IAC1B,8IAA8I;IAC9I,MAAM,CAAC,SAAS,CAAC,IAAY,EAAE,KAAa;QAC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G,CAAC,CAAC;IAC5F,CAAC;IAED,2DAA2D;IAC3D,OAAO,CAAC,KAAa;QACjB,oEAAoE;QACpE,MAAM,KAAK,GAAY,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC/C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,OAAO,EAAE,CAAC;QACd,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACxB,MAAM,IAAI,+CAAsB,CAC5B,IAAI,KAAK,mBAAmB,EAC5B,IAAI,CAAC,KAAK,EACV,UAAU,KAAK,qCAAqC,CACvD,CAAC;QACN,CAAC;QACD,0EAA0E;QAC1E,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAa,EAAE,EAAE,CAC/B,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,gBAAgB,KAAK,GAAG,CAAC,CAC5D,CAAC;IACN,CAAC;CACJ;AA9GD,gCA8GC","sourcesContent":["import { OpenApiGenerationError } from '../OpenApiGenerationError';\n\n/**\n * A narrowing reader over ONE parsed JSON object.\n *\n * ## Why this class exists at all\n *\n * `JSON.parse` returns something with no shape, and a loader that passed that shapelessness around\n * would spread it over every method that touches the manifest. Concentrating it HERE means the rest\n * of the package deals only in `string`, `JsonReader` and the manifest classes — and it means the\n * \"this value came off disk and has not been checked yet\" state exists in exactly one file, where a\n * reader can see every check that state is subjected to.\n *\n * ## Every miss is a HARD FAILURE naming the field\n *\n * There is deliberately no defaulting of anything a reader would notice. A published document quietly\n * missing a section is indistinguishable, from the outside, from an API that genuinely has no error\n * contract — so a mistyped `errors` must stop the run rather than silently publish less.\n */\nexport class JsonReader {\n private constructor(\n // webpieces-disable no-any-unknown -- parsed JSON is genuinely shapeless until the accessors below narrow it; this is the ONE place that state exists\n private readonly entries: ReadonlyMap<string, unknown>,\n /** The file this came from, so every failure names something somebody can open. */\n readonly where: string,\n ) {}\n\n /** Parse a whole file. */\n // webpieces-disable no-function-outside-class -- static factory; the private constructor is what keeps unchecked JSON out of every other file\n static parseFile(text: string, where: string): JsonReader {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package, with its cure\n try {\n // webpieces-disable no-any-unknown -- JSON.parse's result, before anything has narrowed it\n const parsed: unknown = JSON.parse(text);\n return JsonReader.of(parsed, where, 'the manifest');\n } catch (err: unknown) {\n //const error = toError(err);\n if (err instanceof OpenApiGenerationError) {\n throw err;\n }\n throw new OpenApiGenerationError(\n `not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n where,\n 'Fix the JSON syntax. The manifest is read before anything else runs.',\n );\n }\n }\n\n /** One already-parsed value that must be an object. */\n // webpieces-disable no-any-unknown -- the value has not been narrowed yet; that is this method's job\n // webpieces-disable no-function-outside-class -- static factory of this class\n private static of(value: unknown, where: string, what: string): JsonReader {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new OpenApiGenerationError(\n `${what} is not a JSON object`,\n where,\n 'Write it as a JSON object — one `{ ... }` with named fields.',\n );\n }\n return new JsonReader(new Map(Object.entries(value)), where);\n }\n\n has(field: string): boolean {\n return this.entries.get(field) !== undefined;\n }\n\n /** A required, non-empty string. */\n string(field: string): string {\n const value = this.optionalString(field);\n if (value === undefined) {\n throw new OpenApiGenerationError(\n `'${field}' is missing or is not a non-empty string`,\n this.where,\n `Give \"${field}\" a value; an empty one publishes a document nobody can identify.`,\n );\n }\n return value;\n }\n\n optionalString(field: string): string | undefined {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed on the next line\n const value: unknown = this.entries.get(field);\n return typeof value === 'string' && value !== '' ? value : undefined;\n }\n\n /** An array of strings, empty when the field is absent. */\n strings(field: string): readonly string[] {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed below\n const value: unknown = this.entries.get(field);\n if (value === undefined) {\n return [];\n }\n // webpieces-disable no-any-unknown -- element of a not-yet-narrowed array\n if (!Array.isArray(value) || value.some((each: unknown) => typeof each !== 'string')) {\n throw new OpenApiGenerationError(\n `'${field}' is not an array of strings`,\n this.where,\n `Write \"${field}\" as a JSON array of strings, or leave it out.`,\n );\n }\n return value as readonly string[];\n }\n\n /** A nested object, or undefined when the field is absent. */\n object(field: string): JsonReader | undefined {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed by `of`\n const value: unknown = this.entries.get(field);\n return value === undefined ? undefined : JsonReader.of(value, this.where, `'${field}'`);\n }\n\n /** An array of objects, empty when the field is absent. */\n objects(field: string): readonly JsonReader[] {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed below\n const value: unknown = this.entries.get(field);\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new OpenApiGenerationError(\n `'${field}' is not an array`,\n this.where,\n `Write \"${field}\" as a JSON array, or leave it out.`,\n );\n }\n // webpieces-disable no-any-unknown -- element of a not-yet-narrowed array\n return value.map((each: unknown) =>\n JsonReader.of(each, this.where, `an entry of '${field}'`),\n );\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"JsonReader.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/manifest/JsonReader.ts"],"names":[],"mappings":";;;AAAA,sEAAmE;AAEnE;;;;;;;;;;;;;;;;GAgBG;AACH,MAAa,UAAU;IAGE;IAER;IAJb;IACI,sJAAsJ;IACrI,OAAqC;IACtD,mFAAmF;IAC1E,KAAa;QAFL,YAAO,GAAP,OAAO,CAA8B;QAE7C,UAAK,GAAL,KAAK,CAAQ;IACvB,CAAC;IAEJ,0BAA0B;IAC1B,8IAA8I;IAC9I,MAAM,CAAC,SAAS,CAAC,IAAY,EAAE,KAAa;QACxC,gIAAgI;QAChI,IAAI,CAAC;YACD,2FAA2F;YAC3F,MAAM,MAAM,GAAY,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;YACzC,OAAO,UAAU,CAAC,EAAE,CAAC,MAAM,EAAE,KAAK,EAAE,cAAc,CAAC,CAAC;Q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sE;QACtE,MAAM,KAAK,GAAY,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC/C,OAAO,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU,CAAC,EAAE,CAAC,KAAK,EAAE,IAAI,CAAC,KAAK,EAAE,IAAI,KAAK,GAAG,CAAC,CAAC;IAC5F,CAAC;IAED,2DAA2D;IAC3D,OAAO,CAAC,KAAa;QACjB,oEAAoE;QACpE,MAAM,KAAK,GAAY,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;QAC/C,IAAI,KAAK,KAAK,SAAS,EAAE,CAAC;YACtB,OAAO,EAAE,CAAC;QACd,CAAC;QACD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,CAAC;YACxB,MAAM,IAAI,+CAAsB,CAC5B,IAAI,KAAK,mBAAmB,EAC5B,IAAI,CAAC,KAAK,EACV,UAAU,KAAK,qCAAqC,CACvD,CAAC;QACN,CAAC;QACD,0EAA0E;QAC1E,OAAO,KAAK,CAAC,GAAG,CAAC,CAAC,IAAa,EAAE,EAAE,CAC/B,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,IAAI,CAAC,KAAK,EAAE,gBAAgB,KAAK,GAAG,CAAC,CAC5D,CAAC;IACN,CAAC;CACJ;AA/HD,gCA+HC","sourcesContent":["import { OpenApiGenerationError } from '../OpenApiGenerationError';\n\n/**\n * A narrowing reader over ONE parsed JSON object.\n *\n * ## Why this class exists at all\n *\n * `JSON.parse` returns something with no shape, and a loader that passed that shapelessness around\n * would spread it over every method that touches the manifest. Concentrating it HERE means the rest\n * of the package deals only in `string`, `JsonReader` and the manifest classes — and it means the\n * \"this value came off disk and has not been checked yet\" state exists in exactly one file, where a\n * reader can see every check that state is subjected to.\n *\n * ## Every miss is a HARD FAILURE naming the field\n *\n * There is deliberately no defaulting of anything a reader would notice. A published document quietly\n * missing a section is indistinguishable, from the outside, from an API that genuinely has no error\n * contract — so a mistyped `errors` must stop the run rather than silently publish less.\n */\nexport class JsonReader {\n private constructor(\n // webpieces-disable no-any-unknown -- parsed JSON is genuinely shapeless until the accessors below narrow it; this is the ONE place that state exists\n private readonly entries: ReadonlyMap<string, unknown>,\n /** The file this came from, so every failure names something somebody can open. */\n readonly where: string,\n ) {}\n\n /** Parse a whole file. */\n // webpieces-disable no-function-outside-class -- static factory; the private constructor is what keeps unchecked JSON out of every other file\n static parseFile(text: string, where: string): JsonReader {\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- re-thrown as the ONE error type of this package, with its cure\n try {\n // webpieces-disable no-any-unknown -- JSON.parse's result, before anything has narrowed it\n const parsed: unknown = JSON.parse(text);\n return JsonReader.of(parsed, where, 'the manifest');\n } catch (err: unknown) {\n //const error = toError(err);\n if (err instanceof OpenApiGenerationError) {\n throw err;\n }\n throw new OpenApiGenerationError(\n `not valid JSON: ${err instanceof Error ? err.message : String(err)}`,\n where,\n 'Fix the JSON syntax. The manifest is read before anything else runs.',\n );\n }\n }\n\n /** One already-parsed value that must be an object. */\n // webpieces-disable no-any-unknown -- the value has not been narrowed yet; that is this method's job\n // webpieces-disable no-function-outside-class -- static factory of this class\n private static of(value: unknown, where: string, what: string): JsonReader {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n throw new OpenApiGenerationError(\n `${what} is not a JSON object`,\n where,\n 'Write it as a JSON object — one `{ ... }` with named fields.',\n );\n }\n return new JsonReader(new Map(Object.entries(value)), where);\n }\n\n has(field: string): boolean {\n return this.entries.get(field) !== undefined;\n }\n\n /** A required, non-empty string. */\n string(field: string): string {\n const value = this.optionalString(field);\n if (value === undefined) {\n throw new OpenApiGenerationError(\n `'${field}' is missing or is not a non-empty string`,\n this.where,\n `Give \"${field}\" a value; an empty one publishes a document nobody can identify.`,\n );\n }\n return value;\n }\n\n optionalString(field: string): string | undefined {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed on the next line\n const value: unknown = this.entries.get(field);\n return typeof value === 'string' && value !== '' ? value : undefined;\n }\n\n /** A boolean, or undefined when the field is absent. Anything else present is refused. */\n optionalBoolean(field: string): boolean | undefined {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed below\n const value: unknown = this.entries.get(field);\n if (value === undefined) {\n return undefined;\n }\n if (typeof value !== 'boolean') {\n throw new OpenApiGenerationError(\n `'${field}' is not a boolean`,\n this.where,\n `Write \"${field}\" as true or false, or leave it out.`,\n );\n }\n return value;\n }\n\n /** An array of strings, empty when the field is absent. */\n strings(field: string): readonly string[] {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed below\n const value: unknown = this.entries.get(field);\n if (value === undefined) {\n return [];\n }\n // webpieces-disable no-any-unknown -- element of a not-yet-narrowed array\n if (!Array.isArray(value) || value.some((each: unknown) => typeof each !== 'string')) {\n throw new OpenApiGenerationError(\n `'${field}' is not an array of strings`,\n this.where,\n `Write \"${field}\" as a JSON array of strings, or leave it out.`,\n );\n }\n return value as readonly string[];\n }\n\n /** A nested object, or undefined when the field is absent. */\n object(field: string): JsonReader | undefined {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed by `of`\n const value: unknown = this.entries.get(field);\n return value === undefined ? undefined : JsonReader.of(value, this.where, `'${field}'`);\n }\n\n /** An array of objects, empty when the field is absent. */\n objects(field: string): readonly JsonReader[] {\n // webpieces-disable no-any-unknown -- the raw entry, narrowed below\n const value: unknown = this.entries.get(field);\n if (value === undefined) {\n return [];\n }\n if (!Array.isArray(value)) {\n throw new OpenApiGenerationError(\n `'${field}' is not an array`,\n this.where,\n `Write \"${field}\" as a JSON array, or leave it out.`,\n );\n }\n // webpieces-disable no-any-unknown -- element of a not-yet-narrowed array\n return value.map((each: unknown) =>\n JsonReader.of(each, this.where, `an entry of '${field}'`),\n );\n }\n}\n"]}
|
|
@@ -19,6 +19,11 @@ export declare class ManifestLoader {
|
|
|
19
19
|
private read;
|
|
20
20
|
/** @param manifestPath absolute path to a CONTRACT library's `openapi.manifest.json`. */
|
|
21
21
|
load(manifestPath: string): OpenApiManifest;
|
|
22
|
+
/**
|
|
23
|
+
* REQUIRED, with no default (#1270): the operationId is the method name in every client a
|
|
24
|
+
* partner generates, so its spelling is the consumer's decision, stated in the manifest.
|
|
25
|
+
*/
|
|
26
|
+
private operationIds;
|
|
22
27
|
private servers;
|
|
23
28
|
private schemaNames;
|
|
24
29
|
private apis;
|