@webpieces/openapi-generator 0.4.811 → 0.4.813
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 +11 -7
- package/package.json +3 -3
- package/src/cli/OpenApiCli.d.ts +10 -7
- package/src/cli/OpenApiCli.js +15 -13
- package/src/cli/OpenApiCli.js.map +1 -1
- package/src/cli/WpOpenApiMain.js +1 -1
- package/src/cli/WpOpenApiMain.js.map +1 -1
- package/src/generate/SchemaRenderer.d.ts +2 -1
- package/src/generate/SchemaRenderer.js +5 -3
- package/src/generate/SchemaRenderer.js.map +1 -1
package/README.md
CHANGED
|
@@ -27,7 +27,8 @@ customer-facing surface on one screen.
|
|
|
27
27
|
`--format` picks the serialization of whichever documents exist, and defaults to `both`.
|
|
28
28
|
|
|
29
29
|
`diff full-private-openapi.json public-openapi.json` is the complete list of what you do not show a
|
|
30
|
-
customer.
|
|
30
|
+
customer. Neither is committed — both are build output (see "In an nx workspace" below); diff the two
|
|
31
|
+
the build wrote when you need that list.
|
|
31
32
|
|
|
32
33
|
## Hiding ONE method
|
|
33
34
|
|
|
@@ -101,10 +102,12 @@ carries only what JSDoc cannot say: the stable protocol name. `readOnlyHint`, `d
|
|
|
101
102
|
`idempotentHint` are computed from the endpoint's declared `operation`; `openWorldHint` comes from
|
|
102
103
|
`{ openWorld: true }` on the endpoint.
|
|
103
104
|
|
|
104
|
-
Alongside `mcp-openapi.json`, a run writes **`mcp
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
105
|
+
Alongside `mcp-openapi.json`, a run writes ONE **`mcp-<ContractClass>-tools.json`** per contract that
|
|
106
|
+
declares `MCP` and has at least one `@WpMcpTool` (e.g. `mcp-PartnerOrdersApi-tools.json`). Those are
|
|
107
|
+
not documents: they are the RUNTIME catalogs `WpMcpServer` boots from, so the schema an agent is shown
|
|
108
|
+
in `tools/list` and the schema the server validates a call against are the same bytes. One file per
|
|
109
|
+
contract because a server binds contracts, and checks each binding against exactly its own contract's
|
|
110
|
+
file. `--format` does not apply to them.
|
|
108
111
|
|
|
109
112
|
## It refuses to publish a field it has no schema for
|
|
110
113
|
|
|
@@ -119,8 +122,9 @@ is no flag to switch that off — the cure is at the contract, by naming the typ
|
|
|
119
122
|
|
|
120
123
|
## In an nx workspace
|
|
121
124
|
|
|
122
|
-
Inside nx, nobody chooses `--out
|
|
123
|
-
|
|
125
|
+
Inside nx, nobody chooses `--out`. Tag the api library `generate:openapi` and the
|
|
126
|
+
`@webpieces/nx-webpieces-rules` plugin infers an `openapi-generate` target that writes into the
|
|
127
|
+
outputPath of the library's `build` (the @nx/js:tsc target it dependsOn), so the documents are packed and published inside the api
|
|
124
128
|
library's package, and are never committed. It runs THIS package from the consumer's `node_modules`
|
|
125
129
|
and refuses one older than it needs. See `.claude/rules/api-docs.md` in webpieces-ts.
|
|
126
130
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@webpieces/openapi-generator",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.813",
|
|
4
4
|
"description": "Render an ApiDocModel to OpenAPI 3.1.0 — the canonical internal document and the customer-published one, JSON and YAML, from one generation pass. Ships the wp-openapi bin.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -23,8 +23,8 @@
|
|
|
23
23
|
"access": "public"
|
|
24
24
|
},
|
|
25
25
|
"dependencies": {
|
|
26
|
-
"@webpieces/api-doc-model": "0.4.
|
|
27
|
-
"@webpieces/core-util": "0.4.
|
|
26
|
+
"@webpieces/api-doc-model": "0.4.813",
|
|
27
|
+
"@webpieces/core-util": "0.4.813",
|
|
28
28
|
"typescript": "5.9.3"
|
|
29
29
|
},
|
|
30
30
|
"bin": {
|
package/src/cli/OpenApiCli.d.ts
CHANGED
|
@@ -28,15 +28,18 @@ export declare class OpenApiCli {
|
|
|
28
28
|
run(argv: readonly string[], cwd: string): CliResult;
|
|
29
29
|
wantsHelp(argv: readonly string[]): boolean;
|
|
30
30
|
/**
|
|
31
|
-
* `mcp
|
|
31
|
+
* `mcp-<ContractClass>-tools.json` — the RUNTIME artifacts, one per contract, beside the three
|
|
32
|
+
* documents.
|
|
32
33
|
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
34
|
+
* They are not documents and are not serialized by `--format`: `WpMcpServer` boots from them, and
|
|
35
|
+
* `McpToolRegistry` checks every `McpApiBinding` against the file generated from exactly that
|
|
36
|
+
* contract, failing fast at boot when one is missing (#1021). That is what took the MCP runtime off
|
|
37
|
+
* reflect-metadata (#984) — the schema an agent is shown and the schema the server accepts are now
|
|
38
|
+
* the same bytes, rather than two derivations of one contract.
|
|
37
39
|
*
|
|
38
|
-
* Written only
|
|
39
|
-
* follows, for the same reason: an empty file is a claim that there
|
|
40
|
+
* Written only for a contract that declares `MCP` and has at least one renderable tool, which is
|
|
41
|
+
* the same rule `mcp-openapi.json` follows, for the same reason: an empty file is a claim that there
|
|
42
|
+
* are no tools.
|
|
40
43
|
*/
|
|
41
44
|
private static mcpCatalog;
|
|
42
45
|
/** `both` unless told otherwise: the second serialization comes free from the same document. */
|
package/src/cli/OpenApiCli.js
CHANGED
|
@@ -25,8 +25,9 @@ exports.USAGE = [
|
|
|
25
25
|
' public-openapi contracts declaring EXTERNAL_CUSTOMER, minus every { hidden: true } method',
|
|
26
26
|
' mcp-openapi contracts declaring MCP, carrying the x-mcp-* extensions',
|
|
27
27
|
'',
|
|
28
|
-
'Alongside them, mcp
|
|
29
|
-
'
|
|
28
|
+
'Alongside them, one mcp-<ContractClass>-tools.json is written per contract that declares MCP',
|
|
29
|
+
'and has an @WpMcpTool: the RUNTIME catalogs WpMcpServer boots from. They are not documents, so',
|
|
30
|
+
'--format does not apply.',
|
|
30
31
|
'',
|
|
31
32
|
'A document no contract asked for is not written. --format chooses the serialization of',
|
|
32
33
|
'whichever documents were written, and defaults to both.',
|
|
@@ -48,7 +49,7 @@ class CliResult {
|
|
|
48
49
|
}
|
|
49
50
|
}
|
|
50
51
|
exports.CliResult = CliResult;
|
|
51
|
-
/** The MCP half of one run: the
|
|
52
|
+
/** The MCP half of one run: the per-contract catalogs to write, and what they could not carry. */
|
|
52
53
|
class McpArtifacts {
|
|
53
54
|
artifacts;
|
|
54
55
|
skipped;
|
|
@@ -90,15 +91,18 @@ class OpenApiCli {
|
|
|
90
91
|
return argv.includes(HELP);
|
|
91
92
|
}
|
|
92
93
|
/**
|
|
93
|
-
* `mcp
|
|
94
|
+
* `mcp-<ContractClass>-tools.json` — the RUNTIME artifacts, one per contract, beside the three
|
|
95
|
+
* documents.
|
|
94
96
|
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
*
|
|
97
|
+
* They are not documents and are not serialized by `--format`: `WpMcpServer` boots from them, and
|
|
98
|
+
* `McpToolRegistry` checks every `McpApiBinding` against the file generated from exactly that
|
|
99
|
+
* contract, failing fast at boot when one is missing (#1021). That is what took the MCP runtime off
|
|
100
|
+
* reflect-metadata (#984) — the schema an agent is shown and the schema the server accepts are now
|
|
101
|
+
* the same bytes, rather than two derivations of one contract.
|
|
99
102
|
*
|
|
100
|
-
* Written only
|
|
101
|
-
* follows, for the same reason: an empty file is a claim that there
|
|
103
|
+
* Written only for a contract that declares `MCP` and has at least one renderable tool, which is
|
|
104
|
+
* the same rule `mcp-openapi.json` follows, for the same reason: an empty file is a claim that there
|
|
105
|
+
* are no tools.
|
|
102
106
|
*/
|
|
103
107
|
// webpieces-disable no-function-outside-class -- private static composition step of this class
|
|
104
108
|
static mcpCatalog(inputs) {
|
|
@@ -109,9 +113,7 @@ class OpenApiCli {
|
|
|
109
113
|
return new McpArtifacts([], []);
|
|
110
114
|
}
|
|
111
115
|
const rendered = api_doc_model_1.McpSchemaRenderer.catalogOf(models);
|
|
112
|
-
const artifacts = rendered.catalog.
|
|
113
|
-
? []
|
|
114
|
-
: [new ArtifactWriter_1.GeneratedArtifact('mcp-tools.json', rendered.catalog.toJsonText())];
|
|
116
|
+
const artifacts = rendered.catalogs.map((catalog) => new ArtifactWriter_1.GeneratedArtifact(catalog.fileName, catalog.toJsonText()));
|
|
115
117
|
return new McpArtifacts(artifacts, rendered.skipped);
|
|
116
118
|
}
|
|
117
119
|
/** `both` unless told otherwise: the second serialization comes free from the same document. */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OpenApiCli.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/cli/OpenApiCli.ts"],"names":[],"mappings":";;;;AAAA,wDAAkC;AAClC,oDAA2C;AAC3C,4DAA+F;AAC/F,2DAAyF;AAEzF,mEAAgE;AAChE,uDAAoD;AACpD,sEAAmE;AAEnE,MAAM,QAAQ,GAAG,YAAY,CAAC;AAC9B,MAAM,GAAG,GAAG,OAAO,CAAC;AACpB,MAAM,MAAM,GAAG,UAAU,CAAC;AAC1B,MAAM,IAAI,GAAG,QAAQ,CAAC;AAEtB,MAAM,KAAK,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,MAAM,CAAC,CAAC;AACtC,MAAM,OAAO,GAAsB,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAE/C,QAAA,KAAK,GAAG;IACjB,qFAAqF;IACrF,EAAE;IACF,6FAA6F;IAC7F,+FAA+F;IAC/F,EAAE;IACF,uFAAuF;IACvF,qGAAqG;IACrG,mFAAmF;IACnF,EAAE;IACF,4FAA4F;IAC5F,6FAA6F;IAC7F,EAAE;IACF,wFAAwF;IACxF,yDAAyD;IACzD,EAAE;IACF,4FAA4F;IAC5F,wFAAwF;CAC3F,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAEb,yFAAyF;AACzF,MAAa,SAAS;IAEL;IACA;IAEA;IAJb,YACa,OAA0B,EAC1B,SAAuC;IAChD,oFAAoF;IAC3E,kBAA6C,EAAE;QAH/C,YAAO,GAAP,OAAO,CAAmB;QAC1B,cA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AI,EAAE,MAAM,CAAC,CAAC;QAC5C,IAAI,QAAQ,KAAK,SAAS,EAAE,CAAC;YACzB,OAAO,MAAM,CAAC;QAClB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;YAC9B,MAAM,IAAI,+CAAsB,CAC5B,WAAW,MAAM,KAAK,QAAQ,GAAG,EACjC,YAAY,EACZ,GAAG,MAAM,kBAAkB,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CACnD,CAAC;QACN,CAAC;QACD,OAAO,QAAwB,CAAC;IACpC,CAAC;IAED;;;;OAIG;IACK,OAAO,CAAC,IAAuB,EAAE,IAAY;QACjD,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YACnC,MAAM,QAAQ,GAAG,IAAI,CAAC,CAAC,CAAE,CAAC;YAC1B,IAAI,QAAQ,KAAK,IAAI,EAAE,CAAC;gBACpB,OAAO,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;YACvB,CAAC;YACD,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACzD,MAAM,IAAI,+CAAsB,CAC5B,iBAAiB,QAAQ,GAAG,EAC5B,YAAY,EACZ,oBAAoB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAC5D,CAAC;YACN,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;CACJ;AAlGD,gCAkGC","sourcesContent":["import * as path from 'node:path';\nimport { MCP } from '@webpieces/core-util';\nimport { McpCatalogRender, McpSchemaRenderer, SkippedMcpTool } from '@webpieces/api-doc-model';\nimport { ArtifactWriter, GeneratedArtifact, OutputFormat } from '../emit/ArtifactWriter';\nimport { ContractModel, GenerationInputs } from '../generate/GenerationInputs';\nimport { OpenApiGenerator } from '../generate/OpenApiGenerator';\nimport { InputsLoader } from '../load/InputsLoader';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\n\nconst MANIFEST = '--manifest';\nconst OUT = '--out';\nconst FORMAT = '--format';\nconst HELP = '--help';\n\nconst FLAGS = [MANIFEST, OUT, FORMAT];\nconst FORMATS: readonly string[] = ['json', 'yaml', 'both'];\n\nexport const USAGE = [\n 'wp-openapi --manifest <openapi.manifest.json> --out <dir> [--format json|yaml|both]',\n '',\n 'Renders the contracts a manifest names into OpenAPI 3.1.0. WHICH documents are written is a',\n \"property of the contracts themselves — each one's @ApiType(...) names the documents it feeds:\",\n '',\n ' full-private-openapi every contract declaring SVC_TO_SVC, hidden methods included',\n ' public-openapi contracts declaring EXTERNAL_CUSTOMER, minus every { hidden: true } method',\n ' mcp-openapi contracts declaring MCP, carrying the x-mcp-* extensions',\n '',\n 'Alongside them, mcp-tools.json is written whenever some contract declares MCP: the RUNTIME',\n 'artifact WpMcpServer is constructed with. It is not a document, so --format does not apply.',\n '',\n 'A document no contract asked for is not written. --format chooses the serialization of',\n 'whichever documents were written, and defaults to both.',\n '',\n 'It exits non-zero, naming the JSON pointer of every offending field, rather than writing a',\n 'document containing a field it has no schema for. There is no flag to switch that off.',\n].join('\\n');\n\n/** The result of one run: what was written, so a caller can print it or assert on it. */\nexport class CliResult {\n constructor(\n readonly written: readonly string[],\n readonly artifacts: readonly GeneratedArtifact[],\n /** `@WpMcpTool`s the MCP catalog could not carry, with the reason. Never silent. */\n readonly skippedMcpTools: readonly SkippedMcpTool[] = [],\n ) {}\n}\n\n/** The MCP half of one run: the artifact to write, if any, and what it could not carry. */\nclass McpArtifacts {\n constructor(\n readonly artifacts: readonly GeneratedArtifact[],\n readonly skipped: readonly SkippedMcpTool[],\n ) {}\n}\n\n/**\n * `wp-openapi`'s argument parsing and composition, with NO process-level concerns in it — no\n * `process.exit`, no `console` — so the whole command is exercised by the suite exactly as a user\n * runs it. The bin is the only thing that knows about the process.\n *\n * `--manifest` and `--out` are REQUIRED and have no defaults. A defaulted `--out` writes generated\n * documents somewhere the caller did not name, and a defaulted `--manifest` picks a service out of\n * whatever directory the command happened to start in.\n */\nexport class OpenApiCli {\n private readonly loader = new InputsLoader();\n private readonly generator = new OpenApiGenerator();\n private readonly writer = new ArtifactWriter();\n\n /** @param argv the arguments AFTER the program name. @param cwd what relative paths resolve against. */\n run(argv: readonly string[], cwd: string): CliResult {\n const manifest = this.valueOf(argv, MANIFEST);\n const out = this.valueOf(argv, OUT);\n if (manifest === undefined || out === undefined) {\n throw new OpenApiGenerationError(\n `wp-openapi needs both ${MANIFEST} and ${OUT}`,\n 'wp-openapi',\n `Run: wp-openapi ${MANIFEST} <openapi.manifest.json> ${OUT} <dir>`,\n );\n }\n const inputs = this.loader.load(path.resolve(cwd, manifest));\n const documents = this.generator.generate(inputs);\n const mcp = OpenApiCli.mcpCatalog(inputs);\n const artifacts = [\n ...this.writer.artifacts(documents, this.formatOf(argv)),\n ...mcp.artifacts,\n ];\n return new CliResult(\n this.writer.write(path.resolve(cwd, out), artifacts),\n artifacts,\n mcp.skipped,\n );\n }\n\n wantsHelp(argv: readonly string[]): boolean {\n return argv.includes(HELP);\n }\n\n /**\n * `mcp-tools.json` — the RUNTIME artifact, beside the three documents.\n *\n * It is not a document and is not serialized by `--format`: `WpMcpServer` is constructed with it,\n * and `McpToolRegistry` fails fast at boot when a registered `@WpMcpTool` is missing from it. That\n * is what took the MCP runtime off reflect-metadata (#984) — the schema an agent is shown and the\n * schema the server accepts are now the same bytes, rather than two derivations of one contract.\n *\n * Written only when some contract declares `MCP`, which is the same rule `mcp-openapi.json`\n * follows, for the same reason: an empty file is a claim that there are no tools.\n */\n // webpieces-disable no-function-outside-class -- private static composition step of this class\n private static mcpCatalog(inputs: GenerationInputs): McpArtifacts {\n const models = inputs.contracts\n .filter((contract: ContractModel) => contract.model.apiTypes.includes(MCP))\n .map((contract: ContractModel) => contract.model);\n if (models.length === 0) {\n return new McpArtifacts([], []);\n }\n const rendered: McpCatalogRender = McpSchemaRenderer.catalogOf(models);\n const artifacts =\n rendered.catalog.tools.length === 0\n ? []\n : [new GeneratedArtifact('mcp-tools.json', rendered.catalog.toJsonText())];\n return new McpArtifacts(artifacts, rendered.skipped);\n }\n\n /** `both` unless told otherwise: the second serialization comes free from the same document. */\n private formatOf(argv: readonly string[]): OutputFormat {\n const declared = this.valueOf(argv, FORMAT);\n if (declared === undefined) {\n return 'both';\n }\n if (!FORMATS.includes(declared)) {\n throw new OpenApiGenerationError(\n `unknown ${FORMAT} '${declared}'`,\n 'wp-openapi',\n `${FORMAT} takes one of: ${FORMATS.join(', ')}.`,\n );\n }\n return declared as OutputFormat;\n }\n\n /**\n * The value after a flag. An UNKNOWN flag is refused rather than ignored: a mistyped `--manifets`\n * would otherwise fall through to \"needs both flags\", which sends the reader looking at the wrong\n * thing.\n */\n private valueOf(argv: readonly string[], flag: string): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const argument = argv[i]!;\n if (argument === flag) {\n return argv[i + 1];\n }\n if (argument.startsWith('--') && !FLAGS.includes(argument)) {\n throw new OpenApiGenerationError(\n `unknown flag '${argument}'`,\n 'wp-openapi',\n `wp-openapi takes ${FLAGS.join(', ')}, and nothing else.`,\n );\n }\n }\n return undefined;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"OpenApiCli.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/cli/OpenApiCli.ts"],"names":[],"mappings":";;;;AAAA,wDAAkC;AAClC,oDAA+D;AAC/D,4DAA+F;AAC/F,2DAAyF;AAEzF,mEAAgE;AAChE,uDAAoD;AACpD,sEAAmE;AAEnE,MAAM,QAAQ,GAAG,YAAY,CAAC;AAC9B,MAAM,GAAG,GAAG,OAAO,CAAC;AACpB,MAAM,MAAM,GAAG,UAAU,CAAC;AAC1B,MAAM,IAAI,GAAG,QAAQ,CAAC;AAEtB,MAAM,KAAK,GAAG,CAAC,QAAQ,EAA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AAC;YACvB,CAAC;YACD,IAAI,QAAQ,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;gBACzD,MAAM,IAAI,+CAAsB,CAC5B,iBAAiB,QAAQ,GAAG,EAC5B,YAAY,EACZ,oBAAoB,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qBAAqB,CAC5D,CAAC;YACN,CAAC;QACL,CAAC;QACD,OAAO,SAAS,CAAC;IACrB,CAAC;CACJ;AApGD,gCAoGC","sourcesContent":["import * as path from 'node:path';\nimport { MCP, McpToolCatalogFile } from '@webpieces/core-util';\nimport { McpCatalogRender, McpSchemaRenderer, SkippedMcpTool } from '@webpieces/api-doc-model';\nimport { ArtifactWriter, GeneratedArtifact, OutputFormat } from '../emit/ArtifactWriter';\nimport { ContractModel, GenerationInputs } from '../generate/GenerationInputs';\nimport { OpenApiGenerator } from '../generate/OpenApiGenerator';\nimport { InputsLoader } from '../load/InputsLoader';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\n\nconst MANIFEST = '--manifest';\nconst OUT = '--out';\nconst FORMAT = '--format';\nconst HELP = '--help';\n\nconst FLAGS = [MANIFEST, OUT, FORMAT];\nconst FORMATS: readonly string[] = ['json', 'yaml', 'both'];\n\nexport const USAGE = [\n 'wp-openapi --manifest <openapi.manifest.json> --out <dir> [--format json|yaml|both]',\n '',\n 'Renders the contracts a manifest names into OpenAPI 3.1.0. WHICH documents are written is a',\n \"property of the contracts themselves — each one's @ApiType(...) names the documents it feeds:\",\n '',\n ' full-private-openapi every contract declaring SVC_TO_SVC, hidden methods included',\n ' public-openapi contracts declaring EXTERNAL_CUSTOMER, minus every { hidden: true } method',\n ' mcp-openapi contracts declaring MCP, carrying the x-mcp-* extensions',\n '',\n 'Alongside them, one mcp-<ContractClass>-tools.json is written per contract that declares MCP',\n 'and has an @WpMcpTool: the RUNTIME catalogs WpMcpServer boots from. They are not documents, so',\n '--format does not apply.',\n '',\n 'A document no contract asked for is not written. --format chooses the serialization of',\n 'whichever documents were written, and defaults to both.',\n '',\n 'It exits non-zero, naming the JSON pointer of every offending field, rather than writing a',\n 'document containing a field it has no schema for. There is no flag to switch that off.',\n].join('\\n');\n\n/** The result of one run: what was written, so a caller can print it or assert on it. */\nexport class CliResult {\n constructor(\n readonly written: readonly string[],\n readonly artifacts: readonly GeneratedArtifact[],\n /** `@WpMcpTool`s the MCP catalog could not carry, with the reason. Never silent. */\n readonly skippedMcpTools: readonly SkippedMcpTool[] = [],\n ) {}\n}\n\n/** The MCP half of one run: the per-contract catalogs to write, and what they could not carry. */\nclass McpArtifacts {\n constructor(\n readonly artifacts: readonly GeneratedArtifact[],\n readonly skipped: readonly SkippedMcpTool[],\n ) {}\n}\n\n/**\n * `wp-openapi`'s argument parsing and composition, with NO process-level concerns in it — no\n * `process.exit`, no `console` — so the whole command is exercised by the suite exactly as a user\n * runs it. The bin is the only thing that knows about the process.\n *\n * `--manifest` and `--out` are REQUIRED and have no defaults. A defaulted `--out` writes generated\n * documents somewhere the caller did not name, and a defaulted `--manifest` picks a service out of\n * whatever directory the command happened to start in.\n */\nexport class OpenApiCli {\n private readonly loader = new InputsLoader();\n private readonly generator = new OpenApiGenerator();\n private readonly writer = new ArtifactWriter();\n\n /** @param argv the arguments AFTER the program name. @param cwd what relative paths resolve against. */\n run(argv: readonly string[], cwd: string): CliResult {\n const manifest = this.valueOf(argv, MANIFEST);\n const out = this.valueOf(argv, OUT);\n if (manifest === undefined || out === undefined) {\n throw new OpenApiGenerationError(\n `wp-openapi needs both ${MANIFEST} and ${OUT}`,\n 'wp-openapi',\n `Run: wp-openapi ${MANIFEST} <openapi.manifest.json> ${OUT} <dir>`,\n );\n }\n const inputs = this.loader.load(path.resolve(cwd, manifest));\n const documents = this.generator.generate(inputs);\n const mcp = OpenApiCli.mcpCatalog(inputs);\n const artifacts = [\n ...this.writer.artifacts(documents, this.formatOf(argv)),\n ...mcp.artifacts,\n ];\n return new CliResult(\n this.writer.write(path.resolve(cwd, out), artifacts),\n artifacts,\n mcp.skipped,\n );\n }\n\n wantsHelp(argv: readonly string[]): boolean {\n return argv.includes(HELP);\n }\n\n /**\n * `mcp-<ContractClass>-tools.json` — the RUNTIME artifacts, one per contract, beside the three\n * documents.\n *\n * They are not documents and are not serialized by `--format`: `WpMcpServer` boots from them, and\n * `McpToolRegistry` checks every `McpApiBinding` against the file generated from exactly that\n * contract, failing fast at boot when one is missing (#1021). That is what took the MCP runtime off\n * reflect-metadata (#984) — the schema an agent is shown and the schema the server accepts are now\n * the same bytes, rather than two derivations of one contract.\n *\n * Written only for a contract that declares `MCP` and has at least one renderable tool, which is\n * the same rule `mcp-openapi.json` follows, for the same reason: an empty file is a claim that there\n * are no tools.\n */\n // webpieces-disable no-function-outside-class -- private static composition step of this class\n private static mcpCatalog(inputs: GenerationInputs): McpArtifacts {\n const models = inputs.contracts\n .filter((contract: ContractModel) => contract.model.apiTypes.includes(MCP))\n .map((contract: ContractModel) => contract.model);\n if (models.length === 0) {\n return new McpArtifacts([], []);\n }\n const rendered: McpCatalogRender = McpSchemaRenderer.catalogOf(models);\n const artifacts = rendered.catalogs.map(\n (catalog: McpToolCatalogFile) => new GeneratedArtifact(catalog.fileName, catalog.toJsonText()),\n );\n return new McpArtifacts(artifacts, rendered.skipped);\n }\n\n /** `both` unless told otherwise: the second serialization comes free from the same document. */\n private formatOf(argv: readonly string[]): OutputFormat {\n const declared = this.valueOf(argv, FORMAT);\n if (declared === undefined) {\n return 'both';\n }\n if (!FORMATS.includes(declared)) {\n throw new OpenApiGenerationError(\n `unknown ${FORMAT} '${declared}'`,\n 'wp-openapi',\n `${FORMAT} takes one of: ${FORMATS.join(', ')}.`,\n );\n }\n return declared as OutputFormat;\n }\n\n /**\n * The value after a flag. An UNKNOWN flag is refused rather than ignored: a mistyped `--manifets`\n * would otherwise fall through to \"needs both flags\", which sends the reader looking at the wrong\n * thing.\n */\n private valueOf(argv: readonly string[], flag: string): string | undefined {\n for (let i = 0; i < argv.length; i++) {\n const argument = argv[i]!;\n if (argument === flag) {\n return argv[i + 1];\n }\n if (argument.startsWith('--') && !FLAGS.includes(argument)) {\n throw new OpenApiGenerationError(\n `unknown flag '${argument}'`,\n 'wp-openapi',\n `wp-openapi takes ${FLAGS.join(', ')}, and nothing else.`,\n );\n }\n }\n return undefined;\n }\n}\n"]}
|
package/src/cli/WpOpenApiMain.js
CHANGED
|
@@ -40,7 +40,7 @@ class WpOpenApiMain {
|
|
|
40
40
|
// `McpToolRegistry` refuses to boot while it is still declared — see
|
|
41
41
|
// `McpSchemaRenderer.catalogOf` for why that is the right place for the failure.
|
|
42
42
|
for (const skipped of result.skippedMcpTools) {
|
|
43
|
-
out.write(`no MCP schema, left out of
|
|
43
|
+
out.write(`no MCP schema, left out of its contract's MCP tool catalog: ${skipped}\n`);
|
|
44
44
|
}
|
|
45
45
|
return 0;
|
|
46
46
|
// webpieces-disable no-any-unknown -- the catch binding, which TypeScript types for us
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WpOpenApiMain.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/cli/WpOpenApiMain.ts"],"names":[],"mappings":";;;AAAA,6CAA4D;AAC5D,sEAAmE;AAEnE;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,aAAa;IACL,GAAG,GAAG,IAAI,uBAAU,EAAE,CAAC;IAExC,2EAA2E;IAC3E,GAAG,CAAC,IAAuB,EAAE,GAAW,EAAE,GAAuB;QAC7D,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3B,GAAG,CAAC,KAAK,CAAC,GAAG,kBAAK,IAAI,CAAC,CAAC;YACxB,OAAO,CAAC,CAAC;QACb,CAAC;QACD,sGAAsG;QACtG,IAAI,CAAC;YACD,MAAM,MAAM,GAAc,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAClD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBAChC,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;YACjC,CAAC;YACD,iFAAiF;YACjF,qEAAqE;YACrE,iFAAiF;YACjF,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;gBAC3C,GAAG,CAAC,KAAK,CAAC,
|
|
1
|
+
{"version":3,"file":"WpOpenApiMain.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/cli/WpOpenApiMain.ts"],"names":[],"mappings":";;;AAAA,6CAA4D;AAC5D,sEAAmE;AAEnE;;;;;;;;;;;;;;;;;;GAkBG;AACH,MAAa,aAAa;IACL,GAAG,GAAG,IAAI,uBAAU,EAAE,CAAC;IAExC,2EAA2E;IAC3E,GAAG,CAAC,IAAuB,EAAE,GAAW,EAAE,GAAuB;QAC7D,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC;YAC3B,GAAG,CAAC,KAAK,CAAC,GAAG,kBAAK,IAAI,CAAC,CAAC;YACxB,OAAO,CAAC,CAAC;QACb,CAAC;QACD,sGAAsG;QACtG,IAAI,CAAC;YACD,MAAM,MAAM,GAAc,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;YAClD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,OAAO,EAAE,CAAC;gBAChC,GAAG,CAAC,KAAK,CAAC,SAAS,IAAI,IAAI,CAAC,CAAC;YACjC,CAAC;YACD,iFAAiF;YACjF,qEAAqE;YACrE,iFAAiF;YACjF,KAAK,MAAM,OAAO,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;gBAC3C,GAAG,CAAC,KAAK,CAAC,+DAA+D,OAAO,IAAI,CAAC,CAAC;YAC1F,CAAC;YACD,OAAO,CAAC,CAAC;YACT,uFAAuF;QAC3F,CAAC;QAAC,OAAO,GAAY,EAAE,CAAC;YACpB,6BAA6B;YAC7B,GAAG,CAAC,KAAK,CAAC,GAAG,IAAI,CAAC,MAAM,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;YACnC,OAAO,CAAC,CAAC;QACb,CAAC;IACL,CAAC;IAED,yGAAyG;IACjG,MAAM,CAAC,GAAY;QACvB,IAAI,CAAC,CAAC,GAAG,YAAY,+CAAsB,CAAC,EAAE,CAAC;YAC3C,OAAO,sBAAsB,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,CAAC;QACpF,CAAC;QACD,MAAM,KAAK,GAAG,CAAC,uBAAuB,GAAG,CAAC,OAAO,EAAE,CAAC,CAAC;QACrD,KAAK,MAAM,OAAO,IAAI,GAAG,CAAC,QAAQ,EAAE,CAAC;YACjC,KAAK,CAAC,IAAI,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC;QAC/B,CAAC;QACD,KAAK,CAAC,IAAI,CAAC,KAAK,GAAG,CAAC,IAAI,EAAE,CAAC,CAAC;QAC5B,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5B,CAAC;CACJ;AA1CD,sCA0CC","sourcesContent":["import { CliResult, OpenApiCli, USAGE } from './OpenApiCli';\nimport { OpenApiGenerationError } from '../OpenApiGenerationError';\n\n/**\n * The body of the `wp-openapi` bin: argument handling, the SINGLE top-level handler, and the exit\n * code — with nothing that touches the process itself, so the suite runs the whole command.\n *\n * ## The single top-level handler\n *\n * Everything below here THROWS {@link OpenApiGenerationError} and prints nothing, so this is the only\n * renderer of a failure and the only writer of an exit code (`.claude/review/error-output.md`). It\n * renders from the error's FIELDS — the message, the location, the cure, the pointers — rather than\n * from a string somebody baked a cure into, so one audience's formatting never freezes into a thrower.\n *\n * ## Why an unmapped field exits NON-ZERO\n *\n * A field with no schema publishes as \"anything\", so a document containing one is a green build\n * handing a partner a field with no shape. That is worse than no document, because nobody reads a\n * published contract looking for the field that was quietly left undefined. There is deliberately no\n * flag to downgrade it — the cure is at the contract, by naming the type, and every pointer needed to\n * do that is printed.\n */\nexport class WpOpenApiMain {\n private readonly cli = new OpenApiCli();\n\n /** @returns the process exit code. 0 on success, 1 on a stated failure. */\n run(argv: readonly string[], cwd: string, out: NodeJS.WriteStream): number {\n if (this.cli.wantsHelp(argv)) {\n out.write(`${USAGE}\\n`);\n return 0;\n }\n // eslint-disable-next-line @webpieces/no-unmanaged-exceptions -- this IS the single top-level handler\n try {\n const result: CliResult = this.cli.run(argv, cwd);\n for (const file of result.written) {\n out.write(`wrote ${file}\\n`);\n }\n // NAMED, never silent. A tool with no MCP schema is one no server can carry, and\n // `McpToolRegistry` refuses to boot while it is still declared — see\n // `McpSchemaRenderer.catalogOf` for why that is the right place for the failure.\n for (const skipped of result.skippedMcpTools) {\n out.write(`no MCP schema, left out of its contract's MCP tool catalog: ${skipped}\\n`);\n }\n return 0;\n // webpieces-disable no-any-unknown -- the catch binding, which TypeScript types for us\n } catch (err: unknown) {\n //const error = toError(err);\n out.write(`${this.render(err)}\\n`);\n return 1;\n }\n }\n\n // webpieces-disable no-any-unknown -- a caught value; this method is the audience-facing narrowing of it\n private render(err: unknown): string {\n if (!(err instanceof OpenApiGenerationError)) {\n return `wp-openapi failed: ${err instanceof Error ? err.message : String(err)}`;\n }\n const lines = [`wp-openapi refused: ${err.message}`];\n for (const pointer of err.pointers) {\n lines.push(` ${pointer}`);\n }\n lines.push(` ${err.cure}`);\n return lines.join('\\n');\n }\n}\n"]}
|
|
@@ -55,7 +55,8 @@ export declare class SchemaRenderer {
|
|
|
55
55
|
private namedType;
|
|
56
56
|
/**
|
|
57
57
|
* A union, with a `discriminator` ONLY when the model derived one — which it does only when every
|
|
58
|
-
* branch carries the same property typed as a
|
|
58
|
+
* branch carries the same property typed as string values (a literal, a string-enum member, or a
|
|
59
|
+
* union of them) that no two branches share. An invented discriminator
|
|
59
60
|
* would claim a narrowing TypeScript itself cannot do.
|
|
60
61
|
*/
|
|
61
62
|
private union;
|
|
@@ -114,7 +114,8 @@ class SchemaRenderer {
|
|
|
114
114
|
}
|
|
115
115
|
/**
|
|
116
116
|
* A union, with a `discriminator` ONLY when the model derived one — which it does only when every
|
|
117
|
-
* branch carries the same property typed as a
|
|
117
|
+
* branch carries the same property typed as string values (a literal, a string-enum member, or a
|
|
118
|
+
* union of them) that no two branches share. An invented discriminator
|
|
118
119
|
* would claim a narrowing TypeScript itself cannot do.
|
|
119
120
|
*/
|
|
120
121
|
union(type) {
|
|
@@ -126,9 +127,10 @@ class SchemaRenderer {
|
|
|
126
127
|
return schema;
|
|
127
128
|
}
|
|
128
129
|
const mapping = new JsonObject_1.JsonObject();
|
|
130
|
+
// EVERY value a branch's property may hold maps to that branch — `mode: 'a' | 'b'` is two
|
|
131
|
+
// entries pointing at one schema, which OpenAPI's mapping allows (#1023).
|
|
129
132
|
for (const branch of type.unionRefNames) {
|
|
130
|
-
const value
|
|
131
|
-
if (value !== undefined) {
|
|
133
|
+
for (const value of type.discriminator.branchValues.get(branch) ?? []) {
|
|
132
134
|
mapping.set(value, `#/components/schemas/${branch}`);
|
|
133
135
|
}
|
|
134
136
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SchemaRenderer.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/SchemaRenderer.ts"],"names":[],"mappings":";;;AACA,mDAA2D;AAE3D,qGAAqG;AACrG,MAAa,aAAa;IAGT;IAEA;IAJb;IACI,qEAAqE;IAC5D,OAAe;IACxB,qFAAqF;IAC5E,QAAgB;QAFhB,YAAO,GAAP,OAAO,CAAQ;QAEf,aAAQ,GAAR,QAAQ,CAAQ;IAC1B,CAAC;CACP;AAPD,sCAOC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,cAAc;IAIM;IAHZ,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAC5B,cAAc,GA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G,CAAC,CAAC,IAAY,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAChE,CAAC;IACN,CAAC;IAEO,SAAS,CAAC,GAAY;QAC1B,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YAC9B,0FAA0F;YAC1F,mEAAmE;YACnE,OAAO,IAAI,uBAAU,EAAE,CAAC;QAC5B,CAAC;QACD,OAAO,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,SAAU,CAAC,CAAC;IAClF,CAAC;IAEO,SAAS,CAAC,IAAY;QAC1B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACvB,OAAO,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,wBAAwB,IAAI,EAAE,CAAC,CAAC;IACxE,CAAC;IAED,+FAA+F;IACvF,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;AAjOD,wCAiOC","sourcesContent":["import { DocumentedField, DocumentedType, TypeRef } from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\n\n/** ONE field the renderer could not give a shape to, and WHERE in the document it would have sat. */\nexport class UnmappedField {\n constructor(\n /** A JSON pointer into the document that would have been written. */\n readonly pointer: string,\n /** The verbatim TypeScript type text, so the cure names the thing to go and type. */\n readonly typeText: string,\n ) {}\n}\n\n/**\n * {@link TypeRef} / {@link DocumentedType} -> JSON Schema 2020-12, which IS OpenAPI 3.1's schema\n * dialect and IS what MCP `tools/list` speaks. That identity is the reason #982 specifies 3.1 rather\n * than 3.0: the two are not \"similar dialects\", they are the same schemas, so the MCP projection\n * (#984) is a selection and an inline pass, not a translation.\n *\n * ## Three things 3.1 lets this renderer state HONESTLY that 3.0 could not\n *\n * - `type: [T, \"null\"]` for a nullable field, instead of 3.0's `nullable: true` keyword, which is not\n * JSON Schema at all.\n * - `description` BESIDE a `$ref`. In 3.0 a sibling of `$ref` is ignored, so a documented field whose\n * type is a named DTO simply lost its prose.\n * - OPTIONAL and NULLABLE as separate facts — absent from `required` versus `\"null\"` in `type`. `{}`\n * and `{x: null}` are different wire documents and a schema that conflates them rejects one.\n *\n * ## It records what it cannot map rather than emitting an untyped field\n *\n * An unmapped type yields an EMPTY schema, which in JSON Schema means \"anything\". That is precisely\n * the green-build-publishes-a-shapeless-field defect the guard exists to stop, so every one is\n * recorded with the pointer it would have occupied and {@link OpenApiGenerator} refuses on the set.\n */\nexport class SchemaRenderer {\n private readonly reached = new Set<string>();\n private readonly unmappedFields: UnmappedField[] = [];\n\n constructor(private readonly types: ReadonlyMap<string, DocumentedType>) {}\n\n /** Named types this renderer has been asked for, directly or through another schema. */\n reachedTypes(): ReadonlySet<string> {\n return this.reached;\n }\n\n /** Every field with no shape, with its pointer. Empty means the document is fully typed. */\n unmapped(): readonly UnmappedField[] {\n return this.unmappedFields;\n }\n\n /**\n * `components.schemas` for everything reachable from whatever has been rendered so far, expanded\n * to a FIXPOINT.\n *\n * A worklist and not recursion-with-a-guard because rendering a type reaches more types, and the\n * set has to close over that. It terminates for the same reason the extractor's walk does: a\n * named type is registered once, so the worklist strictly shrinks.\n */\n components(): JsonObject {\n const rendered = new Map<string, JsonObject | undefined>();\n let grew = true;\n while (grew) {\n grew = false;\n for (const name of Array.from(this.reached)) {\n if (rendered.has(name)) {\n continue;\n }\n const type = this.types.get(name);\n // Rendering it can add MORE names to `reached`, which is what the outer loop is for.\n rendered.set(name, type === undefined ? undefined : this.namedType(type));\n grew = true;\n }\n }\n const schemas = new JsonObject();\n // Alphabetical, because `components.schemas` is a lookup table and nothing reads it in order\n // — whereas discovery order would move every time an operation was added above another.\n for (const name of Array.from(rendered.keys()).sort()) {\n schemas.set(name, rendered.get(name));\n }\n return schemas;\n }\n\n /** One named type: an object DTO, a string enum, or a union with its DERIVED discriminator. */\n private namedType(type: DocumentedType): JsonObject {\n const pointer = `#/components/schemas/${type.name}`;\n if (type.enumValues.length > 0) {\n return new JsonObject()\n .set('type', 'string')\n .set('description', this.prose(type.description))\n .set('enum', type.enumValues.slice());\n }\n if (type.unionRefNames.length > 0) {\n return this.union(type);\n }\n const properties = new JsonObject();\n const required: string[] = [];\n for (const field of type.fields) {\n properties.set(field.name, this.field(field, `${pointer}/properties/${field.name}`));\n if (!field.optional) {\n required.push(field.name);\n }\n }\n return new JsonObject()\n .set('type', 'object')\n .set('description', this.prose(type.description))\n .set('properties', properties.isEmpty() ? undefined : properties)\n .set('required', required.length === 0 ? undefined : required)\n .set(\n 'additionalProperties',\n type.indexSignatureValue === undefined\n ? undefined\n : this.type(type.indexSignatureValue, `${pointer}/additionalProperties`),\n );\n }\n\n /**\n * A union, with a `discriminator` ONLY when the model derived one — which it does only when every\n * branch carries the same property typed as a single string literal. An invented discriminator\n * would claim a narrowing TypeScript itself cannot do.\n */\n private union(type: DocumentedType): JsonObject {\n const branches: JsonValue[] = type.unionRefNames.map((name: string) =>\n this.reference(name),\n );\n const schema = new JsonObject()\n .set('description', this.prose(type.description))\n .set('oneOf', branches);\n if (type.discriminator === undefined) {\n return schema;\n }\n const mapping = new JsonObject();\n for (const branch of type.unionRefNames) {\n const value = type.discriminator.branchValues.get(branch);\n if (value !== undefined) {\n mapping.set(value, `#/components/schemas/${branch}`);\n }\n }\n return schema.set(\n 'discriminator',\n new JsonObject()\n .set('propertyName', type.discriminator.propertyName)\n .set('mapping', mapping),\n );\n }\n\n /**\n * One FIELD: its type, plus the prose and the constraints that hang off the field rather than the\n * type. `@format`, `@WpMin` and `@WpMax` land on the SCALAR — on an array, on the ITEM — because\n * `minimum` on an array means nothing and a reader would have to guess which half was meant.\n */\n field(field: DocumentedField, pointer: string): JsonObject {\n const isArray = field.type.kind === 'array';\n const leafPointer = isArray ? `${pointer}/items` : pointer;\n const leaf = this.constrain(\n isArray ? this.type(field.type.items!, leafPointer) : this.type(field.type, pointer),\n field,\n );\n const schema = isArray\n ? new JsonObject().set('type', 'array').set('items', leaf)\n : this.nullable(leaf, field.nullable);\n if (isArray && field.nullable) {\n return this.described(this.nullable(schema, true), field);\n }\n return this.described(schema, field);\n }\n\n /** `description`, and the `@mcp` override as `x-mcp-description` when the author wrote one. */\n private described(schema: JsonObject, field: DocumentedField): JsonObject {\n return schema\n .set('description', this.prose(field.description))\n .set('x-mcp-description', this.prose(field.mcpDescription));\n }\n\n private constrain(leaf: JsonObject, field: DocumentedField): JsonObject {\n return leaf.set('format', field.format).set('minimum', field.min).set('maximum', field.max);\n }\n\n /** `type: [T, \"null\"]` where there is a type to widen; `anyOf` where the shape is a `$ref`. */\n private nullable(schema: JsonObject, isNullable: boolean): JsonObject {\n if (!isNullable) {\n return schema;\n }\n const declared = schema.get('type');\n if (typeof declared === 'string') {\n return schema.set('type', [declared, 'null']);\n }\n return new JsonObject().set('anyOf', [schema, new JsonObject().set('type', 'null')]);\n }\n\n /** One resolved type, with no field-level prose or constraints on it. */\n type(ref: TypeRef, pointer: string): JsonObject {\n switch (ref.kind) {\n case 'primitive':\n return this.primitive(ref);\n case 'ref':\n return this.reference(ref.refName!);\n case 'array':\n return new JsonObject()\n .set('type', 'array')\n .set('items', this.type(ref.items!, `${pointer}/items`));\n case 'openMap':\n return new JsonObject()\n .set('type', 'object')\n .set(\n 'additionalProperties',\n this.type(ref.values!, `${pointer}/additionalProperties`),\n );\n case 'enum':\n return new JsonObject().set('type', 'string').set('enum', ref.enumValues.slice());\n case 'union':\n return this.namedUnion(ref);\n default:\n this.unmappedFields.push(\n new UnmappedField(pointer, ref.unmappedText ?? '<unknown>'),\n );\n return new JsonObject();\n }\n }\n\n /**\n * A union, as a `$ref` at the NAMED alias when the model registered one.\n *\n * The model records a `type X = A | B` alias as its own entry — carrying the DERIVED\n * discriminator — while the FIELD that used it holds a bare union of branch names. Rendering the\n * field's union inline would therefore publish the `oneOf` and silently drop the discriminator,\n * which is the one part of a union a client actually needs to narrow on. So the alias is looked\n * up by its branch list and referenced.\n */\n private namedUnion(ref: TypeRef): JsonObject {\n const branches = ref.unionRefNames.join(',');\n for (const name of Array.from(this.types.keys())) {\n if (this.types.get(name)!.unionRefNames.join(',') === branches) {\n return this.reference(name);\n }\n }\n return new JsonObject().set(\n 'oneOf',\n ref.unionRefNames.map((each: string) => this.reference(each)),\n );\n }\n\n private primitive(ref: TypeRef): JsonObject {\n if (ref.primitive === 'unknown') {\n // No `type` at all: JSON Schema's honest spelling of \"any shape\". It is only ever reached\n // by a `void` return, which is why it is not the unmapped refusal.\n return new JsonObject();\n }\n return new JsonObject().set('type', ref.integer ? 'integer' : ref.primitive!);\n }\n\n private reference(name: string): JsonObject {\n this.reached.add(name);\n return new JsonObject().set('$ref', `#/components/schemas/${name}`);\n }\n\n /** Empty prose is ABSENT prose. An empty `description` key is noise in every rendered page. */\n private prose(text: string | undefined): string | undefined {\n return text === undefined || text.trim() === '' ? undefined : text;\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"SchemaRenderer.js","sourceRoot":"","sources":["../../../../../../packages/docs/openapi-generator/src/generate/SchemaRenderer.ts"],"names":[],"mappings":";;;AACA,mDAA2D;AAE3D,qGAAqG;AACrG,MAAa,aAAa;IAGT;IAEA;IAJb;IACI,qEAAqE;IAC5D,OAAe;IACxB,qFAAqF;IAC5E,QAAgB;QAFhB,YAAO,GAAP,OAAO,CAAQ;QAEf,aAAQ,GAAR,QAAQ,CAAQ;IAC1B,CAAC;CACP;AAPD,sCAOC;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAa,cAAc;IAIM;IAHZ,OAAO,GAAG,IAAI,GAAG,EAAU,CAAC;IAC5B,cAAc,GAAoB,EAAE,CAAC;IAEtD,YAA6B,KAA0C;QAA1C,UAAK,GAA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I,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAChE,CAAC;IACN,CAAC;IAEO,SAAS,CAAC,GAAY;QAC1B,IAAI,GAAG,CAAC,SAAS,KAAK,SAAS,EAAE,CAAC;YAC9B,0FAA0F;YAC1F,mEAAmE;YACnE,OAAO,IAAI,uBAAU,EAAE,CAAC;QAC5B,CAAC;QACD,OAAO,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,SAAU,CAAC,CAAC;IAClF,CAAC;IAEO,SAAS,CAAC,IAAY;QAC1B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC;QACvB,OAAO,IAAI,uBAAU,EAAE,CAAC,GAAG,CAAC,MAAM,EAAE,wBAAwB,IAAI,EAAE,CAAC,CAAC;IACxE,CAAC;IAED,+FAA+F;IACvF,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;AAnOD,wCAmOC","sourcesContent":["import { DocumentedField, DocumentedType, TypeRef } from '@webpieces/api-doc-model';\nimport { JsonObject, JsonValue } from '../json/JsonObject';\n\n/** ONE field the renderer could not give a shape to, and WHERE in the document it would have sat. */\nexport class UnmappedField {\n constructor(\n /** A JSON pointer into the document that would have been written. */\n readonly pointer: string,\n /** The verbatim TypeScript type text, so the cure names the thing to go and type. */\n readonly typeText: string,\n ) {}\n}\n\n/**\n * {@link TypeRef} / {@link DocumentedType} -> JSON Schema 2020-12, which IS OpenAPI 3.1's schema\n * dialect and IS what MCP `tools/list` speaks. That identity is the reason #982 specifies 3.1 rather\n * than 3.0: the two are not \"similar dialects\", they are the same schemas, so the MCP projection\n * (#984) is a selection and an inline pass, not a translation.\n *\n * ## Three things 3.1 lets this renderer state HONESTLY that 3.0 could not\n *\n * - `type: [T, \"null\"]` for a nullable field, instead of 3.0's `nullable: true` keyword, which is not\n * JSON Schema at all.\n * - `description` BESIDE a `$ref`. In 3.0 a sibling of `$ref` is ignored, so a documented field whose\n * type is a named DTO simply lost its prose.\n * - OPTIONAL and NULLABLE as separate facts — absent from `required` versus `\"null\"` in `type`. `{}`\n * and `{x: null}` are different wire documents and a schema that conflates them rejects one.\n *\n * ## It records what it cannot map rather than emitting an untyped field\n *\n * An unmapped type yields an EMPTY schema, which in JSON Schema means \"anything\". That is precisely\n * the green-build-publishes-a-shapeless-field defect the guard exists to stop, so every one is\n * recorded with the pointer it would have occupied and {@link OpenApiGenerator} refuses on the set.\n */\nexport class SchemaRenderer {\n private readonly reached = new Set<string>();\n private readonly unmappedFields: UnmappedField[] = [];\n\n constructor(private readonly types: ReadonlyMap<string, DocumentedType>) {}\n\n /** Named types this renderer has been asked for, directly or through another schema. */\n reachedTypes(): ReadonlySet<string> {\n return this.reached;\n }\n\n /** Every field with no shape, with its pointer. Empty means the document is fully typed. */\n unmapped(): readonly UnmappedField[] {\n return this.unmappedFields;\n }\n\n /**\n * `components.schemas` for everything reachable from whatever has been rendered so far, expanded\n * to a FIXPOINT.\n *\n * A worklist and not recursion-with-a-guard because rendering a type reaches more types, and the\n * set has to close over that. It terminates for the same reason the extractor's walk does: a\n * named type is registered once, so the worklist strictly shrinks.\n */\n components(): JsonObject {\n const rendered = new Map<string, JsonObject | undefined>();\n let grew = true;\n while (grew) {\n grew = false;\n for (const name of Array.from(this.reached)) {\n if (rendered.has(name)) {\n continue;\n }\n const type = this.types.get(name);\n // Rendering it can add MORE names to `reached`, which is what the outer loop is for.\n rendered.set(name, type === undefined ? undefined : this.namedType(type));\n grew = true;\n }\n }\n const schemas = new JsonObject();\n // Alphabetical, because `components.schemas` is a lookup table and nothing reads it in order\n // — whereas discovery order would move every time an operation was added above another.\n for (const name of Array.from(rendered.keys()).sort()) {\n schemas.set(name, rendered.get(name));\n }\n return schemas;\n }\n\n /** One named type: an object DTO, a string enum, or a union with its DERIVED discriminator. */\n private namedType(type: DocumentedType): JsonObject {\n const pointer = `#/components/schemas/${type.name}`;\n if (type.enumValues.length > 0) {\n return new JsonObject()\n .set('type', 'string')\n .set('description', this.prose(type.description))\n .set('enum', type.enumValues.slice());\n }\n if (type.unionRefNames.length > 0) {\n return this.union(type);\n }\n const properties = new JsonObject();\n const required: string[] = [];\n for (const field of type.fields) {\n properties.set(field.name, this.field(field, `${pointer}/properties/${field.name}`));\n if (!field.optional) {\n required.push(field.name);\n }\n }\n return new JsonObject()\n .set('type', 'object')\n .set('description', this.prose(type.description))\n .set('properties', properties.isEmpty() ? undefined : properties)\n .set('required', required.length === 0 ? undefined : required)\n .set(\n 'additionalProperties',\n type.indexSignatureValue === undefined\n ? undefined\n : this.type(type.indexSignatureValue, `${pointer}/additionalProperties`),\n );\n }\n\n /**\n * A union, with a `discriminator` ONLY when the model derived one — which it does only when every\n * branch carries the same property typed as string values (a literal, a string-enum member, or a\n * union of them) that no two branches share. An invented discriminator\n * would claim a narrowing TypeScript itself cannot do.\n */\n private union(type: DocumentedType): JsonObject {\n const branches: JsonValue[] = type.unionRefNames.map((name: string) =>\n this.reference(name),\n );\n const schema = new JsonObject()\n .set('description', this.prose(type.description))\n .set('oneOf', branches);\n if (type.discriminator === undefined) {\n return schema;\n }\n const mapping = new JsonObject();\n // EVERY value a branch's property may hold maps to that branch — `mode: 'a' | 'b'` is two\n // entries pointing at one schema, which OpenAPI's mapping allows (#1023).\n for (const branch of type.unionRefNames) {\n for (const value of type.discriminator.branchValues.get(branch) ?? []) {\n mapping.set(value, `#/components/schemas/${branch}`);\n }\n }\n return schema.set(\n 'discriminator',\n new JsonObject()\n .set('propertyName', type.discriminator.propertyName)\n .set('mapping', mapping),\n );\n }\n\n /**\n * One FIELD: its type, plus the prose and the constraints that hang off the field rather than the\n * type. `@format`, `@WpMin` and `@WpMax` land on the SCALAR — on an array, on the ITEM — because\n * `minimum` on an array means nothing and a reader would have to guess which half was meant.\n */\n field(field: DocumentedField, pointer: string): JsonObject {\n const isArray = field.type.kind === 'array';\n const leafPointer = isArray ? `${pointer}/items` : pointer;\n const leaf = this.constrain(\n isArray ? this.type(field.type.items!, leafPointer) : this.type(field.type, pointer),\n field,\n );\n const schema = isArray\n ? new JsonObject().set('type', 'array').set('items', leaf)\n : this.nullable(leaf, field.nullable);\n if (isArray && field.nullable) {\n return this.described(this.nullable(schema, true), field);\n }\n return this.described(schema, field);\n }\n\n /** `description`, and the `@mcp` override as `x-mcp-description` when the author wrote one. */\n private described(schema: JsonObject, field: DocumentedField): JsonObject {\n return schema\n .set('description', this.prose(field.description))\n .set('x-mcp-description', this.prose(field.mcpDescription));\n }\n\n private constrain(leaf: JsonObject, field: DocumentedField): JsonObject {\n return leaf.set('format', field.format).set('minimum', field.min).set('maximum', field.max);\n }\n\n /** `type: [T, \"null\"]` where there is a type to widen; `anyOf` where the shape is a `$ref`. */\n private nullable(schema: JsonObject, isNullable: boolean): JsonObject {\n if (!isNullable) {\n return schema;\n }\n const declared = schema.get('type');\n if (typeof declared === 'string') {\n return schema.set('type', [declared, 'null']);\n }\n return new JsonObject().set('anyOf', [schema, new JsonObject().set('type', 'null')]);\n }\n\n /** One resolved type, with no field-level prose or constraints on it. */\n type(ref: TypeRef, pointer: string): JsonObject {\n switch (ref.kind) {\n case 'primitive':\n return this.primitive(ref);\n case 'ref':\n return this.reference(ref.refName!);\n case 'array':\n return new JsonObject()\n .set('type', 'array')\n .set('items', this.type(ref.items!, `${pointer}/items`));\n case 'openMap':\n return new JsonObject()\n .set('type', 'object')\n .set(\n 'additionalProperties',\n this.type(ref.values!, `${pointer}/additionalProperties`),\n );\n case 'enum':\n return new JsonObject().set('type', 'string').set('enum', ref.enumValues.slice());\n case 'union':\n return this.namedUnion(ref);\n default:\n this.unmappedFields.push(\n new UnmappedField(pointer, ref.unmappedText ?? '<unknown>'),\n );\n return new JsonObject();\n }\n }\n\n /**\n * A union, as a `$ref` at the NAMED alias when the model registered one.\n *\n * The model records a `type X = A | B` alias as its own entry — carrying the DERIVED\n * discriminator — while the FIELD that used it holds a bare union of branch names. Rendering the\n * field's union inline would therefore publish the `oneOf` and silently drop the discriminator,\n * which is the one part of a union a client actually needs to narrow on. So the alias is looked\n * up by its branch list and referenced.\n */\n private namedUnion(ref: TypeRef): JsonObject {\n const branches = ref.unionRefNames.join(',');\n for (const name of Array.from(this.types.keys())) {\n if (this.types.get(name)!.unionRefNames.join(',') === branches) {\n return this.reference(name);\n }\n }\n return new JsonObject().set(\n 'oneOf',\n ref.unionRefNames.map((each: string) => this.reference(each)),\n );\n }\n\n private primitive(ref: TypeRef): JsonObject {\n if (ref.primitive === 'unknown') {\n // No `type` at all: JSON Schema's honest spelling of \"any shape\". It is only ever reached\n // by a `void` return, which is why it is not the unmapped refusal.\n return new JsonObject();\n }\n return new JsonObject().set('type', ref.integer ? 'integer' : ref.primitive!);\n }\n\n private reference(name: string): JsonObject {\n this.reached.add(name);\n return new JsonObject().set('$ref', `#/components/schemas/${name}`);\n }\n\n /** Empty prose is ABSENT prose. An empty `description` key is noise in every rendered page. */\n private prose(text: string | undefined): string | undefined {\n return text === undefined || text.trim() === '' ? undefined : text;\n }\n}\n"]}
|