specshield 3.4.15 → 3.4.17

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 CHANGED
@@ -1,5 +1,62 @@
1
1
  # SpecShield CLI changelog
2
2
 
3
+ ## Unreleased — a gate teams can leave blocking: `specshield gate`
4
+
5
+ ### Added
6
+
7
+ - **`specshield gate [spec]`** — the CI check. Compares the spec with the merge base of
8
+ the branch (never the base branch's tip or production), so changes merged since the
9
+ branch forked never fail an unrelated PR. Baseline from the CI event: GitHub
10
+ `pull_request`, `merge_group` (merge queue base), `push`; GitLab MR; Bitbucket PR;
11
+ else `origin`'s default branch; `--base` overrides. Shallow checkouts are fetched and
12
+ deepened as needed (`--no-fetch` to forbid). Writes a GitHub job summary and annotations.
13
+ - **Waivers** in `.specshield/waivers.yml`: change type, optional operation/field, and a
14
+ required owner, reason and expiry (≤ 90 days, `gate.maxWaiverDays`). Expired waivers stop
15
+ applying and say whose lapsed; invalid ones never apply; a waiver added in the PR that
16
+ matches nothing is flagged. `specshield waivers add` / `specshield waivers [list] [--check]`.
17
+ The legacy `ignore:` list still applies, and the gate says how to move it to a waiver.
18
+ - **Shadow mode** (`--shadow`, `gate.mode: shadow`): report what would have been blocked,
19
+ exit 0. `--upload` records each run for the dashboard's graduation report and prints its
20
+ headline ("Would have blocked 3 PRs — all 3 were real breaks. Safe to turn on blocking.").
21
+ - `gate.*` keys in `.specshield.yml`; `--usage` works as in `compare`.
22
+
23
+ ### Tested on real data
24
+
25
+ - Redocly/museum-openapi-example PR #18 (open, far behind `main`), depth-1 checkout from
26
+ GitHub: comparing with `main`'s tip reports 14 breaking changes, all from commits merged
27
+ after the branch forked; the gate found the merge base (the PR's original base) over
28
+ HTTPS in ~1 s and reported 0.
29
+
30
+
31
+ ## Unreleased — break → fix: `specshield fix`
32
+
33
+ ### Added
34
+
35
+ - **`specshield fix <base> <target>`** writes the non-breaking version of a breaking
36
+ change as minimal edits to the target spec (comments and layout kept): renamed fields
37
+ keep both names, removed things come back `deprecated` (`--sunset`), newly required
38
+ input becomes optional, type changes keep the old type, removed enum values return.
39
+ Every fix is verified by re-running the diff engine; one that leaves its break or adds
40
+ another is not applied. `--out`, `--write`, `--dry-run`, `--json`.
41
+ - **`--spring <dir> --package <pkg>`** generates a Spring Boot 3 version layer
42
+ (`ResponseBodyAdvice`/`RequestBodyAdvice`): old clients get the old JSON shape (renames,
43
+ scalar conversions, enum mappings, request defaults, list envelopes), each rewrite
44
+ checked on sample payloads against the old schema first. Compiled and tested in a Spring
45
+ Boot 3.2 and 3.5 app (`test-harness/spring-compat/verify.sh`).
46
+ - `compare` points at `specshield fix` when it finds breaking changes.
47
+ - `specshield deprecations` also honours `x-deprecated: true` (Swagger 2.0 schemas).
48
+
49
+ ### Tested on real data
50
+
51
+ - Kubernetes `swagger.json` v1.37.1 → master: 552 breaking changes, all fixed and verified
52
+ (7 s); an independent `compare` of v1.37.1 against the fixed spec reports 0.
53
+ - GitHub's REST API description, April → October 2026 (13 MB): 429 breaking changes, all
54
+ fixed and verified (22 s), independently re-checked. This run removed two kinds of
55
+ guesses: "renames" between unrelated fields that happened to be the only ones of a type
56
+ (`budget_type` → `expires_at`; now a rename needs a shared word), and enum "renames"
57
+ between single-value constants of `oneOf` variants that moved. A format-only change
58
+ (`integer` → `int64`) no longer suggests a new field.
59
+
3
60
  ## Unreleased — safe removal: deprecate → watch traffic drain → remove
4
61
 
5
62
  ### Added
package/README.md CHANGED
@@ -42,7 +42,7 @@ What the CLI does:
42
42
  - [vs. Alternatives](#vs-alternatives) · [Pricing](#pricing)
43
43
 
44
44
  **Commands — local & hosted compare**
45
- - [Local Compare](#local-compare) · [**Who does a change break? (usage-aware compare)**](#who-does-a-change-break--usage-aware-compare) · [**Safe removal: deprecate → drain → remove**](#safe-removal-deprecate--watch-traffic-drain--remove) · [Remote Compare](#remote-compare) · [Comparison History](#comparison-history) · [Share a Comparison](#share-a-comparison) · [GitHub App PR Checks](#github-app--pr-checks)
45
+ - [Local Compare](#local-compare) · [**Who does a change break? (usage-aware compare)**](#who-does-a-change-break--usage-aware-compare) · [**Safe removal: deprecate → drain → remove**](#safe-removal-deprecate--watch-traffic-drain--remove) · [**Break → fix: `specshield fix`**](#break--fix-generate-the-non-breaking-version) · [**CI gate: `specshield gate`**](#a-gate-you-can-leave-blocking-specshield-gate) · [Remote Compare](#remote-compare) · [Comparison History](#comparison-history) · [Share a Comparison](#share-a-comparison) · [GitHub App PR Checks](#github-app--pr-checks)
46
46
 
47
47
  **Governance — lint & gate**
48
48
  - [`specshield govern`](#governance--lint-a-spec-and-gate-the-pr)
@@ -434,6 +434,150 @@ and emails whoever uploaded. Only the report is sent — counts per client, neve
434
434
  specshield deprecations api/openapi.yaml --usage usage.json --upload --org acme --api payments
435
435
  ```
436
436
 
437
+ ## Break → fix: generate the non-breaking version
438
+
439
+ A blocked PR with no way forward is why teams switch gates off. `specshield fix` takes
440
+ the change that broke the gate and writes the **non-breaking version** of it — the
441
+ expand-and-contract edit you'd make by hand if you had the time.
442
+
443
+ ```bash
444
+ specshield fix api/openapi.base.yaml api/openapi.yaml
445
+ ```
446
+
447
+ ```text
448
+ SpecShield™ Fix — Payments API 1.0.0 → 2.0.0
449
+ 16 breaking changes · 14 fixed · 2 need a decision
450
+ Each fix was re-checked with the diff engine: it removes its breaking change and adds none.
451
+
452
+ ✔ `status` was renamed to `paymentStatus`: return both, `status` deprecated
453
+ POST /payments, GET /payments/{id}
454
+ → The server must return `status` with the same value as `paymentStatus`.
455
+ ✔ Make `currency` optional (default "EUR")
456
+ → Clients that don't send it get the default "EUR".
457
+ ✔ Keep `amount` as integer; return the string value as `amountV2`
458
+ ✔ Keep "ENABLED" as an allowed value of status (renamed to "ACTIVE")
459
+ ✔ Keep GET /payments/{id}/receipt, marked deprecated
460
+ …
461
+ ✖ NEEDS A DECISION (2)
462
+ ● Type of "responses.200" changed from "array" to "object" in GET /payments
463
+ the list moved into `data` — one schema can't describe both shapes, so this needs a version layer (--spring)
464
+
465
+ ✔ Wrote openapi.fixed.yaml (12 edits, comments and layout kept)
466
+ ```
467
+
468
+ | The change | The fix |
469
+ |---|---|
470
+ | Field or parameter renamed | keep both names, the old one `deprecated` (a rename needs the same type **and** a shared word in the name) |
471
+ | Field, parameter, operation, response or schema removed | restore it, `deprecated` (`--sunset 2027-03-31` adds `x-sunset`) — then `specshield deprecations` tracks it draining |
472
+ | Request field or parameter became required | optional again; the report says the server must default it |
473
+ | Field type changed | request: keep the old type · response: keep the old type, new type as `<field>V2` |
474
+ | Format only (`integer` → `int64`) | keep the old format |
475
+ | Enum value removed | keep it (a value renamed while others stay is recognised) |
476
+ | Body changed shape (list → `{ data: [...] }`) | no spec can say both → `--spring` |
477
+
478
+ - **Nothing unverified is written.** Every fix is applied and the diff engine re-run; a fix
479
+ that leaves its breaking change or adds another is dropped and listed with the reason.
480
+ Fixes that depend on each other (restoring a field brings back an enum value it needs)
481
+ are applied in rounds, and the result may not contain any break the target didn't have.
482
+ - The fix is written to `<target>.fixed.yaml` (or `--out`, or `--write` in place) as
483
+ minimal edits: comments, ordering and quoting of every untouched line are kept, so
484
+ `git diff` shows only the fix. `--dry-run` writes nothing; `--json` for scripts.
485
+ - Exit code `0` when everything was fixed, `1` when something still needs a decision.
486
+ - Each fix tells you what the **server** must do for the spec to be true — return the old
487
+ field too, accept the old value, default a missing one.
488
+
489
+ ### Spring Boot: old clients keep the old shape
490
+
491
+ Some changes can't be undone in the spec — a list wrapped in an envelope, a field that now
492
+ holds a string. `--spring` generates a Stripe-style **version layer** for a Spring Boot 3
493
+ service instead: the controllers speak only the new API; clients that don't send
494
+ `X-API-Version: 2.0.0` get the old JSON, and their old requests are upgraded on the way in.
495
+
496
+ ```bash
497
+ specshield fix base.yaml target.yaml --spring src/main/java --package com.acme.payments.compat
498
+ ```
499
+
500
+ - Generated: `ApiVersion_2_0_0.java` (this change's rewrites, as data) plus a small fixed
501
+ runtime — a `ResponseBodyAdvice` and a `RequestBodyAdvice` on Jackson. No changes to
502
+ your controllers.
503
+ - Rewrites: rename a field, convert a scalar's type (`"1250"` ↔ `1250`, only when the value
504
+ converts exactly), map an enum value, default a missing request field, unwrap a list from
505
+ its envelope — at any depth, inside arrays and maps.
506
+ - **Checked before it is generated**: for every operation, a sample payload of the new
507
+ shape is rewritten and validated against the *old* schema (and old requests against the
508
+ new one). A rewrite that can't produce the old shape is not generated — e.g. a required
509
+ field the new code no longer returns at all — and the report says why.
510
+ - Renames and enum mappings are inferred from the diff; they're marked
511
+ `/* inferred rename — check */` in the generated code.
512
+ - Clients with no version header are treated as on the old version, so existing
513
+ integrations keep working without a change. Set the header name with
514
+ `--version-header` or `specshield.compat.header`; a later `fix` run adds another
515
+ `ApiVersion_<v>` class and the layer chains them.
516
+ - Tested by compiling the generated code into a Spring Boot app and calling it as an old
517
+ and a new client (`test-harness/spring-compat/verify.sh`), on Spring Boot 3.2 and 3.5.
518
+
519
+ ## A gate you can leave blocking: `specshield gate`
520
+
521
+ `compare` diffs two files you choose. `gate` is the CI check: it decides **which** spec a change is judged against, which breaks the team has accepted, and whether failing is safe yet.
522
+
523
+ ```bash
524
+ specshield gate openapi.yaml # in CI, or locally on your branch
525
+ ```
526
+
527
+ **Right baseline, automatically.** The spec is compared with the commit your branch started from (the merge base), never with the base branch's current tip and never with what's deployed. Against the tip, a branch that is behind sees every change merged since it forked as "removed", and a break that already landed fails every unrelated PR until someone notices — the fastest way for a gate to lose the team's trust. The baseline comes from the CI event:
528
+
529
+ | Where | Baseline |
530
+ |---|---|
531
+ | GitHub `pull_request` | merge base of the PR's base commit and HEAD |
532
+ | GitHub `merge_group` (merge queue) | the queue's base, so each PR is judged only on its own change |
533
+ | GitHub `push` | the commit before the push |
534
+ | GitLab merge request | `CI_MERGE_REQUEST_DIFF_BASE_SHA` |
535
+ | Bitbucket PR / anywhere else | merge base with the destination / `origin`'s default branch |
536
+
537
+ `--base <ref>` overrides it. CI checkouts are usually shallow: the gate fetches the base commit and deepens history until the merge base is reachable (`--no-fetch` to forbid that, or use `fetch-depth: 0`). A PR that doesn't touch the spec passes without a diff.
538
+
539
+ **Waivers with an owner, a reason and an expiry.** Accepted breaks live in `.specshield/waivers.yml`, committed with the change they accept so the waiver is reviewed in the same PR:
540
+
541
+ ```bash
542
+ specshield waivers add response-field-removed --operation "GET /pets/{id}" --field legacy_id \
543
+ --owner @alice --reason "Mobile 4.2+ stopped reading it; older builds unsupported" --days 30 --ticket PET-12
544
+ specshield waivers # list: owner, reason, days left; --check exits 1 on expired/invalid ones
545
+ ```
546
+
547
+ ```yaml
548
+ waivers:
549
+ - change: response-field-removed # change type; "*" = any type on `operation`
550
+ operation: GET /pets/{id} # optional; "*" / "**" globs, "/pets/**" = any method
551
+ field: legacy_id # optional; name or dotted suffix
552
+ owner: "@alice"
553
+ reason: Mobile 4.2+ stopped reading it; older builds unsupported
554
+ created: "2026-10-27"
555
+ expires: "2026-11-26" # at most 90 days out (gate.maxWaiverDays)
556
+ ticket: PET-12
557
+ ```
558
+
559
+ Owner, reason (10+ characters) and expiry are required; a waiver missing one never applies. A waiver with an `operation` must cover **every** endpoint the change affects. After the expiry day the change blocks again and the output says whose waiver lapsed. Without `operation`/`field` a waiver covers every change of that type — a policy decision the expiry forces someone to revisit. The legacy `ignore:` list still works, but the gate reports what it skipped and how to move it to a waiver. The SpecShield GitHub App reads the same file with the same rules.
560
+
561
+ **Shadow mode, then graduate.** `--shadow` (or `gate.mode: shadow`) reports what the gate would have blocked and always exits 0. Add `--upload` (Team plan) and each run lands on **Dashboard → Gate Readiness**, which shows after two weeks: *"Would have blocked 3 PRs — all 3 were real breaks. Safe to turn on blocking."* A PR fixed after the warning, or accepted with a waiver, counts as a real break; anything merged with an unwaived break is yours to mark *real* or *false alarm*. Any false alarm, or any failure on a PR that didn't touch the spec, keeps it from graduating.
562
+
563
+ **Merge queues.** Add `merge_group` to the workflow triggers; the gate reports on the queue's commit with the queue's base as baseline.
564
+
565
+ ```yaml
566
+ # .github/workflows/api-gate.yml
567
+ on: [pull_request, merge_group]
568
+ jobs:
569
+ api-gate: # make this the required check
570
+ runs-on: ubuntu-latest
571
+ steps:
572
+ - uses: actions/checkout@v4 # shallow is fine; the gate fetches what it needs
573
+ - run: npx -y specshield@3 gate openapi.yaml --shadow --upload --org <org-key>
574
+ env: { SPECSHIELD_API_KEY: "${{ secrets.SPECSHIELD_API_KEY }}" }
575
+ ```
576
+
577
+ In GitHub Actions the gate also writes a job summary and annotations (`--no-summary` to skip). With `--usage usage.json`, breaking changes no client calls stop blocking ([usage-aware compare](#who-does-a-change-break--usage-aware-compare)). Exit codes: `1` when something blocks in blocking mode, `0` otherwise, `2` on errors. `--json` prints the full result: baseline, blocking and waived changes, and waiver-file health.
578
+
579
+ ---
580
+
437
581
  ## Remote Compare
438
582
 
439
583
  Sends your specs to SpecShield's hosted diff engine. Useful for keeping the
@@ -513,18 +657,13 @@ time from the dashboard.
513
657
 
514
658
  Install once at **Dashboard → GitHub Integration**, choose your repos, done. Every PR that touches the OpenAPI spec gets:
515
659
 
516
- - A GitHub check run (pass/fail) visible on the PR
517
- - A sticky PR comment with the full diff (breaking changes highlighted)
518
- - Configurable `failOnBreaking` per repository
660
+ - A GitHub check run visible on the PR, comparing the spec with the commit the branch started from (the merge base), not the base branch's moving tip
661
+ - A sticky PR comment with the breaking changes, any waived ones, and a ready-to-paste waiver
662
+ - Waivers read from `.specshield/waivers.yml` at the PR's head commit — the same file and rules as [`specshield gate`](#a-gate-you-can-leave-blocking-specshield-gate)
663
+ - Merge queue support: subscribe the App to **Merge group** events and the check runs on the queue's commit too
664
+ - **Shadow mode** for new repos: the check never fails, records what it would have blocked, and **Dashboard → Gate Readiness** tells you when it's safe to switch to blocking
519
665
 
520
- Configure per-repo via `.specshield.yml`:
521
-
522
- ```yaml
523
- github:
524
- specPath: api/openapi.yaml
525
- failOnBreaking: true
526
- commentOnPr: true
527
- ```
666
+ Spec path, waiver file and shadow/blocking mode are set per repository in **Dashboard → GitHub**.
528
667
 
529
668
  ---
530
669
 
@@ -1385,6 +1524,15 @@ severity: error # info | warning | error
1385
1524
  ignore:
1386
1525
  - "DELETE /admin removed" # match by substring; repeatable
1387
1526
 
1527
+ # CI gate (specshield gate; flags win).
1528
+ # gate:
1529
+ # spec: openapi.yaml
1530
+ # mode: shadow # shadow | blocking (default blocking)
1531
+ # waivers: .specshield/waivers.yml
1532
+ # maxWaiverDays: 90
1533
+ # upload: true # record runs for the readiness report (Team)
1534
+ # org: <org-key>
1535
+
1388
1536
  # Usage-aware compare (same as --usage …; see "Who does a change break?").
1389
1537
  # usage:
1390
1538
  # file: usage.json
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "specshield",
3
- "version": "3.4.15",
3
+ "version": "3.4.17",
4
4
  "description": "Contract compatibility testing for APIs — catch breaking OpenAPI changes before they reach your consumers, with can-i-deploy deploy gating and GitHub PR checks. (a.k.a. bidirectional contract testing.)",
5
5
  "main": "src/cli.js",
6
6
  "homepage": "https://specshield.io",
@@ -72,7 +72,8 @@
72
72
  "fs-extra": "^11.2.0",
73
73
  "js-yaml": "^4.1.0",
74
74
  "ora": "^5.4.1",
75
- "prompts": "^2.4.2"
75
+ "prompts": "^2.4.2",
76
+ "yaml": "^2.8.1"
76
77
  },
77
78
  "devDependencies": {
78
79
  "jest": "^29.7.0"
@@ -128,6 +128,13 @@ async function uploadDeprecationReport(server, apiToken, payload) {
128
128
  } catch (err) { throw apiError(err); }
129
129
  }
130
130
 
131
+ async function uploadGateRun(server, apiToken, payload) {
132
+ try {
133
+ const res = await buildClient(server, apiToken).post('/api/gate/runs', payload);
134
+ return res.data;
135
+ } catch (err) { throw apiError(err); }
136
+ }
137
+
131
138
  module.exports = {
132
139
  publishProviderSpec,
133
140
  publishConsumerContract,
@@ -139,4 +146,5 @@ module.exports = {
139
146
  listConsumerContracts,
140
147
  governanceGate,
141
148
  uploadDeprecationReport,
149
+ uploadGateRun,
142
150
  };
package/src/cli.js CHANGED
@@ -13,6 +13,9 @@ const shareCommand = require('./commands/share');
13
13
  const whoamiCommand = require('./commands/whoami');
14
14
  const usageCommand = require('./commands/usage');
15
15
  const deprecationsCommand = require('./commands/deprecations');
16
+ const fixCommand = require('./commands/fix');
17
+ const gateCommand = require('./commands/gate');
18
+ const waiversCommand = require('./commands/waivers');
16
19
 
17
20
  const program = new Command();
18
21
 
@@ -36,6 +39,9 @@ program.addCommand(shareCommand);
36
39
  program.addCommand(whoamiCommand);
37
40
  program.addCommand(usageCommand);
38
41
  program.addCommand(deprecationsCommand);
42
+ program.addCommand(fixCommand);
43
+ program.addCommand(gateCommand);
44
+ program.addCommand(waiversCommand);
39
45
 
40
46
  program.parseAsync(process.argv).catch((err) => {
41
47
  const logger = require('./utils/logger');
@@ -3,7 +3,6 @@
3
3
  const { Command } = require('commander');
4
4
  const chalk = require('chalk');
5
5
  const ora = require('ora');
6
- const path = require('path');
7
6
  const { loadSpec } = require('../core/loadSpec');
8
7
  const { parseSpec } = require('../core/parseSpec');
9
8
  const { normalizeSpec } = require('../core/normalizeSpec');
@@ -154,38 +153,8 @@ compare
154
153
  });
155
154
 
156
155
  async function applyUsage(result, base, options) {
157
- const { loadUsage } = require('../core/usage/usageStore');
158
- const { applyUsageImpact } = require('../core/usage/impact');
159
-
160
- const usage = await loadUsage(options.usage);
161
- const baseSpec = parseSpec(await loadSpec(base), base);
162
- const num = (value, flag, max = Infinity) => {
163
- const n = Number(value);
164
- if (!Number.isFinite(n) || n < 0 || n > max) throw new Error(`${flag} must be a number from 0 to ${max}, got "${value}"`);
165
- return n;
166
- };
167
- const minDays = num(options.usageMinDays, '--usage-min-days');
168
- const maxAgeDays = num(options.usageMaxAge, '--usage-max-age');
169
- const minCoverage = num(options.usageMinCoverage, '--usage-min-coverage', 100);
170
-
171
- const { result: annotated, meta } = applyUsageImpact(result, {
172
- usage,
173
- baseSpec,
174
- baseNorm: normalizeSpec(baseSpec),
175
- file: path.basename(options.usage),
176
- ignoreClients: options.usageIgnoreClient,
177
- minDays,
178
- maxAgeDays,
179
- minCoverage,
180
- downgrade: options.usageDowngrade,
181
- });
182
- if (!meta.trusted && meta.totalCalls > 0) {
183
- logger.warn(`None of the calls in ${options.usage} match an operation in ${base}. ` +
184
- 'Is it the right usage file? If the API is served under a prefix, re-import with --base-path.');
185
- }
186
- const { annotateDeprecations } = require('../core/usage/deprecations');
187
- const quietDays = num(options.usageQuietDays, '--usage-quiet-days');
188
- return { ...annotateDeprecations(annotated, baseSpec, { meta, quietDays }), usage: { ...meta, quietDays } };
156
+ const { applyUsage: join } = require('../core/usage/applyUsage');
157
+ return join(result, parseSpec(await loadSpec(base), base), options, base);
189
158
  }
190
159
 
191
160
  async function runLocalComparison(base, target, options, spinner) {
@@ -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;