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,61 @@
|
|
|
1
|
+
import { stubStatus } from './plugin-server-routes.js';
|
|
2
|
+
const UNSAFE = { '<': '\\u003C', '>': '\\u003E', '\u2028': '\\u2028', '\u2029': '\\u2029' };
|
|
3
|
+
export const literal = (value) => (JSON.stringify(value) ?? 'undefined').replaceAll(/[<>\u2028\u2029]/gu, (character) => UNSAFE[character]);
|
|
4
|
+
export const commented = (text) => text.replaceAll('*/', '*\\/');
|
|
5
|
+
export const lines = (...text) => `${text.join('\n')}\n`;
|
|
6
|
+
export const pascal = (name) => `${name.charAt(0).toUpperCase()}${name.slice(1)}`;
|
|
7
|
+
export const segmentName = (name) => name.replaceAll(/\W/gu, '_');
|
|
8
|
+
export const routePath = (path) => path
|
|
9
|
+
.split(/(\{[^}]*\})/u)
|
|
10
|
+
.map((piece, index) => (index % 2 === 1 ? `:${segmentName(piece.slice(1, -1))}` : piece.replaceAll(/[\\()[\]?+!*:]/gu, '\\$&')))
|
|
11
|
+
.join('');
|
|
12
|
+
export const colonPath = (path) => {
|
|
13
|
+
const segments = path.split('/').map((segment) => {
|
|
14
|
+
if (/^\{[^{}]+\}$/u.test(segment))
|
|
15
|
+
return `:${segmentName(segment.slice(1, -1))}`;
|
|
16
|
+
return /[{}:*?]/u.test(segment) ? undefined : segment;
|
|
17
|
+
});
|
|
18
|
+
return segments.includes(undefined) ? undefined : segments.join('/');
|
|
19
|
+
};
|
|
20
|
+
export const readAs = (part, name) => {
|
|
21
|
+
if (part === 'header')
|
|
22
|
+
return name.toLowerCase();
|
|
23
|
+
return part === 'path' ? segmentName(name) : name;
|
|
24
|
+
};
|
|
25
|
+
export const isCode = (status) => !Number.isNaN(Number(status));
|
|
26
|
+
const statusType = (status) => (isCode(status) ? status : 'number');
|
|
27
|
+
const statusKey = (status) => (isCode(status) ? status : literal(status));
|
|
28
|
+
export const where = (route) => `${route.method.toUpperCase()} ${commented(route.path)}`;
|
|
29
|
+
export const partsOf = (route) => ['path', 'query', 'header'].filter((part) => route.params.some((param) => param.part === part));
|
|
30
|
+
export const operationTypes = (route) => {
|
|
31
|
+
const type = `${pascal(route.name)}Operation`;
|
|
32
|
+
const { body } = route;
|
|
33
|
+
const member = (response) => {
|
|
34
|
+
const content = response.content === undefined ? 'readonly body?: undefined' : `readonly body: ${type}["responses"][${statusKey(response.status)}]["content"][${literal(response.content.media)}]`;
|
|
35
|
+
return ` | { readonly status: ${statusType(response.status)}; ${content}; readonly headers?: Readonly<Record<string, string>> }`;
|
|
36
|
+
};
|
|
37
|
+
const outputs = route.responses.map((response) => member(response));
|
|
38
|
+
const optional = body?.required === true ? '' : '?';
|
|
39
|
+
return [
|
|
40
|
+
`type ${type} = paths[${literal(route.path)}][${literal(route.method)}];`,
|
|
41
|
+
'',
|
|
42
|
+
`/** What \`${route.name}\` receives: ${where(route)}. */`,
|
|
43
|
+
`export interface ${pascal(route.name)}Input {`,
|
|
44
|
+
...partsOf(route).map((part) => ` readonly ${part}: NonNullable<${type}["parameters"][${literal(part)}]>;`),
|
|
45
|
+
...(body === undefined ? [] : [` readonly body${optional}: NonNullable<${type}["requestBody"]>["content"][${literal(body.media)}];`]),
|
|
46
|
+
'}',
|
|
47
|
+
'',
|
|
48
|
+
`/** What \`${route.name}\` answers: one member per response the spec declares. */`,
|
|
49
|
+
`export type ${pascal(route.name)}Output =`,
|
|
50
|
+
`${outputs.length === 0 ? ' never' : outputs.join('\n')};`,
|
|
51
|
+
];
|
|
52
|
+
};
|
|
53
|
+
export const stubResponse = (route) => {
|
|
54
|
+
const wanted = stubStatus(route.responses.map((candidate) => candidate.status));
|
|
55
|
+
const response = route.responses.find((candidate) => candidate.status === wanted);
|
|
56
|
+
if (response === undefined)
|
|
57
|
+
return 'throw new Error("not implemented");';
|
|
58
|
+
const first = response.status === 'default' ? '2' : response.status.charAt(0);
|
|
59
|
+
const status = isCode(response.status) ? response.status : `${first}00`;
|
|
60
|
+
return `return { status: ${status}${response.content === undefined ? '' : `, body: ${literal(response.content.example)}`} };`;
|
|
61
|
+
};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { lines, literal } from './plugin-server-code.js';
|
|
2
|
+
import { UsageError } from './run-config.js';
|
|
3
|
+
export const RUNNERS = ['vitest', 'node', 'jest'];
|
|
4
|
+
export const SERVER_OPTIONS = {
|
|
5
|
+
validators: { type: 'string', description: 'import path of the `validator` target\'s output; default "./validators.js"' },
|
|
6
|
+
types: { type: 'string', description: 'import path of the `types` target\'s output; default "./types.js"' },
|
|
7
|
+
testRunner: { type: 'string', choices: [...RUNNERS], description: 'the runner the contract tests import: vitest (default), node or jest' },
|
|
8
|
+
};
|
|
9
|
+
export const serverOptions = (target, options) => {
|
|
10
|
+
const path = (name, fallback) => {
|
|
11
|
+
const value = options[name] ?? fallback;
|
|
12
|
+
if (typeof value !== 'string' || value === '')
|
|
13
|
+
throw new UsageError(`${target}: \`${name}\` is not an import path. fix: set it to where the ${name === 'types' ? 'types' : 'validator'} target writes, e.g. "${fallback}"`);
|
|
14
|
+
return value;
|
|
15
|
+
};
|
|
16
|
+
const { testRunner = 'vitest' } = options;
|
|
17
|
+
if (!RUNNERS.includes(testRunner))
|
|
18
|
+
throw new UsageError(`${target}: testRunner is "${String(testRunner)}". fix: set \`testRunner\` to one of ${RUNNERS.join(', ')}`);
|
|
19
|
+
return { validators: path('validators', './validators.js'), types: path('types', './types.js'), testRunner: testRunner };
|
|
20
|
+
};
|
|
21
|
+
const RUNNER_MODULES = { vitest: 'vitest', node: 'node:test', jest: '@jest/globals' };
|
|
22
|
+
const NODE_HOOKS = { afterAll: 'after as afterAll', beforeAll: 'before as beforeAll' };
|
|
23
|
+
export const runnerImport = (runner, hooks) => {
|
|
24
|
+
const names = hooks.map((hook) => (runner === 'node' ? NODE_HOOKS[hook] : hook));
|
|
25
|
+
return `import { ${[...names, 'describe', 'it'].join(', ')} } from '${RUNNER_MODULES[runner]}';`;
|
|
26
|
+
};
|
|
27
|
+
export const exampleUrl = (route) => {
|
|
28
|
+
let path = route.path;
|
|
29
|
+
for (const param of route.params.filter((candidate) => candidate.part === 'path'))
|
|
30
|
+
path = path.replaceAll(`{${param.name}}`, encodeURIComponent(String(param.example)));
|
|
31
|
+
const query = new URLSearchParams();
|
|
32
|
+
for (const param of route.params.filter((candidate) => candidate.part === 'query')) {
|
|
33
|
+
for (const value of Array.isArray(param.example) ? param.example : [param.example])
|
|
34
|
+
query.append(param.name, typeof value === 'string' ? value : JSON.stringify(value));
|
|
35
|
+
}
|
|
36
|
+
const search = query.toString();
|
|
37
|
+
return search === '' ? path : `${path}?${search}`;
|
|
38
|
+
};
|
|
39
|
+
const json = (media) => media === 'application/json' || media.endsWith('+json');
|
|
40
|
+
export const contractTest = (route, imports, runner, harness) => {
|
|
41
|
+
const headers = Object.fromEntries(route.params.filter((param) => param.part === 'header').map((param) => [param.name, typeof param.example === 'string' ? param.example : JSON.stringify(param.example)]));
|
|
42
|
+
if (route.body !== undefined)
|
|
43
|
+
headers['content-type'] = route.body.media;
|
|
44
|
+
const init = [`method: ${literal(route.method.toUpperCase())}`, `headers: ${literal(headers)}`, ...(route.body === undefined ? [] : [`body: ${literal(JSON.stringify(route.body.example))}`])];
|
|
45
|
+
return lines("import assert from 'node:assert/strict';", '', ...harness.framework, runnerImport(runner, harness.hooks), '', ...harness.local, ...(route.responses.some((response) => response.content !== undefined) ? [`import { operations as validators } from ${literal(imports.validators)};`] : []), '', '/** Each declared response: its validator, and whether its body is JSON. Absent for a response with no content. */', 'const responses: Readonly<Record<string, { readonly check: (value: unknown) => boolean; readonly json: boolean } | undefined>> = {', ...route.responses.map(({ status, content }) => content === undefined
|
|
46
|
+
? ` ${literal(status)}: undefined,`
|
|
47
|
+
: ` ${literal(status)}: { check: validators[${literal(route.id)}][${literal(content.payload)}], json: ${String(json(content.media))} },`), '};', '', `describe(${literal(`${route.name}: ${route.method.toUpperCase()} ${route.path}`)}, () => {`, ...harness.setup, " it('answers the example request with a response the spec declares', async () => {", ` const response = await ${harness.call(literal(exampleUrl(route)), `{ ${init.join(', ')} }`)};`, ' const status = String(response.status);', " const key = [status, `${status.charAt(0)}XX`, 'default'].find((candidate) => candidate in responses);", ' assert.ok(key !== undefined, `the route answered ${status}, which the spec does not declare`);', ' const declared = responses[key];', ' const text = await response.text();', ' if (declared === undefined) return;', ' // Malformed JSON is a body the spec does not declare: it fails the assertion below, with its text.', ' const body: unknown = declared.json ? (() => { try { return JSON.parse(text) as unknown; } catch { return text; } })() : text;', ' assert.ok(declared.check(body), `the route answered ${status} with a body the spec does not declare: ${text}`);', ' });', '});');
|
|
48
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
const DEPTH = 8;
|
|
2
|
+
const isDict = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
3
|
+
const FORMATS = {
|
|
4
|
+
date: '2026-01-01',
|
|
5
|
+
'date-time': '2026-01-01T00:00:00Z',
|
|
6
|
+
email: 'user@example.com',
|
|
7
|
+
uri: 'https://example.com/',
|
|
8
|
+
uuid: '00000000-0000-4000-8000-000000000000',
|
|
9
|
+
};
|
|
10
|
+
const typeOf = (schema) => (Array.isArray(schema.type) ? schema.type.find((type) => type !== 'null') : schema.type);
|
|
11
|
+
const named = (schema) => {
|
|
12
|
+
if ('const' in schema)
|
|
13
|
+
return { value: schema.const };
|
|
14
|
+
if (Array.isArray(schema.enum))
|
|
15
|
+
return { value: schema.enum[0] };
|
|
16
|
+
if ('example' in schema)
|
|
17
|
+
return { value: schema.example };
|
|
18
|
+
if (Array.isArray(schema.examples) && schema.examples.length > 0)
|
|
19
|
+
return { value: schema.examples[0] };
|
|
20
|
+
return 'default' in schema ? { value: schema.default } : undefined;
|
|
21
|
+
};
|
|
22
|
+
const ofType = (schema, next) => {
|
|
23
|
+
const type = typeOf(schema) ?? (isDict(schema.properties) ? 'object' : undefined);
|
|
24
|
+
if (type === 'string')
|
|
25
|
+
return FORMATS[String(schema.format)] ?? 'example';
|
|
26
|
+
if (type === 'integer' || type === 'number')
|
|
27
|
+
return typeof schema.minimum === 'number' ? schema.minimum : 1;
|
|
28
|
+
if (type === 'boolean')
|
|
29
|
+
return true;
|
|
30
|
+
if (type === 'array')
|
|
31
|
+
return [next(schema.items)];
|
|
32
|
+
if (type !== 'object')
|
|
33
|
+
return null;
|
|
34
|
+
const properties = isDict(schema.properties) ? schema.properties : {};
|
|
35
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
36
|
+
return Object.fromEntries(Object.entries(properties).filter(([name]) => required.includes(name)).map(([name, inner]) => [name, next(inner)]));
|
|
37
|
+
};
|
|
38
|
+
export const synthesise = (schema, deref, depth = 0) => {
|
|
39
|
+
if (!isDict(schema) || depth > DEPTH)
|
|
40
|
+
return null;
|
|
41
|
+
const resolved = deref(schema);
|
|
42
|
+
const given = named(resolved);
|
|
43
|
+
if (given !== undefined)
|
|
44
|
+
return given.value;
|
|
45
|
+
const next = (inner) => synthesise(inner, deref, depth + 1);
|
|
46
|
+
if (Array.isArray(resolved.allOf))
|
|
47
|
+
return Object.assign({}, ...resolved.allOf.map((inner) => next(inner)).filter((value) => isDict(value)));
|
|
48
|
+
const [first] = [resolved.oneOf, resolved.anyOf].find((list) => Array.isArray(list)) ?? [];
|
|
49
|
+
return first === undefined ? ofType(resolved, next) : next(first);
|
|
50
|
+
};
|
|
51
|
+
export const exampleOf = (holder, schema, deref) => {
|
|
52
|
+
if ('example' in holder)
|
|
53
|
+
return { value: holder.example, synthesised: false };
|
|
54
|
+
const [entry] = Object.values(isDict(holder.examples) ? holder.examples : {});
|
|
55
|
+
const named = deref(entry);
|
|
56
|
+
if ('value' in named)
|
|
57
|
+
return { value: named.value, synthesised: false };
|
|
58
|
+
const resolved = isDict(schema) ? deref(schema) : {};
|
|
59
|
+
if ('example' in resolved)
|
|
60
|
+
return { value: resolved.example, synthesised: false };
|
|
61
|
+
return { value: synthesise(schema, deref), synthesised: true };
|
|
62
|
+
};
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { lines, literal, operationTypes, pascal, readAs, stubResponse, where } from './plugin-server-code.js';
|
|
2
|
+
import { contractTest, serverOptions } from './plugin-server-contract.js';
|
|
3
|
+
import { routesOf } from './plugin-server-routes.js';
|
|
4
|
+
import { ROUTER_RUNTIME } from './plugin-server-runtime.js';
|
|
5
|
+
const specificity = (served) => served.route.path.replaceAll(/\{[^}]*\}/gu, '\uFFFF');
|
|
6
|
+
const bySpecificity = (served) => [...new Set(served.map((entry) => specificity(entry)))].toSorted().flatMap((key) => served.filter((entry) => specificity(entry) === key));
|
|
7
|
+
const row = (served) => {
|
|
8
|
+
const { route } = served;
|
|
9
|
+
const validator = (payload) => `validators[${literal(route.id)}][${literal(payload)}]`;
|
|
10
|
+
const { body } = route;
|
|
11
|
+
return [
|
|
12
|
+
' {',
|
|
13
|
+
` operation: ${literal(route.name)},`,
|
|
14
|
+
` method: ${literal(route.method)},`,
|
|
15
|
+
` path: ${literal(served.path)},`,
|
|
16
|
+
...(route.params.length === 0
|
|
17
|
+
? [' params: [],']
|
|
18
|
+
: [
|
|
19
|
+
' params: [',
|
|
20
|
+
...route.params.map((param) => ` { part: ${literal(param.part)}, name: ${literal(param.name)}, key: ${literal(readAs(param.part, param.name))}, kind: ${literal(param.kind)}, required: ${String(param.required)}, check: ${validator(param.payload)} },`),
|
|
21
|
+
' ],',
|
|
22
|
+
]),
|
|
23
|
+
...(body === undefined ? [] : [` body: { media: ${literal(body.media)}, required: ${String(body.required)}, check: ${validator(body.payload)} },`]),
|
|
24
|
+
...(route.responses.length === 0
|
|
25
|
+
? [' responses: {},']
|
|
26
|
+
: [
|
|
27
|
+
' responses: {',
|
|
28
|
+
...route.responses.map(({ status, content }) => ` ${literal(status)}: ${content === undefined ? '{}' : `{ media: ${literal(content.media)}, check: ${validator(content.payload)} }`},`),
|
|
29
|
+
' },',
|
|
30
|
+
]),
|
|
31
|
+
' },',
|
|
32
|
+
];
|
|
33
|
+
};
|
|
34
|
+
export const routesFile = (framework, served, options) => {
|
|
35
|
+
const routes = served.map(({ route }) => route);
|
|
36
|
+
const validated = routes.some((route) => route.params.length > 0 || route.body !== undefined || route.responses.some((response) => response.content !== undefined));
|
|
37
|
+
return lines(...framework.imports, '', "import { handle, type Route } from './contract-runtime.js';", `import { type paths } from ${literal(options.types)};`, ...(validated ? [`import { operations as validators } from ${literal(options.validators)};`] : []), '', ...routes.flatMap((route) => [...operationTypes(route), '']), '/**', ' * One method per operation; `handlers.ts` implements it. A new operation in the spec is a new', ' * member here, so `handlers.ts` stops compiling until it has one.', ' */', 'export interface Handlers {', ...routes.map((route) => ` /** ${where(route)}. */\n ${route.name}(input: ${pascal(route.name)}Input): ${pascal(route.name)}Output | Promise<${pascal(route.name)}Output>;`), '}', '', `/** Every route, as ${framework.name} reads it: the handler it calls, what it reads and checks, and what it may answer. */`, 'export const routes: readonly Route<Handlers>[] = [', ...served.flatMap((entry) => row(entry)), '];', '', ...framework.register);
|
|
38
|
+
};
|
|
39
|
+
export const handlersFile = (framework, routes) => lines('/**', ' * The handlers the routes call, one per operation. contractdiff wrote this file once and never', ' * rewrites it: change it freely. `Handlers` (routes.ts, regenerated) declares one method per', " * operation, and the routes validate every request and response; each method here answers the spec's", ` * example until you replace it. ${framework.usage}`, ' */', "import { type Handlers } from './routes.js';", '', 'export const handlers: Handlers = {', ...routes.flatMap((route, index) => [...(index === 0 ? [] : ['']), ` /** ${where(route)}. */`, ` ${route.name}(_input) {`, ` ${stubResponse(route)}`, ' },']), '};');
|
|
40
|
+
export const runRouter = (framework, contract, options) => {
|
|
41
|
+
const checked = serverOptions(framework.target, options);
|
|
42
|
+
const { controllers, findings } = routesOf(contract, framework.name);
|
|
43
|
+
const served = [];
|
|
44
|
+
const unsupported = [];
|
|
45
|
+
for (const route of controllers.flatMap((controller) => controller.routes)) {
|
|
46
|
+
const path = framework.path(route.path);
|
|
47
|
+
if (path === undefined) {
|
|
48
|
+
unsupported.push({
|
|
49
|
+
code: 'server-path-unsupported',
|
|
50
|
+
pointer: route.source,
|
|
51
|
+
message: `\`${route.id}\` is served at ${route.path}, which ${framework.name} cannot route: a parameter must be a whole segment, and a \`:\`, \`*\` or \`?\` cannot be written`,
|
|
52
|
+
fix: 'serve it outside the generated routes, or give it a path the framework can route',
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
else
|
|
56
|
+
served.push({ route, path });
|
|
57
|
+
}
|
|
58
|
+
const table = bySpecificity(served);
|
|
59
|
+
const routes = table.map(({ route }) => route);
|
|
60
|
+
const files = [
|
|
61
|
+
{ path: 'contract-runtime.ts', owner: 'generated', content: ROUTER_RUNTIME },
|
|
62
|
+
...(table.length === 0
|
|
63
|
+
? []
|
|
64
|
+
: [
|
|
65
|
+
{ path: 'routes.ts', owner: 'generated', content: routesFile(framework, table, checked), symbols: routes.map((route) => ({ operation: route.id, symbol: 'Handlers' })) },
|
|
66
|
+
{
|
|
67
|
+
path: 'handlers.ts',
|
|
68
|
+
owner: 'user',
|
|
69
|
+
content: handlersFile(framework, routes),
|
|
70
|
+
symbols: routes.map((route) => ({ operation: route.id, symbol: `handlers.${route.name}` })),
|
|
71
|
+
},
|
|
72
|
+
]),
|
|
73
|
+
...routes.map((route) => ({ path: `${route.name}.contract.test.ts`, owner: 'generated', content: contractTest(route, checked, checked.testRunner, framework.harness) })),
|
|
74
|
+
];
|
|
75
|
+
const byPath = new Map(files.map((file) => [file.path, file]));
|
|
76
|
+
return { files: [...byPath.keys()].toSorted().map((key) => byPath.get(key)), findings: [...findings, ...unsupported] };
|
|
77
|
+
};
|
|
@@ -0,0 +1,155 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
import { exampleOf } from './plugin-server-example.js';
|
|
3
|
+
const METHODS = new Set(['get', 'put', 'post', 'delete', 'options', 'head', 'patch']);
|
|
4
|
+
const PROBLEM_STATUSES = new Set(['400', '4XX', 'default']);
|
|
5
|
+
export const stubStatus = (statuses) => statuses.find((status) => status.startsWith('2')) ?? statuses[0];
|
|
6
|
+
const isDict = (value) => typeof value === 'object' && value !== null;
|
|
7
|
+
const dict = (value) => (isDict(value) ? value : {});
|
|
8
|
+
const finding = (code, pointer, message, fix) => ({ code, pointer, message, fix });
|
|
9
|
+
const words = (text) => text.split(/[^A-Za-z0-9]+/u).filter((word) => word !== '');
|
|
10
|
+
const upper = (word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`;
|
|
11
|
+
const lower = (word) => `${word.charAt(0).toLowerCase()}${word.slice(1)}`;
|
|
12
|
+
export const camel = (text) => {
|
|
13
|
+
const name = lower(words(text).map(upper).join(''));
|
|
14
|
+
if (name === '')
|
|
15
|
+
return 'operation';
|
|
16
|
+
return /^\d/u.test(name) ? `_${name}` : name;
|
|
17
|
+
};
|
|
18
|
+
export const kebab = (text) => words(text).join('-').toLowerCase() || 'default';
|
|
19
|
+
export const classOf = (file) => {
|
|
20
|
+
const name = words(file).map(upper).join('');
|
|
21
|
+
return /^\d/u.test(name) ? `_${name}` : name;
|
|
22
|
+
};
|
|
23
|
+
export const fallbackName = (method, path) => camel([method, ...path.split('/').map((segment) => (/^\{.+\}$/u.test(segment) ? `by ${segment}` : segment))].join(' '));
|
|
24
|
+
export const unique = (base, taken) => {
|
|
25
|
+
let name = base;
|
|
26
|
+
for (let suffix = 2; taken.has(name.toLowerCase()); suffix += 1)
|
|
27
|
+
name = `${base}${String(suffix)}`;
|
|
28
|
+
taken.add(name.toLowerCase());
|
|
29
|
+
return name;
|
|
30
|
+
};
|
|
31
|
+
const isJson = (media) => media === 'application/json' || media.endsWith('+json');
|
|
32
|
+
const derefIn = (document) => (value) => {
|
|
33
|
+
let node = value;
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
while (isDict(node) && typeof node.$ref === 'string' && !seen.has(node.$ref)) {
|
|
36
|
+
seen.add(node.$ref);
|
|
37
|
+
node = pointerGet(document, node.$ref);
|
|
38
|
+
}
|
|
39
|
+
return dict(node);
|
|
40
|
+
};
|
|
41
|
+
const typeOf = (schema) => (Array.isArray(schema.type) ? schema.type.find((type) => type !== 'null') : schema.type);
|
|
42
|
+
export const kindOf = (schema, deref) => {
|
|
43
|
+
const resolved = deref(schema);
|
|
44
|
+
const type = typeOf(resolved);
|
|
45
|
+
if (type === 'array')
|
|
46
|
+
return `${kindOf(resolved.items, deref)}[]`;
|
|
47
|
+
if (type === 'integer' || type === 'number')
|
|
48
|
+
return 'number';
|
|
49
|
+
return type === 'boolean' ? 'boolean' : 'string';
|
|
50
|
+
};
|
|
51
|
+
const partsOf = (name) => {
|
|
52
|
+
const parts = name.split(':');
|
|
53
|
+
return [parts[1], parts.slice(2).join(':')];
|
|
54
|
+
};
|
|
55
|
+
const media = (payloads) => payloads.filter((payload) => !payload.name.endsWith(':item'));
|
|
56
|
+
const mediaOf = (name) => (name.startsWith('body:') ? name.slice('body:'.length) : partsOf(name)[1]);
|
|
57
|
+
const pick = (payloads) => {
|
|
58
|
+
const chosen = payloads.find((payload) => isJson(mediaOf(payload.name))) ?? payloads[0];
|
|
59
|
+
return { chosen, dropped: payloads.filter((payload) => payload !== chosen) };
|
|
60
|
+
};
|
|
61
|
+
export const routesOf = (contract, framework) => {
|
|
62
|
+
const { document } = contract;
|
|
63
|
+
const deref = derefIn(document);
|
|
64
|
+
const findings = [];
|
|
65
|
+
const taken = new Set();
|
|
66
|
+
const examples = (picked, label, source) => {
|
|
67
|
+
if (picked.synthesised) {
|
|
68
|
+
findings.push(finding('server-example-synthesised', source, `${label} has no example: the contract test sends one made from its schema`, 'add an `example` to the spec, so the contract test sends a value you chose'));
|
|
69
|
+
}
|
|
70
|
+
return picked.value;
|
|
71
|
+
};
|
|
72
|
+
const dropped = (operation, payloads, what) => {
|
|
73
|
+
for (const payload of payloads) {
|
|
74
|
+
findings.push(finding('server-media-type-skipped', operation.source, `\`${operation.id}\` ${what} in ${mediaOf(payload.name)} is not served: the route serves one media type, JSON first`, 'serve the other media type outside the generated route'));
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const paramsOf = (operation, declared, shared) => {
|
|
78
|
+
const declaredParams = new Map();
|
|
79
|
+
for (const entry of [shared, declared.parameters].flat()) {
|
|
80
|
+
const parameter = deref(entry);
|
|
81
|
+
declaredParams.set(`param:${String(parameter.in)}:${String(parameter.name)}`, parameter);
|
|
82
|
+
}
|
|
83
|
+
return operation.payloads
|
|
84
|
+
.filter((candidate) => candidate.name.startsWith('param:'))
|
|
85
|
+
.flatMap((payload) => {
|
|
86
|
+
const [part, paramName] = partsOf(payload.name);
|
|
87
|
+
if (part !== 'path' && part !== 'query' && part !== 'header') {
|
|
88
|
+
findings.push(finding('server-parameter-skipped', operation.source, `\`${operation.id}\` reads ${part} parameter "${paramName}", which the generated route does not pass on`, 'read it from the request in your handler'));
|
|
89
|
+
return [];
|
|
90
|
+
}
|
|
91
|
+
const parameter = dict(declaredParams.get(payload.name));
|
|
92
|
+
const example = examples(exampleOf(parameter, payload.schema, deref), `\`${operation.id}\` ${part} parameter "${paramName}"`, operation.source);
|
|
93
|
+
return [{ name: paramName, part, payload: payload.name, required: payload.required, kind: kindOf(payload.schema, deref), example }];
|
|
94
|
+
});
|
|
95
|
+
};
|
|
96
|
+
const bodyOf = (operation, declared) => {
|
|
97
|
+
const bodies = media(operation.payloads.filter((payload) => payload.name.startsWith('body:')));
|
|
98
|
+
if (bodies.length === 0)
|
|
99
|
+
return undefined;
|
|
100
|
+
const { chosen, dropped: others } = pick(bodies);
|
|
101
|
+
dropped(operation, others, 'accepts a body');
|
|
102
|
+
const type = mediaOf(chosen.name);
|
|
103
|
+
const holder = deref(dict(deref(declared.requestBody).content)[type]);
|
|
104
|
+
return { payload: chosen.name, media: type, required: chosen.required, example: examples(exampleOf(holder, chosen.schema, deref), `\`${operation.id}\` body`, operation.source) };
|
|
105
|
+
};
|
|
106
|
+
const responsesOf = (operation, declared, statuses) => {
|
|
107
|
+
const stub = stubStatus(statuses);
|
|
108
|
+
return statuses.map((status) => {
|
|
109
|
+
const all = media(operation.payloads.filter((payload) => payload.name.startsWith(`response:${status}:`)));
|
|
110
|
+
if (all.length === 0)
|
|
111
|
+
return { status };
|
|
112
|
+
const { chosen, dropped: others } = pick(all);
|
|
113
|
+
dropped(operation, others, `answers ${status}`);
|
|
114
|
+
const type = mediaOf(chosen.name);
|
|
115
|
+
if (status !== stub)
|
|
116
|
+
return { status, content: { media: type, payload: chosen.name, example: undefined } };
|
|
117
|
+
const holder = deref(dict(deref(dict(declared.responses)[status]).content)[type]);
|
|
118
|
+
return { status, content: { media: type, payload: chosen.name, example: examples(exampleOf(holder, chosen.schema, deref), `\`${operation.id}\` response ${status}`, operation.source) } };
|
|
119
|
+
});
|
|
120
|
+
};
|
|
121
|
+
const build = (operation) => {
|
|
122
|
+
const match = /^#\/paths\/([^/]+)\/([a-z]+)$/u.exec(operation.source);
|
|
123
|
+
if (match === null || !METHODS.has(match[2])) {
|
|
124
|
+
findings.push(finding('server-operation-skipped', operation.source, `\`${operation.id}\` is not a route ${framework} serves (a webhook, or a method the target does not route)`, 'serve it outside the generated routes'));
|
|
125
|
+
return undefined;
|
|
126
|
+
}
|
|
127
|
+
const token = match[1];
|
|
128
|
+
const method = match[2];
|
|
129
|
+
const path = token.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
130
|
+
const declared = deref(pointerGet(document, operation.source));
|
|
131
|
+
const name = unique(typeof declared.operationId === 'string' ? camel(declared.operationId) : fallbackName(method, path), taken);
|
|
132
|
+
const params = paramsOf(operation, declared, deref(pointerGet(document, `#/paths/${token}`)).parameters);
|
|
133
|
+
for (const payload of operation.payloads.filter((candidate) => candidate.name.endsWith(':item'))) {
|
|
134
|
+
findings.push(finding('server-stream-skipped', operation.source, `\`${operation.id}\` streams ${payload.name.slice(0, -':item'.length)} item by item, which the generated route does not`, 'stream it from your handler, outside the generated route'));
|
|
135
|
+
}
|
|
136
|
+
const body = bodyOf(operation, declared);
|
|
137
|
+
const statuses = [...new Set(operation.payloads.filter((payload) => payload.name.startsWith('response:')).map((payload) => partsOf(payload.name)[0]))];
|
|
138
|
+
const responses = responsesOf(operation, declared, statuses);
|
|
139
|
+
if ((params.length > 0 || body !== undefined) && !statuses.some((status) => PROBLEM_STATUSES.has(status))) {
|
|
140
|
+
findings.push(finding('server-problem-undeclared', operation.source, `\`${operation.id}\` answers a request the contract refuses with 400 Problem Details, which its responses do not declare`, 'declare a `400` response with `application/problem+json` content'));
|
|
141
|
+
}
|
|
142
|
+
const tags = Array.isArray(declared.tags) ? declared.tags : [];
|
|
143
|
+
const route = { id: operation.id, method, path, source: operation.source, name, params, ...(body === undefined ? {} : { body }), responses };
|
|
144
|
+
return { route, tag: kebab(typeof tags[0] === 'string' ? tags[0] : '') };
|
|
145
|
+
};
|
|
146
|
+
const ids = [...new Set(contract.operations.map((operation) => operation.id))].toSorted();
|
|
147
|
+
const built = ids
|
|
148
|
+
.flatMap((id) => contract.operations.filter((operation) => operation.id === id))
|
|
149
|
+
.map((operation) => build(operation))
|
|
150
|
+
.filter((entry) => entry !== undefined);
|
|
151
|
+
const routes = built.map(({ route, tag }) => ({ tag, route: { ...route, handler: unique(`handle${upper(route.name)}`, taken) } }));
|
|
152
|
+
const files = [...new Set(routes.map(({ tag }) => tag))].toSorted();
|
|
153
|
+
const controllers = files.map((file) => ({ file, name: classOf(file), routes: routes.filter(({ tag }) => tag === file).map(({ route }) => route) }));
|
|
154
|
+
return { controllers, findings };
|
|
155
|
+
};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { lines } from './plugin-server-code.js';
|
|
2
|
+
export const RUNTIME = lines('/**', ' * What every generated controller calls: coercion of path, query and header strings, validation', ' * of the request and the response, and RFC 9457 Problem Details for a request the contract refuses.', ' */', '', "/** What a reply offers: Express's `Response` and Fastify's `FastifyReply` both do. */", 'export interface Reply {', ' status(code: number): unknown;', ' header(name: string, value: string): unknown;', '}', '', '/** A validator the `validator` target generated. */', 'export type Check = (value: unknown) => boolean;', '', '/** One error in a Problem Details answer: where in the request, and what is wrong there. */', 'export interface ProblemError {', ' readonly pointer: string;', ' readonly detail: string;', '}', '', '/** RFC 9457 Problem Details, answered as `application/problem+json`. */', 'export interface ProblemDetails {', ' readonly type: string;', ' readonly title: string;', ' readonly status: number;', ' readonly detail: string;', ' readonly errors?: readonly ProblemError[];', '}', '', '/** One part of the request, and the validator the contract gives it. */', 'export interface Field {', ' readonly pointer: string;', ' readonly value: unknown;', ' readonly required: boolean;', ' readonly check: Check;', '}', '', '/** A declared response: its media type and validator, both absent when it has no content. */', 'export interface Declared {', ' readonly media?: string;', ' readonly check?: Check;', '}', '', '/** What a handler returns. */', 'export interface Output {', ' readonly status: number;', ' readonly body?: unknown;', ' readonly headers?: Readonly<Record<string, string>>;', '}', '', 'const number = (value: unknown): unknown => {', " if (typeof value !== 'string' || value.trim() === '') return value;", ' const parsed = Number(value);', ' return Number.isNaN(parsed) ? value : parsed;', '};', '', 'const boolean = (value: unknown): unknown => {', " if (value === 'true') return true;", " return value === 'false' ? false : value;", '};', '', '/** A string from the URL or a header as the contract types it: `number`, `boolean`, `string`, or a list of one (`number[]`). */', 'export const coerce = (value: unknown, kind: string): unknown => {', ' if (value === undefined) return undefined;', " if (kind.endsWith('[]')) return (Array.isArray(value) ? value : [value]).map((item) => coerce(item, kind.slice(0, -2)));", " if (kind === 'number') return number(value);", " return kind === 'boolean' ? boolean(value) : value;", '};', '', '/** Every part of the request the contract refuses: a missing required part, or a value its validator rejects. */', 'export const invalid = (fields: readonly Field[]): ProblemError[] =>', ' fields.flatMap((field): ProblemError[] => {', " if (field.value === undefined) return field.required ? [{ pointer: field.pointer, detail: 'is required' }] : [];", " return field.check(field.value) ? [] : [{ pointer: field.pointer, detail: 'does not match the contract' }];", ' });', '', '/** Answer Problem Details. */', 'export const problem = (reply: Reply, status: number, title: string, detail: string, errors?: readonly ProblemError[]): ProblemDetails => {', ' reply.status(status);', " reply.header('content-type', 'application/problem+json');", " return { type: 'about:blank', title, status, detail, ...(errors === undefined ? {} : { errors }) };", '};', '', '/** The declared response a status answers under: its own code, then its range (`4XX`), then `default`. */', 'export const declared = (responses: Readonly<Record<string, Declared>>, status: number): Declared | undefined =>', ' responses[String(status)] ?? responses[`${String(status).charAt(0)}XX`] ?? responses.default;', '', '/** Send what a handler returned. One the contract does not declare is not sent: the client gets a 500. */', 'export const send = (reply: Reply, output: Output, responses: Readonly<Record<string, Declared>>): unknown => {', ' const response = declared(responses, output.status);', ' // A no-content response has no check: a body there is as undeclared as a body that fails one.', ' if (response === undefined || (response.check === undefined ? output.body !== undefined : !response.check(output.body))) {', " return problem(reply, 500, 'Internal Server Error', `The handler answered ${String(output.status)} with a response the contract does not declare.`);", ' }', ' reply.status(output.status);', " if (response.media !== undefined) reply.header('content-type', response.media);", ' for (const [name, value] of Object.entries(output.headers ?? {})) reply.header(name, value);', ' return output.body;', '};');
|
|
3
|
+
export const ROUTER_RUNTIME = `${RUNTIME}${lines('', '/** The methods a route table lists, as Hono, Fastify and Express name them. */', "export type Method = 'get' | 'put' | 'post' | 'delete' | 'options' | 'head' | 'patch';", '', '/** One path, query or header parameter: where it is read, how its string is coerced, and its validator. */', 'export interface Param {', " readonly part: 'path' | 'query' | 'header';", ' /** The name the spec gives it: its key in the input. */', ' readonly name: string;', ' /** Its key in what the framework hands over: lower case for a header, the route segment\'s name for a path parameter. */', ' readonly key: string;', ' readonly kind: string;', ' readonly required: boolean;', ' readonly check: Check;', '}', '', '/** The body a route reads: its media type and its validator. */', 'export interface Body {', ' readonly media: string;', ' readonly required: boolean;', ' readonly check: Check;', '}', '', '/** One row of a route table: the handler it calls, where it is served, what it reads, and what it may answer. */', 'export interface Route<Handlers> {', ' readonly operation: keyof Handlers;', ' readonly method: Method;', ' /** As the framework reads it, e.g. `/pets/:petId`. */', ' readonly path: string;', ' readonly params: readonly Param[];', ' readonly body?: Body;', ' readonly responses: Readonly<Record<string, Declared>>;', '}', '', '/** A request as the framework hands it over: each part by key, and the body as text or as a parser left it. */', 'export interface Incoming {', ' readonly path: Readonly<Record<string, unknown>>;', ' readonly query: Readonly<Record<string, unknown>>;', ' readonly header: Readonly<Record<string, unknown>>;', ' readonly body: unknown;', '}', '', '/** What the framework sends: the status, the headers, and the body as the wire carries it. */', 'export interface Answer {', ' readonly status: number;', ' readonly headers: Readonly<Record<string, string>>;', ' readonly body: string | undefined;', '}', '', "const json = (media: string): boolean => media === 'application/json' || media.endsWith('+json');", '', '/** A parameter as its kind types it; a repeated one is a list only when the parameter is one. */', "const read = (value: unknown, kind: string): unknown => coerce(!kind.endsWith('[]') && Array.isArray(value) ? value[0] : value, kind);", '', '/** A body given as text, parsed: JSON for a JSON media type, the text itself otherwise, nothing when empty. One a parser already read is kept. */', 'const parse = (body: unknown, media: string): unknown => {', " if (typeof body !== 'string') return body;", " if (body === '') return undefined;", ' return json(media) ? JSON.parse(body) : body;', '};', '', '/** A body as the wire carries it: none without a content type, JSON for a JSON one or for a value that is not text, else the text. */', 'const wire = (media: string | undefined, body: unknown): string | undefined => {', ' if (media === undefined || body === undefined) return undefined;', " return json(media) || typeof body !== 'string' ? JSON.stringify(body) : body;", '};', '', '/** Answer one request: read and check it, call the handler, and send what it answers only when the contract declares it. */', 'export const handle = async <Handlers>(route: Route<Handlers>, handlers: Handlers, request: Incoming): Promise<Answer> => {', ' const headers: Record<string, string> = {};', ' let status = 500;', ' const reply: Reply = {', ' status: (code) => (status = code),', ' header: (name, value) => (headers[name] = value),', ' };', " const answer = (body: unknown): Answer => ({ status, headers, body: wire(headers['content-type'], body) });", ' const input: Record<string, unknown> = {};', ' const fields = route.params.map((param): Field => {', ' const value = read(request[param.part][param.key], param.kind);', ' input[param.part] = { ...(input[param.part] as object | undefined), [param.name]: value };', ' return { pointer: `/${param.part}/${param.name}`, value, required: param.required, check: param.check };', ' });', ' if (route.body !== undefined) {', ' try {', ' input.body = parse(request.body, route.body.media);', ' } catch {', " return answer(problem(reply, 400, 'Bad Request', 'The request does not match the contract.', [{ pointer: '/body', detail: 'is not JSON' }]));", ' }', " fields.push({ pointer: '/body', value: input.body, required: route.body.required, check: route.body.check });", ' }', ' const errors = invalid(fields);', " if (errors.length > 0) return answer(problem(reply, 400, 'Bad Request', 'The request does not match the contract.', errors));", ' const handler = handlers[route.operation] as unknown as (input: unknown) => Output | Promise<Output>;', ' return answer(send(reply, await handler.call(handlers, input), route.responses));', '};')}`;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
export const SAMPLE_DOCUMENT = {
|
|
2
|
+
openapi: '3.1.0',
|
|
3
|
+
info: { title: 'Pets', version: '1.0.0' },
|
|
4
|
+
paths: {
|
|
5
|
+
'/pets': {
|
|
6
|
+
get: {
|
|
7
|
+
tags: ['pets'],
|
|
8
|
+
parameters: [{ name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1 } }],
|
|
9
|
+
responses: { '200': { description: 'Pets', content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/Pet' } }, example: [{ id: 1, name: 'Rex' }] } } } },
|
|
10
|
+
},
|
|
11
|
+
post: {
|
|
12
|
+
operationId: 'createPet',
|
|
13
|
+
tags: ['pets'],
|
|
14
|
+
requestBody: { required: true, content: { 'application/json': { schema: { $ref: '#/components/schemas/NewPet' }, example: { name: 'Rex' } } } },
|
|
15
|
+
responses: {
|
|
16
|
+
'201': { description: 'Created', content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet' }, example: { id: 1, name: 'Rex' } } } },
|
|
17
|
+
'400': { description: 'Invalid', content: { 'application/problem+json': { schema: { $ref: '#/components/schemas/Problem' } } } },
|
|
18
|
+
},
|
|
19
|
+
},
|
|
20
|
+
},
|
|
21
|
+
'/pets/{petId}': {
|
|
22
|
+
get: {
|
|
23
|
+
operationId: 'getPet',
|
|
24
|
+
tags: ['pets'],
|
|
25
|
+
parameters: [{ name: 'petId', in: 'path', required: true, schema: { type: 'integer' }, example: 1 }],
|
|
26
|
+
responses: {
|
|
27
|
+
'200': { description: 'A pet', content: { 'application/json': { schema: { $ref: '#/components/schemas/Pet' }, example: { id: 1, name: 'Rex' } } } },
|
|
28
|
+
'404': { description: 'Not found' },
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
components: {
|
|
34
|
+
schemas: {
|
|
35
|
+
Pet: { type: 'object', required: ['id', 'name'], properties: { id: { type: 'integer' }, name: { type: 'string' } } },
|
|
36
|
+
NewPet: { type: 'object', required: ['name'], properties: { name: { type: 'string' } } },
|
|
37
|
+
Problem: { type: 'object', required: ['title', 'status'], properties: { type: { type: 'string' }, title: { type: 'string' }, status: { type: 'integer' }, detail: { type: 'string' } } },
|
|
38
|
+
},
|
|
39
|
+
},
|
|
40
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const document = { "openapi": "3.1.0", "paths": { "/pets": { "get": { "operationId": "listPets", "responses": {} }, "post": { "operationId": "createPet", "responses": {} } } } };
|
|
2
|
+
export const SAMPLE_SWR = `import { type Client, type CreatePetInput, type ListPetsInput } from "./client.js";
|
|
3
|
+
|
|
4
|
+
/** A value with its object keys sorted at every depth: the same input in any property order is the same key. */
|
|
5
|
+
export const stable = (value: unknown): unknown => {
|
|
6
|
+
if (Array.isArray(value)) return value.map(stable);
|
|
7
|
+
if (typeof value !== "object" || value === null) return value;
|
|
8
|
+
const record = value as Readonly<Record<string, unknown>>;
|
|
9
|
+
return Object.fromEntries(Object.keys(record).sort().map((name) => [name, stable(record[name])]));
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const createPetSWRMutation = (client: Client) => ({
|
|
13
|
+
key: ["createPet"] as const,
|
|
14
|
+
fetcher: async (_key: unknown, { arg }: { readonly arg: CreatePetInput }) => client["createPet"](arg),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const listPetsSWR = (client: Client, input: ListPetsInput = {}) => ({
|
|
18
|
+
key: ["listPets", stable(input)] as const,
|
|
19
|
+
fetcher: async () => client["listPets"](input),
|
|
20
|
+
});
|
|
21
|
+
`;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { optional } from './plugin-fetch-client.js';
|
|
2
|
+
import { routesOf } from './plugin-fetch-routes.js';
|
|
3
|
+
import { lines, literal } from './plugin-fetch-text.js';
|
|
4
|
+
import { document, SAMPLE_SWR } from './plugin-swr-sample.js';
|
|
5
|
+
import { camel, QUERY_METHODS, STABLE } from './plugin-tanstack-query.js';
|
|
6
|
+
export const SWR_FILE = 'swr.ts';
|
|
7
|
+
const symbolOf = (route) => `${camel(route.name)}${QUERY_METHODS.includes(route.method) ? 'SWR' : 'SWRMutation'}`;
|
|
8
|
+
const pair = (route) => {
|
|
9
|
+
const call = `client[${literal(route.id)}]`;
|
|
10
|
+
if (QUERY_METHODS.includes(route.method)) {
|
|
11
|
+
return [
|
|
12
|
+
`export const ${symbolOf(route)} = (client: Client, input: ${route.name}Input${optional(route) ? ' = {}' : ''}) => ({`,
|
|
13
|
+
` key: [${literal(route.id)}, stable(input)] as const,`,
|
|
14
|
+
` fetcher: async () => ${call}(input),`,
|
|
15
|
+
'});',
|
|
16
|
+
'',
|
|
17
|
+
];
|
|
18
|
+
}
|
|
19
|
+
return [
|
|
20
|
+
`export const ${symbolOf(route)} = (client: Client) => ({`,
|
|
21
|
+
` key: [${literal(route.id)}] as const,`,
|
|
22
|
+
` fetcher: async (_key: unknown, { arg }: { readonly arg: ${route.name}Input }) => ${call}(arg),`,
|
|
23
|
+
'});',
|
|
24
|
+
'',
|
|
25
|
+
];
|
|
26
|
+
};
|
|
27
|
+
export const swrFile = (routes, client) => lines(`import { ${['type Client', ...routes.map((route) => `type ${route.name}Input`)].join(', ')} } from ${literal(client)};`, '', ...STABLE, '', ...routes.flatMap((route) => pair(route))).replace(/\n\n$/u, '\n');
|
|
28
|
+
const run = (contract, options) => {
|
|
29
|
+
const { routes, findings } = routesOf(contract);
|
|
30
|
+
const client = typeof options.client === 'string' ? options.client : './client.js';
|
|
31
|
+
const symbols = routes.map((route) => ({ operation: route.id, symbol: symbolOf(route) }));
|
|
32
|
+
return { files: [{ path: SWR_FILE, owner: 'generated', content: swrFile(routes, client), symbols }], findings };
|
|
33
|
+
};
|
|
34
|
+
const swr = {
|
|
35
|
+
description: 'SWR keys and fetchers for every operation over the fetch client, with stable keys',
|
|
36
|
+
inputs: ['openapi'],
|
|
37
|
+
sample: { document, files: [{ path: SWR_FILE, owner: 'generated', content: SAMPLE_SWR }] },
|
|
38
|
+
run,
|
|
39
|
+
};
|
|
40
|
+
export const plugin = { name: 'swr', generators: { swr } };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export const document = { "openapi": "3.1.0", "paths": { "/pets": { "get": { "operationId": "listPets", "responses": {} }, "post": { "operationId": "createPet", "responses": {} } } } };
|
|
2
|
+
export const SAMPLE_QUERIES = `import { type Client, type CreatePetInput, type ListPetsInput } from "./client.js";
|
|
3
|
+
|
|
4
|
+
/** A value with its object keys sorted at every depth: the same input in any property order is the same key. */
|
|
5
|
+
export const stable = (value: unknown): unknown => {
|
|
6
|
+
if (Array.isArray(value)) return value.map(stable);
|
|
7
|
+
if (typeof value !== "object" || value === null) return value;
|
|
8
|
+
const record = value as Readonly<Record<string, unknown>>;
|
|
9
|
+
return Object.fromEntries(Object.keys(record).sort().map((name) => [name, stable(record[name])]));
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export const createPetMutationOptions = (client: Client) => ({
|
|
13
|
+
mutationKey: ["createPet"] as const,
|
|
14
|
+
mutationFn: async (input: CreatePetInput) => client["createPet"](input),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const listPetsQueryOptions = (client: Client, input: ListPetsInput = {}) => ({
|
|
18
|
+
queryKey: ["listPets", stable(input)] as const,
|
|
19
|
+
queryFn: async () => client["listPets"](input),
|
|
20
|
+
});
|
|
21
|
+
`;
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { optional } from './plugin-fetch-client.js';
|
|
2
|
+
import { routesOf } from './plugin-fetch-routes.js';
|
|
3
|
+
import { lines, literal } from './plugin-fetch-text.js';
|
|
4
|
+
import { document, SAMPLE_QUERIES } from './plugin-tanstack-query-sample.js';
|
|
5
|
+
export const QUERIES_FILE = 'queries.ts';
|
|
6
|
+
export const QUERY_METHODS = ['get', 'head'];
|
|
7
|
+
export const STABLE = [
|
|
8
|
+
'/** A value with its object keys sorted at every depth: the same input in any property order is the same key. */',
|
|
9
|
+
'export const stable = (value: unknown): unknown => {',
|
|
10
|
+
' if (Array.isArray(value)) return value.map(stable);',
|
|
11
|
+
' if (typeof value !== "object" || value === null) return value;',
|
|
12
|
+
' const record = value as Readonly<Record<string, unknown>>;',
|
|
13
|
+
' return Object.fromEntries(Object.keys(record).sort().map((name) => [name, stable(record[name])]));',
|
|
14
|
+
'};',
|
|
15
|
+
];
|
|
16
|
+
export const camel = (name) => `${name.charAt(0).toLowerCase()}${name.slice(1)}`;
|
|
17
|
+
const factory = (route) => {
|
|
18
|
+
const input = `input: ${route.name}Input${optional(route) ? ' = {}' : ''}`;
|
|
19
|
+
const call = `client[${literal(route.id)}]`;
|
|
20
|
+
if (QUERY_METHODS.includes(route.method)) {
|
|
21
|
+
return [
|
|
22
|
+
`export const ${camel(route.name)}QueryOptions = (client: Client, ${input}) => ({`,
|
|
23
|
+
` queryKey: [${literal(route.id)}, stable(input)] as const,`,
|
|
24
|
+
` queryFn: async () => ${call}(input),`,
|
|
25
|
+
'});',
|
|
26
|
+
'',
|
|
27
|
+
];
|
|
28
|
+
}
|
|
29
|
+
return [
|
|
30
|
+
`export const ${camel(route.name)}MutationOptions = (client: Client) => ({`,
|
|
31
|
+
` mutationKey: [${literal(route.id)}] as const,`,
|
|
32
|
+
` mutationFn: async (input: ${route.name}Input) => ${call}(input),`,
|
|
33
|
+
'});',
|
|
34
|
+
'',
|
|
35
|
+
];
|
|
36
|
+
};
|
|
37
|
+
export const queriesFile = (routes, client) => lines(`import { ${['type Client', ...routes.map((route) => `type ${route.name}Input`)].join(', ')} } from ${literal(client)};`, '', ...STABLE, '', ...routes.flatMap((route) => factory(route))).replace(/\n\n$/u, '\n');
|
|
38
|
+
const run = (contract, options) => {
|
|
39
|
+
const { routes, findings } = routesOf(contract);
|
|
40
|
+
const client = typeof options.client === 'string' ? options.client : './client.js';
|
|
41
|
+
const symbols = routes.map((route) => ({ operation: route.id, symbol: `${camel(route.name)}${QUERY_METHODS.includes(route.method) ? 'Query' : 'Mutation'}Options` }));
|
|
42
|
+
return { files: [{ path: QUERIES_FILE, owner: 'generated', content: queriesFile(routes, client), symbols }], findings };
|
|
43
|
+
};
|
|
44
|
+
const tanstackQuery = {
|
|
45
|
+
description: 'TanStack Query options for every operation over the fetch client, with stable query keys',
|
|
46
|
+
inputs: ['openapi'],
|
|
47
|
+
sample: {
|
|
48
|
+
document,
|
|
49
|
+
files: [
|
|
50
|
+
{
|
|
51
|
+
path: QUERIES_FILE,
|
|
52
|
+
owner: 'generated',
|
|
53
|
+
content: SAMPLE_QUERIES,
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
},
|
|
57
|
+
run,
|
|
58
|
+
};
|
|
59
|
+
export const plugin = { name: 'tanstack-query', generators: { 'tanstack-query': tanstackQuery } };
|