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,116 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, resolve } from 'node:path';
|
|
3
|
+
import { defineCommand, ExitCode } from 'burgee';
|
|
4
|
+
import { noGit, readContract, uriOf } from './command-diff.js';
|
|
5
|
+
import { MODES, SIDES } from './diff-classify.js';
|
|
6
|
+
import { bufIn, builtImages } from './input-buf.js';
|
|
7
|
+
import { emitArbitraries } from './props-emit.js';
|
|
8
|
+
import { PROPERTIES, runProps } from './props-run.js';
|
|
9
|
+
const TEXT = Symbol.for('burgee.text');
|
|
10
|
+
export const DEFAULT_RUNS = 1000;
|
|
11
|
+
const SHOWN = 300;
|
|
12
|
+
const NAMED = 3;
|
|
13
|
+
const COLUMN = 'round-trip'.length;
|
|
14
|
+
const cut = (value) => {
|
|
15
|
+
const text = JSON.stringify(value) ?? String(value);
|
|
16
|
+
return text.length > SHOWN ? `${text.slice(0, SHOWN)}…` : text;
|
|
17
|
+
};
|
|
18
|
+
const line = (found) => [` ${found.property} ${found.operation} ${found.payload}: ${found.detail}`, ` value: ${cut(found.value)}`];
|
|
19
|
+
export const toText = (report, label, emitted, wrote) => {
|
|
20
|
+
const lines = [`${report.counterexamples.length === 0 ? 'ok' : 'failed'}: ${label}, ${String(report.runs)} run(s) per payload, seed ${String(report.seed)}`];
|
|
21
|
+
for (const property of PROPERTIES) {
|
|
22
|
+
const { checked, discarded, failed } = report.tallies[property];
|
|
23
|
+
lines.push(` ${property.padEnd(COLUMN)} ${String(checked)} checked, ${String(discarded)} discarded, ${String(failed)} failed`);
|
|
24
|
+
}
|
|
25
|
+
if (report.counterexamples.length > 0)
|
|
26
|
+
lines.push('', 'counterexamples (replay with the same --seed):', ...report.counterexamples.flatMap(line));
|
|
27
|
+
if (report.reported.length > 0) {
|
|
28
|
+
lines.push('', 'values made without these keywords, and kept only where the validator accepted them:');
|
|
29
|
+
for (const { keyword, at } of report.reported)
|
|
30
|
+
lines.push(` ${keyword} ${at.slice(0, NAMED).join(', ')}${at.length > NAMED ? ` and ${String(at.length - NAMED)} more` : ''}`);
|
|
31
|
+
}
|
|
32
|
+
if (report.skipped.length > 0)
|
|
33
|
+
lines.push('', 'not checked:', ...report.skipped.map((skipped) => ` ${skipped.operation} ${skipped.payload}: ${skipped.reason}`));
|
|
34
|
+
if (emitted !== undefined)
|
|
35
|
+
lines.push('', wrote ? `arbitraries written to ${emitted}` : `arbitraries in ${emitted} already up to date`);
|
|
36
|
+
return lines.join('\n');
|
|
37
|
+
};
|
|
38
|
+
export const toSarif = (report, file) => ({
|
|
39
|
+
version: '2.1.0',
|
|
40
|
+
$schema: 'https://json.schemastore.org/sarif-2.1.0.json',
|
|
41
|
+
runs: [
|
|
42
|
+
{
|
|
43
|
+
tool: { driver: { name: 'contractdiff props', rules: PROPERTIES.map((property) => ({ id: `props/${property}` })) } },
|
|
44
|
+
results: report.counterexamples.map((found) => ({
|
|
45
|
+
ruleId: `props/${found.property}`,
|
|
46
|
+
level: 'error',
|
|
47
|
+
message: { text: `${found.property}: ${found.operation} ${found.payload}: ${found.detail}. value: ${cut(found.value)}. fix: replay with --seed ${String(report.seed)}` },
|
|
48
|
+
locations: [{ physicalLocation: { artifactLocation: { uri: uriOf(file) } }, logicalLocations: [{ fullyQualifiedName: `${found.operation} ${found.payload}` }] }],
|
|
49
|
+
})),
|
|
50
|
+
},
|
|
51
|
+
],
|
|
52
|
+
});
|
|
53
|
+
export const props = (options) => {
|
|
54
|
+
const git = options.git ?? noGit;
|
|
55
|
+
const side = readContract(options.contract, options.cwd, git, options.built);
|
|
56
|
+
const against = options.against === undefined ? undefined : readContract(options.against, options.cwd, git, options.built).contract;
|
|
57
|
+
const report = runProps(side.contract, { runs: options.runs, seed: options.seed, against, mode: options.mode, side: options.side, subject: options.subject });
|
|
58
|
+
let wrote = false;
|
|
59
|
+
if (options.emit !== undefined) {
|
|
60
|
+
const file = resolve(options.cwd, options.emit);
|
|
61
|
+
const text = emitArbitraries(side.contract, side.label).text;
|
|
62
|
+
wrote = !existsSync(file) || readFileSync(file, 'utf8') !== text;
|
|
63
|
+
if (wrote) {
|
|
64
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
65
|
+
writeFileSync(file, text);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const failed = report.counterexamples.length > 0;
|
|
69
|
+
const sarif = options.sarif === true ? toSarif(report, side.file) : undefined;
|
|
70
|
+
const data = {
|
|
71
|
+
...report,
|
|
72
|
+
contract: side.label,
|
|
73
|
+
...(options.against === undefined ? {} : { against: options.against }),
|
|
74
|
+
...(options.emit === undefined ? {} : { emitted: options.emit }),
|
|
75
|
+
changed: wrote,
|
|
76
|
+
...(sarif === undefined ? {} : { sarif }),
|
|
77
|
+
...(failed ? { exitCode: ExitCode.RUNTIME, fix: `each counterexample is a bug in the code its property names: replay it with --seed ${String(report.seed)}` } : {}),
|
|
78
|
+
};
|
|
79
|
+
data[TEXT] = () => (sarif === undefined ? toText(report, side.label, options.emit, wrote) : JSON.stringify(sarif, undefined, 2));
|
|
80
|
+
return data;
|
|
81
|
+
};
|
|
82
|
+
const HERE = '.';
|
|
83
|
+
const freshSeed = () => Date.now() >>> 0;
|
|
84
|
+
export const command = defineCommand({
|
|
85
|
+
name: 'props',
|
|
86
|
+
description: 'Property tests drawn from the contract: validator agreement, round-trip, normalisation and diff soundness, with no server',
|
|
87
|
+
effects: 'idempotent',
|
|
88
|
+
examples: [
|
|
89
|
+
{ command: 'contractdiff props openapi.yaml', description: 'the properties on every payload, 1000 values each' },
|
|
90
|
+
{ command: 'contractdiff props new.yaml --against old.yaml --seed 7', description: 'also check that what diff calls compatible is, replayably' },
|
|
91
|
+
{ command: 'contractdiff props openapi.yaml --emit test/arbitraries.ts --runs 0', description: 'write fast-check arbitraries for your own tests' },
|
|
92
|
+
{ command: 'contractdiff props openapi.yaml --seed 7 --sarif', description: 'counterexamples as SARIF, for code scanning' },
|
|
93
|
+
],
|
|
94
|
+
arguments: [{ name: 'contract', description: 'the contract: a file, or git:<ref>:<path>' }],
|
|
95
|
+
options: {
|
|
96
|
+
against: { type: 'string', description: 'the contract before, to check diff soundness against: a file, or git:<ref>:<path>', placeholder: 'old' },
|
|
97
|
+
runs: { type: 'number', default: DEFAULT_RUNS, description: 'values drawn per payload and property', placeholder: 'n' },
|
|
98
|
+
seed: { type: 'number', description: 'the seed to draw from (default: one from the clock, printed)', placeholder: 'n' },
|
|
99
|
+
mode: { type: 'string', choices: MODES, description: 'the compatibility question soundness checks, as in diff (default backward)' },
|
|
100
|
+
side: { type: 'string', choices: SIDES, description: 'whose code the question is about, as in diff (default caller)' },
|
|
101
|
+
emit: { type: 'string', description: 'write the fast-check arbitraries to this file', placeholder: 'file' },
|
|
102
|
+
sarif: { type: 'boolean', description: 'print SARIF 2.1.0 for code scanning instead of text' },
|
|
103
|
+
},
|
|
104
|
+
run: async ({ args, options }) => props({
|
|
105
|
+
built: await builtImages([args.contract, options.against], HERE, bufIn()),
|
|
106
|
+
cwd: HERE,
|
|
107
|
+
contract: args.contract,
|
|
108
|
+
against: options.against,
|
|
109
|
+
runs: options.runs,
|
|
110
|
+
seed: options.seed ?? freshSeed(),
|
|
111
|
+
mode: options.mode,
|
|
112
|
+
side: options.side,
|
|
113
|
+
emit: options.emit,
|
|
114
|
+
sarif: options.sarif,
|
|
115
|
+
}),
|
|
116
|
+
});
|
package/dist/commands.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { command as diff } from './command-diff.js';
|
|
2
|
+
import { command as explain } from './command-explain.js';
|
|
3
|
+
import { command as lint } from './command-lint.js';
|
|
4
|
+
import { command as migrate } from './command-migrate.js';
|
|
5
|
+
import { command as plugin } from './command-plugin.js';
|
|
6
|
+
import { command as props } from './command-props.js';
|
|
7
|
+
export const commands = [explain, diff, lint, migrate, plugin, props];
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The one model every input format is read into (spec.md R1): a contract is a set of operations,
|
|
3
|
+
* and an operation is a set of payloads, each a JSON Schema travelling in one direction.
|
|
4
|
+
*/
|
|
5
|
+
/** A JSON Schema as it appears in a document: `true`, `false`, or an object of keywords. */
|
|
6
|
+
export type JsonSchema = boolean | {
|
|
7
|
+
readonly [keyword: string]: unknown;
|
|
8
|
+
};
|
|
9
|
+
export declare const DIRECTIONS: readonly ["request", "response", "publish", "subscribe", "tool-call", "tool-result", "argv"];
|
|
10
|
+
/** Who sends a payload. Compatibility is decided per direction (spec.md R3), so it lives here. */
|
|
11
|
+
export type Direction = (typeof DIRECTIONS)[number];
|
|
12
|
+
export interface Payload {
|
|
13
|
+
/** Stable within its operation, e.g. `body:application/json` or `response:200:application/json`. */
|
|
14
|
+
readonly name: string;
|
|
15
|
+
readonly direction: Direction;
|
|
16
|
+
readonly schema: JsonSchema;
|
|
17
|
+
readonly required: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface Operation {
|
|
20
|
+
/** Stable across runs: the spec's own id where it has one. */
|
|
21
|
+
readonly id: string;
|
|
22
|
+
/** JSON Pointer to where the operation is declared in the source document. */
|
|
23
|
+
readonly source: string;
|
|
24
|
+
readonly payloads: readonly Payload[];
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* Something a reader or a generator could not carry over exactly. Never a silent loss: a keyword
|
|
28
|
+
* dropped, a construct translated, a value synthesised (program.md, definition of done 7).
|
|
29
|
+
*/
|
|
30
|
+
export interface ContractFinding {
|
|
31
|
+
/** Stable, kebab-case, e.g. `keyword-dropped`. */
|
|
32
|
+
readonly code: string;
|
|
33
|
+
/** JSON Pointer into the source document. */
|
|
34
|
+
readonly pointer: string;
|
|
35
|
+
readonly message: string;
|
|
36
|
+
readonly fix: string;
|
|
37
|
+
}
|
|
38
|
+
export interface Contract {
|
|
39
|
+
/** The input format's name, e.g. `openapi`. */
|
|
40
|
+
readonly format: string;
|
|
41
|
+
/** The parsed source, untouched: a generator that must reproduce an incumbent's output reads it. */
|
|
42
|
+
readonly document: unknown;
|
|
43
|
+
readonly operations: readonly Operation[];
|
|
44
|
+
/** What the reader had to translate or could not read exactly. */
|
|
45
|
+
readonly findings?: readonly ContractFinding[];
|
|
46
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const DIRECTIONS = ['request', 'response', 'publish', 'subscribe', 'tool-call', 'tool-result', 'argv'];
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `$ref` resolver (spec.md R-Q3, modelled in `.sdlc/intents/contractdiff/adapter.qnt`).
|
|
3
|
+
*/
|
|
4
|
+
/** A reference that cannot be followed. The message ends in a `fix:` line. */
|
|
5
|
+
export declare class RefError extends Error {
|
|
6
|
+
readonly ref: string;
|
|
7
|
+
constructor(ref: string, reason: string, fix: string);
|
|
8
|
+
}
|
|
9
|
+
/** The value a local reference (`#`, `#/a/b`) points at, by RFC 6901. */
|
|
10
|
+
export declare const pointerGet: (document: unknown, ref: string) => unknown;
|
|
11
|
+
export interface Inlined {
|
|
12
|
+
/** A copy of the input with every followed reference replaced by its target. */
|
|
13
|
+
readonly value: unknown;
|
|
14
|
+
/** References kept because their target was already open: the cycles. */
|
|
15
|
+
readonly cycles: readonly string[];
|
|
16
|
+
/** References kept because they point outside the document. */
|
|
17
|
+
readonly external: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Inline every local reference under `node`.
|
|
21
|
+
*/
|
|
22
|
+
export declare const inline: (document: unknown, node: unknown) => Inlined;
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
const isObject = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
2
|
+
const hasOwn = (value, key) => typeof value === 'object' && value !== null && Object.hasOwn(value, key);
|
|
3
|
+
export class RefError extends Error {
|
|
4
|
+
ref;
|
|
5
|
+
constructor(ref, reason, fix) {
|
|
6
|
+
super(`cannot resolve \`${ref}\`: ${reason}. fix: ${fix}`);
|
|
7
|
+
this.name = 'RefError';
|
|
8
|
+
this.ref = ref;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
const decode = (ref) => {
|
|
12
|
+
try {
|
|
13
|
+
return decodeURIComponent(ref.slice(1));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
throw new RefError(ref, 'it is not a valid URI fragment', 'percent-encode the reference correctly');
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
export const pointerGet = (document, ref) => {
|
|
20
|
+
if (!ref.startsWith('#')) {
|
|
21
|
+
throw new RefError(ref, 'it points outside this document', 'bundle the document first, or use a `#/…` reference');
|
|
22
|
+
}
|
|
23
|
+
const fragment = decode(ref);
|
|
24
|
+
if (fragment === '')
|
|
25
|
+
return document;
|
|
26
|
+
if (!fragment.startsWith('/')) {
|
|
27
|
+
throw new RefError(ref, 'a JSON Pointer starts with `/`', `write \`#/${fragment}\``);
|
|
28
|
+
}
|
|
29
|
+
let node = document;
|
|
30
|
+
for (const token of fragment.slice(1).split('/')) {
|
|
31
|
+
const key = token.replaceAll('~1', '/').replaceAll('~0', '~');
|
|
32
|
+
if (!hasOwn(node, key)) {
|
|
33
|
+
throw new RefError(ref, `nothing is at \`${key}\``, 'point it at a value the document defines');
|
|
34
|
+
}
|
|
35
|
+
node = node[key];
|
|
36
|
+
}
|
|
37
|
+
return node;
|
|
38
|
+
};
|
|
39
|
+
export const inline = (document, node) => {
|
|
40
|
+
const cycles = new Set();
|
|
41
|
+
const external = new Set();
|
|
42
|
+
const open = new Set();
|
|
43
|
+
const walk = (value) => {
|
|
44
|
+
if (Array.isArray(value))
|
|
45
|
+
return value.map((item) => walk(item));
|
|
46
|
+
if (!isObject(value))
|
|
47
|
+
return value;
|
|
48
|
+
const walked = (entries) => Object.fromEntries(entries.map(([key, child]) => [key, walk(child)]));
|
|
49
|
+
const ref = value.$ref;
|
|
50
|
+
if (typeof ref !== 'string')
|
|
51
|
+
return walked(Object.entries(value));
|
|
52
|
+
const siblings = walked(Object.entries(value).filter(([key]) => key !== '$ref'));
|
|
53
|
+
if (!ref.startsWith('#')) {
|
|
54
|
+
external.add(ref);
|
|
55
|
+
return { ...siblings, $ref: ref };
|
|
56
|
+
}
|
|
57
|
+
if (open.has(ref)) {
|
|
58
|
+
cycles.add(ref);
|
|
59
|
+
return { ...siblings, $ref: ref };
|
|
60
|
+
}
|
|
61
|
+
open.add(ref);
|
|
62
|
+
const target = walk(pointerGet(document, ref));
|
|
63
|
+
open.delete(ref);
|
|
64
|
+
if (Object.keys(siblings).length === 0)
|
|
65
|
+
return target;
|
|
66
|
+
const rest = Array.isArray(siblings.allOf) ? siblings.allOf : [];
|
|
67
|
+
return { ...siblings, allOf: [target, ...rest] };
|
|
68
|
+
};
|
|
69
|
+
const value = walk(node);
|
|
70
|
+
return { value, cycles: [...cycles], external: [...external] };
|
|
71
|
+
};
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { serverReceives } from './diff-schema.js';
|
|
2
|
+
export const MODES = ['backward', 'forward', 'full'];
|
|
3
|
+
export const SIDES = ['caller', 'server'];
|
|
4
|
+
export const payloadRules = (direction, mode, side) => {
|
|
5
|
+
const questions = mode === 'full' ? ['backward', 'forward'] : [mode];
|
|
6
|
+
return questions.map((question) => {
|
|
7
|
+
const callerIsOld = (question === 'backward') === (side === 'caller');
|
|
8
|
+
const senderIsCaller = serverReceives(direction);
|
|
9
|
+
return senderIsCaller === callerIsOld ? 'backward' : 'forward';
|
|
10
|
+
});
|
|
11
|
+
};
|
|
12
|
+
const keeps = (rule, effect) => (rule === 'backward' ? effect === 'widens' : effect === 'narrows');
|
|
13
|
+
export const classify = (change, direction, mode, side) => {
|
|
14
|
+
const { effect } = change;
|
|
15
|
+
if (effect === 'unknown')
|
|
16
|
+
return 'unknown';
|
|
17
|
+
if (effect === 'neutral')
|
|
18
|
+
return 'non-breaking';
|
|
19
|
+
return payloadRules(direction, mode, side).every((rule) => keeps(rule, effect)) ? 'non-breaking' : 'breaking';
|
|
20
|
+
};
|
|
21
|
+
const DANGEROUS_ANYWHERE = new Set(['default-changed', 'path-parameter-renamed']);
|
|
22
|
+
const DANGEROUS_TO_READERS = new Set(['enum-value-added', 'became-nullable', 'pattern-unset', 'format-unset']);
|
|
23
|
+
export const isDangerous = (rule, direction) => DANGEROUS_ANYWHERE.has(rule) || (DANGEROUS_TO_READERS.has(rule) && !serverReceives(direction));
|
|
24
|
+
export const refine = (change, direction, verdict, dangerousBreaking = false) => {
|
|
25
|
+
if (change.frozen === true)
|
|
26
|
+
return 'breaking';
|
|
27
|
+
if (verdict !== 'non-breaking' || !isDangerous(change.rule, direction))
|
|
28
|
+
return verdict;
|
|
29
|
+
return dangerousBreaking ? 'breaking' : 'dangerous';
|
|
30
|
+
};
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { pointerGet } from './core/resolve.js';
|
|
2
|
+
import { classify, refine } from './diff-classify.js';
|
|
3
|
+
import { ruleId } from './diff-rules.js';
|
|
4
|
+
import { compareSchemas, isFrozen, serverReceives } from './diff-schema.js';
|
|
5
|
+
import { compareSecurity } from './diff-security.js';
|
|
6
|
+
export const SEVERITY = ['breaking', 'unknown', 'dangerous', 'non-breaking'];
|
|
7
|
+
export const routeOf = (source) => {
|
|
8
|
+
const match = /^#?\/paths\/(?<path>[^/]+)\/(?<method>[a-z]+)$/.exec(source);
|
|
9
|
+
if (match === null)
|
|
10
|
+
return undefined;
|
|
11
|
+
const { path, method } = match.groups;
|
|
12
|
+
return `${method} ${path.replaceAll('~1', '/').replaceAll('~0', '~').replaceAll(/\{[^}]*\}/g, '{}')}`;
|
|
13
|
+
};
|
|
14
|
+
export const pair = (a, b) => {
|
|
15
|
+
const rest = [...b];
|
|
16
|
+
const take = (match) => {
|
|
17
|
+
const index = rest.findIndex(match);
|
|
18
|
+
return index === -1 ? undefined : rest.splice(index, 1)[0];
|
|
19
|
+
};
|
|
20
|
+
const pairs = a.map((operation) => [operation, take((other) => other.id === operation.id)]);
|
|
21
|
+
for (const entry of pairs) {
|
|
22
|
+
const route = routeOf(entry[0].source);
|
|
23
|
+
if (entry[1] === undefined && route !== undefined)
|
|
24
|
+
entry[1] = take((other) => routeOf(other.source) === route);
|
|
25
|
+
}
|
|
26
|
+
return [...pairs, ...rest.map((operation) => [undefined, operation])];
|
|
27
|
+
};
|
|
28
|
+
const CALLS = { response: 'request', publish: 'subscribe', 'tool-result': 'tool-call' };
|
|
29
|
+
const callDirection = (operation) => {
|
|
30
|
+
const first = operation.payloads[0]?.direction ?? 'request';
|
|
31
|
+
return CALLS[first] ?? first;
|
|
32
|
+
};
|
|
33
|
+
const kindOf = (name) => {
|
|
34
|
+
if (name.startsWith('param:'))
|
|
35
|
+
return 'parameter';
|
|
36
|
+
if (name.startsWith('body'))
|
|
37
|
+
return 'request-body';
|
|
38
|
+
return name.startsWith('response:') ? 'response' : 'payload';
|
|
39
|
+
};
|
|
40
|
+
const groupOf = (name) => name.split(':').slice(0, kindOf(name) === 'response' ? 2 : 1).join(':');
|
|
41
|
+
const presenceRule = (name, others, change) => {
|
|
42
|
+
const kind = kindOf(name);
|
|
43
|
+
const whole = !others.some((other) => groupOf(other.name) === groupOf(name));
|
|
44
|
+
if (kind === 'response')
|
|
45
|
+
return `response-${whole ? 'status' : 'media-type'}-${change}`;
|
|
46
|
+
if (kind === 'request-body')
|
|
47
|
+
return `request-body-${whole ? '' : 'media-type-'}${change}`;
|
|
48
|
+
return `payload-${change}`;
|
|
49
|
+
};
|
|
50
|
+
const comparePresence = (name, { old, nu }) => {
|
|
51
|
+
const before = old.payloads.find((payload) => payload.name === name);
|
|
52
|
+
const present = (before ?? nu.payloads.find((payload) => payload.name === name));
|
|
53
|
+
const base = { payload: name, direction: present.direction, pointer: '' };
|
|
54
|
+
const removed = before !== undefined;
|
|
55
|
+
const { required, schema } = present;
|
|
56
|
+
if (kindOf(name) === 'parameter') {
|
|
57
|
+
if (removed)
|
|
58
|
+
return [{ ...base, rule: 'parameter-removed', before: schema, after: undefined, effect: required ? 'widens' : 'neutral' }];
|
|
59
|
+
return [{ ...base, rule: required ? 'required-parameter-added' : 'parameter-added', before: undefined, after: schema, effect: required ? 'narrows' : 'neutral' }];
|
|
60
|
+
}
|
|
61
|
+
if (schema === false)
|
|
62
|
+
return [];
|
|
63
|
+
if (removed)
|
|
64
|
+
return [{ ...base, rule: presenceRule(name, nu.payloads, 'removed'), before: schema, after: undefined, effect: 'narrows' }];
|
|
65
|
+
return [{ ...base, rule: presenceRule(name, old.payloads, 'added'), before: undefined, after: schema, effect: 'widens' }];
|
|
66
|
+
};
|
|
67
|
+
const comparePayload = (documents, before, after) => {
|
|
68
|
+
const { name, direction } = after;
|
|
69
|
+
const changes = compareSchemas(before.schema, after.schema, direction, documents).map((change) => ({ ...change, payload: name, direction }));
|
|
70
|
+
if (before.required === after.required)
|
|
71
|
+
return changes;
|
|
72
|
+
const rule = `${kindOf(name)}-became-${after.required ? 'required' : 'optional'}`;
|
|
73
|
+
return [{ rule, payload: name, direction, pointer: '', before: before.required, after: after.required, effect: after.required ? 'narrows' : 'widens' }, ...changes];
|
|
74
|
+
};
|
|
75
|
+
const PATH = 'param:path:';
|
|
76
|
+
const pathParametersOnlyIn = (operation, other) => operation.payloads.filter((payload) => payload.name.startsWith(PATH) && !other.payloads.some((o) => o.name === payload.name)).map((payload) => payload.name);
|
|
77
|
+
const renamedPathParameters = ({ old, nu }) => {
|
|
78
|
+
const after = pathParametersOnlyIn(nu, old);
|
|
79
|
+
return new Map(pathParametersOnlyIn(old, nu).flatMap((name, index) => (index < after.length ? [[after[index], name]] : [])));
|
|
80
|
+
};
|
|
81
|
+
const renameOf = (after, before) => ({ rule: 'path-parameter-renamed', payload: after, direction: 'request', pointer: '', before: before.slice(PATH.length), after: after.slice(PATH.length), effect: 'neutral' });
|
|
82
|
+
const securityRaws = (a, b, { old, nu }) => {
|
|
83
|
+
const change = compareSecurity(a, b, old, nu);
|
|
84
|
+
return change === undefined ? [] : [{ ...change, direction: 'request', pointer: '' }];
|
|
85
|
+
};
|
|
86
|
+
const comparePayloads = (a, b, pair) => {
|
|
87
|
+
const renamed = renamedPathParameters(pair);
|
|
88
|
+
const names = [...new Set([...pair.old.payloads, ...pair.nu.payloads].map((payload) => payload.name))].filter((name) => ![...renamed.values()].includes(name));
|
|
89
|
+
const renames = [...renamed].map(([after, before]) => renameOf(after, before));
|
|
90
|
+
return [...renames, ...securityRaws(a, b, pair)].concat(names.flatMap((name) => {
|
|
91
|
+
const before = pair.old.payloads.find((payload) => payload.name === (renamed.get(name) ?? name));
|
|
92
|
+
const after = pair.nu.payloads.find((payload) => payload.name === name);
|
|
93
|
+
if (before === undefined || after === undefined)
|
|
94
|
+
return comparePresence(name, pair);
|
|
95
|
+
return comparePayload({ old: a.document, new: b.document }, before, after);
|
|
96
|
+
}));
|
|
97
|
+
};
|
|
98
|
+
const compareOperation = (old, nu) => {
|
|
99
|
+
const added = old === undefined;
|
|
100
|
+
return {
|
|
101
|
+
rule: added ? 'operation-added' : 'operation-removed',
|
|
102
|
+
direction: callDirection((nu ?? old)),
|
|
103
|
+
pointer: '',
|
|
104
|
+
before: old?.id,
|
|
105
|
+
after: nu?.id,
|
|
106
|
+
effect: added ? 'widens' : 'narrows',
|
|
107
|
+
};
|
|
108
|
+
};
|
|
109
|
+
const dangerFix = (raw, where) => {
|
|
110
|
+
if (raw.rule === 'default-changed')
|
|
111
|
+
return `a caller that leaves ${where} out now gets ${JSON.stringify(raw.after) ?? 'no default'} instead of ${JSON.stringify(raw.before) ?? 'no default'}: keep the old default, or say so in the release notes`;
|
|
112
|
+
if (raw.rule === 'path-parameter-renamed')
|
|
113
|
+
return `a client generated from the old contract passes \`${String(raw.before)}\` by name, and it is now \`${String(raw.after)}\`: keep the old name, or say so in the release notes`;
|
|
114
|
+
return `a reader that rejects values it did not expect at ${where} may fail on this: make readers tolerate it, or say so in the release notes`;
|
|
115
|
+
};
|
|
116
|
+
const fixFor = (raw, verdict, operation) => {
|
|
117
|
+
const where = [operation, raw.payload, raw.pointer].filter((part) => part !== undefined && part !== '').join(' ');
|
|
118
|
+
if (raw.frozen === true)
|
|
119
|
+
return `${where} is under \`x-frozen\`, so nothing under it may change (\`${raw.rule}\`): revert it, or publish the change as a new version of the contract`;
|
|
120
|
+
if (verdict === 'dangerous')
|
|
121
|
+
return dangerFix(raw, where);
|
|
122
|
+
if (verdict === 'unknown')
|
|
123
|
+
return `review ${where} by hand: contractdiff cannot tell what \`${raw.rule}\` does to the values it accepts`;
|
|
124
|
+
if (verdict === 'non-breaking')
|
|
125
|
+
return 'nothing to do';
|
|
126
|
+
if (raw.rule === 'security-narrowed')
|
|
127
|
+
return `keep letting into ${where} every caller the old security requirement let in, or release this as a major version`;
|
|
128
|
+
if (raw.effect === 'narrows')
|
|
129
|
+
return `keep accepting at ${where} what the old contract accepted, or release this as a major version`;
|
|
130
|
+
return `keep ${where} within what the old contract allowed, or release this as a major version`;
|
|
131
|
+
};
|
|
132
|
+
export const overall = (summary) => {
|
|
133
|
+
return SEVERITY.find((verdict) => summary[verdict] > 0) ?? 'non-breaking';
|
|
134
|
+
};
|
|
135
|
+
const nodeAt = (document, pointer) => {
|
|
136
|
+
try {
|
|
137
|
+
return pointerGet(document, pointer);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
const frozenOperation = (a, old) => isFrozen(a.document) || (old !== undefined && isFrozen(nodeAt(a.document, old.source)));
|
|
144
|
+
const whereOf = (finding) => `${finding.source} ${finding.payload ?? ''} ${finding.pointer} ${finding.id}`;
|
|
145
|
+
export const sortFindings = (findings) => findings.sort((x, y) => SEVERITY.indexOf(x.verdict) - SEVERITY.indexOf(y.verdict) || whereOf(x).localeCompare(whereOf(y), 'en'));
|
|
146
|
+
export const summaryOf = (findings) => Object.fromEntries(SEVERITY.map((verdict) => [verdict, findings.filter((finding) => finding.verdict === verdict).length]));
|
|
147
|
+
const FROZEN = { id: 'ac-frozen-changed', scheme: 'contractdiff' };
|
|
148
|
+
export const compareContracts = (a, b, options = {}) => {
|
|
149
|
+
const mode = options.mode ?? 'backward';
|
|
150
|
+
const side = options.side ?? 'caller';
|
|
151
|
+
const findings = pair(a.operations, b.operations).flatMap(([old, nu]) => {
|
|
152
|
+
const operation = (nu ?? old);
|
|
153
|
+
const compared = old === undefined || nu === undefined ? [compareOperation(old, nu)] : comparePayloads(a, b, { old, nu });
|
|
154
|
+
const raws = frozenOperation(a, old) ? compared.map((raw) => ({ ...raw, frozen: true })) : compared;
|
|
155
|
+
return raws.map((raw) => {
|
|
156
|
+
const verdict = refine(raw, raw.direction, classify(raw, raw.direction, mode, side), options.dangerousBreaking);
|
|
157
|
+
return {
|
|
158
|
+
...(raw.frozen === true ? FROZEN : ruleId(raw.rule, raw.direction, raw.payload, raw.pointer)),
|
|
159
|
+
verdict,
|
|
160
|
+
effect: raw.effect,
|
|
161
|
+
operation: operation.id,
|
|
162
|
+
source: operation.source,
|
|
163
|
+
document: nu === undefined ? 'old' : 'new',
|
|
164
|
+
...(raw.payload === undefined ? {} : { payload: raw.payload }),
|
|
165
|
+
direction: raw.direction,
|
|
166
|
+
pointer: raw.pointer,
|
|
167
|
+
before: raw.before,
|
|
168
|
+
after: raw.after,
|
|
169
|
+
fix: fixFor(raw, verdict, operation.id),
|
|
170
|
+
};
|
|
171
|
+
});
|
|
172
|
+
});
|
|
173
|
+
sortFindings(findings);
|
|
174
|
+
const summary = summaryOf(findings);
|
|
175
|
+
return { mode, side, verdict: overall(summary), summary, findings };
|
|
176
|
+
};
|