contractdiff 0.0.0-stage → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/bin.js +4 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +24 -0
- package/dist/command-diff.js +310 -0
- package/dist/command-explain-cap.js +36 -0
- package/dist/command-explain-inline.js +17 -0
- package/dist/command-explain-name.js +31 -0
- package/dist/command-explain-operation.js +85 -0
- package/dist/command-explain-text.js +21 -0
- package/dist/command-explain.js +54 -0
- package/dist/command-lint.js +280 -0
- package/dist/command-migrate.js +70 -0
- package/dist/command-plugin.js +32 -0
- package/dist/command-props.js +116 -0
- package/dist/commands.js +7 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/model.d.ts +46 -0
- package/dist/core/model.js +1 -0
- package/dist/core/resolve.d.ts +22 -0
- package/dist/core/resolve.js +71 -0
- package/dist/diff-classify.js +30 -0
- package/dist/diff-contract.js +176 -0
- package/dist/diff-decisions.js +446 -0
- package/dist/diff-normalise.js +143 -0
- package/dist/diff-rules.js +109 -0
- package/dist/diff-schema.js +335 -0
- package/dist/diff-security.js +33 -0
- package/dist/diff-transitive.js +26 -0
- package/dist/diff-usage.js +59 -0
- package/dist/extract-normalise.js +85 -0
- package/dist/extract-roundtrip.js +28 -0
- package/dist/extract-standard.js +79 -0
- package/dist/gen-ts-ast.d.ts +135 -0
- package/dist/gen-ts-ast.js +52 -0
- package/dist/gen-ts-bundle.js +233 -0
- package/dist/gen-ts-comment.js +48 -0
- package/dist/gen-ts-context.d.ts +83 -0
- package/dist/gen-ts-context.js +45 -0
- package/dist/gen-ts-dict.d.ts +14 -0
- package/dist/gen-ts-dict.js +14 -0
- package/dist/gen-ts-discriminators.d.ts +7 -0
- package/dist/gen-ts-discriminators.js +117 -0
- package/dist/gen-ts-document.d.ts +12 -0
- package/dist/gen-ts-document.js +82 -0
- package/dist/gen-ts-enums.js +139 -0
- package/dist/gen-ts-helpers.js +30 -0
- package/dist/gen-ts-index.d.ts +49 -0
- package/dist/gen-ts-index.js +110 -0
- package/dist/gen-ts-operations.js +277 -0
- package/dist/gen-ts-print.js +113 -0
- package/dist/gen-ts-ref.d.ts +30 -0
- package/dist/gen-ts-ref.js +75 -0
- package/dist/gen-ts-schema.js +283 -0
- package/dist/gen-ts-text.d.ts +24 -0
- package/dist/gen-ts-text.js +98 -0
- package/dist/host.d.ts +145 -0
- package/dist/host.js +273 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/input-asyncapi.js +167 -0
- package/dist/input-buf.js +58 -0
- package/dist/input-jsonschema.js +165 -0
- package/dist/input-mcp.js +111 -0
- package/dist/input-overlay-jsonpath.js +265 -0
- package/dist/input-overlay.js +138 -0
- package/dist/input-protobuf.js +212 -0
- package/dist/input-swagger2.js +331 -0
- package/dist/inputs.js +8 -0
- package/dist/lint-code-read.js +129 -0
- package/dist/lint-code.d.ts +56 -0
- package/dist/lint-code.js +64 -0
- package/dist/lint-engine.d.ts +93 -0
- package/dist/lint-engine.js +87 -0
- package/dist/lint-functions.js +95 -0
- package/dist/lint-history.js +133 -0
- package/dist/lint-jsonpath.js +92 -0
- package/dist/lint-names.d.ts +11 -0
- package/dist/lint-names.js +2 -0
- package/dist/lint-redocly.js +141 -0
- package/dist/lint-rules.js +189 -0
- package/dist/lint-select.d.ts +33 -0
- package/dist/lint-select.js +129 -0
- package/dist/lint-since.js +20 -0
- package/dist/lint-spectral.js +167 -0
- package/dist/lint-stats.js +58 -0
- package/dist/migrate-hey-api.js +144 -0
- package/dist/migrate-literal.js +139 -0
- package/dist/migrate-openapi-fetch.js +62 -0
- package/dist/migrate-openapi-typescript.js +159 -0
- package/dist/migrate-orval.js +119 -0
- package/dist/migrate-shared.js +31 -0
- package/dist/openapi-typescript.d.ts +9 -0
- package/dist/openapi-typescript.js +36 -0
- package/dist/openapi.d.ts +20 -0
- package/dist/openapi.js +94 -0
- package/dist/plugin-express.js +66 -0
- package/dist/plugin-extract-hono.js +1 -0
- package/dist/plugin-extract-nest.js +1 -0
- package/dist/plugin-extract-openapi.js +246 -0
- package/dist/plugin-extract-standard-schema.js +42 -0
- package/dist/plugin-extract-trpc.js +1 -0
- package/dist/plugin-extract-ts-rest.js +77 -0
- package/dist/plugin-fastify.js +68 -0
- package/dist/plugin-fetch-client.js +172 -0
- package/dist/plugin-fetch-routes.js +110 -0
- package/dist/plugin-fetch-sample.js +155 -0
- package/dist/plugin-fetch-text.js +5 -0
- package/dist/plugin-fetch.js +19 -0
- package/dist/plugin-hono.js +42 -0
- package/dist/plugin-json-schema-build.js +289 -0
- package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
- package/dist/plugin-json-schema-dialect-gemini.js +29 -0
- package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
- package/dist/plugin-json-schema-dialect-mcp.js +13 -0
- package/dist/plugin-json-schema-dialect-openai.js +37 -0
- package/dist/plugin-json-schema-dialect.js +180 -0
- package/dist/plugin-json-schema.js +125 -0
- package/dist/plugin-markdown.js +114 -0
- package/dist/plugin-mcp-code.js +28 -0
- package/dist/plugin-mcp-tools.js +152 -0
- package/dist/plugin-mcp.js +107 -0
- package/dist/plugin-msw-files.js +50 -0
- package/dist/plugin-msw-sample.js +45 -0
- package/dist/plugin-msw-synth.js +116 -0
- package/dist/plugin-msw.js +30 -0
- package/dist/plugin-nest-code.js +68 -0
- package/dist/plugin-nest-contract.js +23 -0
- package/dist/plugin-nest.js +44 -0
- package/dist/plugin-server-code.js +61 -0
- package/dist/plugin-server-contract.js +48 -0
- package/dist/plugin-server-example.js +62 -0
- package/dist/plugin-server-router.js +77 -0
- package/dist/plugin-server-routes.js +155 -0
- package/dist/plugin-server-runtime.js +3 -0
- package/dist/plugin-server-sample.js +40 -0
- package/dist/plugin-swr-sample.js +21 -0
- package/dist/plugin-swr.js +40 -0
- package/dist/plugin-tanstack-query-sample.js +21 -0
- package/dist/plugin-tanstack-query.js +59 -0
- package/dist/plugin-types.js +80 -0
- package/dist/plugin-validator-code.js +41 -0
- package/dist/plugin-validator-names.js +27 -0
- package/dist/plugin-validator.js +103 -0
- package/dist/plugins.js +21 -0
- package/dist/props-emit.js +194 -0
- package/dist/props-generate.js +409 -0
- package/dist/props-judge.js +61 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +176 -0
- package/dist/props-shrink.js +75 -0
- package/dist/run-apply.js +25 -0
- package/dist/run-command.js +31 -0
- package/dist/run-commit.d.ts +51 -0
- package/dist/run-commit.js +48 -0
- package/dist/run-config.d.ts +193 -0
- package/dist/run-config.js +256 -0
- package/dist/run-diff.js +24 -0
- package/dist/run-extract.d.ts +13 -0
- package/dist/run-extract.js +21 -0
- package/dist/run-gen.d.ts +15 -0
- package/dist/run-gen.js +43 -0
- package/dist/run-header.js +37 -0
- package/dist/run-input.js +31 -0
- package/dist/run-load.js +32 -0
- package/dist/run-map.d.ts +41 -0
- package/dist/run-map.js +52 -0
- package/dist/run-plan.d.ts +31 -0
- package/dist/run-plan.js +35 -0
- package/dist/scaffold-seed.js +43 -0
- package/dist/scaffold-write.js +17 -0
- package/dist/scaffold.js +196 -0
- package/dist/testing-lint.js +43 -0
- package/dist/testing-owner.js +17 -0
- package/dist/testing-probe.js +25 -0
- package/dist/testing-rules.d.ts +65 -0
- package/dist/testing-rules.js +115 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.js +79 -0
- package/package.json +108 -4
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { fitted, unique } from './command-explain-name.js';
|
|
2
|
+
import { describe, tagsOf } from './command-explain-operation.js';
|
|
3
|
+
import { UsageError } from './run-config.js';
|
|
4
|
+
export const MAX_TOOLS = 40;
|
|
5
|
+
export const MAX_NAME = 64;
|
|
6
|
+
export const HIDDEN_TAGS = ['internal', 'health'];
|
|
7
|
+
export const CHARS_PER_TOKEN = 4;
|
|
8
|
+
const LARGEST = 3;
|
|
9
|
+
const LOCATIONS = ['path', 'query', 'header', 'cookie'];
|
|
10
|
+
const READ_ONLY = new Set(['GET', 'HEAD', 'OPTIONS']);
|
|
11
|
+
export const snake = (id) => id
|
|
12
|
+
.replaceAll(/([a-z\d])([A-Z])/gu, '$1_$2')
|
|
13
|
+
.replaceAll(/([A-Z])([A-Z][a-z])/gu, '$1_$2')
|
|
14
|
+
.replaceAll(/[^A-Za-z\d]+/gu, '_')
|
|
15
|
+
.replaceAll(/^_|_$/gu, '')
|
|
16
|
+
.toLowerCase() || 'operation';
|
|
17
|
+
export const toolNames = (ids) => unique(ids, (id) => fitted(snake(id), id, MAX_NAME), MAX_NAME);
|
|
18
|
+
const membersOf = (value) => Object(value);
|
|
19
|
+
const object = (properties, required) => ({
|
|
20
|
+
type: 'object',
|
|
21
|
+
properties,
|
|
22
|
+
...(required.length === 0 ? {} : { required }),
|
|
23
|
+
});
|
|
24
|
+
const inputOf = (explanation) => {
|
|
25
|
+
const properties = {};
|
|
26
|
+
const required = [];
|
|
27
|
+
for (const location of LOCATIONS) {
|
|
28
|
+
const prefix = `param:${location}:`;
|
|
29
|
+
const params = explanation.payloads.filter((payload) => payload.name.startsWith(prefix)).map((payload) => ({ ...payload, name: payload.name.slice(prefix.length) }));
|
|
30
|
+
if (params.length === 0)
|
|
31
|
+
continue;
|
|
32
|
+
const needed = params.filter((param) => param.required).map((param) => param.name);
|
|
33
|
+
properties[location] = object(Object.fromEntries(params.map((param) => [param.name, param.schema])), needed);
|
|
34
|
+
if (needed.length > 0)
|
|
35
|
+
required.push(location);
|
|
36
|
+
}
|
|
37
|
+
const bodies = explanation.payloads.filter((payload) => payload.name.startsWith('body:') && !payload.name.endsWith(':item'));
|
|
38
|
+
const body = bodies.find((payload) => payload.name.includes('json')) ?? bodies[0];
|
|
39
|
+
if (body !== undefined) {
|
|
40
|
+
properties.body = body.schema;
|
|
41
|
+
if (body.required)
|
|
42
|
+
required.push('body');
|
|
43
|
+
}
|
|
44
|
+
return { ...object(properties, required), additionalProperties: false };
|
|
45
|
+
};
|
|
46
|
+
const outputOf = (explanation) => {
|
|
47
|
+
const success = explanation.payloads.find((payload) => /response:2\d\d:[^:]*json[^:]*$/u.test(payload.name));
|
|
48
|
+
if (success === undefined)
|
|
49
|
+
return { wrap: false };
|
|
50
|
+
if (membersOf(success.schema).type === 'object')
|
|
51
|
+
return { schema: success.schema, wrap: false };
|
|
52
|
+
return { schema: object({ result: success.schema }, ['result']), wrap: true };
|
|
53
|
+
};
|
|
54
|
+
const toolOf = (explanation, name) => {
|
|
55
|
+
const method = explanation.method;
|
|
56
|
+
const route = explanation.path;
|
|
57
|
+
const output = outputOf(explanation);
|
|
58
|
+
const prose = [explanation.summary, explanation.description].filter((text) => text !== undefined);
|
|
59
|
+
return {
|
|
60
|
+
name,
|
|
61
|
+
...(explanation.summary === undefined ? {} : { title: explanation.summary }),
|
|
62
|
+
description: prose.length === 0 ? `${method} ${route}` : prose.join('\n\n'),
|
|
63
|
+
inputSchema: inputOf(explanation),
|
|
64
|
+
...(output.schema === undefined ? {} : { outputSchema: output.schema }),
|
|
65
|
+
annotations: { readOnlyHint: READ_ONLY.has(method) },
|
|
66
|
+
route: { operationId: explanation.id, method, path: route, output: output.schema !== undefined, wrap: output.wrap },
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
const listed = ({ route: _route, ...tool }) => tool;
|
|
70
|
+
export const tokensOf = (tools) => Math.ceil(JSON.stringify(tools.map(listed)).length / CHARS_PER_TOKEN);
|
|
71
|
+
export const optionsOf = (options) => {
|
|
72
|
+
const { include, transport = 'stdio', budget } = options;
|
|
73
|
+
if (transport !== 'stdio' && transport !== 'http')
|
|
74
|
+
throw new UsageError(`mcp: transport is "${String(transport)}". fix: set \`transport\` to "stdio" or "http"`);
|
|
75
|
+
if (budget !== undefined && !(Number.isSafeInteger(budget) && budget > 0)) {
|
|
76
|
+
throw new UsageError(`mcp: budget is ${JSON.stringify(budget)}. fix: set \`budget\` to a whole number of tokens above 0, e.g. 4000`);
|
|
77
|
+
}
|
|
78
|
+
const sized = budget === undefined ? {} : { budget: budget };
|
|
79
|
+
if (include === undefined)
|
|
80
|
+
return { transport, ...sized };
|
|
81
|
+
if (!Array.isArray(include) || !include.every((entry) => typeof entry === 'string' && entry !== '')) {
|
|
82
|
+
throw new UsageError('mcp: `include` is not a list of operation ids. fix: set `include` to ids or `tag:<name>` entries, e.g. ["listPets", "tag:admin"]');
|
|
83
|
+
}
|
|
84
|
+
return { include: include, transport, ...sized };
|
|
85
|
+
};
|
|
86
|
+
const finding = (code, pointer, message, fix) => ({ code, pointer, message, fix });
|
|
87
|
+
export const toolsOf = (contract, options) => {
|
|
88
|
+
const findings = [];
|
|
89
|
+
const { include } = options;
|
|
90
|
+
const hidden = [];
|
|
91
|
+
const hiddenBy = new Set();
|
|
92
|
+
const chosen = contract.operations.filter((operation) => {
|
|
93
|
+
const tags = tagsOf(contract, operation);
|
|
94
|
+
const named = (entry) => (entry.startsWith('tag:') ? tags.includes(entry.slice('tag:'.length)) : entry === operation.id);
|
|
95
|
+
const hiding = tags.filter((tag) => HIDDEN_TAGS.includes(tag));
|
|
96
|
+
const unhidden = include?.some((entry) => entry === operation.id || hiding.some((tag) => entry === `tag:${tag}`)) === true;
|
|
97
|
+
if (hiding.length > 0 && !unhidden) {
|
|
98
|
+
if (include === undefined || include.some(named)) {
|
|
99
|
+
hidden.push(operation.id);
|
|
100
|
+
for (const tag of hiding)
|
|
101
|
+
hiddenBy.add(tag);
|
|
102
|
+
}
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
return include === undefined || include.some(named);
|
|
106
|
+
});
|
|
107
|
+
const tagsHiding = HIDDEN_TAGS.filter((tag) => hiddenBy.has(tag));
|
|
108
|
+
if (hidden.length > 0) {
|
|
109
|
+
findings.push(finding('mcp-hidden', '#/paths', `left out ${String(hidden.length)} operation(s) tagged ${tagsHiding.join(' or ')}: ${hidden.join(', ')}`, `name one in \`include\` (its id, or ${tagsHiding.map((tag) => `\`tag:${tag}\``).join(' or ')}) if an agent should call it`));
|
|
110
|
+
}
|
|
111
|
+
for (const entry of include ?? []) {
|
|
112
|
+
const matched = contract.operations.some((operation) => (entry.startsWith('tag:') ? tagsOf(contract, operation).includes(entry.slice('tag:'.length)) : entry === operation.id));
|
|
113
|
+
if (!matched)
|
|
114
|
+
findings.push(finding('mcp-include-unmatched', '#', `\`include\` names "${entry}", which matches no operation`, 'use an operation id from `contractdiff explain --list`, or `tag:<name>` with a tag the spec declares'));
|
|
115
|
+
}
|
|
116
|
+
const explained = chosen.map((operation) => describe(contract, operation));
|
|
117
|
+
const routed = explained.filter((explanation) => {
|
|
118
|
+
if (explanation.method !== undefined)
|
|
119
|
+
return true;
|
|
120
|
+
findings.push(finding('mcp-not-http', explanation.source, `"${explanation.id}" has no HTTP route, so it is not a tool`, 'leave it out of `include`; a webhook is called by the API, not by an agent'));
|
|
121
|
+
return false;
|
|
122
|
+
});
|
|
123
|
+
if (include === undefined && routed.length > MAX_TOOLS) {
|
|
124
|
+
findings.push(finding('mcp-too-many-tools', '#/paths', `the spec has ${String(routed.length)} operations and no tool was generated: past ${String(MAX_TOOLS)} tools an agent picks worse`, 'set the `include` option of the mcp target to the operation ids or `tag:<name>` entries the agent needs'));
|
|
125
|
+
return { tools: [], findings };
|
|
126
|
+
}
|
|
127
|
+
const names = toolNames(routed.map((explanation) => explanation.id));
|
|
128
|
+
for (const explanation of routed) {
|
|
129
|
+
if (explanation.cycles !== undefined) {
|
|
130
|
+
findings.push(finding('mcp-cycle-cut', explanation.source, `"${explanation.id}" has a recursive schema; the tool's schema accepts anything where it repeats (${explanation.cycles.join(', ')})`, 'accept the looser schema, or validate the recursion in the handler'));
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
const tools = routed.map((explanation) => toolOf(explanation, names.get(explanation.id)));
|
|
134
|
+
return options.budget === undefined ? { tools, findings } : withinBudget(tools, findings, options.budget);
|
|
135
|
+
};
|
|
136
|
+
const withinBudget = (tools, findings, budget) => {
|
|
137
|
+
const size = tokensOf(tools);
|
|
138
|
+
const estimate = `about ${String(size)} of ${String(budget)} tokens (estimate: characters ÷ ${String(CHARS_PER_TOKEN)})`;
|
|
139
|
+
if (size <= budget)
|
|
140
|
+
return { tools, findings: [...findings, finding('mcp-budget', '#', `${String(tools.length)} tool(s), ${estimate}`, 'nothing to do')] };
|
|
141
|
+
const largest = [...tools]
|
|
142
|
+
.sort((a, b) => tokensOf([b]) - tokensOf([a]) || a.name.localeCompare(b.name, 'en'))
|
|
143
|
+
.slice(0, LARGEST)
|
|
144
|
+
.map((tool) => `${tool.name} (${String(tokensOf([tool]))})`);
|
|
145
|
+
return {
|
|
146
|
+
tools: [],
|
|
147
|
+
findings: [
|
|
148
|
+
...findings,
|
|
149
|
+
finding('mcp-over-budget', '#', `no tool was generated: ${String(tools.length)} tool(s) take ${estimate}; the largest are ${largest.join(', ')}`, 'narrow `include` to the operation ids or `tag:<name>` entries the agent needs, or raise `budget`'),
|
|
150
|
+
],
|
|
151
|
+
};
|
|
152
|
+
};
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { clientFile, HANDLERS, serverFile, toolsFile } from './plugin-mcp-code.js';
|
|
2
|
+
import { optionsOf, toolsOf } from './plugin-mcp-tools.js';
|
|
3
|
+
const membersOf = (value) => Object(value);
|
|
4
|
+
const text = (value, fallback) => (typeof value === 'string' && value !== '' ? value : fallback);
|
|
5
|
+
const identity = (document) => {
|
|
6
|
+
const info = membersOf(membersOf(document).info);
|
|
7
|
+
return { name: text(info.title, 'api'), version: text(info.version, '0.0.0') };
|
|
8
|
+
};
|
|
9
|
+
export const run = (contract, options) => {
|
|
10
|
+
const checked = optionsOf(options);
|
|
11
|
+
const { tools, findings } = toolsOf(contract, checked);
|
|
12
|
+
const { name, version } = identity(contract.document);
|
|
13
|
+
const files = [
|
|
14
|
+
{ path: 'tools.ts', owner: 'generated', content: toolsFile(tools) },
|
|
15
|
+
{ path: 'client.ts', owner: 'generated', content: clientFile(tools.map((tool) => tool.name)) },
|
|
16
|
+
{ path: 'server.ts', owner: 'generated', content: serverFile(name, version, checked.transport) },
|
|
17
|
+
{ path: 'handlers.ts', owner: 'user', content: HANDLERS },
|
|
18
|
+
];
|
|
19
|
+
return { files, findings: findings };
|
|
20
|
+
};
|
|
21
|
+
const document = {
|
|
22
|
+
openapi: '3.1.0',
|
|
23
|
+
info: { title: 'Pets', version: '1.0.0' },
|
|
24
|
+
paths: {
|
|
25
|
+
'/pets/{petId}': {
|
|
26
|
+
get: {
|
|
27
|
+
operationId: 'getPet',
|
|
28
|
+
summary: 'One pet',
|
|
29
|
+
parameters: [{ name: 'petId', in: 'path', schema: { type: 'string' } }],
|
|
30
|
+
responses: { '200': { content: { 'application/json': { schema: { type: 'object', properties: { id: { type: 'string' } } } } } } },
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
};
|
|
35
|
+
const SAMPLE_TOOLS = `import { type Tool } from '@modelcontextprotocol/sdk/types.js';
|
|
36
|
+
|
|
37
|
+
/** One tool per operation: what \`tools/list\` answers. */
|
|
38
|
+
export const tools: Tool[] = [
|
|
39
|
+
{
|
|
40
|
+
"name": "get_pet",
|
|
41
|
+
"title": "One pet",
|
|
42
|
+
"description": "One pet",
|
|
43
|
+
"inputSchema": {
|
|
44
|
+
"type": "object",
|
|
45
|
+
"properties": {
|
|
46
|
+
"path": {
|
|
47
|
+
"type": "object",
|
|
48
|
+
"properties": {
|
|
49
|
+
"petId": {
|
|
50
|
+
"type": "string"
|
|
51
|
+
}
|
|
52
|
+
},
|
|
53
|
+
"required": [
|
|
54
|
+
"petId"
|
|
55
|
+
]
|
|
56
|
+
}
|
|
57
|
+
},
|
|
58
|
+
"required": [
|
|
59
|
+
"path"
|
|
60
|
+
],
|
|
61
|
+
"additionalProperties": false
|
|
62
|
+
},
|
|
63
|
+
"outputSchema": {
|
|
64
|
+
"type": "object",
|
|
65
|
+
"properties": {
|
|
66
|
+
"id": {
|
|
67
|
+
"type": "string"
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
"annotations": {
|
|
72
|
+
"readOnlyHint": true
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
];
|
|
76
|
+
|
|
77
|
+
/** The HTTP route each tool calls, and whether its result is sent as structured content. */
|
|
78
|
+
export const routes = {
|
|
79
|
+
"get_pet": {
|
|
80
|
+
"operationId": "getPet",
|
|
81
|
+
"method": "GET",
|
|
82
|
+
"path": "/pets/{petId}",
|
|
83
|
+
"output": true,
|
|
84
|
+
"wrap": false
|
|
85
|
+
}
|
|
86
|
+
} as const;
|
|
87
|
+
`;
|
|
88
|
+
const mcp = {
|
|
89
|
+
description: 'An MCP server with one tool per operation: schemas, read-only hints, and handlers that call the API',
|
|
90
|
+
inputs: ['openapi', 'swagger2'],
|
|
91
|
+
options: {
|
|
92
|
+
include: { type: 'string', multiple: true, description: 'only these operation ids, or `tag:<name>`; required past 40 operations' },
|
|
93
|
+
transport: { type: 'string', choices: ['stdio', 'http'], description: 'stdio (default) or Streamable HTTP' },
|
|
94
|
+
budget: { type: 'number', description: 'the most tokens the tool list may take (estimated as characters ÷ 4); over it, no tool is generated' },
|
|
95
|
+
},
|
|
96
|
+
sample: {
|
|
97
|
+
document,
|
|
98
|
+
files: [
|
|
99
|
+
{ path: 'tools.ts', owner: 'generated', content: SAMPLE_TOOLS },
|
|
100
|
+
{ path: 'client.ts', owner: 'generated', content: clientFile(['get_pet']) },
|
|
101
|
+
{ path: 'server.ts', owner: 'generated', content: serverFile('Pets', '1.0.0', 'stdio') },
|
|
102
|
+
{ path: 'handlers.ts', owner: 'user', content: HANDLERS },
|
|
103
|
+
],
|
|
104
|
+
},
|
|
105
|
+
run,
|
|
106
|
+
};
|
|
107
|
+
export const plugin = { name: 'mcp', generators: { mcp } };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { lines, literal } from './plugin-fetch-text.js';
|
|
2
|
+
import { exampleOf, seedOf, synth } from './plugin-msw-synth.js';
|
|
3
|
+
const isRecord = (value) => typeof value === 'object' && value !== null;
|
|
4
|
+
const DEFAULT_STATUS = 500;
|
|
5
|
+
const RANGE = 100;
|
|
6
|
+
const statusOf = (key, exact) => {
|
|
7
|
+
if (/^\d+$/u.test(key))
|
|
8
|
+
return Number(key);
|
|
9
|
+
const first = key === 'default' ? DEFAULT_STATUS : Number(key.charAt(0)) * RANGE;
|
|
10
|
+
let status = first;
|
|
11
|
+
while (exact.includes(String(status)))
|
|
12
|
+
status += 1;
|
|
13
|
+
return status;
|
|
14
|
+
};
|
|
15
|
+
export const scenariosOf = (routes, root) => {
|
|
16
|
+
const findings = [];
|
|
17
|
+
const scenario = (route, response, exact) => {
|
|
18
|
+
const status = statusOf(response.key, exact);
|
|
19
|
+
const [media] = response.media;
|
|
20
|
+
if (media === undefined)
|
|
21
|
+
return { status };
|
|
22
|
+
const examples = Object.values(isRecord(media.declared.examples) ? media.declared.examples : {});
|
|
23
|
+
const given = exampleOf(media.declared) ?? (examples.length > 0 ? { value: examples[0].value } : undefined) ?? (isRecord(media.schema) ? exampleOf(media.schema) : undefined);
|
|
24
|
+
if (given !== undefined)
|
|
25
|
+
return { status, contentType: media.type, body: given.value };
|
|
26
|
+
findings.push({
|
|
27
|
+
code: 'value-synthesised',
|
|
28
|
+
pointer: media.pointer,
|
|
29
|
+
message: `the ${response.key} response of "${route.id}" has no example, so its mock body is synthesised from the schema`,
|
|
30
|
+
fix: 'add an `example` to the media type to mock it with a value you chose',
|
|
31
|
+
});
|
|
32
|
+
return { status, contentType: media.type, body: synth(media.schema, seedOf(`${route.id} ${response.key}`), root) };
|
|
33
|
+
};
|
|
34
|
+
const scenarios = Object.fromEntries(routes.map((route) => {
|
|
35
|
+
const exact = route.responses.map((response) => response.key);
|
|
36
|
+
return [route.id, Object.fromEntries(route.responses.map((response) => [response.key, scenario(route, response, exact)]))];
|
|
37
|
+
}));
|
|
38
|
+
return { scenarios, findings };
|
|
39
|
+
};
|
|
40
|
+
export const scenariosFile = (built) => lines('/** One response for a declared status: what a mock answers with. */', 'export interface Scenario {', ' readonly status: number;', ' readonly contentType?: string;', ' readonly body?: unknown;', '}', '', '/** Every operation\'s scenarios, by operation id and the status as the spec writes it. */', 'export const scenarios = {', ...Object.entries(built.scenarios).flatMap(([id, byStatus]) => [
|
|
41
|
+
` ${literal(id)}: {`,
|
|
42
|
+
...Object.entries(byStatus).map(([status, scenario]) => ` ${literal(status)}: ${literal(scenario)},`),
|
|
43
|
+
' },',
|
|
44
|
+
]), '} as const satisfies Readonly<Record<string, Readonly<Record<string, Scenario>>>>;');
|
|
45
|
+
const preferred = (route) => (route.responses.find((response) => response.key.startsWith('2')) ?? route.responses[0])?.key;
|
|
46
|
+
const mswPath = (path) => `*${path.replaceAll(/\{([^}]+)\}/gu, ':$1')}`;
|
|
47
|
+
export const handlersFile = (routes) => lines("import { http, HttpResponse } from 'msw';", '', "import { type Scenario, scenarios } from './scenarios.js';", '', 'const routes = {', ...routes.map((route) => ` ${literal(route.id)}: [${literal(route.method)}, ${literal(mswPath(route.path))}],`), '} as const;', '', 'type Scenarios = typeof scenarios;', '', '/** A scenario as a response. */', 'const reply = (scenario: Scenario): Response => {', ' if (scenario.body === undefined) return new HttpResponse(null, { status: scenario.status });', ' const type = scenario.contentType ?? "application/json";', ' const text = /[/+]json(?:;|$)/u.test(type) ? JSON.stringify(scenario.body) : String(scenario.body);', ' return new HttpResponse(text, { status: scenario.status, headers: { "content-type": type } });', '};', '', '/** The handler answering `operation` with the scenario for `status`, e.g. `server.use(handler("getPet", "404"))`. */', 'export const handler = <O extends keyof Scenarios>(operation: O, status: keyof Scenarios[O]) => {', ' const [method, path] = routes[operation];', ' return http[method](path, () => reply(scenarios[operation][status] as Scenario));', '};', '', '/** One handler per operation, answering with its first 2xx scenario. */', 'export const handlers = [', ...routes.flatMap((route) => {
|
|
48
|
+
const status = preferred(route);
|
|
49
|
+
return status === undefined ? [] : [` handler(${literal(route.id)}, ${literal(status)}),`];
|
|
50
|
+
}), '];');
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
export const document = { "openapi": "3.1.0", "paths": { "/pets/{petId}": { "get": { "operationId": "getPet", "responses": { "200": { "content": { "application/json": { "example": { "id": "p1", "name": "Rex" } } } }, "404": { "content": { "application/json": { "schema": { "properties": { "message": { "type": "string" } } } } } } } } } } };
|
|
2
|
+
export const SAMPLE_HANDLERS = `import { http, HttpResponse } from 'msw';
|
|
3
|
+
|
|
4
|
+
import { type Scenario, scenarios } from './scenarios.js';
|
|
5
|
+
|
|
6
|
+
const routes = {
|
|
7
|
+
"getPet": ["get", "*/pets/:petId"],
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
type Scenarios = typeof scenarios;
|
|
11
|
+
|
|
12
|
+
/** A scenario as a response. */
|
|
13
|
+
const reply = (scenario: Scenario): Response => {
|
|
14
|
+
if (scenario.body === undefined) return new HttpResponse(null, { status: scenario.status });
|
|
15
|
+
const type = scenario.contentType ?? "application/json";
|
|
16
|
+
const text = /[/+]json(?:;|$)/u.test(type) ? JSON.stringify(scenario.body) : String(scenario.body);
|
|
17
|
+
return new HttpResponse(text, { status: scenario.status, headers: { "content-type": type } });
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
/** The handler answering \`operation\` with the scenario for \`status\`, e.g. \`server.use(handler("getPet", "404"))\`. */
|
|
21
|
+
export const handler = <O extends keyof Scenarios>(operation: O, status: keyof Scenarios[O]) => {
|
|
22
|
+
const [method, path] = routes[operation];
|
|
23
|
+
return http[method](path, () => reply(scenarios[operation][status] as Scenario));
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/** One handler per operation, answering with its first 2xx scenario. */
|
|
27
|
+
export const handlers = [
|
|
28
|
+
handler("getPet", "200"),
|
|
29
|
+
];
|
|
30
|
+
`;
|
|
31
|
+
export const SAMPLE_SCENARIOS = `/** One response for a declared status: what a mock answers with. */
|
|
32
|
+
export interface Scenario {
|
|
33
|
+
readonly status: number;
|
|
34
|
+
readonly contentType?: string;
|
|
35
|
+
readonly body?: unknown;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Every operation's scenarios, by operation id and the status as the spec writes it. */
|
|
39
|
+
export const scenarios = {
|
|
40
|
+
"getPet": {
|
|
41
|
+
"200": {"status":200,"contentType":"application/json","body":{"id":"p1","name":"Rex"}},
|
|
42
|
+
"404": {"status":404,"contentType":"application/json","body":{"message":"hotel"}},
|
|
43
|
+
},
|
|
44
|
+
} as const satisfies Readonly<Record<string, Readonly<Record<string, Scenario>>>>;
|
|
45
|
+
`;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
const FORMATS = {
|
|
4
|
+
date: '2024-01-15',
|
|
5
|
+
'date-time': '2024-01-15T09:30:00Z',
|
|
6
|
+
time: '09:30:00Z',
|
|
7
|
+
email: 'user@example.com',
|
|
8
|
+
uuid: '3f2b6c1e-8d4a-4c7e-9b1f-5a6d7e8f9a0b',
|
|
9
|
+
uri: 'https://example.com/',
|
|
10
|
+
hostname: 'example.com',
|
|
11
|
+
ipv4: '192.0.2.1',
|
|
12
|
+
ipv6: '2001:db8::1',
|
|
13
|
+
};
|
|
14
|
+
const FNV_OFFSET = 2_166_136_261;
|
|
15
|
+
const FNV_PRIME = 16_777_619;
|
|
16
|
+
const LCG_MULTIPLIER = 1_103_515_245;
|
|
17
|
+
const LCG_INCREMENT = 12_345;
|
|
18
|
+
const HIGH_HALF = 16;
|
|
19
|
+
const SPAN = 99;
|
|
20
|
+
const WORDS = ['alpha', 'bravo', 'charlie', 'delta', 'echo', 'foxtrot', 'golf', 'hotel'];
|
|
21
|
+
export const seedOf = (text) => {
|
|
22
|
+
let hash = FNV_OFFSET;
|
|
23
|
+
for (const character of text)
|
|
24
|
+
hash = Math.imul(hash ^ character.codePointAt(0), FNV_PRIME) >>> 0;
|
|
25
|
+
return hash;
|
|
26
|
+
};
|
|
27
|
+
export const exampleOf = (node) => {
|
|
28
|
+
if (node.example !== undefined)
|
|
29
|
+
return { value: node.example };
|
|
30
|
+
if (Array.isArray(node.examples) && node.examples.length > 0)
|
|
31
|
+
return { value: node.examples[0] };
|
|
32
|
+
return undefined;
|
|
33
|
+
};
|
|
34
|
+
const typeOf = (node) => {
|
|
35
|
+
if (Array.isArray(node.type))
|
|
36
|
+
return node.type.find((type) => type !== 'null');
|
|
37
|
+
if (node.type !== undefined)
|
|
38
|
+
return node.type;
|
|
39
|
+
if (node.properties !== undefined)
|
|
40
|
+
return 'object';
|
|
41
|
+
return node.items === undefined ? undefined : 'array';
|
|
42
|
+
};
|
|
43
|
+
const bound = (node, inclusive, exclusive, step) => {
|
|
44
|
+
if (typeof node[inclusive] === 'number')
|
|
45
|
+
return node[inclusive];
|
|
46
|
+
return typeof node[exclusive] === 'number' ? Math.floor(node[exclusive]) + step : undefined;
|
|
47
|
+
};
|
|
48
|
+
export const synth = (schema, seed, root = schema) => {
|
|
49
|
+
let state = seed >>> 0;
|
|
50
|
+
const draw = (count) => {
|
|
51
|
+
state = (Math.imul(state, LCG_MULTIPLIER) + LCG_INCREMENT) >>> 0;
|
|
52
|
+
return (state >>> HIGH_HALF) % count;
|
|
53
|
+
};
|
|
54
|
+
const open = new Set();
|
|
55
|
+
const value = (node) => {
|
|
56
|
+
if (!isDict(node))
|
|
57
|
+
return null;
|
|
58
|
+
if (typeof node.$ref === 'string') {
|
|
59
|
+
if (open.has(node.$ref))
|
|
60
|
+
return undefined;
|
|
61
|
+
open.add(node.$ref);
|
|
62
|
+
const target = value(pointerGet(root, node.$ref));
|
|
63
|
+
open.delete(node.$ref);
|
|
64
|
+
return target;
|
|
65
|
+
}
|
|
66
|
+
if ('const' in node)
|
|
67
|
+
return node.const;
|
|
68
|
+
if (Array.isArray(node.enum) && node.enum.length > 0)
|
|
69
|
+
return node.enum[draw(node.enum.length)];
|
|
70
|
+
const example = exampleOf(node);
|
|
71
|
+
if (example !== undefined)
|
|
72
|
+
return example.value;
|
|
73
|
+
return composed(node);
|
|
74
|
+
};
|
|
75
|
+
const composed = (node) => {
|
|
76
|
+
if (Array.isArray(node.allOf)) {
|
|
77
|
+
const parts = node.allOf.map((part) => value(part));
|
|
78
|
+
return parts.every((part) => isDict(part)) ? Object.assign({}, ...parts) : parts[0];
|
|
79
|
+
}
|
|
80
|
+
const [branch] = [node.oneOf, node.anyOf].find((list) => Array.isArray(list)) ?? [];
|
|
81
|
+
return branch === undefined ? typed(node) : value(branch);
|
|
82
|
+
};
|
|
83
|
+
const text = (node) => {
|
|
84
|
+
const format = String(node.format);
|
|
85
|
+
if (Object.hasOwn(FORMATS, format))
|
|
86
|
+
return FORMATS[format];
|
|
87
|
+
const word = WORDS[draw(WORDS.length)];
|
|
88
|
+
return word.padEnd(node.minLength, word).slice(0, node.maxLength);
|
|
89
|
+
};
|
|
90
|
+
const typed = (node) => {
|
|
91
|
+
switch (typeOf(node)) {
|
|
92
|
+
case 'string':
|
|
93
|
+
return text(node);
|
|
94
|
+
case 'integer':
|
|
95
|
+
case 'number': {
|
|
96
|
+
const low = bound(node, 'minimum', 'exclusiveMinimum', 1) ?? 0;
|
|
97
|
+
const high = bound(node, 'maximum', 'exclusiveMaximum', -1) ?? low + SPAN;
|
|
98
|
+
return low + draw(high - low + 1);
|
|
99
|
+
}
|
|
100
|
+
case 'boolean':
|
|
101
|
+
return draw(2) === 0;
|
|
102
|
+
case 'array': {
|
|
103
|
+
const item = value(node.items);
|
|
104
|
+
const count = typeof node.minItems === 'number' ? Math.max(node.minItems, 1) : 1;
|
|
105
|
+
return item === undefined ? [] : Array.from({ length: count }, (_, index) => (index === 0 ? item : value(node.items)));
|
|
106
|
+
}
|
|
107
|
+
case 'object':
|
|
108
|
+
return Object.fromEntries(Object.entries(isDict(node.properties) ? node.properties : {})
|
|
109
|
+
.map(([name, property]) => [name, value(property)])
|
|
110
|
+
.filter((entry) => entry[1] !== undefined));
|
|
111
|
+
default:
|
|
112
|
+
return null;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
return value(schema) ?? null;
|
|
116
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { routesOf } from './plugin-fetch-routes.js';
|
|
2
|
+
import { handlersFile, scenariosFile, scenariosOf } from './plugin-msw-files.js';
|
|
3
|
+
import { document, SAMPLE_HANDLERS, SAMPLE_SCENARIOS } from './plugin-msw-sample.js';
|
|
4
|
+
export const HANDLERS_FILE = 'handlers.ts';
|
|
5
|
+
export const SCENARIOS_FILE = 'scenarios.ts';
|
|
6
|
+
const run = (contract) => {
|
|
7
|
+
const { routes, findings } = routesOf(contract);
|
|
8
|
+
const built = scenariosOf(routes, contract.document);
|
|
9
|
+
const symbols = routes.map((route) => ({ operation: route.id, symbol: route.id }));
|
|
10
|
+
return {
|
|
11
|
+
files: [
|
|
12
|
+
{ path: HANDLERS_FILE, owner: 'generated', content: handlersFile(routes), symbols },
|
|
13
|
+
{ path: SCENARIOS_FILE, owner: 'generated', content: scenariosFile(built), symbols },
|
|
14
|
+
],
|
|
15
|
+
findings: [...findings, ...built.findings],
|
|
16
|
+
};
|
|
17
|
+
};
|
|
18
|
+
const msw = {
|
|
19
|
+
description: 'MSW handlers and a scenario for every declared response, from the spec’s examples or a seeded synthesis',
|
|
20
|
+
inputs: ['openapi'],
|
|
21
|
+
sample: {
|
|
22
|
+
document,
|
|
23
|
+
files: [
|
|
24
|
+
{ path: HANDLERS_FILE, owner: 'generated', content: SAMPLE_HANDLERS },
|
|
25
|
+
{ path: SCENARIOS_FILE, owner: 'generated', content: SAMPLE_SCENARIOS },
|
|
26
|
+
],
|
|
27
|
+
},
|
|
28
|
+
run,
|
|
29
|
+
};
|
|
30
|
+
export const plugin = { name: 'msw', generators: { msw } };
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { lines, literal, operationTypes, partsOf, pascal, readAs, routePath, stubResponse, where } from './plugin-server-code.js';
|
|
2
|
+
const DECORATORS = { get: 'Get', put: 'Put', post: 'Post', delete: 'Delete', options: 'Options', head: 'Head', patch: 'Patch' };
|
|
3
|
+
const handler = (route) => {
|
|
4
|
+
const validator = (payload) => `validators[${literal(route.id)}][${literal(payload)}]`;
|
|
5
|
+
const parts = partsOf(route);
|
|
6
|
+
const DECORATED = { path: '@Param() path: Record<string, unknown>', query: '@Query() query: Record<string, unknown>', header: '@Headers() header: Record<string, unknown>' };
|
|
7
|
+
const parameters = [...parts.map((part) => DECORATED[part]), ...(route.body === undefined ? [] : ['@Body() body: unknown']), '@Res({ passthrough: true }) reply: Reply'];
|
|
8
|
+
const input = [
|
|
9
|
+
...parts.map((part) => {
|
|
10
|
+
const fields = route.params.filter((param) => param.part === part).map((param) => `${literal(param.name)}: coerce(${part}[${literal(readAs(part, param.name))}], ${literal(param.kind)})`);
|
|
11
|
+
return ` ${part}: { ${fields.join(', ')} },`;
|
|
12
|
+
}),
|
|
13
|
+
...(route.body === undefined ? [] : [' body,']),
|
|
14
|
+
];
|
|
15
|
+
const fields = [
|
|
16
|
+
...route.params.map((param) => ` { pointer: ${literal(`/${param.part}/${param.name}`)}, value: input.${param.part}[${literal(param.name)}], required: ${String(param.required)}, check: ${validator(param.payload)} },`),
|
|
17
|
+
...(route.body === undefined ? [] : [` { pointer: "/body", value: input.body, required: ${String(route.body.required)}, check: ${validator(route.body.payload)} },`]),
|
|
18
|
+
];
|
|
19
|
+
const responses = route.responses.map(({ status, content }) => {
|
|
20
|
+
const declared = content === undefined ? '{}' : `{ media: ${literal(content.media)}, check: ${validator(content.payload)} }`;
|
|
21
|
+
return ` ${literal(status)}: ${declared},`;
|
|
22
|
+
});
|
|
23
|
+
return [
|
|
24
|
+
` /** ${where(route)}: validates the request, calls \`${route.name}\`, and checks what it answers. */`,
|
|
25
|
+
` @${DECORATORS[route.method]}(${literal(routePath(route.path))})`,
|
|
26
|
+
` async ${route.handler}(${parameters.join(', ')}): Promise<unknown> {`,
|
|
27
|
+
' const input = {',
|
|
28
|
+
...input,
|
|
29
|
+
' };',
|
|
30
|
+
' const errors = invalid([',
|
|
31
|
+
...fields,
|
|
32
|
+
' ]);',
|
|
33
|
+
" if (errors.length > 0) return problem(reply, 400, 'Bad Request', 'The request does not match the contract.', errors);",
|
|
34
|
+
` return send(reply, await this.${route.name}(input as unknown as ${pascal(route.name)}Input), {`,
|
|
35
|
+
...responses,
|
|
36
|
+
' });',
|
|
37
|
+
' }',
|
|
38
|
+
];
|
|
39
|
+
};
|
|
40
|
+
export const baseFile = (controller, imports) => {
|
|
41
|
+
const decorators = new Set(['Res']);
|
|
42
|
+
for (const route of controller.routes) {
|
|
43
|
+
decorators.add(DECORATORS[route.method]);
|
|
44
|
+
if (route.params.some((param) => param.part === 'path'))
|
|
45
|
+
decorators.add('Param');
|
|
46
|
+
if (route.params.some((param) => param.part === 'query'))
|
|
47
|
+
decorators.add('Query');
|
|
48
|
+
if (route.params.some((param) => param.part === 'header'))
|
|
49
|
+
decorators.add('Headers');
|
|
50
|
+
if (route.body !== undefined)
|
|
51
|
+
decorators.add('Body');
|
|
52
|
+
}
|
|
53
|
+
const coerced = controller.routes.some((route) => route.params.length > 0);
|
|
54
|
+
const validated = coerced || controller.routes.some((route) => route.body !== undefined || route.responses.some((response) => response.content !== undefined));
|
|
55
|
+
return lines(`import { ${[...decorators].toSorted().join(', ')} } from '@nestjs/common';`, '', `import { ${[...(coerced ? ['coerce'] : []), 'invalid', 'problem', 'type Reply', 'send'].join(', ')} } from './contract-runtime.js';`, `import { type paths } from ${literal(imports.types)};`, ...(validated ? [`import { operations as validators } from ${literal(imports.validators)};`] : []), '', ...controller.routes.flatMap((route) => [...operationTypes(route), '']), '/**', ` * Every \`${controller.file}\` route. Extend it with a class decorated \`@Controller()\` and implement each method:`, ' * a new operation in the spec is a new abstract method, so the extending class stops compiling until it has one.', ' */', `export abstract class ${controller.name}ControllerBase {`, ...controller.routes.flatMap((route) => [
|
|
56
|
+
` /** ${where(route)}. */`,
|
|
57
|
+
` abstract ${route.name}(input: ${pascal(route.name)}Input): ${pascal(route.name)}Output | Promise<${pascal(route.name)}Output>;`,
|
|
58
|
+
'',
|
|
59
|
+
]), ...controller.routes.flatMap((route, index) => [...(index === 0 ? [] : ['']), ...handler(route)]), '}');
|
|
60
|
+
};
|
|
61
|
+
export const controllerFile = (controller) => lines('/**', ` * The \`${controller.file}\` routes. contractdiff wrote this file once and never rewrites it: change it freely.`, ` * \`${controller.name}ControllerBase\` (${controller.file}.controller.base.ts, regenerated) declares one method per`, ' * operation and validates every request and response; each method here answers the spec\'s example until you replace it.', ' */', "import { Controller } from '@nestjs/common';", '', `import { ${[`${controller.name}ControllerBase`, ...controller.routes.flatMap((route) => [`type ${pascal(route.name)}Input`, `type ${pascal(route.name)}Output`])].join(', ')} } from './${controller.file}.controller.base.js';`, '', '@Controller()', `export class ${controller.name}Controller extends ${controller.name}ControllerBase {`, ...controller.routes.flatMap((route, index) => [
|
|
62
|
+
...(index === 0 ? [] : ['']),
|
|
63
|
+
` /** ${where(route)}. */`,
|
|
64
|
+
` ${route.name}(_input: ${pascal(route.name)}Input): ${pascal(route.name)}Output {`,
|
|
65
|
+
` ${stubResponse(route)}`,
|
|
66
|
+
' }',
|
|
67
|
+
]), '}');
|
|
68
|
+
export const moduleFile = (controllers) => lines("import { Module } from '@nestjs/common';", '', ...controllers.map((controller) => `import { ${controller.name}Controller } from './${controller.file}.controller.js';`), '', '/** Every controller generated from the spec. Import it into your application\'s module. */', `@Module({ controllers: [${controllers.map((controller) => `${controller.name}Controller`).join(', ')}] })`, 'export class ApiModule {}');
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import { contractTest as serverContractTest } from './plugin-server-contract.js';
|
|
2
|
+
export const NEST_HARNESS = {
|
|
3
|
+
framework: ["import { type INestApplication } from '@nestjs/common';", "import { NestFactory } from '@nestjs/core';"],
|
|
4
|
+
hooks: ['afterAll', 'beforeAll'],
|
|
5
|
+
local: ["import { ApiModule } from './api.module.js';"],
|
|
6
|
+
setup: [
|
|
7
|
+
' let app: INestApplication;',
|
|
8
|
+
' let base: string;',
|
|
9
|
+
'',
|
|
10
|
+
' beforeAll(async () => {',
|
|
11
|
+
' app = await NestFactory.create(ApiModule, { logger: false });',
|
|
12
|
+
" await app.listen(0, '127.0.0.1');",
|
|
13
|
+
' base = await app.getUrl();',
|
|
14
|
+
' });',
|
|
15
|
+
'',
|
|
16
|
+
' afterAll(async () => {',
|
|
17
|
+
' await app.close();',
|
|
18
|
+
' });',
|
|
19
|
+
'',
|
|
20
|
+
],
|
|
21
|
+
call: (url, init) => `fetch(new URL(${url}, base), ${init})`,
|
|
22
|
+
};
|
|
23
|
+
export const contractTest = (route, imports, runner) => serverContractTest(route, imports, runner, NEST_HARNESS);
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import { read } from './openapi.js';
|
|
2
|
+
import { baseFile, controllerFile, moduleFile } from './plugin-nest-code.js';
|
|
3
|
+
import { contractTest } from './plugin-nest-contract.js';
|
|
4
|
+
import { SERVER_OPTIONS, serverOptions } from './plugin-server-contract.js';
|
|
5
|
+
import { routesOf } from './plugin-server-routes.js';
|
|
6
|
+
import { RUNTIME } from './plugin-server-runtime.js';
|
|
7
|
+
import { SAMPLE_DOCUMENT } from './plugin-server-sample.js';
|
|
8
|
+
export const optionsOf = (options) => serverOptions('nest', options);
|
|
9
|
+
export const run = (contract, options) => {
|
|
10
|
+
const checked = optionsOf(options);
|
|
11
|
+
const { controllers, findings } = routesOf(contract, 'NestJS');
|
|
12
|
+
const files = [
|
|
13
|
+
{ path: 'contract-runtime.ts', owner: 'generated', content: RUNTIME },
|
|
14
|
+
...(controllers.length === 0 ? [] : [{ path: 'api.module.ts', owner: 'generated', content: moduleFile(controllers) }]),
|
|
15
|
+
...controllers.flatMap((controller) => [
|
|
16
|
+
{
|
|
17
|
+
path: `${controller.file}.controller.base.ts`,
|
|
18
|
+
owner: 'generated',
|
|
19
|
+
content: baseFile(controller, checked),
|
|
20
|
+
symbols: controller.routes.map((route) => ({ operation: route.id, symbol: `${controller.name}ControllerBase` })),
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
path: `${controller.file}.controller.ts`,
|
|
24
|
+
owner: 'user',
|
|
25
|
+
content: controllerFile(controller),
|
|
26
|
+
symbols: controller.routes.map((route) => ({ operation: route.id, symbol: `${controller.name}Controller.${route.name}` })),
|
|
27
|
+
},
|
|
28
|
+
...controller.routes.map((route) => ({ path: `${route.name}.contract.test.ts`, owner: 'generated', content: contractTest(route, checked, checked.testRunner) })),
|
|
29
|
+
]),
|
|
30
|
+
];
|
|
31
|
+
const byPath = new Map(files.map((file) => [file.path, file]));
|
|
32
|
+
return { files: [...byPath.keys()].toSorted().map((key) => byPath.get(key)), findings };
|
|
33
|
+
};
|
|
34
|
+
const nest = {
|
|
35
|
+
description: 'NestJS controllers: a generated abstract base per tag that validates requests and responses, a controller you own, and a contract test per operation',
|
|
36
|
+
inputs: ['openapi'],
|
|
37
|
+
options: SERVER_OPTIONS,
|
|
38
|
+
sample: {
|
|
39
|
+
document: SAMPLE_DOCUMENT,
|
|
40
|
+
files: run(read(SAMPLE_DOCUMENT), {}).files,
|
|
41
|
+
},
|
|
42
|
+
run,
|
|
43
|
+
};
|
|
44
|
+
export const plugin = { name: 'nest', generators: { nest } };
|