specshield 3.4.14 → 3.4.16
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/CHANGELOG.md +58 -1
- package/README.md +186 -1
- package/package.json +3 -2
- package/src/api/bdctClient.js +8 -0
- package/src/cli.js +4 -0
- package/src/commands/compare.js +7 -1
- package/src/commands/deprecations.js +236 -0
- package/src/commands/fix.js +173 -0
- package/src/core/classifyChanges.js +1 -1
- package/src/core/configLoader.js +6 -1
- package/src/core/fix/fixSpec.js +179 -0
- package/src/core/fix/locate.js +263 -0
- package/src/core/fix/ops.js +233 -0
- package/src/core/fix/shim/spring.js +532 -0
- package/src/core/fix/shim/transforms.js +231 -0
- package/src/core/fix/strategies.js +578 -0
- package/src/core/outputFormatter.js +23 -1
- package/src/core/usage/deprecations.js +438 -0
- package/src/core/usage/impact.js +42 -24
- package/src/core/usage/usageStore.js +32 -5
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { Command } = require('commander');
|
|
4
|
+
const chalk = require('chalk');
|
|
5
|
+
const path = require('path');
|
|
6
|
+
const fsExtra = require('fs-extra');
|
|
7
|
+
const { loadSpec } = require('../core/loadSpec');
|
|
8
|
+
const { parseSpec } = require('../core/parseSpec');
|
|
9
|
+
const { fixSpec } = require('../core/fix/fixSpec');
|
|
10
|
+
const { applyOpsToText } = require('../core/fix/ops');
|
|
11
|
+
const { buildShim } = require('../core/fix/shim/transforms');
|
|
12
|
+
const { generateSpring } = require('../core/fix/shim/spring');
|
|
13
|
+
const { plural } = require('../core/usage/format');
|
|
14
|
+
const logger = require('../utils/logger');
|
|
15
|
+
const exitAfterFlush = require('../utils/exitAfterFlush');
|
|
16
|
+
|
|
17
|
+
const fix = new Command('fix')
|
|
18
|
+
.description('Turn breaking changes into non-breaking ones: expand-and-contract edits to the new spec, each verified by the diff engine')
|
|
19
|
+
.argument('<base>', 'The spec your clients use today')
|
|
20
|
+
.argument('<target>', 'The new spec with breaking changes')
|
|
21
|
+
.option('--out <file>', 'Where to write the fixed spec (default: <target>.fixed.<ext>)')
|
|
22
|
+
.option('--write', 'Edit <target> in place instead of writing a new file')
|
|
23
|
+
.option('--dry-run', 'Only report; write nothing')
|
|
24
|
+
.option('--sunset <date>', 'Add x-sunset: <date> to everything restored as deprecated (YYYY-MM-DD)')
|
|
25
|
+
.option('--spring <dir>', 'Also generate a Spring Boot version layer (Java) into this directory')
|
|
26
|
+
.option('--package <name>', 'Java package for --spring', 'com.example.api.compat')
|
|
27
|
+
.option('--version-header <name>', 'Request header that carries the client\'s API version (--spring)', 'X-API-Version')
|
|
28
|
+
.option('--json', 'Output machine-readable JSON')
|
|
29
|
+
.action(async (basePath, targetPath, opts) => {
|
|
30
|
+
try {
|
|
31
|
+
if (opts.sunset && !/^\d{4}-\d{2}-\d{2}$/.test(opts.sunset)) throw new Error('--sunset must be a date like 2027-03-31');
|
|
32
|
+
if (opts.write && opts.out) throw new Error('Use either --write or --out, not both');
|
|
33
|
+
const targetText = await loadSpec(targetPath);
|
|
34
|
+
const baseDoc = parseSpec(await loadSpec(basePath), basePath);
|
|
35
|
+
const targetDoc = parseSpec(targetText, targetPath);
|
|
36
|
+
|
|
37
|
+
const result = fixSpec(baseDoc, targetDoc, { sunset: opts.sunset || null });
|
|
38
|
+
const verified = result.suggestions.filter((s) => s.status === 'verified');
|
|
39
|
+
|
|
40
|
+
let outFile = null;
|
|
41
|
+
if (!opts.dryRun && result.ops.length > 0) {
|
|
42
|
+
outFile = opts.write ? targetPath : (opts.out || defaultOut(targetPath));
|
|
43
|
+
const json = path.extname(targetPath).toLowerCase() === '.json' || /^\s*\{/.test(targetText);
|
|
44
|
+
await fsExtra.outputFile(outFile, applyOpsToText(targetText, result.ops, { json }));
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
let shim = null;
|
|
48
|
+
if (opts.spring) {
|
|
49
|
+
shim = buildShim(result, baseDoc, targetDoc);
|
|
50
|
+
if (!opts.dryRun && shim.transforms.length > 0) {
|
|
51
|
+
shim.files = await generateSpring(shim, {
|
|
52
|
+
dir: opts.spring, pkg: opts.package, header: opts.versionHeader,
|
|
53
|
+
version: String((targetDoc.info && targetDoc.info.version) || 'next'),
|
|
54
|
+
basePath: serverBasePath(targetDoc),
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (opts.json) {
|
|
60
|
+
process.stdout.write(JSON.stringify({
|
|
61
|
+
before: result.before,
|
|
62
|
+
after: result.after,
|
|
63
|
+
output: outFile,
|
|
64
|
+
suggestions: result.suggestions.map(({ ops, ...s }) => ({ ...s, edits: ops.length })),
|
|
65
|
+
remaining: result.remaining,
|
|
66
|
+
...(shim ? { spring: { transforms: shim.transforms, skipped: shim.skipped, files: shim.files || [] } } : {}),
|
|
67
|
+
}, null, 2) + '\n');
|
|
68
|
+
} else {
|
|
69
|
+
process.stdout.write(render(result, { baseDoc, targetDoc, outFile, verified, shim, dryRun: opts.dryRun, targetPath }) + '\n');
|
|
70
|
+
}
|
|
71
|
+
exitAfterFlush(result.after > 0 ? 1 : 0);
|
|
72
|
+
} catch (err) {
|
|
73
|
+
logger.error(`Error: ${err.message}`);
|
|
74
|
+
process.exit(2);
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
function defaultOut(target) {
|
|
79
|
+
const ext = path.extname(target);
|
|
80
|
+
return path.join(path.dirname(target), `${path.basename(target, ext)}.fixed${ext || '.yaml'}`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function serverBasePath(doc) {
|
|
84
|
+
if (typeof doc.basePath === 'string') return doc.basePath.replace(/\/$/, '');
|
|
85
|
+
const url = doc.servers && doc.servers[0] && doc.servers[0].url;
|
|
86
|
+
if (!url) return '';
|
|
87
|
+
const p = url.replace(/^[a-z]+:\/\/[^/]+/i, '').replace(/\{[^}]+\}/g, '').replace(/\/$/, '');
|
|
88
|
+
return p.startsWith('/') ? p : '';
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function render(r, { baseDoc, targetDoc, outFile, verified, shim, dryRun, targetPath }) {
|
|
92
|
+
const lines = [''];
|
|
93
|
+
const v = (d) => (d.info && d.info.version ? ` ${d.info.version}` : '');
|
|
94
|
+
lines.push(chalk.bold(` SpecShield™ Fix — ${(targetDoc.info && targetDoc.info.title) || 'API'}${v(baseDoc)} →${v(targetDoc)}`));
|
|
95
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
96
|
+
if (r.before === 0) {
|
|
97
|
+
lines.push(chalk.green(' ✔ No breaking changes — nothing to fix.'));
|
|
98
|
+
lines.push('');
|
|
99
|
+
return lines.join('\n');
|
|
100
|
+
}
|
|
101
|
+
const fixedCount = r.before - r.after;
|
|
102
|
+
lines.push(` ${plural(r.before, 'breaking change')} · ${chalk.green(`${fixedCount} fixed`)}` +
|
|
103
|
+
(r.after ? ` · ${chalk.red(`${r.after} need${r.after === 1 ? 's' : ''} a decision`)}` : ''));
|
|
104
|
+
lines.push(chalk.gray(' Each fix was re-checked with the diff engine: it removes its breaking change and adds none.'));
|
|
105
|
+
|
|
106
|
+
if (verified.length) {
|
|
107
|
+
lines.push('');
|
|
108
|
+
lines.push(chalk.green.bold(` ✔ FIXES (${verified.length})`));
|
|
109
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
110
|
+
for (const s of verified) {
|
|
111
|
+
lines.push(` ${chalk.green('✔')} ${s.title}`);
|
|
112
|
+
lines.push(chalk.gray(` ${where(s.changes)}`));
|
|
113
|
+
lines.push(` ${chalk.cyan('→')} ${s.detail}`);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const open = r.suggestions.filter((s) => s.status === 'manual' || s.status === 'rejected');
|
|
118
|
+
if (open.length) {
|
|
119
|
+
lines.push('');
|
|
120
|
+
lines.push(chalk.red.bold(` ✖ NEEDS A DECISION (${open.length})`));
|
|
121
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
122
|
+
for (const s of open) {
|
|
123
|
+
const c = s.changes[0];
|
|
124
|
+
lines.push(` ${chalk.red('●')} ${c.description || `${c.type} ${c.method ? c.method.toUpperCase() : ''} ${c.path || ''} ${c.field || ''}`}`);
|
|
125
|
+
lines.push(chalk.gray(` ${s.status === 'rejected' ? `fix not applied — ${s.reason}` : s.reason}`));
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (shim) {
|
|
130
|
+
lines.push('');
|
|
131
|
+
lines.push(chalk.bold(' Spring Boot version layer'));
|
|
132
|
+
lines.push(chalk.gray(' ─────────────────────────────────────────'));
|
|
133
|
+
if (shim.transforms.length === 0) {
|
|
134
|
+
lines.push(chalk.gray(' Nothing to generate: no change here can be undone by reshaping JSON.'));
|
|
135
|
+
} else {
|
|
136
|
+
lines.push(` ${plural(shim.transforms.length, 'transform')} — old clients get the old JSON shape; each was checked against sample payloads.`);
|
|
137
|
+
for (const t of shim.transforms) {
|
|
138
|
+
const assumed = t.kind === 'rename' || t.kind === 'enum';
|
|
139
|
+
lines.push(chalk.gray(` ${describeTransform(t)}`) + (assumed ? chalk.yellow(' (inferred rename — check)') : ''));
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
for (const s of shim.skipped) lines.push(chalk.yellow(` not generated: ${s}`));
|
|
143
|
+
if (shim.files) for (const f of shim.files) lines.push(chalk.green(` ✔ ${f}`));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
lines.push('');
|
|
147
|
+
if (outFile) {
|
|
148
|
+
lines.push(chalk.green(` ✔ Wrote ${outFile}`) + chalk.gray(` (${plural(r.ops.length, 'edit')}, comments and layout kept)`));
|
|
149
|
+
if (outFile !== targetPath) lines.push(chalk.gray(` Review: diff -u ${targetPath} ${outFile}`));
|
|
150
|
+
} else if (dryRun && r.ops.length) {
|
|
151
|
+
lines.push(chalk.gray(' --dry-run: nothing written.'));
|
|
152
|
+
}
|
|
153
|
+
lines.push('');
|
|
154
|
+
return lines.join('\n');
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function where(changes) {
|
|
158
|
+
const eps = [...new Set(changes.filter((c) => c.method).map((c) => `${c.method.toUpperCase()} ${c.path}`))];
|
|
159
|
+
if (eps.length === 0) return changes[0].field || '';
|
|
160
|
+
return eps.length <= 3 ? eps.join(', ') : `${eps.slice(0, 3).join(', ')} and ${eps.length - 3} more`;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function describeTransform(t) {
|
|
164
|
+
const at = `${t.method} ${t.path} ${t.side}`;
|
|
165
|
+
if (t.kind === 'rename') return `${at}: ${t.from} → ${t.to}`;
|
|
166
|
+
if (t.kind === 'convert') return `${at}: ${t.field} ${t.from} → ${t.to}`;
|
|
167
|
+
if (t.kind === 'enum') return `${at}: ${t.field} "${t.from}" → "${t.to}"`;
|
|
168
|
+
if (t.kind === 'default') return `${at}: ${t.field} defaults to ${JSON.stringify(t.value)}`;
|
|
169
|
+
if (t.kind === 'unwrap') return `${at}: unwrap the list from \`${t.property}\``;
|
|
170
|
+
return `${at}: ${t.kind}`;
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
module.exports = fix;
|
package/src/core/configLoader.js
CHANGED
|
@@ -116,7 +116,7 @@ function validateConfig(config, filePath) {
|
|
|
116
116
|
if (u.minDays !== undefined && !(Number(u.minDays) >= 0)) {
|
|
117
117
|
throw new Error(`Config error in "${filePath}": usage.minDays must be a number ≥ 0`);
|
|
118
118
|
}
|
|
119
|
-
for (const key of ['maxAgeDays', 'minCoverage']) {
|
|
119
|
+
for (const key of ['maxAgeDays', 'minCoverage', 'quietDays']) {
|
|
120
120
|
if (u[key] !== undefined && !(Number(u[key]) >= 0)) {
|
|
121
121
|
throw new Error(`Config error in "${filePath}": usage.${key} must be a number ≥ 0`);
|
|
122
122
|
}
|
|
@@ -124,6 +124,9 @@ function validateConfig(config, filePath) {
|
|
|
124
124
|
if (u.downgrade !== undefined && typeof u.downgrade !== 'boolean') {
|
|
125
125
|
throw new Error(`Config error in "${filePath}": usage.downgrade must be a boolean`);
|
|
126
126
|
}
|
|
127
|
+
if (u.contacts !== undefined && (typeof u.contacts !== 'object' || u.contacts === null || Array.isArray(u.contacts))) {
|
|
128
|
+
throw new Error(`Config error in "${filePath}": usage.contacts must map client ids to contacts`);
|
|
129
|
+
}
|
|
127
130
|
valid.usage = {
|
|
128
131
|
file: u.file || null,
|
|
129
132
|
ignoreClients: (u.ignoreClients || []).filter(Boolean).map(String),
|
|
@@ -131,6 +134,8 @@ function validateConfig(config, filePath) {
|
|
|
131
134
|
maxAgeDays: u.maxAgeDays !== undefined ? Number(u.maxAgeDays) : undefined,
|
|
132
135
|
minCoverage: u.minCoverage !== undefined ? Number(u.minCoverage) : undefined,
|
|
133
136
|
downgrade: u.downgrade,
|
|
137
|
+
quietDays: u.quietDays !== undefined ? Number(u.quietDays) : undefined,
|
|
138
|
+
contacts: u.contacts || {},
|
|
134
139
|
};
|
|
135
140
|
} else {
|
|
136
141
|
throw new Error(`Config error in "${filePath}": usage must be a file path or an object`);
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { normalizeSpec } = require('../normalizeSpec');
|
|
4
|
+
const { diffSpecs } = require('../diffEngine');
|
|
5
|
+
const { BREAKING_TYPES } = require('../classifyChanges');
|
|
6
|
+
const { suggest, detectRenames, detectEnumRenames, reshapedBodies, sig } = require('./strategies');
|
|
7
|
+
const { applyOps, clone } = require('./ops');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Break → fix. For every breaking change between `baseDoc` and `targetDoc`
|
|
11
|
+
* (raw parsed specs), proposes the expand-and-contract edit to the target
|
|
12
|
+
* that keeps existing clients working — and keeps it only if the diff engine
|
|
13
|
+
* agrees: applied on top of the fixes accepted so far, the suggestion must
|
|
14
|
+
* remove the breaking change(s) it addresses and must not introduce any other
|
|
15
|
+
* breaking change. Suggestions are applied in that order, so the returned
|
|
16
|
+
* `fixedDoc` is exactly what was verified.
|
|
17
|
+
*/
|
|
18
|
+
function fixSpec(baseDoc, targetDoc, { sunset = null, depth = 0 } = {}) {
|
|
19
|
+
const baseNorm = normalizeSpec(baseDoc);
|
|
20
|
+
const raw = diffSpecs(baseNorm, normalizeSpec(targetDoc));
|
|
21
|
+
const breaking = raw.filter((d) => BREAKING_TYPES.has(d.type));
|
|
22
|
+
const original = new Set(breaking.map(sig));
|
|
23
|
+
const deprecate = deprecator(targetDoc, sunset);
|
|
24
|
+
|
|
25
|
+
// Fixes depend on each other: restoring a removed field that references an
|
|
26
|
+
// enum which lost a value brings that enum break into view, and only a
|
|
27
|
+
// second round can fix it. So run rounds; within a round a fix is accepted
|
|
28
|
+
// when it removes its own break(s), even if it exposes another. At the end the
|
|
29
|
+
// result must contain no break the original target didn't have — otherwise
|
|
30
|
+
// fall back to strict mode, where no fix may introduce anything.
|
|
31
|
+
const relaxed = run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict: false });
|
|
32
|
+
const ok = [...relaxed.currentBreaking].every((x) => original.has(x));
|
|
33
|
+
const result = ok ? relaxed : run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict: true });
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
suggestions: result.suggestions,
|
|
37
|
+
fixedDoc: result.current,
|
|
38
|
+
ops: result.ops,
|
|
39
|
+
before: breaking.length,
|
|
40
|
+
after: result.currentBreaking.size,
|
|
41
|
+
remaining: breaking.filter((c) => result.currentBreaking.has(sig(c))),
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function run({ baseDoc, targetDoc, baseNorm, deprecate, depth, strict }) {
|
|
46
|
+
let current = clone(targetDoc);
|
|
47
|
+
let currentBreaking = breakingSigs(baseNorm, current);
|
|
48
|
+
const ops = [];
|
|
49
|
+
const all = [];
|
|
50
|
+
const seen = new Set();
|
|
51
|
+
|
|
52
|
+
for (let round = 0; round < 5; round++) {
|
|
53
|
+
const raw = diffSpecs(baseNorm, normalizeSpec(current));
|
|
54
|
+
const ctx = {
|
|
55
|
+
base: baseDoc,
|
|
56
|
+
target: current,
|
|
57
|
+
renames: detectRenames(raw, baseNorm, normalizeSpec(current)),
|
|
58
|
+
enumRenames: detectEnumRenames(raw, baseNorm, normalizeSpec(current)),
|
|
59
|
+
reshaped: reshapedBodies(raw),
|
|
60
|
+
deprecate,
|
|
61
|
+
// Transforms for changes nested inside a reshaped body (see bodyShapeChanged).
|
|
62
|
+
nested: depth < 2
|
|
63
|
+
? (b, t) => fixSpec(b, t, { depth: depth + 1 }).suggestions.flatMap((x) => x.transforms)
|
|
64
|
+
: null,
|
|
65
|
+
};
|
|
66
|
+
const fresh = raw.filter((d) => BREAKING_TYPES.has(d.type) && !seen.has(sig(d)));
|
|
67
|
+
if (fresh.length === 0 && round > 0) break;
|
|
68
|
+
const suggestions = mergeIdentical(raw.filter((d) => BREAKING_TYPES.has(d.type) && (round === 0 || !seen.has(sig(d)) || retry(all, d)))
|
|
69
|
+
.map((c) => suggest(c, ctx)));
|
|
70
|
+
for (const d of raw) if (BREAKING_TYPES.has(d.type)) seen.add(sig(d));
|
|
71
|
+
|
|
72
|
+
let progress = false;
|
|
73
|
+
for (const s of suggestions) {
|
|
74
|
+
if (!s.strategy) { s.status = 'manual'; continue; }
|
|
75
|
+
if (s.changes.every((c) => !currentBreaking.has(sig(c)))) { s.status = 'covered'; continue; }
|
|
76
|
+
let candidate;
|
|
77
|
+
let after;
|
|
78
|
+
try {
|
|
79
|
+
candidate = applyOps(clone(current), s.ops);
|
|
80
|
+
after = breakingSigs(baseNorm, candidate);
|
|
81
|
+
} catch (err) {
|
|
82
|
+
reject(s, `the edited spec no longer parses: ${err.message}`);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const unfixed = s.changes.filter((c) => after.has(sig(c)));
|
|
86
|
+
const introduced = [...after].filter((x) => !currentBreaking.has(x));
|
|
87
|
+
if (unfixed.length > 0) { reject(s, 'the diff engine still reports the breaking change'); continue; }
|
|
88
|
+
// Relaxed rounds let a fix expose a break that a later round fixes (a
|
|
89
|
+
// restored field brings its enum's removed value back into view); the
|
|
90
|
+
// final subset check in fixSpec keeps that honest.
|
|
91
|
+
if (introduced.length > 0 && strict) {
|
|
92
|
+
reject(s, `it would add a breaking change: ${describe(introduced[0])}`);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
s.status = 'verified';
|
|
96
|
+
current = candidate;
|
|
97
|
+
currentBreaking = after;
|
|
98
|
+
ops.push(...s.ops);
|
|
99
|
+
progress = true;
|
|
100
|
+
}
|
|
101
|
+
mergeInto(all, suggestions);
|
|
102
|
+
if (!progress) break;
|
|
103
|
+
}
|
|
104
|
+
return { suggestions: all, current, currentBreaking, ops };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** A change rejected in an earlier round gets another chance once other fixes landed. */
|
|
108
|
+
function retry(all, d) {
|
|
109
|
+
return all.some((s) => s.status === 'rejected' && s.changes.some((c) => sig(c) === sig(d)));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** Later rounds' verdicts replace earlier ones for the same changes. */
|
|
113
|
+
function mergeInto(all, next) {
|
|
114
|
+
for (const s of next) {
|
|
115
|
+
const keys = new Set(s.changes.map(sig));
|
|
116
|
+
for (let i = all.length - 1; i >= 0; i--) {
|
|
117
|
+
if (all[i].changes.some((c) => keys.has(sig(c))) && all[i].status !== 'verified') all.splice(i, 1);
|
|
118
|
+
}
|
|
119
|
+
if (s.status === 'covered' && all.some((x) => x.status === 'verified' && x.changes.some((c) => keys.has(sig(c))))) continue;
|
|
120
|
+
all.push(s);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function reject(s, reason) {
|
|
125
|
+
s.status = 'rejected';
|
|
126
|
+
s.reason = reason;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function breakingSigs(baseNorm, doc) {
|
|
130
|
+
return new Set(diffSpecs(baseNorm, normalizeSpec(doc)).filter((d) => BREAKING_TYPES.has(d.type)).map(sig));
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function describe(signature) {
|
|
134
|
+
const [type, method, path, field] = signature.split('|');
|
|
135
|
+
return `${type}${method ? ` ${method.toUpperCase()} ${path}` : ''}${field ? ` ${field}` : ''}`;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* A change to a shared component shows up once per operation that uses it;
|
|
140
|
+
* the fix is the same edit each time. One suggestion, many changes.
|
|
141
|
+
*/
|
|
142
|
+
function mergeIdentical(list) {
|
|
143
|
+
const byOps = new Map();
|
|
144
|
+
const out = [];
|
|
145
|
+
for (const s of list) {
|
|
146
|
+
if (!s.strategy || s.ops.length === 0) { out.push(s); continue; }
|
|
147
|
+
const key = JSON.stringify(s.ops);
|
|
148
|
+
const prev = byOps.get(key);
|
|
149
|
+
if (prev) {
|
|
150
|
+
prev.changes.push(...s.changes);
|
|
151
|
+
prev.transforms.push(...s.transforms);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
byOps.set(key, s);
|
|
155
|
+
out.push(s);
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Marks a restored node deprecated the way the spec's version allows:
|
|
162
|
+
* `deprecated: true` (OpenAPI 3; beside a $ref it is honoured by 3.1 and
|
|
163
|
+
* ignored by 3.0 tools), `x-deprecated` on Swagger 2.0 schemas, and
|
|
164
|
+
* `x-sunset` when a sunset date was given.
|
|
165
|
+
*/
|
|
166
|
+
function deprecator(targetDoc, sunset) {
|
|
167
|
+
const swagger2 = typeof targetDoc.swagger === 'string';
|
|
168
|
+
return (node, note = null) => {
|
|
169
|
+
if (!node || typeof node !== 'object') return node;
|
|
170
|
+
const isSchemaish = !node.responses && !node.in;
|
|
171
|
+
if (swagger2 && isSchemaish) node['x-deprecated'] = true;
|
|
172
|
+
else node.deprecated = true;
|
|
173
|
+
if (sunset) node['x-sunset'] = sunset;
|
|
174
|
+
if (note && !node.$ref) node.description = node.description ? `${node.description} Deprecated: ${note}` : `Deprecated: ${note}`;
|
|
175
|
+
return node;
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
module.exports = { fixSpec };
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Finds things inside a RAW (un-normalized) spec document by the coordinates
|
|
5
|
+
* the diff engine reports — (method, path, field) — and returns JSON-pointer
|
|
6
|
+
* style paths (arrays of keys) into that document. Fixes are edits at those
|
|
7
|
+
* paths, so they land where the author would make them: inside the shared
|
|
8
|
+
* component a `$ref` points to, not in a copy.
|
|
9
|
+
*
|
|
10
|
+
* Field paths are the diff engine's: `requestBody.owner.name`,
|
|
11
|
+
* `responses.200.items[items].tag`, `responses.200.data.oneOf[1].x`,
|
|
12
|
+
* `requestBody.meta.<*>.label` (map values), `parameters.sort`.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'head', 'options'];
|
|
16
|
+
const REF_PREFIXES = [
|
|
17
|
+
['#/components/schemas/', ['components', 'schemas']],
|
|
18
|
+
['#/definitions/', ['definitions']],
|
|
19
|
+
['#/components/parameters/', ['components', 'parameters']],
|
|
20
|
+
['#/parameters/', ['parameters']],
|
|
21
|
+
['#/components/responses/', ['components', 'responses']],
|
|
22
|
+
['#/responses/', ['responses']],
|
|
23
|
+
['#/components/requestBodies/', ['components', 'requestBodies']],
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
function get(doc, ptr) {
|
|
27
|
+
let cur = doc;
|
|
28
|
+
for (const k of ptr) {
|
|
29
|
+
if (cur === null || typeof cur !== 'object') return undefined;
|
|
30
|
+
cur = cur[k];
|
|
31
|
+
}
|
|
32
|
+
return cur;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** "#/components/schemas/Pet" → ['components', 'schemas', 'Pet'] (also any local JSON pointer). */
|
|
36
|
+
function refToPtr(ref) {
|
|
37
|
+
if (typeof ref !== 'string' || !ref.startsWith('#/')) return null;
|
|
38
|
+
return ref.slice(2).split('/').map((s) => s.replace(/~1/g, '/').replace(/~0/g, '~'));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function ptrToRef(ptr) {
|
|
42
|
+
return '#/' + ptr.map((s) => String(s).replace(/~/g, '~0').replace(/\//g, '~1')).join('/');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Follows $ref chains from `ptr`; returns the pointer of the node that holds the content. */
|
|
46
|
+
function derefPtr(doc, ptr) {
|
|
47
|
+
let cur = ptr;
|
|
48
|
+
for (let i = 0; i < 20; i++) {
|
|
49
|
+
const node = get(doc, cur);
|
|
50
|
+
if (!node || typeof node !== 'object' || typeof node.$ref !== 'string') return cur;
|
|
51
|
+
const next = refToPtr(node.$ref);
|
|
52
|
+
if (!next) return cur; // external ref: stop here
|
|
53
|
+
cur = next;
|
|
54
|
+
}
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function operationPtr(doc, method, path) {
|
|
59
|
+
const ptr = ['paths', path, method.toLowerCase()];
|
|
60
|
+
return get(doc, ptr) ? ptr : null;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Path-level + operation-level parameters, op-level winning — like normalizeSpec. */
|
|
64
|
+
function parameterPtrs(doc, method, path) {
|
|
65
|
+
const out = new Map();
|
|
66
|
+
for (const base of [['paths', path, 'parameters'], ['paths', path, method.toLowerCase(), 'parameters']]) {
|
|
67
|
+
const list = get(doc, base);
|
|
68
|
+
if (!Array.isArray(list)) continue;
|
|
69
|
+
list.forEach((_, i) => {
|
|
70
|
+
const p = derefPtr(doc, [...base, i]);
|
|
71
|
+
const node = p && get(doc, p);
|
|
72
|
+
if (node && node.name && node.in) out.set(`${node.in}:${node.name}`, { ptr: p, listPtr: [...base, i], node });
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
return [...out.values()];
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function findParameter(doc, method, path, name) {
|
|
79
|
+
return parameterPtrs(doc, method, path).find((p) => p.node.name === name && p.node.in !== 'body') || null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function mediaSchemaPtr(doc, contentPtr) {
|
|
83
|
+
const content = get(doc, contentPtr);
|
|
84
|
+
if (!content || typeof content !== 'object') return null;
|
|
85
|
+
const type = content['application/json'] ? 'application/json' : Object.keys(content)[0];
|
|
86
|
+
if (!type || !content[type] || !content[type].schema) return null;
|
|
87
|
+
return [...contentPtr, type, 'schema'];
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Pointer to the request body schema of an operation (OpenAPI 3 or Swagger 2.0 `in: body`). */
|
|
91
|
+
function requestSchemaPtr(doc, method, path) {
|
|
92
|
+
const op = operationPtr(doc, method, path);
|
|
93
|
+
if (!op) return null;
|
|
94
|
+
const rb = get(doc, [...op, 'requestBody']);
|
|
95
|
+
if (rb) {
|
|
96
|
+
const rbPtr = derefPtr(doc, [...op, 'requestBody']);
|
|
97
|
+
return rbPtr && mediaSchemaPtr(doc, [...rbPtr, 'content']);
|
|
98
|
+
}
|
|
99
|
+
const body = parameterPtrs(doc, method, path).find((p) => p.node.in === 'body');
|
|
100
|
+
return body && body.node.schema ? [...body.ptr, 'schema'] : null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function responseSchemaPtr(doc, method, path, code) {
|
|
104
|
+
const op = operationPtr(doc, method, path);
|
|
105
|
+
if (!op || !get(doc, [...op, 'responses', code])) return null;
|
|
106
|
+
const rPtr = derefPtr(doc, [...op, 'responses', code]);
|
|
107
|
+
const resp = rPtr && get(doc, rPtr);
|
|
108
|
+
if (!resp) return null;
|
|
109
|
+
if (resp.schema) return [...rPtr, 'schema']; // Swagger 2.0
|
|
110
|
+
return resp.content ? mediaSchemaPtr(doc, [...rPtr, 'content']) : null;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Splits a diff field path into its root and schema steps:
|
|
115
|
+
* "responses.200.items[items].tag" → { side: 'response', code: '200', steps: ['items', '[items]', 'tag'] }
|
|
116
|
+
*/
|
|
117
|
+
function parseField(field) {
|
|
118
|
+
let m = /^requestBody(.*)$/.exec(field || '');
|
|
119
|
+
let side;
|
|
120
|
+
let code = null;
|
|
121
|
+
let rest;
|
|
122
|
+
if (m) { side = 'request'; rest = m[1]; } else {
|
|
123
|
+
m = /^responses\.([^.[]+)(.*)$/.exec(field || '');
|
|
124
|
+
if (!m) return null;
|
|
125
|
+
side = 'response'; code = m[1]; rest = m[2];
|
|
126
|
+
}
|
|
127
|
+
const steps = [];
|
|
128
|
+
const re = /\.(oneOf|anyOf)\[(\d+)\]|\[items\]|\.<\*>|\.([^.[]+)/g;
|
|
129
|
+
let pos = 0;
|
|
130
|
+
let t;
|
|
131
|
+
while ((t = re.exec(rest)) !== null) {
|
|
132
|
+
if (t.index !== pos) return null;
|
|
133
|
+
pos = re.lastIndex;
|
|
134
|
+
if (t[1]) steps.push({ variant: t[1], index: Number(t[2]) });
|
|
135
|
+
else if (t[0] === '[items]') steps.push({ items: true });
|
|
136
|
+
else if (t[0] === '.<*>') steps.push({ map: true });
|
|
137
|
+
else steps.push({ prop: t[3] });
|
|
138
|
+
}
|
|
139
|
+
if (pos !== rest.length) return null;
|
|
140
|
+
return { side, code, steps };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function rootSchemaPtr(doc, method, path, parsed) {
|
|
144
|
+
return parsed.side === 'request'
|
|
145
|
+
? requestSchemaPtr(doc, method, path)
|
|
146
|
+
: responseSchemaPtr(doc, method, path, parsed.code);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Finds the schema object that declares property `name`, starting at the
|
|
151
|
+
* schema at `ptr` and looking through $ref and allOf. Returns the pointer of
|
|
152
|
+
* that (dereferenced) schema object, or null.
|
|
153
|
+
*/
|
|
154
|
+
function propertyOwnerPtr(doc, ptr, name, depth = 0) {
|
|
155
|
+
if (!ptr || depth > 12) return null;
|
|
156
|
+
const s = derefPtr(doc, ptr);
|
|
157
|
+
const node = s && get(doc, s);
|
|
158
|
+
if (!node || typeof node !== 'object') return null;
|
|
159
|
+
if (node.properties && Object.prototype.hasOwnProperty.call(node.properties, name)) return s;
|
|
160
|
+
for (let i = 0; i < (node.allOf || []).length; i++) {
|
|
161
|
+
const found = propertyOwnerPtr(doc, [...s, 'allOf', i], name, depth + 1);
|
|
162
|
+
if (found) return found;
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Walks `steps` from the schema at `ptr`. Returns the pointer of the last
|
|
169
|
+
* step's schema node (not dereferenced), or null when a step is missing.
|
|
170
|
+
*/
|
|
171
|
+
function walk(doc, ptr, steps) {
|
|
172
|
+
let cur = ptr;
|
|
173
|
+
for (const step of steps) {
|
|
174
|
+
if (!cur) return null;
|
|
175
|
+
if (step.prop !== undefined) {
|
|
176
|
+
const owner = propertyOwnerPtr(doc, cur, step.prop);
|
|
177
|
+
if (!owner) return null;
|
|
178
|
+
cur = [...owner, 'properties', step.prop];
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const s = derefPtr(doc, cur);
|
|
182
|
+
const node = s && get(doc, s);
|
|
183
|
+
if (!node) return null;
|
|
184
|
+
if (step.items) cur = node.items ? [...s, 'items'] : null;
|
|
185
|
+
else if (step.map) cur = node.additionalProperties && typeof node.additionalProperties === 'object' ? [...s, 'additionalProperties'] : null;
|
|
186
|
+
else cur = Array.isArray(node[step.variant]) && node[step.variant][step.index] ? [...s, step.variant, step.index] : null;
|
|
187
|
+
}
|
|
188
|
+
return cur;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Pointer of the schema node a diff field names, in `doc`. */
|
|
192
|
+
function fieldPtr(doc, method, path, field) {
|
|
193
|
+
const parsed = parseField(field);
|
|
194
|
+
if (!parsed) return null;
|
|
195
|
+
const root = rootSchemaPtr(doc, method, path, parsed);
|
|
196
|
+
return root && walk(doc, root, parsed.steps);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* For a property path (last step is a property), the pointer of the schema
|
|
201
|
+
* object that should hold it in `doc` — where a removed property goes back.
|
|
202
|
+
* Prefers the schema that declares the property's siblings.
|
|
203
|
+
*/
|
|
204
|
+
function parentObjectPtr(doc, method, path, field) {
|
|
205
|
+
const parsed = parseField(field);
|
|
206
|
+
if (!parsed || parsed.steps.length === 0) return null;
|
|
207
|
+
const last = parsed.steps[parsed.steps.length - 1];
|
|
208
|
+
if (last.prop === undefined) return null;
|
|
209
|
+
const root = rootSchemaPtr(doc, method, path, parsed);
|
|
210
|
+
const parent = root && walk(doc, root, parsed.steps.slice(0, -1));
|
|
211
|
+
if (!parent) return null;
|
|
212
|
+
return objectHolder(doc, parent);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function objectHolder(doc, ptr, depth = 0) {
|
|
216
|
+
const s = derefPtr(doc, ptr);
|
|
217
|
+
const node = s && get(doc, s);
|
|
218
|
+
if (!node || typeof node !== 'object' || depth > 12) return null;
|
|
219
|
+
if (node.properties || !node.allOf) return s;
|
|
220
|
+
// allOf: the last part that declares properties is the "own" part of a
|
|
221
|
+
// composed schema (allOf: [$ref Base, { properties: … }]).
|
|
222
|
+
for (let i = node.allOf.length - 1; i >= 0; i--) {
|
|
223
|
+
const part = get(doc, [...s, 'allOf', i]);
|
|
224
|
+
if (part && !part.$ref && part.properties) return [...s, 'allOf', i];
|
|
225
|
+
}
|
|
226
|
+
return objectHolder(doc, [...s, 'allOf', node.allOf.length - 1], depth + 1);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Every local $ref target reachable from `node` in `doc`, transitively (pointers). */
|
|
230
|
+
function collectRefs(doc, node, out = new Map()) {
|
|
231
|
+
if (!node || typeof node !== 'object') return out;
|
|
232
|
+
if (Array.isArray(node)) { node.forEach((n) => collectRefs(doc, n, out)); return out; }
|
|
233
|
+
if (typeof node.$ref === 'string') {
|
|
234
|
+
const ptr = refToPtr(node.$ref);
|
|
235
|
+
if (ptr && !out.has(node.$ref)) {
|
|
236
|
+
out.set(node.$ref, ptr);
|
|
237
|
+
collectRefs(doc, get(doc, ptr), out);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
for (const [k, v] of Object.entries(node)) if (k !== '$ref') collectRefs(doc, v, out);
|
|
241
|
+
return out;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Inlines local $refs (cycles cut at `depth`) — for validating sample payloads with ajv. */
|
|
245
|
+
function inline(doc, node, depth = 0) {
|
|
246
|
+
if (!node || typeof node !== 'object') return node;
|
|
247
|
+
if (Array.isArray(node)) return node.map((n) => inline(doc, n, depth));
|
|
248
|
+
if (typeof node.$ref === 'string') {
|
|
249
|
+
const ptr = refToPtr(node.$ref);
|
|
250
|
+
if (!ptr || depth > 8) return {};
|
|
251
|
+
return inline(doc, get(doc, ptr), depth + 1);
|
|
252
|
+
}
|
|
253
|
+
const out = {};
|
|
254
|
+
for (const [k, v] of Object.entries(node)) out[k] = inline(doc, v, depth);
|
|
255
|
+
return out;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
module.exports = {
|
|
259
|
+
HTTP_METHODS, REF_PREFIXES,
|
|
260
|
+
get, refToPtr, ptrToRef, derefPtr, operationPtr, parameterPtrs, findParameter,
|
|
261
|
+
requestSchemaPtr, responseSchemaPtr, parseField, rootSchemaPtr, propertyOwnerPtr, walk,
|
|
262
|
+
fieldPtr, parentObjectPtr, collectRefs, inline,
|
|
263
|
+
};
|