contractdiff 0.0.0-stage → 0.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +228 -2
- package/dist/bin.js +4 -0
- package/dist/cli.d.ts +3 -0
- package/dist/cli.js +24 -0
- package/dist/command-diff.js +310 -0
- package/dist/command-explain-cap.js +36 -0
- package/dist/command-explain-inline.js +17 -0
- package/dist/command-explain-name.js +31 -0
- package/dist/command-explain-operation.js +85 -0
- package/dist/command-explain-text.js +21 -0
- package/dist/command-explain.js +54 -0
- package/dist/command-lint.js +280 -0
- package/dist/command-migrate.js +70 -0
- package/dist/command-plugin.js +32 -0
- package/dist/command-props.js +116 -0
- package/dist/commands.js +7 -0
- package/dist/core/index.d.ts +2 -0
- package/dist/core/index.js +2 -0
- package/dist/core/model.d.ts +46 -0
- package/dist/core/model.js +1 -0
- package/dist/core/resolve.d.ts +22 -0
- package/dist/core/resolve.js +71 -0
- package/dist/diff-classify.js +30 -0
- package/dist/diff-contract.js +176 -0
- package/dist/diff-decisions.js +446 -0
- package/dist/diff-normalise.js +143 -0
- package/dist/diff-rules.js +109 -0
- package/dist/diff-schema.js +335 -0
- package/dist/diff-security.js +33 -0
- package/dist/diff-transitive.js +26 -0
- package/dist/diff-usage.js +59 -0
- package/dist/extract-normalise.js +85 -0
- package/dist/extract-roundtrip.js +28 -0
- package/dist/extract-standard.js +79 -0
- package/dist/gen-ts-ast.d.ts +135 -0
- package/dist/gen-ts-ast.js +52 -0
- package/dist/gen-ts-bundle.js +233 -0
- package/dist/gen-ts-comment.js +48 -0
- package/dist/gen-ts-context.d.ts +83 -0
- package/dist/gen-ts-context.js +45 -0
- package/dist/gen-ts-dict.d.ts +14 -0
- package/dist/gen-ts-dict.js +14 -0
- package/dist/gen-ts-discriminators.d.ts +7 -0
- package/dist/gen-ts-discriminators.js +117 -0
- package/dist/gen-ts-document.d.ts +12 -0
- package/dist/gen-ts-document.js +82 -0
- package/dist/gen-ts-enums.js +139 -0
- package/dist/gen-ts-helpers.js +30 -0
- package/dist/gen-ts-index.d.ts +49 -0
- package/dist/gen-ts-index.js +110 -0
- package/dist/gen-ts-operations.js +277 -0
- package/dist/gen-ts-print.js +113 -0
- package/dist/gen-ts-ref.d.ts +30 -0
- package/dist/gen-ts-ref.js +75 -0
- package/dist/gen-ts-schema.js +283 -0
- package/dist/gen-ts-text.d.ts +24 -0
- package/dist/gen-ts-text.js +98 -0
- package/dist/host.d.ts +145 -0
- package/dist/host.js +273 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +5 -0
- package/dist/input-asyncapi.js +167 -0
- package/dist/input-buf.js +58 -0
- package/dist/input-jsonschema.js +165 -0
- package/dist/input-mcp.js +111 -0
- package/dist/input-overlay-jsonpath.js +265 -0
- package/dist/input-overlay.js +138 -0
- package/dist/input-protobuf.js +212 -0
- package/dist/input-swagger2.js +331 -0
- package/dist/inputs.js +8 -0
- package/dist/lint-code-read.js +129 -0
- package/dist/lint-code.d.ts +56 -0
- package/dist/lint-code.js +64 -0
- package/dist/lint-engine.d.ts +93 -0
- package/dist/lint-engine.js +87 -0
- package/dist/lint-functions.js +95 -0
- package/dist/lint-history.js +133 -0
- package/dist/lint-jsonpath.js +92 -0
- package/dist/lint-names.d.ts +11 -0
- package/dist/lint-names.js +2 -0
- package/dist/lint-redocly.js +141 -0
- package/dist/lint-rules.js +189 -0
- package/dist/lint-select.d.ts +33 -0
- package/dist/lint-select.js +129 -0
- package/dist/lint-since.js +20 -0
- package/dist/lint-spectral.js +167 -0
- package/dist/lint-stats.js +58 -0
- package/dist/migrate-hey-api.js +144 -0
- package/dist/migrate-literal.js +139 -0
- package/dist/migrate-openapi-fetch.js +62 -0
- package/dist/migrate-openapi-typescript.js +159 -0
- package/dist/migrate-orval.js +119 -0
- package/dist/migrate-shared.js +31 -0
- package/dist/openapi-typescript.d.ts +9 -0
- package/dist/openapi-typescript.js +36 -0
- package/dist/openapi.d.ts +20 -0
- package/dist/openapi.js +94 -0
- package/dist/plugin-express.js +66 -0
- package/dist/plugin-extract-hono.js +1 -0
- package/dist/plugin-extract-nest.js +1 -0
- package/dist/plugin-extract-openapi.js +246 -0
- package/dist/plugin-extract-standard-schema.js +42 -0
- package/dist/plugin-extract-trpc.js +1 -0
- package/dist/plugin-extract-ts-rest.js +77 -0
- package/dist/plugin-fastify.js +68 -0
- package/dist/plugin-fetch-client.js +172 -0
- package/dist/plugin-fetch-routes.js +110 -0
- package/dist/plugin-fetch-sample.js +155 -0
- package/dist/plugin-fetch-text.js +5 -0
- package/dist/plugin-fetch.js +19 -0
- package/dist/plugin-hono.js +42 -0
- package/dist/plugin-json-schema-build.js +289 -0
- package/dist/plugin-json-schema-dialect-anthropic.js +41 -0
- package/dist/plugin-json-schema-dialect-gemini.js +29 -0
- package/dist/plugin-json-schema-dialect-mcp-elicitation.js +32 -0
- package/dist/plugin-json-schema-dialect-mcp.js +13 -0
- package/dist/plugin-json-schema-dialect-openai.js +37 -0
- package/dist/plugin-json-schema-dialect.js +180 -0
- package/dist/plugin-json-schema.js +125 -0
- package/dist/plugin-markdown.js +114 -0
- package/dist/plugin-mcp-code.js +28 -0
- package/dist/plugin-mcp-tools.js +152 -0
- package/dist/plugin-mcp.js +107 -0
- package/dist/plugin-msw-files.js +50 -0
- package/dist/plugin-msw-sample.js +45 -0
- package/dist/plugin-msw-synth.js +116 -0
- package/dist/plugin-msw.js +30 -0
- package/dist/plugin-nest-code.js +68 -0
- package/dist/plugin-nest-contract.js +23 -0
- package/dist/plugin-nest.js +44 -0
- package/dist/plugin-server-code.js +61 -0
- package/dist/plugin-server-contract.js +48 -0
- package/dist/plugin-server-example.js +62 -0
- package/dist/plugin-server-router.js +77 -0
- package/dist/plugin-server-routes.js +155 -0
- package/dist/plugin-server-runtime.js +3 -0
- package/dist/plugin-server-sample.js +40 -0
- package/dist/plugin-swr-sample.js +21 -0
- package/dist/plugin-swr.js +40 -0
- package/dist/plugin-tanstack-query-sample.js +21 -0
- package/dist/plugin-tanstack-query.js +59 -0
- package/dist/plugin-types.js +80 -0
- package/dist/plugin-validator-code.js +41 -0
- package/dist/plugin-validator-names.js +27 -0
- package/dist/plugin-validator.js +103 -0
- package/dist/plugins.js +21 -0
- package/dist/props-emit.js +194 -0
- package/dist/props-generate.js +409 -0
- package/dist/props-judge.js +61 -0
- package/dist/props-mutate.js +144 -0
- package/dist/props-random.js +25 -0
- package/dist/props-run.js +176 -0
- package/dist/props-shrink.js +75 -0
- package/dist/run-apply.js +25 -0
- package/dist/run-command.js +31 -0
- package/dist/run-commit.d.ts +51 -0
- package/dist/run-commit.js +48 -0
- package/dist/run-config.d.ts +193 -0
- package/dist/run-config.js +256 -0
- package/dist/run-diff.js +24 -0
- package/dist/run-extract.d.ts +13 -0
- package/dist/run-extract.js +21 -0
- package/dist/run-gen.d.ts +15 -0
- package/dist/run-gen.js +43 -0
- package/dist/run-header.js +37 -0
- package/dist/run-input.js +31 -0
- package/dist/run-load.js +32 -0
- package/dist/run-map.d.ts +41 -0
- package/dist/run-map.js +52 -0
- package/dist/run-plan.d.ts +31 -0
- package/dist/run-plan.js +35 -0
- package/dist/scaffold-seed.js +43 -0
- package/dist/scaffold-write.js +17 -0
- package/dist/scaffold.js +196 -0
- package/dist/testing-lint.js +43 -0
- package/dist/testing-owner.js +17 -0
- package/dist/testing-probe.js +25 -0
- package/dist/testing-rules.d.ts +65 -0
- package/dist/testing-rules.js +115 -0
- package/dist/testing.d.ts +32 -0
- package/dist/testing.js +79 -0
- package/package.json +108 -4
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { generate } from './gen-ts-index.js';
|
|
2
|
+
export const TYPES_FILE = 'types.ts';
|
|
3
|
+
const document = {
|
|
4
|
+
openapi: '3.1.0',
|
|
5
|
+
paths: {
|
|
6
|
+
'/pets': {
|
|
7
|
+
get: {
|
|
8
|
+
operationId: 'listPets',
|
|
9
|
+
parameters: [{ name: 'limit', in: 'query', required: true, schema: { type: 'integer' } }],
|
|
10
|
+
responses: { '200': { description: 'Pets', content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/Pet' } } } } } },
|
|
11
|
+
},
|
|
12
|
+
},
|
|
13
|
+
},
|
|
14
|
+
components: { schemas: { Pet: { required: ['id'], properties: { id: { type: 'string' }, name: { type: 'string' } } } } },
|
|
15
|
+
};
|
|
16
|
+
const SAMPLE_TYPES = `export interface paths {
|
|
17
|
+
"/pets": {
|
|
18
|
+
parameters: {
|
|
19
|
+
query?: never;
|
|
20
|
+
header?: never;
|
|
21
|
+
path?: never;
|
|
22
|
+
cookie?: never;
|
|
23
|
+
};
|
|
24
|
+
get: operations["listPets"];
|
|
25
|
+
put?: never;
|
|
26
|
+
post?: never;
|
|
27
|
+
delete?: never;
|
|
28
|
+
options?: never;
|
|
29
|
+
head?: never;
|
|
30
|
+
patch?: never;
|
|
31
|
+
trace?: never;
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
export type webhooks = Record<string, never>;
|
|
35
|
+
export interface components {
|
|
36
|
+
schemas: {
|
|
37
|
+
Pet: {
|
|
38
|
+
id: string;
|
|
39
|
+
name?: string;
|
|
40
|
+
};
|
|
41
|
+
};
|
|
42
|
+
responses: never;
|
|
43
|
+
parameters: never;
|
|
44
|
+
requestBodies: never;
|
|
45
|
+
headers: never;
|
|
46
|
+
pathItems: never;
|
|
47
|
+
}
|
|
48
|
+
export type $defs = Record<string, never>;
|
|
49
|
+
export interface operations {
|
|
50
|
+
listPets: {
|
|
51
|
+
parameters: {
|
|
52
|
+
query: {
|
|
53
|
+
limit: number;
|
|
54
|
+
};
|
|
55
|
+
header?: never;
|
|
56
|
+
path?: never;
|
|
57
|
+
cookie?: never;
|
|
58
|
+
};
|
|
59
|
+
requestBody?: never;
|
|
60
|
+
responses: {
|
|
61
|
+
/** @description Pets */
|
|
62
|
+
200: {
|
|
63
|
+
headers: {
|
|
64
|
+
[name: string]: unknown;
|
|
65
|
+
};
|
|
66
|
+
content: {
|
|
67
|
+
"application/json": components["schemas"]["Pet"][];
|
|
68
|
+
};
|
|
69
|
+
};
|
|
70
|
+
};
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
`;
|
|
74
|
+
const types = {
|
|
75
|
+
description: 'TypeScript types for every path, operation and schema, as openapi-typescript 7.13.0 writes them',
|
|
76
|
+
inputs: ['openapi', 'swagger2'],
|
|
77
|
+
sample: { document, files: [{ path: TYPES_FILE, owner: 'generated', content: SAMPLE_TYPES }] },
|
|
78
|
+
run: (contract, options) => [{ path: TYPES_FILE, owner: 'generated', content: generate(contract.document, options) }],
|
|
79
|
+
};
|
|
80
|
+
export const plugin = { name: 'types', generators: { types } };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { emit, emitWith, typeOf } from 'truefit/emit';
|
|
2
|
+
import { fromJsonSchema } from 'truefit/json-schema';
|
|
3
|
+
export const DOOR_IMPORTS = "import { check } from 'truefit';\nimport { fromJsonSchema } from 'truefit/json-schema';";
|
|
4
|
+
const guard = (name) => `(value: unknown) => value is ${name}`;
|
|
5
|
+
const declared = (name, schema) => {
|
|
6
|
+
const { text, aliases } = typeOf(schema, name);
|
|
7
|
+
return [`export type ${name} = ${text};`, ...[...aliases].map(([alias, type]) => `export type ${alias} = ${type};`)].join('\n');
|
|
8
|
+
};
|
|
9
|
+
export const UNTYPED = "// @ts-nocheck -- at least one validator below was emitted untyped (typed: false), so its parameters carry no types";
|
|
10
|
+
export const comment = (lines) => `/**\n${lines.map((line) => ` * ${line.replaceAll('*/', '*\\/')}`.trimEnd()).join('\n')}\n */`;
|
|
11
|
+
export const validatorCode = (name, document, where) => {
|
|
12
|
+
const { schema, findings: read } = fromJsonSchema(document);
|
|
13
|
+
const findings = read.map((finding) => ({
|
|
14
|
+
code: 'validator-not-read',
|
|
15
|
+
pointer: where.at,
|
|
16
|
+
message: `${where.label}: at "${finding.path}" in the document, \`${finding.keyword}\`: ${finding.message}`,
|
|
17
|
+
fix: 'the validator accepts more than the document there: check it in code, or rewrite the schema with keywords the validator reads',
|
|
18
|
+
}));
|
|
19
|
+
const typed = where.typed === true;
|
|
20
|
+
const [type, declaration] = typed ? [`${declared(name, schema)}\n`, guard(name)] : ['', '(value: unknown) => boolean'];
|
|
21
|
+
if (emitWith(schema).hooks.length === 0) {
|
|
22
|
+
return { text: `${type}${comment(where.doc)}\nexport const ${name}: ${declaration} = ${emit(schema, { typescript: typed, ...(typed && { type: name }) })};`, findings, door: false, typed };
|
|
23
|
+
}
|
|
24
|
+
findings.push({
|
|
25
|
+
code: 'validator-runtime-door',
|
|
26
|
+
pointer: where.at,
|
|
27
|
+
message: `${where.label}: the schema names a format that is a function, not a pattern, which code cannot carry: the validator checks the document at run time`,
|
|
28
|
+
fix: 'nothing to do; or use a format with a pattern, to have it compiled ahead of time',
|
|
29
|
+
});
|
|
30
|
+
const held = `${name}Schema`;
|
|
31
|
+
const text = [
|
|
32
|
+
`const ${held} = fromJsonSchema(${JSON.stringify(document)}).schema;`,
|
|
33
|
+
`${type}${comment([...where.doc, '', 'Checked at run time: the schema names a format that is a function.'])}`,
|
|
34
|
+
`export const ${name}: ${declaration} = (value)${typed ? `: value is ${name}` : ''} => check(${held}, value);`,
|
|
35
|
+
].join('\n');
|
|
36
|
+
return { text, findings, door: true, typed };
|
|
37
|
+
};
|
|
38
|
+
export const moduleOf = (codes, after = []) => {
|
|
39
|
+
const head = [...(codes.some((code) => !code.typed) ? [UNTYPED] : []), ...(codes.some((code) => code.door) ? [DOOR_IMPORTS] : [])];
|
|
40
|
+
return `${[...(head.length > 0 ? [head.join('\n')] : []), ...codes.map((code) => code.text), ...after].join('\n\n')}\n`;
|
|
41
|
+
};
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
const JSON_MEDIA = ':application/json';
|
|
2
|
+
const pascal = (text) => text
|
|
3
|
+
.split(/[^A-Za-z0-9]+/u)
|
|
4
|
+
.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`)
|
|
5
|
+
.join('');
|
|
6
|
+
export const baseName = (operation, payload) => {
|
|
7
|
+
const media = payload.endsWith(JSON_MEDIA) ? payload.slice(0, -JSON_MEDIA.length) : payload;
|
|
8
|
+
const name = `${pascal(operation)}${pascal(media)}`;
|
|
9
|
+
if (name === '')
|
|
10
|
+
return 'Payload';
|
|
11
|
+
return /^\d/u.test(name) ? `_${name}` : name;
|
|
12
|
+
};
|
|
13
|
+
export const unique = (base, taken) => {
|
|
14
|
+
let name = base;
|
|
15
|
+
for (let suffix = 2; taken.has(name); suffix += 1)
|
|
16
|
+
name = `${base}${String(suffix)}`;
|
|
17
|
+
taken.add(name);
|
|
18
|
+
return name;
|
|
19
|
+
};
|
|
20
|
+
export const namedPayloads = (contract) => {
|
|
21
|
+
const taken = new Set();
|
|
22
|
+
const ids = [...new Set(contract.operations.map((operation) => operation.id))].toSorted();
|
|
23
|
+
const operations = ids.flatMap((id) => contract.operations.filter((operation) => operation.id === id));
|
|
24
|
+
return operations.flatMap((operation) => operation.payloads.map((payload) => {
|
|
25
|
+
return { name: unique(baseName(operation.id, payload.name), taken), operation, payload };
|
|
26
|
+
}));
|
|
27
|
+
};
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import { build, sourceOf } from './plugin-json-schema-build.js';
|
|
2
|
+
import { comment, moduleOf, validatorCode } from './plugin-validator-code.js';
|
|
3
|
+
import { namedPayloads } from './plugin-validator-names.js';
|
|
4
|
+
export const VALIDATORS_FILE = 'validators.ts';
|
|
5
|
+
export const INPUTS = ['openapi', 'swagger2', 'asyncapi', 'mcp', 'protobuf', 'jsonschema'];
|
|
6
|
+
export const generateValidators = (contract) => {
|
|
7
|
+
const source = sourceOf(contract);
|
|
8
|
+
const findings = [];
|
|
9
|
+
const codes = [];
|
|
10
|
+
const named = namedPayloads(contract);
|
|
11
|
+
for (const { name, operation, payload } of named) {
|
|
12
|
+
const where = { label: name, at: operation.source };
|
|
13
|
+
const built = build(contract.document, payload.schema, { draft: '2020-12', refs: 'keep', source, ...where });
|
|
14
|
+
const code = validatorCode(name, built.schema, { ...where, typed: true, doc: [`\`${operation.id}\` ${payload.name} (${payload.direction}${payload.required ? '' : ', optional'}).`] });
|
|
15
|
+
findings.push(...built.findings, ...code.findings);
|
|
16
|
+
codes.push(code);
|
|
17
|
+
}
|
|
18
|
+
const byOperation = new Map();
|
|
19
|
+
for (const { name, operation, payload } of named) {
|
|
20
|
+
byOperation.set(operation.id, [...(byOperation.get(operation.id) ?? []), ` ${JSON.stringify(payload.name)}: ${name},`]);
|
|
21
|
+
}
|
|
22
|
+
const map = [
|
|
23
|
+
comment(['Every validator, by operation id and payload name.']),
|
|
24
|
+
'export const operations = {',
|
|
25
|
+
...[...byOperation].map(([id, lines]) => ` ${JSON.stringify(id)}: {\n${lines.join('\n')}\n },`),
|
|
26
|
+
'} as const;',
|
|
27
|
+
].join('\n');
|
|
28
|
+
const file = {
|
|
29
|
+
path: VALIDATORS_FILE,
|
|
30
|
+
owner: 'generated',
|
|
31
|
+
content: moduleOf(codes, [map]),
|
|
32
|
+
symbols: named.map(({ name, operation }) => ({ operation: operation.id, symbol: name })),
|
|
33
|
+
};
|
|
34
|
+
return { files: [file], findings };
|
|
35
|
+
};
|
|
36
|
+
const document = {
|
|
37
|
+
openapi: '3.1.0',
|
|
38
|
+
paths: {
|
|
39
|
+
'/pets': {
|
|
40
|
+
get: {
|
|
41
|
+
operationId: 'listPets',
|
|
42
|
+
parameters: [{ name: 'limit', in: 'query', schema: { type: 'integer', minimum: 1 } }],
|
|
43
|
+
responses: { '200': { content: { 'application/json': { schema: { type: 'array', items: { $ref: '#/components/schemas/Pet' } } } } } },
|
|
44
|
+
},
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
components: { schemas: { Pet: { type: 'object', required: ['id'], properties: { id: { type: 'string' } } } } },
|
|
48
|
+
};
|
|
49
|
+
const SAMPLE = `export type ListPetsParamQueryLimit = number;
|
|
50
|
+
/**
|
|
51
|
+
* \`listPets\` param:query:limit (request, optional).
|
|
52
|
+
*/
|
|
53
|
+
export const ListPetsParamQueryLimit: (value: unknown) => value is ListPetsParamQueryLimit = (() => {
|
|
54
|
+
|
|
55
|
+
return (v: any): v is ListPetsParamQueryLimit => typeof v === "number" && v >= 1 && v <= 1.7976931348623157e+308 && Number.isInteger(v);
|
|
56
|
+
})();
|
|
57
|
+
|
|
58
|
+
export type ListPetsResponse200 = { "id": string }[];
|
|
59
|
+
/**
|
|
60
|
+
* \`listPets\` response:200:application/json (response).
|
|
61
|
+
*/
|
|
62
|
+
export const ListPetsResponse200: (value: unknown) => value is ListPetsResponse200 = (() => {
|
|
63
|
+
const f0 = (v: any): boolean => typeof v === "object" && v !== null && !Array.isArray(v)
|
|
64
|
+
&& (typeof v["id"] === "string");
|
|
65
|
+
const g0 = (v: any): boolean => f0(v);
|
|
66
|
+
const f2 = (v: any): boolean => {
|
|
67
|
+
if (!Array.isArray(v)) return false;
|
|
68
|
+
for (let i = 0; i < v.length; i++) if (!(g0(v[i]))) return false;
|
|
69
|
+
return true;
|
|
70
|
+
};
|
|
71
|
+
return (v: any): v is ListPetsResponse200 => f2(v);
|
|
72
|
+
})();
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Every validator, by operation id and payload name.
|
|
76
|
+
*/
|
|
77
|
+
export const operations = {
|
|
78
|
+
"listPets": {
|
|
79
|
+
"param:query:limit": ListPetsParamQueryLimit,
|
|
80
|
+
"response:200:application/json": ListPetsResponse200,
|
|
81
|
+
},
|
|
82
|
+
} as const;
|
|
83
|
+
`;
|
|
84
|
+
const validator = {
|
|
85
|
+
description: 'A validator for every payload, compiled ahead of time to straight-line code, and an `operations` map to look one up',
|
|
86
|
+
inputs: INPUTS,
|
|
87
|
+
sample: {
|
|
88
|
+
document,
|
|
89
|
+
files: [
|
|
90
|
+
{
|
|
91
|
+
path: VALIDATORS_FILE,
|
|
92
|
+
owner: 'generated',
|
|
93
|
+
symbols: [
|
|
94
|
+
{ operation: 'listPets', symbol: 'ListPetsParamQueryLimit' },
|
|
95
|
+
{ operation: 'listPets', symbol: 'ListPetsResponse200' },
|
|
96
|
+
],
|
|
97
|
+
content: SAMPLE,
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
},
|
|
101
|
+
run: (contract) => generateValidators(contract),
|
|
102
|
+
};
|
|
103
|
+
export const plugin = { name: 'validator', generators: { validator } };
|
package/dist/plugins.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { plugin as express } from './plugin-express.js';
|
|
2
|
+
import { plugin as extractHono } from './plugin-extract-hono.js';
|
|
3
|
+
import { plugin as extractNest } from './plugin-extract-nest.js';
|
|
4
|
+
import { plugin as extractOpenapi } from './plugin-extract-openapi.js';
|
|
5
|
+
import { plugin as extractStandardSchema } from './plugin-extract-standard-schema.js';
|
|
6
|
+
import { plugin as extractTrpc } from './plugin-extract-trpc.js';
|
|
7
|
+
import { plugin as extractTsRest } from './plugin-extract-ts-rest.js';
|
|
8
|
+
import { plugin as fastify } from './plugin-fastify.js';
|
|
9
|
+
import { plugin as fetch } from './plugin-fetch.js';
|
|
10
|
+
import { plugin as hono } from './plugin-hono.js';
|
|
11
|
+
import { plugin as jsonSchema } from './plugin-json-schema.js';
|
|
12
|
+
import { plugin as markdown } from './plugin-markdown.js';
|
|
13
|
+
import { plugin as mcp } from './plugin-mcp.js';
|
|
14
|
+
import { plugin as msw } from './plugin-msw.js';
|
|
15
|
+
import { plugin as nest } from './plugin-nest.js';
|
|
16
|
+
import { plugin as swr } from './plugin-swr.js';
|
|
17
|
+
import { plugin as tanstackQuery } from './plugin-tanstack-query.js';
|
|
18
|
+
import { plugin as types } from './plugin-types.js';
|
|
19
|
+
import { plugin as validator } from './plugin-validator.js';
|
|
20
|
+
const planned = [types, validator, jsonSchema, nest, hono, fastify, express, fetch, tanstackQuery, msw, swr, mcp, markdown, extractStandardSchema, extractOpenapi, extractNest, extractHono, extractTrpc, extractTsRest];
|
|
21
|
+
export const builtins = planned.filter((p) => p !== undefined);
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
import { has, isDict } from './diff-normalise.js';
|
|
3
|
+
import { isFormat, itemsOf, rangeOf, typesOf, wholeIn } from './props-generate.js';
|
|
4
|
+
import { draftOf } from './props-judge.js';
|
|
5
|
+
const json = (value) => JSON.stringify(value);
|
|
6
|
+
const FORMAT_ARBITRARY = {
|
|
7
|
+
date: "fc.date({ min: new Date('1970-01-01T00:00:00Z'), max: new Date('2099-12-31T00:00:00Z'), noInvalidDate: true }).map((d) => d.toISOString().slice(0, 10))",
|
|
8
|
+
'date-time': "fc.date({ min: new Date('1970-01-01T00:00:00Z'), max: new Date('2099-12-31T00:00:00Z'), noInvalidDate: true }).map((d) => d.toISOString())",
|
|
9
|
+
time: "fc.date({ min: new Date('1970-01-01T00:00:00Z'), max: new Date('2099-12-31T00:00:00Z'), noInvalidDate: true }).map((d) => d.toISOString().slice(11))",
|
|
10
|
+
duration: "fc.integer({ min: 1, max: 99 }).map((n) => `P${n}D`)",
|
|
11
|
+
email: 'fc.emailAddress()',
|
|
12
|
+
hostname: 'fc.domain()',
|
|
13
|
+
ipv4: 'fc.ipV4()',
|
|
14
|
+
ipv6: 'fc.ipV6()',
|
|
15
|
+
uuid: 'fc.uuid({ version: 4 })',
|
|
16
|
+
regex: "fc.constantFrom('^a$', '[0-9]+', 'x|y')",
|
|
17
|
+
byte: 'fc.uint8Array({ maxLength: 16 }).map((bytes) => btoa(String.fromCodePoint(...bytes)))',
|
|
18
|
+
};
|
|
19
|
+
const note = (map, key, value) => {
|
|
20
|
+
map.set(key, new Set([...(map.get(key) ?? []), value]));
|
|
21
|
+
};
|
|
22
|
+
const loose = (emit, keyword) => {
|
|
23
|
+
note(emit.loose, emit.key, keyword);
|
|
24
|
+
};
|
|
25
|
+
const looseness = (emit, keys) => keys.flatMap((key) => {
|
|
26
|
+
const reached = new Set();
|
|
27
|
+
for (let queue = [...(emit.uses.get(key) ?? [])]; queue.length > 0;) {
|
|
28
|
+
const ref = queue.shift();
|
|
29
|
+
if (reached.has(ref))
|
|
30
|
+
continue;
|
|
31
|
+
reached.add(ref);
|
|
32
|
+
queue = [...queue, ...(emit.uses.get(ref) ?? [])];
|
|
33
|
+
}
|
|
34
|
+
const own = [...(emit.loose.get(key) ?? [])];
|
|
35
|
+
const via = [...reached].filter((ref) => ref !== key && emit.loose.has(ref)).map((ref) => `via ${ref}`);
|
|
36
|
+
return [...own, ...via].sort().map((keyword) => ({ key, keyword }));
|
|
37
|
+
});
|
|
38
|
+
const options = (entries) => {
|
|
39
|
+
const set = Object.entries(entries).filter(([, value]) => value !== undefined);
|
|
40
|
+
return set.length === 0 ? '' : `{ ${set.map(([key, value]) => `${key}: ${String(value)}`).join(', ')} }`;
|
|
41
|
+
};
|
|
42
|
+
const integerArbitrary = (emit, schema) => {
|
|
43
|
+
const range = rangeOf(schema, emit.draft);
|
|
44
|
+
const [low, high] = wholeIn(range);
|
|
45
|
+
const whole = Number.isInteger(schema.multipleOf);
|
|
46
|
+
const step = whole ? schema.multipleOf : 1;
|
|
47
|
+
if (has(schema, 'multipleOf') && !whole)
|
|
48
|
+
loose(emit, 'multipleOf');
|
|
49
|
+
const min = boundOf(schema, 'Minimum') ? Math.ceil(low / step) : undefined;
|
|
50
|
+
const max = boundOf(schema, 'Maximum') ? Math.floor(high / step) : undefined;
|
|
51
|
+
const base = `fc.integer(${options({ min, max })})`;
|
|
52
|
+
return step === 1 ? base : `${base}.map((n) => n * ${String(step)})`;
|
|
53
|
+
};
|
|
54
|
+
const boundOf = (schema, side) => typeof schema[side === 'Minimum' ? 'minimum' : 'maximum'] === 'number' || typeof schema[`exclusive${side}`] === 'number';
|
|
55
|
+
const excluded = (out, bound) => (out && bound !== undefined ? true : undefined);
|
|
56
|
+
const unknownType = (type) => (emit) => {
|
|
57
|
+
loose(emit, `type:${type}`);
|
|
58
|
+
return 'fc.jsonValue()';
|
|
59
|
+
};
|
|
60
|
+
const doubleArbitrary = (emit, schema) => {
|
|
61
|
+
if (has(schema, 'multipleOf'))
|
|
62
|
+
loose(emit, 'multipleOf');
|
|
63
|
+
const range = rangeOf(schema, emit.draft);
|
|
64
|
+
const min = boundOf(schema, 'Minimum') ? range.low : undefined;
|
|
65
|
+
const max = boundOf(schema, 'Maximum') ? range.high : undefined;
|
|
66
|
+
return `fc.double(${options({ min, max, minExcluded: excluded(range.lowOut, min), maxExcluded: excluded(range.highOut, max), noNaN: true, noDefaultInfinity: true })}).map((n) => n + 0)`;
|
|
67
|
+
};
|
|
68
|
+
const string = (emit, schema) => {
|
|
69
|
+
if (has(schema, 'pattern'))
|
|
70
|
+
loose(emit, 'pattern');
|
|
71
|
+
const format = schema.format;
|
|
72
|
+
if (isFormat(format))
|
|
73
|
+
return new Map(Object.entries(FORMAT_ARBITRARY)).get(format);
|
|
74
|
+
if (format !== undefined)
|
|
75
|
+
loose(emit, `format:${String(format)}`);
|
|
76
|
+
return `fc.string(${options({ minLength: schema.minLength, maxLength: schema.maxLength })})`;
|
|
77
|
+
};
|
|
78
|
+
const length = (low, high) => options({ minLength: low > 0 ? low : undefined, maxLength: high }) || '{}';
|
|
79
|
+
const array = (emit, schema) => {
|
|
80
|
+
for (const keyword of ['uniqueItems', 'contains'])
|
|
81
|
+
if (has(schema, keyword))
|
|
82
|
+
loose(emit, keyword);
|
|
83
|
+
const { tuple, rest } = itemsOf(schema);
|
|
84
|
+
const minItems = typeof schema.minItems === 'number' ? schema.minItems : 0;
|
|
85
|
+
const maxItems = typeof schema.maxItems === 'number' ? schema.maxItems : undefined;
|
|
86
|
+
if (tuple.length === 0)
|
|
87
|
+
return `fc.array(${arbitrary(emit, rest)}, ${length(minItems, maxItems)})`;
|
|
88
|
+
const restMax = maxItems === undefined ? undefined : Math.max(0, maxItems - tuple.length);
|
|
89
|
+
const restArbitrary = rest === false || restMax === 0 ? 'fc.constant([])' : `fc.array(${arbitrary(emit, rest)}, ${length(minItems - tuple.length, restMax)})`;
|
|
90
|
+
const longest = Math.min(tuple.length, maxItems ?? tuple.length);
|
|
91
|
+
const cut = `fc.integer({ min: ${String(Math.min(minItems, longest))}, max: ${String(longest)} })`;
|
|
92
|
+
return `fc.tuple(fc.tuple(${tuple.map((item) => arbitrary(emit, item)).join(', ')}), ${restArbitrary}, ${cut}).map(([head, tail, cut]) => (cut < head.length ? head.slice(0, cut) : [...head, ...tail]))`;
|
|
93
|
+
};
|
|
94
|
+
const object = (emit, schema) => {
|
|
95
|
+
for (const keyword of ['propertyNames', 'patternProperties', 'dependentRequired', 'dependentSchemas', 'dependencies', 'minProperties', 'maxProperties'])
|
|
96
|
+
if (has(schema, keyword))
|
|
97
|
+
loose(emit, keyword);
|
|
98
|
+
const properties = isDict(schema.properties) ? schema.properties : {};
|
|
99
|
+
const required = Array.isArray(schema.required) ? schema.required.map(String) : [];
|
|
100
|
+
const extra = schema.additionalProperties ?? true;
|
|
101
|
+
const entries = [...Object.keys(properties).map((name) => [name, arbitrary(emit, properties[name])]), ...required.filter((name) => !has(properties, name)).map((name) => [name, arbitrary(emit, extra)])];
|
|
102
|
+
return `fc.record({ ${entries.map(([name, value]) => `${json(name)}: ${String(value)}`).join(', ')} }, { requiredKeys: ${json(required)} })`;
|
|
103
|
+
};
|
|
104
|
+
const TYPED = {
|
|
105
|
+
null: () => 'fc.constant(null)',
|
|
106
|
+
boolean: () => 'fc.boolean()',
|
|
107
|
+
integer: integerArbitrary,
|
|
108
|
+
number: doubleArbitrary,
|
|
109
|
+
string,
|
|
110
|
+
array,
|
|
111
|
+
object,
|
|
112
|
+
};
|
|
113
|
+
const reference = (emit, schema) => {
|
|
114
|
+
const ref = String(schema.$ref);
|
|
115
|
+
try {
|
|
116
|
+
pointerGet(emit.root, ref);
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
loose(emit, '$ref');
|
|
120
|
+
return 'fc.jsonValue()';
|
|
121
|
+
}
|
|
122
|
+
if (!emit.refs.includes(ref))
|
|
123
|
+
emit.refs.push(ref);
|
|
124
|
+
note(emit.uses, emit.key, ref);
|
|
125
|
+
if (emit.draft === '2020-12' && Object.keys(schema).length > 1)
|
|
126
|
+
loose(emit, '$ref-siblings');
|
|
127
|
+
return `tie(${json(ref)})`;
|
|
128
|
+
};
|
|
129
|
+
const union = (emit, schema) => {
|
|
130
|
+
const keyword = ['anyOf', 'oneOf'].find((key) => Array.isArray(schema[key]) && schema[key].length > 0);
|
|
131
|
+
if (keyword === undefined)
|
|
132
|
+
return undefined;
|
|
133
|
+
if (Object.keys(schema).length > 1)
|
|
134
|
+
loose(emit, `${keyword}-siblings`);
|
|
135
|
+
return `fc.oneof(${schema[keyword].map((branch) => arbitrary(emit, branch)).join(', ')})`;
|
|
136
|
+
};
|
|
137
|
+
function arbitrary(emit, schema) {
|
|
138
|
+
if (schema === true)
|
|
139
|
+
return 'fc.jsonValue()';
|
|
140
|
+
if (!isDict(schema)) {
|
|
141
|
+
loose(emit, 'false');
|
|
142
|
+
return 'fc.constant(undefined)';
|
|
143
|
+
}
|
|
144
|
+
for (const keyword of ['not', 'if', 'oneOf', 'unevaluatedProperties', 'unevaluatedItems'])
|
|
145
|
+
if (has(schema, keyword))
|
|
146
|
+
loose(emit, keyword);
|
|
147
|
+
if (typeof schema.$ref === 'string')
|
|
148
|
+
return reference(emit, schema);
|
|
149
|
+
if (Array.isArray(schema.allOf)) {
|
|
150
|
+
loose(emit, 'allOf');
|
|
151
|
+
return arbitrary(emit, schema.allOf[0] ?? true);
|
|
152
|
+
}
|
|
153
|
+
const branches = union(emit, schema);
|
|
154
|
+
if (branches !== undefined)
|
|
155
|
+
return branches;
|
|
156
|
+
if (has(schema, 'const'))
|
|
157
|
+
return `fc.constant(${json(schema.const)})`;
|
|
158
|
+
if (Array.isArray(schema.enum))
|
|
159
|
+
return `fc.constantFrom(${schema.enum.map((value) => json(value)).join(', ')})`;
|
|
160
|
+
const kinds = typesOf(schema, emit.draft).map((type) => (new Map(Object.entries(TYPED)).get(type) ?? unknownType(type))(emit, schema));
|
|
161
|
+
return kinds.length === 1 ? kinds[0] : `fc.oneof(${kinds.join(', ')})`;
|
|
162
|
+
}
|
|
163
|
+
export const emitArbitraries = (contract, label) => {
|
|
164
|
+
const emit = { root: contract.document, draft: draftOf(contract), refs: [], loose: new Map(), uses: new Map(), key: '' };
|
|
165
|
+
const entries = [];
|
|
166
|
+
for (const operation of contract.operations) {
|
|
167
|
+
for (const payload of operation.payloads) {
|
|
168
|
+
if (payload.schema === false)
|
|
169
|
+
continue;
|
|
170
|
+
emit.key = `${operation.id} ${payload.name}`;
|
|
171
|
+
entries.push([emit.key, arbitrary(emit, payload.schema)]);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
for (let index = 0; index < emit.refs.length; index += 1) {
|
|
175
|
+
const ref = emit.refs[index];
|
|
176
|
+
emit.key = ref;
|
|
177
|
+
entries.push([ref, arbitrary(emit, pointerGet(emit.root, ref))]);
|
|
178
|
+
}
|
|
179
|
+
const notGenerated = looseness(emit, entries.map(([key]) => key));
|
|
180
|
+
const text = [
|
|
181
|
+
`// Generated by \`contractdiff props --emit\` from ${label}. Do not edit: run it again.`,
|
|
182
|
+
'// One fast-check arbitrary per payload (`<operation> <payload>`) and per referenced schema.',
|
|
183
|
+
"import fc from 'fast-check';",
|
|
184
|
+
'',
|
|
185
|
+
'export const arbitraries = fc.letrec((tie) => ({',
|
|
186
|
+
...entries.map(([key, value]) => ` ${json(key)}: ${value},`),
|
|
187
|
+
'}));',
|
|
188
|
+
'',
|
|
189
|
+
'/** Keywords an arbitrary above does not hold to: filter its values with your validator. */',
|
|
190
|
+
`export const notGenerated = ${json(notGenerated)};`,
|
|
191
|
+
'',
|
|
192
|
+
].join('\n');
|
|
193
|
+
return { text, count: entries.length };
|
|
194
|
+
};
|