contractdiff 0.0.0-stage → 0.4.0
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 +408 -0
- package/dist/props-judge.js +30 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +170 -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,41 @@
|
|
|
1
|
+
const SAID = { rewrite: 'description' };
|
|
2
|
+
export const dialect = {
|
|
3
|
+
source: 'https://platform.claude.com/docs/en/build-with-claude/structured-outputs#json-schema-limitations',
|
|
4
|
+
read: '2026-11-18',
|
|
5
|
+
keywords: {
|
|
6
|
+
type: 'keep',
|
|
7
|
+
properties: 'keep',
|
|
8
|
+
required: 'keep',
|
|
9
|
+
additionalProperties: 'keep',
|
|
10
|
+
items: 'keep',
|
|
11
|
+
enum: 'keep',
|
|
12
|
+
const: 'keep',
|
|
13
|
+
anyOf: 'keep',
|
|
14
|
+
allOf: 'keep',
|
|
15
|
+
default: 'keep',
|
|
16
|
+
pattern: 'keep',
|
|
17
|
+
format: 'keep',
|
|
18
|
+
minItems: { atMost: 1 },
|
|
19
|
+
title: 'keep',
|
|
20
|
+
description: 'keep',
|
|
21
|
+
minimum: SAID,
|
|
22
|
+
maximum: SAID,
|
|
23
|
+
exclusiveMinimum: SAID,
|
|
24
|
+
exclusiveMaximum: SAID,
|
|
25
|
+
multipleOf: SAID,
|
|
26
|
+
minLength: SAID,
|
|
27
|
+
maxLength: SAID,
|
|
28
|
+
maxItems: SAID,
|
|
29
|
+
},
|
|
30
|
+
formats: ['date-time', 'time', 'date', 'duration', 'email', 'hostname', 'uri', 'ipv4', 'ipv6', 'uuid'],
|
|
31
|
+
rootMustBeObject: true,
|
|
32
|
+
additionalPropertiesFalseRequired: true,
|
|
33
|
+
allRequired: false,
|
|
34
|
+
recursion: false,
|
|
35
|
+
refs: 'inline',
|
|
36
|
+
flat: false,
|
|
37
|
+
limits: [
|
|
38
|
+
{ measure: 'optional', max: 24, per: 'request' },
|
|
39
|
+
{ measure: 'unions', max: 16, per: 'request' },
|
|
40
|
+
],
|
|
41
|
+
};
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
export const dialect = {
|
|
2
|
+
source: 'https://aistudio.google.com/docs/structured-output',
|
|
3
|
+
read: '2026-11-18',
|
|
4
|
+
keywords: {
|
|
5
|
+
type: 'keep',
|
|
6
|
+
properties: 'keep',
|
|
7
|
+
required: 'keep',
|
|
8
|
+
additionalProperties: 'keep',
|
|
9
|
+
enum: 'keep',
|
|
10
|
+
format: 'keep',
|
|
11
|
+
minimum: 'keep',
|
|
12
|
+
maximum: 'keep',
|
|
13
|
+
items: 'keep',
|
|
14
|
+
prefixItems: 'keep',
|
|
15
|
+
minItems: 'keep',
|
|
16
|
+
maxItems: 'keep',
|
|
17
|
+
anyOf: 'keep',
|
|
18
|
+
title: 'keep',
|
|
19
|
+
description: 'keep',
|
|
20
|
+
},
|
|
21
|
+
formats: ['date-time', 'date', 'time'],
|
|
22
|
+
rootMustBeObject: false,
|
|
23
|
+
additionalPropertiesFalseRequired: false,
|
|
24
|
+
allRequired: false,
|
|
25
|
+
recursion: true,
|
|
26
|
+
refs: 'keep',
|
|
27
|
+
flat: false,
|
|
28
|
+
limits: [],
|
|
29
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export const dialect = {
|
|
2
|
+
source: 'https://modelcontextprotocol.io/specification/2026-07-28/client/elicitation.md',
|
|
3
|
+
read: '2026-11-18',
|
|
4
|
+
keywords: {
|
|
5
|
+
type: 'keep',
|
|
6
|
+
properties: 'keep',
|
|
7
|
+
required: 'keep',
|
|
8
|
+
title: 'keep',
|
|
9
|
+
description: 'keep',
|
|
10
|
+
minLength: 'keep',
|
|
11
|
+
maxLength: 'keep',
|
|
12
|
+
format: 'keep',
|
|
13
|
+
minimum: 'keep',
|
|
14
|
+
maximum: 'keep',
|
|
15
|
+
default: 'keep',
|
|
16
|
+
enum: 'keep',
|
|
17
|
+
oneOf: 'keep',
|
|
18
|
+
anyOf: 'keep',
|
|
19
|
+
const: 'keep',
|
|
20
|
+
items: 'keep',
|
|
21
|
+
minItems: 'keep',
|
|
22
|
+
maxItems: 'keep',
|
|
23
|
+
},
|
|
24
|
+
formats: ['email', 'uri', 'date', 'date-time'],
|
|
25
|
+
rootMustBeObject: true,
|
|
26
|
+
additionalPropertiesFalseRequired: false,
|
|
27
|
+
allRequired: false,
|
|
28
|
+
recursion: false,
|
|
29
|
+
refs: 'inline',
|
|
30
|
+
flat: true,
|
|
31
|
+
limits: [],
|
|
32
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { KEYWORDS } from './plugin-json-schema-build.js';
|
|
2
|
+
export const dialect = {
|
|
3
|
+
source: 'https://modelcontextprotocol.io/specification/2026-07-28/server/tools.md',
|
|
4
|
+
read: '2026-11-18',
|
|
5
|
+
keywords: Object.fromEntries([...KEYWORDS.keys()].map((keyword) => [keyword, 'keep'])),
|
|
6
|
+
rootMustBeObject: false,
|
|
7
|
+
additionalPropertiesFalseRequired: false,
|
|
8
|
+
allRequired: false,
|
|
9
|
+
recursion: true,
|
|
10
|
+
refs: 'keep',
|
|
11
|
+
flat: false,
|
|
12
|
+
limits: [],
|
|
13
|
+
};
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
export const dialect = {
|
|
2
|
+
source: 'https://developers.openai.com/api/docs/guides/structured-outputs#supported-schemas',
|
|
3
|
+
read: '2026-11-18',
|
|
4
|
+
keywords: {
|
|
5
|
+
type: 'keep',
|
|
6
|
+
properties: 'keep',
|
|
7
|
+
required: 'keep',
|
|
8
|
+
additionalProperties: 'keep',
|
|
9
|
+
items: 'keep',
|
|
10
|
+
enum: 'keep',
|
|
11
|
+
const: 'keep',
|
|
12
|
+
anyOf: 'keep',
|
|
13
|
+
pattern: 'keep',
|
|
14
|
+
format: 'keep',
|
|
15
|
+
multipleOf: 'keep',
|
|
16
|
+
maximum: 'keep',
|
|
17
|
+
exclusiveMaximum: 'keep',
|
|
18
|
+
minimum: 'keep',
|
|
19
|
+
exclusiveMinimum: 'keep',
|
|
20
|
+
minItems: 'keep',
|
|
21
|
+
maxItems: 'keep',
|
|
22
|
+
title: 'keep',
|
|
23
|
+
description: 'keep',
|
|
24
|
+
},
|
|
25
|
+
formats: ['date-time', 'time', 'date', 'duration', 'email', 'hostname', 'ipv4', 'ipv6', 'uuid'],
|
|
26
|
+
rootMustBeObject: true,
|
|
27
|
+
additionalPropertiesFalseRequired: true,
|
|
28
|
+
allRequired: true,
|
|
29
|
+
recursion: true,
|
|
30
|
+
refs: 'inline',
|
|
31
|
+
flat: false,
|
|
32
|
+
limits: [
|
|
33
|
+
{ measure: 'properties', max: 5000, per: 'schema' },
|
|
34
|
+
{ measure: 'depth', max: 10, per: 'schema' },
|
|
35
|
+
{ measure: 'enum', max: 1000, per: 'schema' },
|
|
36
|
+
],
|
|
37
|
+
};
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
import { KEYWORDS } from './plugin-json-schema-build.js';
|
|
2
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
const token = (key) => key.replaceAll('~', '~0').replaceAll('/', '~1');
|
|
4
|
+
const PRIMITIVES = new Set(['string', 'number', 'integer', 'boolean']);
|
|
5
|
+
const primitive = (schema) => isDict(schema) && (PRIMITIVES.has(schema.type) || (schema.type === 'array' && isDict(schema.items) && ('enum' in schema.items || 'anyOf' in schema.items)));
|
|
6
|
+
const shown = (value) => JSON.stringify(value);
|
|
7
|
+
const noted = (out, notes) => {
|
|
8
|
+
if (notes.length === 0)
|
|
9
|
+
return out;
|
|
10
|
+
const own = typeof out.description === 'string' ? `${out.description} ` : '';
|
|
11
|
+
return { ...out, description: `${own}(${notes.join('; ')})` };
|
|
12
|
+
};
|
|
13
|
+
export const narrow = (name, dialect, schema, where) => {
|
|
14
|
+
const rules = new Map(Object.entries(dialect.keywords));
|
|
15
|
+
const findings = [];
|
|
16
|
+
const dropped = [];
|
|
17
|
+
const say = (code, path, message, fix) => {
|
|
18
|
+
findings.push({ code, pointer: where.at, message: `${where.label}: for ${name}, at "${path}" in the document, ${message}`, fix });
|
|
19
|
+
};
|
|
20
|
+
const lose = (path, key, value, why) => {
|
|
21
|
+
dropped.push(`${path === '' ? '/' : path}: \`${key}\` ${shown(value)}`);
|
|
22
|
+
say('dialect-dropped', path, `\`${key}\` ${why}, and is left out of the narrowed schema: the re-check holds the answer to it`, `validate the answer with the generated re-check before using it`);
|
|
23
|
+
};
|
|
24
|
+
const flatten = (out, path) => {
|
|
25
|
+
const kept = Object.entries(out.properties).filter(([key, value]) => {
|
|
26
|
+
if (primitive(value))
|
|
27
|
+
return true;
|
|
28
|
+
lose(`${path}/properties/${token(key)}`, key, value, `is not a primitive, which ${name} cannot ask for`);
|
|
29
|
+
return false;
|
|
30
|
+
});
|
|
31
|
+
const names = new Set(kept.map(([key]) => key));
|
|
32
|
+
const required = Array.isArray(out.required) ? out.required.filter((key) => names.has(key)) : undefined;
|
|
33
|
+
return { ...out, properties: Object.fromEntries(kept), ...(required !== undefined && { required }) };
|
|
34
|
+
};
|
|
35
|
+
const close = (out, path) => {
|
|
36
|
+
if (out.additionalProperties === false)
|
|
37
|
+
return out;
|
|
38
|
+
if ('additionalProperties' in out)
|
|
39
|
+
lose(path, 'additionalProperties', out.additionalProperties, `must be \`false\` for ${name}`);
|
|
40
|
+
return { ...out, additionalProperties: false };
|
|
41
|
+
};
|
|
42
|
+
const requireAll = (out, path) => {
|
|
43
|
+
const required = new Set(Array.isArray(out.required) ? out.required : []);
|
|
44
|
+
const properties = Object.fromEntries(Object.entries(out.properties).map(([key, value]) => {
|
|
45
|
+
if (required.has(key))
|
|
46
|
+
return [key, value];
|
|
47
|
+
dropped.push(`${path}/properties/${token(key)}: optional, sent as \`null\` when absent`);
|
|
48
|
+
say('dialect-rewritten', `${path}/properties/${token(key)}`, `the optional \`${key}\` is written as required and nullable, as ${name} asks: the answer carries \`null\` where the key is absent`, 'drop a `null` the full schema does not allow before re-checking the answer');
|
|
49
|
+
return [key, { anyOf: [value, { type: 'null' }] }];
|
|
50
|
+
}));
|
|
51
|
+
return { ...out, properties, required: Object.keys(properties) };
|
|
52
|
+
};
|
|
53
|
+
const objects = (out, path, root) => {
|
|
54
|
+
if (out.type !== 'object' && !('properties' in out))
|
|
55
|
+
return out;
|
|
56
|
+
const named = isDict(out.properties);
|
|
57
|
+
const flat = dialect.flat && root && named ? flatten(out, path) : out;
|
|
58
|
+
const closed = dialect.additionalPropertiesFalseRequired ? close(flat, path) : flat;
|
|
59
|
+
return dialect.allRequired && named ? requireAll(closed, path) : closed;
|
|
60
|
+
};
|
|
61
|
+
const keepFormat = (key, value, path) => {
|
|
62
|
+
if (key !== 'format' || dialect.formats === undefined || dialect.formats.includes(value))
|
|
63
|
+
return 'keep';
|
|
64
|
+
lose(path, key, value, `${shown(value)} is not a format ${name} accepts`);
|
|
65
|
+
return 'drop';
|
|
66
|
+
};
|
|
67
|
+
const verdict = (key, value, path) => {
|
|
68
|
+
if (key === '$schema')
|
|
69
|
+
return 'drop';
|
|
70
|
+
if (key === '$defs')
|
|
71
|
+
return dialect.recursion ? 'keep' : 'drop';
|
|
72
|
+
if (key === '$ref') {
|
|
73
|
+
if (dialect.recursion)
|
|
74
|
+
return 'keep';
|
|
75
|
+
lose(path, key, value, `refers to a schema that contains itself, which ${name} does not allow`);
|
|
76
|
+
return 'drop';
|
|
77
|
+
}
|
|
78
|
+
const rule = rules.get(key) ?? 'drop';
|
|
79
|
+
if (rule === 'keep')
|
|
80
|
+
return keepFormat(key, value, path);
|
|
81
|
+
if (rule === 'drop') {
|
|
82
|
+
lose(path, key, value, `is not a keyword ${name} accepts`);
|
|
83
|
+
return 'drop';
|
|
84
|
+
}
|
|
85
|
+
if ('rewrite' in rule) {
|
|
86
|
+
dropped.push(`${path === '' ? '/' : path}: \`${key}\` ${shown(value)}`);
|
|
87
|
+
say('dialect-rewritten', path, `\`${key}\` is not a keyword ${name} enforces: it is said in \`description\` instead`, 'validate the answer with the generated re-check before using it');
|
|
88
|
+
return 'said';
|
|
89
|
+
}
|
|
90
|
+
if (typeof value === 'number' && value > rule.atMost) {
|
|
91
|
+
lose(path, key, value, `above ${String(rule.atMost)} is not accepted by ${name}`);
|
|
92
|
+
return 'drop';
|
|
93
|
+
}
|
|
94
|
+
return 'keep';
|
|
95
|
+
};
|
|
96
|
+
const inner = (key, value, at) => {
|
|
97
|
+
const kind = key === '$defs' ? 'map' : KEYWORDS.get(key);
|
|
98
|
+
if (kind === 'schema')
|
|
99
|
+
return walk(value, at, false);
|
|
100
|
+
if (kind === 'list')
|
|
101
|
+
return value.map((item, index) => walk(item, `${at}/${String(index)}`, false));
|
|
102
|
+
if (kind === 'map')
|
|
103
|
+
return Object.fromEntries(Object.entries(value).map(([sub, item]) => [sub, walk(item, `${at}/${token(sub)}`, false)]));
|
|
104
|
+
return value;
|
|
105
|
+
};
|
|
106
|
+
function walk(node, path, root) {
|
|
107
|
+
if (!isDict(node))
|
|
108
|
+
return node;
|
|
109
|
+
const verdicts = Object.entries(node).map(([key, value]) => [key, value, verdict(key, value, path)]);
|
|
110
|
+
const out = Object.fromEntries(verdicts.filter(([, , kept]) => kept === 'keep').map(([key, value]) => [key, inner(key, value, `${path}/${token(key)}`)]));
|
|
111
|
+
const notes = verdicts.filter(([, , kept]) => kept === 'said').map(([key, value]) => `${key}: ${shown(value)}`);
|
|
112
|
+
return objects(noted(out, notes), path, root);
|
|
113
|
+
}
|
|
114
|
+
const narrowed = walk(schema, '', true);
|
|
115
|
+
if (dialect.rootMustBeObject && narrowed.type !== 'object') {
|
|
116
|
+
say('dialect-root-not-object', '', `${name} takes an object at the root, and this schema is not one: no narrowed schema is written for it`, 'wrap the payload in an object property, or generate without a dialect');
|
|
117
|
+
return { findings };
|
|
118
|
+
}
|
|
119
|
+
return { narrowed: { schema: narrowed, findings, dropped }, findings };
|
|
120
|
+
};
|
|
121
|
+
const subschemas = (node) => {
|
|
122
|
+
if (!isDict(node))
|
|
123
|
+
return [];
|
|
124
|
+
const inner = Object.entries(node).flatMap(([key, value]) => {
|
|
125
|
+
const kind = key === '$defs' ? 'map' : KEYWORDS.get(key);
|
|
126
|
+
if (kind === 'schema')
|
|
127
|
+
return subschemas(value);
|
|
128
|
+
if (kind === 'list')
|
|
129
|
+
return value.flatMap((item) => subschemas(item));
|
|
130
|
+
if (kind === 'map')
|
|
131
|
+
return Object.values(value).flatMap((item) => subschemas(item));
|
|
132
|
+
return [];
|
|
133
|
+
});
|
|
134
|
+
return [node, ...inner];
|
|
135
|
+
};
|
|
136
|
+
const keysOf = (schema) => (isDict(schema.properties) ? Object.keys(schema.properties) : []);
|
|
137
|
+
const depth = (node) => {
|
|
138
|
+
if (!isDict(node))
|
|
139
|
+
return 0;
|
|
140
|
+
const own = node.type === 'object' || 'properties' in node ? 1 : 0;
|
|
141
|
+
const below = Object.entries(node).flatMap(([key, value]) => {
|
|
142
|
+
const kind = KEYWORDS.get(key);
|
|
143
|
+
if (kind === 'schema')
|
|
144
|
+
return [depth(value)];
|
|
145
|
+
if (kind === 'list')
|
|
146
|
+
return value.map((item) => depth(item));
|
|
147
|
+
if (kind === 'map')
|
|
148
|
+
return Object.values(value).map((item) => depth(item));
|
|
149
|
+
return [];
|
|
150
|
+
});
|
|
151
|
+
return own + Math.max(0, ...below);
|
|
152
|
+
};
|
|
153
|
+
const properties = (schema) => subschemas(schema).reduce((sum, node) => sum + keysOf(node).length, 0);
|
|
154
|
+
const optional = (schema) => subschemas(schema).reduce((sum, node) => {
|
|
155
|
+
const required = new Set(Array.isArray(node.required) ? node.required : []);
|
|
156
|
+
return sum + keysOf(node).filter((key) => !required.has(key)).length;
|
|
157
|
+
}, 0);
|
|
158
|
+
const unions = (schema) => subschemas(schema).filter((node) => 'anyOf' in node || Array.isArray(node.type)).length;
|
|
159
|
+
const enums = (schema) => subschemas(schema).reduce((sum, node) => sum + (Array.isArray(node.enum) ? node.enum.length : 0), 0);
|
|
160
|
+
const MEASURES = new Map([
|
|
161
|
+
['properties', properties],
|
|
162
|
+
['optional', optional],
|
|
163
|
+
['unions', unions],
|
|
164
|
+
['depth', depth],
|
|
165
|
+
['enum', enums],
|
|
166
|
+
]);
|
|
167
|
+
const measure = (limit, schema) => MEASURES.get(limit.measure)(schema);
|
|
168
|
+
export const overLimits = (name, dialect, schemas) => dialect.limits.flatMap((limit) => {
|
|
169
|
+
const fix = `split the payloads across requests, or simplify them: ${name} refuses a request over the limit`;
|
|
170
|
+
if (limit.per === 'request') {
|
|
171
|
+
const total = schemas.reduce((sum, { schema }) => sum + measure(limit, schema), 0);
|
|
172
|
+
if (total <= limit.max)
|
|
173
|
+
return [];
|
|
174
|
+
return [{ code: 'dialect-limit', pointer: '', message: `the generated schemas have ${String(total)} ${limit.measure} together, and ${name} takes at most ${String(limit.max)} in one request`, fix }];
|
|
175
|
+
}
|
|
176
|
+
return schemas.flatMap(({ label, at, schema }) => {
|
|
177
|
+
const count = measure(limit, schema);
|
|
178
|
+
return count <= limit.max ? [] : [{ code: 'dialect-limit', pointer: at, message: `${label}: ${String(count)} ${limit.measure}, and ${name} takes at most ${String(limit.max)}`, fix }];
|
|
179
|
+
});
|
|
180
|
+
});
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { build, sourceOf } from './plugin-json-schema-build.js';
|
|
2
|
+
import { dialect as anthropic } from './plugin-json-schema-dialect-anthropic.js';
|
|
3
|
+
import { dialect as gemini } from './plugin-json-schema-dialect-gemini.js';
|
|
4
|
+
import { dialect as mcpElicitation } from './plugin-json-schema-dialect-mcp-elicitation.js';
|
|
5
|
+
import { dialect as mcp } from './plugin-json-schema-dialect-mcp.js';
|
|
6
|
+
import { dialect as openai } from './plugin-json-schema-dialect-openai.js';
|
|
7
|
+
import { narrow, overLimits } from './plugin-json-schema-dialect.js';
|
|
8
|
+
import { moduleOf, validatorCode } from './plugin-validator-code.js';
|
|
9
|
+
import { namedPayloads } from './plugin-validator-names.js';
|
|
10
|
+
import { INPUTS } from './plugin-validator.js';
|
|
11
|
+
export const DIALECTS = new Map([
|
|
12
|
+
['anthropic', anthropic],
|
|
13
|
+
['gemini', gemini],
|
|
14
|
+
['mcp', mcp],
|
|
15
|
+
['mcp-elicitation', mcpElicitation],
|
|
16
|
+
['openai', openai],
|
|
17
|
+
]);
|
|
18
|
+
export const RECHECK_FILE = 'recheck.ts';
|
|
19
|
+
const DRAFTS = new Map([
|
|
20
|
+
[undefined, '2020-12'],
|
|
21
|
+
['2020-12', '2020-12'],
|
|
22
|
+
['07', '07'],
|
|
23
|
+
]);
|
|
24
|
+
const REFS = new Map([
|
|
25
|
+
[undefined, 'keep'],
|
|
26
|
+
['keep', 'keep'],
|
|
27
|
+
['inline', 'inline'],
|
|
28
|
+
]);
|
|
29
|
+
const option = (options, key, values) => {
|
|
30
|
+
const value = values.get(options[key]);
|
|
31
|
+
if (value === undefined) {
|
|
32
|
+
const names = [...values.keys()].filter((name) => name !== undefined).join(', ');
|
|
33
|
+
throw new Error(`json-schema: the option \`${key}\` is ${JSON.stringify(options[key])}. fix: use one of: ${names}`);
|
|
34
|
+
}
|
|
35
|
+
return value;
|
|
36
|
+
};
|
|
37
|
+
const text = (schema) => `${JSON.stringify(schema, null, 2)}\n`;
|
|
38
|
+
export const generateSchemas = (contract, options = {}) => {
|
|
39
|
+
const draft = option(options, 'draft', DRAFTS);
|
|
40
|
+
const refs = option(options, 'refs', REFS);
|
|
41
|
+
const dialect = options.dialect === undefined ? undefined : option(options, 'dialect', DIALECTS);
|
|
42
|
+
const name = options.dialect;
|
|
43
|
+
if (dialect !== undefined && draft !== '2020-12') {
|
|
44
|
+
throw new Error(`json-schema: \`dialect: ${name}\` writes 2020-12, and \`draft\` is ${draft}. fix: leave \`draft\` out, or drop \`dialect\``);
|
|
45
|
+
}
|
|
46
|
+
const source = sourceOf(contract);
|
|
47
|
+
const findings = [];
|
|
48
|
+
const files = [];
|
|
49
|
+
const named = namedPayloads(contract);
|
|
50
|
+
if (dialect === undefined) {
|
|
51
|
+
for (const { name: label, operation, payload } of named) {
|
|
52
|
+
const built = build(contract.document, payload.schema, { draft, refs, source, label, at: operation.source });
|
|
53
|
+
findings.push(...built.findings);
|
|
54
|
+
files.push({ path: `${label}.json`, owner: 'generated', content: text(built.schema), symbols: [{ operation: operation.id, symbol: label }] });
|
|
55
|
+
}
|
|
56
|
+
return { files, findings };
|
|
57
|
+
}
|
|
58
|
+
const rechecks = [];
|
|
59
|
+
const checked = [];
|
|
60
|
+
const narrowed = [];
|
|
61
|
+
for (const { name: label, operation, payload } of named.filter((entry) => entry.payload.schema !== false)) {
|
|
62
|
+
const where = { label, at: operation.source };
|
|
63
|
+
const built = build(contract.document, payload.schema, { draft, refs: dialect.refs, source, ...where });
|
|
64
|
+
const result = narrow(name, dialect, built.schema, where);
|
|
65
|
+
findings.push(...built.findings, ...result.findings);
|
|
66
|
+
if (result.narrowed === undefined)
|
|
67
|
+
continue;
|
|
68
|
+
narrowed.push({ ...where, schema: result.narrowed.schema });
|
|
69
|
+
files.push({ path: `${label}.${name}.json`, owner: 'generated', content: text(result.narrowed.schema), symbols: [{ operation: operation.id, symbol: label }] });
|
|
70
|
+
if (result.narrowed.dropped.length === 0)
|
|
71
|
+
continue;
|
|
72
|
+
const full = build(contract.document, payload.schema, { draft, refs: 'keep', source, ...where });
|
|
73
|
+
const doc = [
|
|
74
|
+
`Re-checks an answer to \`${label}.${name}.json\` against the full schema of \`${operation.id}\` ${payload.name}.`,
|
|
75
|
+
`${name} was given less than the full schema; the narrowed schema does not say:`,
|
|
76
|
+
...result.narrowed.dropped.map((line) => `- ${line}`),
|
|
77
|
+
];
|
|
78
|
+
const code = validatorCode(`${label}Recheck`, full.schema, { ...where, doc });
|
|
79
|
+
findings.push(...code.findings);
|
|
80
|
+
rechecks.push(code);
|
|
81
|
+
checked.push({ operation: operation.id, symbol: `${label}Recheck` });
|
|
82
|
+
}
|
|
83
|
+
findings.push(...overLimits(name, dialect, narrowed));
|
|
84
|
+
if (rechecks.length > 0) {
|
|
85
|
+
files.push({ path: RECHECK_FILE, owner: 'generated', content: moduleOf(rechecks), symbols: checked });
|
|
86
|
+
}
|
|
87
|
+
return { files, findings };
|
|
88
|
+
};
|
|
89
|
+
const document = {
|
|
90
|
+
openapi: '3.1.0',
|
|
91
|
+
paths: {
|
|
92
|
+
'/pets': {
|
|
93
|
+
post: {
|
|
94
|
+
operationId: 'createPet',
|
|
95
|
+
requestBody: { content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet' } } } },
|
|
96
|
+
responses: { '201': {} },
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
},
|
|
100
|
+
components: { schemas: { Pet: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 1 }, tag: { type: 'string' } } } } },
|
|
101
|
+
};
|
|
102
|
+
const SAMPLE_BODY = `${JSON.stringify({
|
|
103
|
+
$schema: 'https://json-schema.org/draft/2020-12/schema',
|
|
104
|
+
$ref: '#/$defs/Pet',
|
|
105
|
+
$defs: { Pet: { type: 'object', required: ['name'], properties: { name: { type: 'string', minLength: 1 }, tag: { type: 'string' } } } },
|
|
106
|
+
}, null, 2)}\n`;
|
|
107
|
+
const SAMPLE_NOTHING = `${JSON.stringify({ $schema: 'https://json-schema.org/draft/2020-12/schema', not: {} }, null, 2)}\n`;
|
|
108
|
+
const jsonSchema = {
|
|
109
|
+
description: 'A JSON Schema document per payload (2020-12 or draft-07), or the subset a model provider accepts with a validator that re-checks the answer',
|
|
110
|
+
inputs: INPUTS,
|
|
111
|
+
options: {
|
|
112
|
+
draft: { type: 'string', choices: ['2020-12', '07'], default: '2020-12', description: 'the JSON Schema dialect to write' },
|
|
113
|
+
refs: { type: 'string', choices: ['keep', 'inline'], default: 'keep', description: 'keep each referenced schema under `$defs`, or copy it in place' },
|
|
114
|
+
dialect: { type: 'string', choices: [...DIALECTS.keys()], description: 'narrow to what this model provider accepts, and write a re-check' },
|
|
115
|
+
},
|
|
116
|
+
sample: {
|
|
117
|
+
document,
|
|
118
|
+
files: [
|
|
119
|
+
{ path: 'CreatePetBody.json', owner: 'generated', content: SAMPLE_BODY, symbols: [{ operation: 'createPet', symbol: 'CreatePetBody' }] },
|
|
120
|
+
{ path: 'CreatePetResponse201.json', owner: 'generated', content: SAMPLE_NOTHING, symbols: [{ operation: 'createPet', symbol: 'CreatePetResponse201' }] },
|
|
121
|
+
],
|
|
122
|
+
},
|
|
123
|
+
run: (contract, options) => generateSchemas(contract, options),
|
|
124
|
+
};
|
|
125
|
+
export const plugin = { name: 'json-schema', generators: { 'json-schema': jsonSchema } };
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { stableHash, fileSlug, unique } from './command-explain-name.js';
|
|
2
|
+
import { capped, describe } from './command-explain-operation.js';
|
|
3
|
+
import { toMarkdown } from './command-explain-text.js';
|
|
4
|
+
const membersOf = (value) => Object(value);
|
|
5
|
+
const MAX_FILE = 100;
|
|
6
|
+
const info = (document) => {
|
|
7
|
+
const declared = membersOf(membersOf(document).info);
|
|
8
|
+
const title = typeof declared.title === 'string' && declared.title !== '' ? declared.title : 'API';
|
|
9
|
+
return typeof declared.description === 'string' && declared.description !== '' ? { title, description: declared.description } : { title };
|
|
10
|
+
};
|
|
11
|
+
const blurb = (explanation) => [explanation.method === undefined ? undefined : `\`${explanation.method} ${explanation.path}\``, explanation.summary].filter((part) => part !== undefined).join(' — ');
|
|
12
|
+
const pages = (ids) => unique(ids, (id) => {
|
|
13
|
+
const slug = fileSlug(id);
|
|
14
|
+
return slug.toLowerCase() === 'index' ? `${slug}_${stableHash(id)}` : slug;
|
|
15
|
+
}, MAX_FILE);
|
|
16
|
+
const write = (path, lines) => ({ path, owner: 'generated', content: `${lines.join('\n')}\n` });
|
|
17
|
+
export const run = (contract, options) => {
|
|
18
|
+
const maxBytes = typeof options.maxBytes === 'number' ? options.maxBytes : undefined;
|
|
19
|
+
const explained = contract.operations.map((operation) => capped(describe(contract, operation), maxBytes));
|
|
20
|
+
const names = pages(explained.map((explanation) => explanation.id));
|
|
21
|
+
const { title, description } = info(contract.document);
|
|
22
|
+
const links = explained.map((explanation) => {
|
|
23
|
+
const text = blurb(explanation);
|
|
24
|
+
return { link: `[${explanation.id}](${names.get(explanation.id)}.md)`, text };
|
|
25
|
+
});
|
|
26
|
+
const lead = description === undefined ? [] : [description, ''];
|
|
27
|
+
return [
|
|
28
|
+
...explained.map((explanation) => ({ path: `${names.get(explanation.id)}.md`, owner: 'generated', content: toMarkdown(explanation) })),
|
|
29
|
+
write('index.md', [`# ${title}`, '', ...lead, ...links.map(({ link, text }) => `- ${link}${text === '' ? '' : ` — ${text}`}`)]),
|
|
30
|
+
write('llms.txt', [
|
|
31
|
+
`# ${title}`,
|
|
32
|
+
'',
|
|
33
|
+
`> ${description ?? 'Every operation of this API, one Markdown page each, with every schema resolved.'}`,
|
|
34
|
+
'',
|
|
35
|
+
'## Operations',
|
|
36
|
+
'',
|
|
37
|
+
...links.map(({ link, text }) => `- ${link}${text === '' ? '' : `: ${text}`}`),
|
|
38
|
+
]),
|
|
39
|
+
];
|
|
40
|
+
};
|
|
41
|
+
const document = {
|
|
42
|
+
openapi: '3.1.0',
|
|
43
|
+
info: { title: 'Pets' },
|
|
44
|
+
paths: {
|
|
45
|
+
'/pets': {
|
|
46
|
+
get: {
|
|
47
|
+
operationId: 'listPets',
|
|
48
|
+
summary: 'List pets',
|
|
49
|
+
responses: { '200': { content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/Pet' } } } } } },
|
|
50
|
+
},
|
|
51
|
+
},
|
|
52
|
+
'/health': { get: { operationId: 'index', responses: { '204': {} } } },
|
|
53
|
+
},
|
|
54
|
+
components: { schemas: { Pet: { type: 'object', properties: { id: { type: 'string' } } } } },
|
|
55
|
+
};
|
|
56
|
+
const LIST_PETS = `# listPets
|
|
57
|
+
|
|
58
|
+
\`GET /pets\` · openapi \`#/paths/~1pets/get\`
|
|
59
|
+
|
|
60
|
+
List pets
|
|
61
|
+
|
|
62
|
+
## response:200:application/json
|
|
63
|
+
|
|
64
|
+
response, required
|
|
65
|
+
|
|
66
|
+
\`\`\`json
|
|
67
|
+
{
|
|
68
|
+
"type": "array",
|
|
69
|
+
"items": {
|
|
70
|
+
"type": "object",
|
|
71
|
+
"properties": {
|
|
72
|
+
"id": {
|
|
73
|
+
"type": "string"
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
\`\`\`
|
|
79
|
+
`;
|
|
80
|
+
const INDEX_PAGE = `# index
|
|
81
|
+
|
|
82
|
+
\`GET /health\` · openapi \`#/paths/~1health/get\`
|
|
83
|
+
|
|
84
|
+
## response:204
|
|
85
|
+
|
|
86
|
+
response, required
|
|
87
|
+
|
|
88
|
+
\`\`\`json
|
|
89
|
+
false
|
|
90
|
+
\`\`\`
|
|
91
|
+
`;
|
|
92
|
+
const INDEX_NAME = `index_${stableHash('index')}`;
|
|
93
|
+
const markdown = {
|
|
94
|
+
description: 'One Markdown page per operation, every schema resolved (what `explain` prints), plus index.md and llms.txt',
|
|
95
|
+
inputs: ['openapi', 'swagger2', 'asyncapi', 'mcp', 'jsonschema'],
|
|
96
|
+
options: {
|
|
97
|
+
maxBytes: { type: 'number', description: 'cap each page as `explain --max-bytes` does: deepest schemas first' },
|
|
98
|
+
},
|
|
99
|
+
sample: {
|
|
100
|
+
document,
|
|
101
|
+
files: [
|
|
102
|
+
{ path: 'listPets.md', owner: 'generated', content: LIST_PETS },
|
|
103
|
+
{ path: `${INDEX_NAME}.md`, owner: 'generated', content: INDEX_PAGE },
|
|
104
|
+
{ path: 'index.md', owner: 'generated', content: `# Pets\n\n- [listPets](listPets.md) — \`GET /pets\` — List pets\n- [index](${INDEX_NAME}.md) — \`GET /health\`\n` },
|
|
105
|
+
{
|
|
106
|
+
path: 'llms.txt',
|
|
107
|
+
owner: 'generated',
|
|
108
|
+
content: `# Pets\n\n> Every operation of this API, one Markdown page each, with every schema resolved.\n\n## Operations\n\n- [listPets](listPets.md): \`GET /pets\` — List pets\n- [index](${INDEX_NAME}.md): \`GET /health\`\n`,
|
|
109
|
+
},
|
|
110
|
+
],
|
|
111
|
+
},
|
|
112
|
+
run,
|
|
113
|
+
};
|
|
114
|
+
export const plugin = { name: 'markdown', generators: { markdown } };
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
const UNSAFE = { '<': '\\u003C', '>': '\\u003E', '\u2028': '\\u2028', '\u2029': '\\u2029' };
|
|
2
|
+
const literal = (value, indent) => JSON.stringify(value, null, indent).replaceAll(/[<>\u2028\u2029]/gu, (character) => UNSAFE[character]);
|
|
3
|
+
const json = (value) => literal(value, 2);
|
|
4
|
+
const lines = (...text) => `${text.join('\n')}\n`;
|
|
5
|
+
export const toolsFile = (tools) => {
|
|
6
|
+
const listed = tools.map(({ route: _route, ...tool }) => tool);
|
|
7
|
+
const routes = Object.fromEntries(tools.map((tool) => [tool.name, tool.route]));
|
|
8
|
+
return lines("import { type Tool } from '@modelcontextprotocol/sdk/types.js';", '', '/** One tool per operation: what `tools/list` answers. */', `export const tools: Tool[] = ${json(listed)};`, '', '/** The HTTP route each tool calls, and whether its result is sent as structured content. */', `export const routes = ${json(routes)} as const;`);
|
|
9
|
+
};
|
|
10
|
+
const STDIO = ["import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';"];
|
|
11
|
+
const HTTP = ["import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';"];
|
|
12
|
+
const NODE_HTTP = ["import { createServer } from 'node:http';", ''];
|
|
13
|
+
const START_STDIO = ['', 'await createMcpServer().connect(new StdioServerTransport());'];
|
|
14
|
+
const START_HTTP = [
|
|
15
|
+
'',
|
|
16
|
+
'createServer((request, response) => {',
|
|
17
|
+
' const server = createMcpServer();',
|
|
18
|
+
' const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });',
|
|
19
|
+
" response.on('close', () => {",
|
|
20
|
+
' void transport.close();',
|
|
21
|
+
' void server.close();',
|
|
22
|
+
' });',
|
|
23
|
+
' void server.connect(transport).then(async () => transport.handleRequest(request, response));',
|
|
24
|
+
'}).listen(Number(process.env.PORT ?? 3000));',
|
|
25
|
+
];
|
|
26
|
+
export const serverFile = (name, version, transport) => lines(...(transport === 'stdio' ? [] : NODE_HTTP), "import { Server } from '@modelcontextprotocol/sdk/server/index.js';", ...(transport === 'stdio' ? STDIO : HTTP), "import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';", '', "import { handlers } from './handlers.js';", "import { routes, tools } from './tools.js';", '', 'type Routed = Readonly<Record<string, { readonly output: boolean; readonly wrap: boolean } | undefined>>;', '', '/** A server that lists the tools and calls the handler a tool names. */', 'export const createMcpServer = (): Server => {', ` const server = new Server({ name: ${literal(name)}, version: ${literal(version)} }, { capabilities: { tools: {} } });`, ' server.setRequestHandler(ListToolsRequestSchema, () => ({ tools }));', ' server.setRequestHandler(CallToolRequestSchema, async (request) => {', ' const { name } = request.params;', ' const route = (routes as Routed)[name];', ' const handler = handlers[name];', " if (route === undefined || handler === undefined) return { isError: true, content: [{ type: 'text', text: `no tool is named ${name}` }] };", ' try {', ' const result = await handler(request.params.arguments ?? {});', " const content = [{ type: 'text' as const, text: JSON.stringify(result) }];", ' if (!route.output) return { content };', ' return { content, structuredContent: route.wrap ? { result } : (result as Record<string, unknown>) };', ' } catch (error) {', " return { isError: true, content: [{ type: 'text', text: error instanceof Error ? error.message : String(error) }] };", ' }', ' });', ' return server;', '};', ...(transport === 'stdio' ? START_STDIO : START_HTTP));
|
|
27
|
+
export const clientFile = (names) => lines("import { routes } from './tools.js';", '', 'export interface Input {', ' readonly path?: Readonly<Record<string, unknown>>;', ' readonly query?: Readonly<Record<string, unknown>>;', ' readonly header?: Readonly<Record<string, unknown>>;', ' readonly cookie?: Readonly<Record<string, unknown>>;', ' readonly body?: unknown;', '}', '', 'export type Handler = (input: Input) => Promise<unknown>;', '', "const base = (): string => (process.env.API_BASE_URL ?? '').replace(/\\/+$/u, '');", 'const authorization = (): string | undefined => process.env.API_AUTHORIZATION;', '', '/** Call one route: path parameters into the path, the rest into the query, headers and a JSON body. */', 'export const call = async (route: { readonly method: string; readonly path: string }, input: Input): Promise<unknown> => {', " if (base() === '') throw new Error('API_BASE_URL is not set. fix: set it to the address of the API, without a trailing slash');", " const path = route.path.replaceAll(/\\{([^}]+)\\}/gu, (_, name: string) => encodeURIComponent(String(input.path?.[name] ?? '')));", ' const url = new URL(`${base()}${path}`);', ' for (const [name, value] of Object.entries(input.query ?? {})) if (value !== undefined) url.searchParams.set(name, String(value));', ' const headers = new Headers();', ' for (const [name, value] of Object.entries(input.header ?? {})) if (value !== undefined) headers.set(name, String(value));', ' const cookies = Object.entries(input.cookie ?? {}).map(([name, value]) => `${encodeURIComponent(name)}=${encodeURIComponent(String(value))}`);', " if (cookies.length > 0) headers.set('cookie', cookies.join('; '));", ' const token = authorization();', " if (token !== undefined) headers.set('authorization', token);", " if (input.body !== undefined) headers.set('content-type', 'application/json');", ' const response = await fetch(url, { method: route.method, headers, body: input.body === undefined ? undefined : JSON.stringify(input.body) });', ' const text = await response.text();', ' if (!response.ok) throw new Error(`${route.method} ${path} answered ${String(response.status)}: ${text}`);', " if (text === '') return null;", " return (response.headers.get('content-type') ?? '').includes('json') ? (JSON.parse(text) as unknown) : text;", '};', '', '/** Every tool, calling its route. `handlers.ts` spreads these and replaces the ones it needs to. */', 'export const defaults: Readonly<Record<string, Handler>> = {', ...names.map((name) => ` ${literal(name)}: async (input) => call(routes[${literal(name)}], input),`), '};');
|
|
28
|
+
export const HANDLERS = lines('/**', ' * The handler each tool runs. contractdiff wrote this file once and never rewrites it: change it freely.', ' * `defaults` (client.ts, regenerated) calls the API for every tool, a new one included; replace an', ' * entry to do something else, e.g. `{ ...defaults, delete_pet: async () => { throw new Error("not here") } }`.', ' */', "import { defaults, type Handler } from './client.js';", '', 'export const handlers: Readonly<Record<string, Handler | undefined>> = { ...defaults };');
|