@skilldeck/migrate 0.1.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.
@@ -0,0 +1,464 @@
1
+ #!/usr/bin/env node
2
+ // migrate / contract-diff.mjs
3
+ //
4
+ // Classify the changes between two versions of an API contract as breaking, warning or safe.
5
+ //
6
+ // node contract-diff.mjs <old> <new> [--json] [--builtin]
7
+ // node contract-diff.mjs <spec> --base <git-ref> [--json] [--builtin]
8
+ //
9
+ // OpenAPI 3.x (JSON; YAML via oasdiff, python3+PyYAML or ruby), GraphQL SDL (.graphql/.gql),
10
+ // protobuf (.proto). Uses oasdiff / graphql-inspector / buf when installed, unless --builtin.
11
+ // Exit 0 when nothing breaks, 1 on breaking changes, 2 on bad usage.
12
+ // Zero dependencies. Node 20+.
13
+
14
+ import fs from 'node:fs'
15
+ import os from 'node:os'
16
+ import path from 'node:path'
17
+ import { spawnSync } from 'node:child_process'
18
+ import { pathToFileURL } from 'node:url'
19
+
20
+ const HELP = `contract-diff: breaking-change check for API contracts
21
+
22
+ node contract-diff.mjs <old> <new> [--json] [--builtin]
23
+ node contract-diff.mjs <spec> --base <git-ref> [--json] [--builtin]
24
+
25
+ --base REF compare <spec> at REF (e.g. main, origin/main, v1.4.0) with the working tree
26
+ --builtin skip oasdiff / graphql-inspector / buf even if installed
27
+ --json machine-readable findings (builtin checker only)
28
+
29
+ Formats: OpenAPI 3.x (.json, .yaml, .yml), GraphQL SDL (.graphql, .gql), protobuf (.proto).
30
+ `
31
+
32
+ const kindOf = (file) => (/\.(graphql|gql)$/i.test(file) ? 'graphql' : /\.proto$/i.test(file) ? 'proto' : 'openapi')
33
+
34
+ /** Collects findings as { level, where, message }. */
35
+ function sink() {
36
+ const list = []
37
+ const add = (level) => (where, message) => list.push({ level, where, message })
38
+ return { list, breaking: add('breaking'), warning: add('warning'), safe: add('safe') }
39
+ }
40
+
41
+ // ---------------------------------------------------------------------------
42
+ // OpenAPI
43
+ // ---------------------------------------------------------------------------
44
+
45
+ const METHODS = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace']
46
+
47
+ function deref(doc, node, seen = new Set()) {
48
+ let cur = node
49
+ while (cur && typeof cur.$ref === 'string' && cur.$ref.startsWith('#/')) {
50
+ if (seen.has(cur.$ref)) return {}
51
+ seen.add(cur.$ref)
52
+ cur = cur.$ref.slice(2).split('/').reduce((o, k) => o?.[k.replace(/~1/g, '/').replace(/~0/g, '~')], doc)
53
+ }
54
+ return cur ?? {}
55
+ }
56
+
57
+ /** Merge allOf branches into one schema so properties/required compare directly. */
58
+ function flatten(doc, schema, seen) {
59
+ const s = deref(doc, schema, new Set(seen))
60
+ if (!Array.isArray(s.allOf)) return s
61
+ const out = { ...s, properties: { ...s.properties }, required: [...(s.required ?? [])] }
62
+ delete out.allOf
63
+ for (const part of s.allOf) {
64
+ const p = flatten(doc, part, seen)
65
+ Object.assign(out.properties, p.properties)
66
+ out.required.push(...(p.required ?? []))
67
+ if (p.type && !out.type) out.type = p.type
68
+ }
69
+ return out
70
+ }
71
+
72
+ const types = (s) => new Set([].concat(s.type ?? []).filter((t) => t !== 'null'))
73
+ const nullable = (s) => s.nullable === true || [].concat(s.type ?? []).includes('null')
74
+
75
+ /**
76
+ * dir = 'request' (client sends it: new constraints break) or 'response'
77
+ * (client reads it: removals and loosened guarantees break).
78
+ */
79
+ function compareSchema(ctx, a0, b0, dir, where, depth = 0, seen = new Set()) {
80
+ if (depth > 20 || !a0 || !b0) return
81
+ const key = `${a0.$ref ?? ''}|${b0.$ref ?? ''}|${dir}`
82
+ if ((a0.$ref || b0.$ref) && seen.has(key)) return
83
+ const nextSeen = new Set(seen).add(key)
84
+ const a = flatten(ctx.a, a0, nextSeen)
85
+ const b = flatten(ctx.b, b0, nextSeen)
86
+ const { breaking, warning, safe } = ctx.out
87
+
88
+ const ta = types(a)
89
+ const tb = types(b)
90
+ if (ta.size && tb.size && [...ta].sort().join() !== [...tb].sort().join()) {
91
+ const widened = dir === 'request' && ta.has('integer') && tb.has('number')
92
+ const narrowed = dir === 'response' && ta.has('number') && tb.has('integer')
93
+ ;(widened || narrowed ? safe : breaking)(where, `type ${[...ta].join('|')} -> ${[...tb].join('|')}`)
94
+ }
95
+ if (dir === 'response' && !nullable(a) && nullable(b)) breaking(where, 'response value can now be null')
96
+ if (dir === 'request' && nullable(a) && !nullable(b)) breaking(where, 'request value can no longer be null')
97
+
98
+ if (Array.isArray(a.enum) || Array.isArray(b.enum)) {
99
+ const ea = new Set(a.enum ?? [])
100
+ const eb = new Set(b.enum ?? [])
101
+ const removed = [...ea].filter((v) => !eb.has(v))
102
+ const added = [...eb].filter((v) => !ea.has(v))
103
+ if (!a.enum && b.enum && dir === 'request') breaking(where, `now restricted to enum ${JSON.stringify(b.enum)}`)
104
+ if (removed.length) (dir === 'request' ? breaking : safe)(where, `enum value(s) removed: ${removed.join(', ')}`)
105
+ if (added.length && a.enum) (dir === 'response' ? warning : safe)(where, `enum value(s) added: ${added.join(', ')}${dir === 'response' ? ' (clients with exhaustive switches may fail)' : ''}`)
106
+ }
107
+
108
+ const pa = a.properties ?? {}
109
+ const pb = b.properties ?? {}
110
+ const ra = new Set(a.required ?? [])
111
+ const rb = new Set(b.required ?? [])
112
+ for (const name of Object.keys(pa)) {
113
+ const w = `${where}.${name}`
114
+ if (!(name in pb)) {
115
+ if (dir === 'response') breaking(w, 'property removed from response')
116
+ else (b.additionalProperties === false ? breaking : warning)(w, 'property removed from request (clients still sending it will be ignored or rejected)')
117
+ continue
118
+ }
119
+ if (dir === 'response' && ra.has(name) && !rb.has(name)) breaking(w, 'response property no longer required (may be absent)')
120
+ if (dir === 'request' && !ra.has(name) && rb.has(name)) breaking(w, 'request property became required')
121
+ compareSchema(ctx, pa[name], pb[name], dir, w, depth + 1, nextSeen)
122
+ }
123
+ for (const name of Object.keys(pb)) {
124
+ if (name in pa) continue
125
+ const w = `${where}.${name}`
126
+ if (dir === 'request' && rb.has(name)) breaking(w, 'new required request property')
127
+ else safe(w, `property added to ${dir}`)
128
+ }
129
+ if (a.items || b.items) compareSchema(ctx, a.items ?? {}, b.items ?? {}, dir, `${where}[]`, depth + 1, nextSeen)
130
+ }
131
+
132
+ function params(doc, pathItem, op) {
133
+ const map = new Map()
134
+ for (const p of [...(pathItem.parameters ?? []), ...(op.parameters ?? [])]) {
135
+ const r = deref(doc, p)
136
+ if (r.name) map.set(`${r.in}:${r.name}`, r)
137
+ }
138
+ return map
139
+ }
140
+
141
+ const firstSchema = (doc, content) => {
142
+ const c = deref(doc, content)
143
+ return c?.schema
144
+ }
145
+
146
+ export function diffOpenApi(a, b) {
147
+ const out = sink()
148
+ const ctx = { a, b, out }
149
+ const pathsA = a.paths ?? {}
150
+ const pathsB = b.paths ?? {}
151
+ for (const [p, itemA0] of Object.entries(pathsA)) {
152
+ const itemA = deref(a, itemA0)
153
+ if (!(p in pathsB)) { out.breaking(p, 'path removed'); continue }
154
+ const itemB = deref(b, pathsB[p])
155
+ for (const m of METHODS) {
156
+ if (!itemA[m]) continue
157
+ const where = `${m.toUpperCase()} ${p}`
158
+ if (!itemB[m]) { out.breaking(where, 'operation removed'); continue }
159
+ const opA = itemA[m]
160
+ const opB = itemB[m]
161
+ if (!opA.deprecated && opB.deprecated) out.warning(where, 'operation deprecated')
162
+
163
+ const qa = params(a, itemA, opA)
164
+ const qb = params(b, itemB, opB)
165
+ for (const [k, pa] of qa) {
166
+ const pb = qb.get(k)
167
+ const w = `${where} param ${k}`
168
+ if (!pb) { out.warning(w, 'parameter removed'); continue }
169
+ if (!pa.required && pb.required) out.breaking(w, 'parameter became required')
170
+ compareSchema(ctx, pa.schema ?? {}, pb.schema ?? {}, 'request', w)
171
+ }
172
+ for (const [k, pb] of qb) if (!qa.has(k)) (pb.required ? out.breaking : out.safe)(`${where} param ${k}`, pb.required ? 'new required parameter' : 'optional parameter added')
173
+
174
+ const bodyA = deref(a, opA.requestBody)
175
+ const bodyB = deref(b, opB.requestBody)
176
+ if (!opA.requestBody && opB.requestBody && bodyB.required) out.breaking(`${where} body`, 'request body now required')
177
+ if (opA.requestBody && opB.requestBody) {
178
+ if (!bodyA.required && bodyB.required) out.breaking(`${where} body`, 'request body became required')
179
+ for (const [ct, mediaA] of Object.entries(bodyA.content ?? {})) {
180
+ const mediaB = bodyB.content?.[ct]
181
+ if (!mediaB) { out.breaking(`${where} body ${ct}`, 'request content type no longer accepted'); continue }
182
+ compareSchema(ctx, firstSchema(a, mediaA) ?? {}, firstSchema(b, mediaB) ?? {}, 'request', `${where} body`)
183
+ }
184
+ }
185
+
186
+ const resA = opA.responses ?? {}
187
+ const resB = opB.responses ?? {}
188
+ for (const [code, rA0] of Object.entries(resA)) {
189
+ const w = `${where} ${code}`
190
+ if (!(code in resB)) { (/^2/.test(code) ? out.breaking : out.warning)(w, 'response status removed'); continue }
191
+ const rA = deref(a, rA0)
192
+ const rB = deref(b, resB[code])
193
+ for (const [ct, mediaA] of Object.entries(rA.content ?? {})) {
194
+ const mediaB = rB.content?.[ct]
195
+ if (!mediaB) { out.breaking(`${w} ${ct}`, 'response content type removed'); continue }
196
+ compareSchema(ctx, firstSchema(a, mediaA) ?? {}, firstSchema(b, mediaB) ?? {}, 'response', `${w} body`)
197
+ }
198
+ }
199
+ for (const code of Object.keys(resB)) if (!(code in resA)) out.safe(`${where} ${code}`, 'response status added')
200
+ }
201
+ for (const m of METHODS) if (itemB[m] && !itemA[m]) out.safe(`${m.toUpperCase()} ${p}`, 'operation added')
202
+ }
203
+ for (const p of Object.keys(pathsB)) if (!(p in pathsA)) out.safe(p, 'path added')
204
+ return out.list
205
+ }
206
+
207
+ // ---------------------------------------------------------------------------
208
+ // GraphQL SDL
209
+ // ---------------------------------------------------------------------------
210
+
211
+ function stripGraphql(src) {
212
+ return src.replace(/"""[\s\S]*?"""/g, '').replace(/"(?:[^"\\\n]|\\.)*"/g, '').replace(/#[^\n]*/g, '')
213
+ }
214
+
215
+ /** Parse SDL into { Name: { kind, fields: { f: { type, args: { a: { type, hasDefault } }, hasDefault } }, values, members } }. */
216
+ export function parseGraphql(src) {
217
+ const code = stripGraphql(src)
218
+ const types = {}
219
+ const re = /\b(?:extend\s+)?(type|interface|input|enum|union|scalar)\s+(\w+)[^{=\n]*(?:\{([^}]*)\}|=\s*([^\n]+))?/g
220
+ for (const m of code.matchAll(re)) {
221
+ const [, kind, name, body = '', union = ''] = m
222
+ const t = types[name] ?? (types[name] = { kind, fields: {}, values: [], members: [] })
223
+ if (kind === 'enum') t.values.push(...body.split(/[\s,]+/).map((v) => v.replace(/@\w+(\([^)]*\))?/g, '')).filter((v) => /^\w+$/.test(v)))
224
+ else if (kind === 'union') t.members.push(...union.split('|').map((s) => s.trim()).filter(Boolean))
225
+ else {
226
+ const fre = /(\w+)\s*(?:\(([^)]*)\))?\s*:\s*([\w![\]]+)(\s*=\s*[^\s,)@]+)?/g
227
+ for (const f of body.matchAll(fre)) {
228
+ const args = {}
229
+ for (const a of (f[2] ?? '').matchAll(/(\w+)\s*:\s*([\w![\]]+)(\s*=\s*[^\s,)@]+)?/g)) args[a[1]] = { type: a[2], hasDefault: !!a[3] }
230
+ t.fields[f[1]] = { type: f[3], args, hasDefault: !!f[4] }
231
+ }
232
+ }
233
+ }
234
+ return types
235
+ }
236
+
237
+ const required = (t) => t.endsWith('!')
238
+ const loosen = (a, b) => a.replace(/!/g, '') === b.replace(/!/g, '')
239
+
240
+ /** Output positions may tighten (T -> T!); input positions may loosen (T! -> T). */
241
+ function gqlTypeChange(out, where, from, to, position) {
242
+ if (from === to) return
243
+ if (loosen(from, to)) {
244
+ const tightened = (to.match(/!/g) ?? []).length > (from.match(/!/g) ?? []).length
245
+ if ((position === 'output') === tightened) return out.safe(where, `type ${from} -> ${to}`)
246
+ }
247
+ out.breaking(where, `type ${from} -> ${to}`)
248
+ }
249
+
250
+ export function diffGraphql(srcA, srcB) {
251
+ const out = sink()
252
+ const A = parseGraphql(srcA)
253
+ const B = parseGraphql(srcB)
254
+ for (const [name, ta] of Object.entries(A)) {
255
+ const tb = B[name]
256
+ if (!tb) { out.breaking(name, `${ta.kind} removed`); continue }
257
+ if (ta.kind !== tb.kind) { out.breaking(name, `kind ${ta.kind} -> ${tb.kind}`); continue }
258
+ if (ta.kind === 'enum') {
259
+ for (const v of ta.values) if (!tb.values.includes(v)) out.breaking(`${name}.${v}`, 'enum value removed')
260
+ for (const v of tb.values) if (!ta.values.includes(v)) out.warning(`${name}.${v}`, 'enum value added (clients with exhaustive switches may fail)')
261
+ continue
262
+ }
263
+ if (ta.kind === 'union') {
264
+ for (const v of ta.members) if (!tb.members.includes(v)) out.breaking(name, `union member ${v} removed`)
265
+ for (const v of tb.members) if (!ta.members.includes(v)) out.warning(name, `union member ${v} added`)
266
+ continue
267
+ }
268
+ const position = ta.kind === 'input' ? 'input' : 'output'
269
+ for (const [f, fa] of Object.entries(ta.fields)) {
270
+ const fb = tb.fields[f]
271
+ const w = `${name}.${f}`
272
+ if (!fb) { out.breaking(w, 'field removed'); continue }
273
+ gqlTypeChange(out, w, fa.type, fb.type, position)
274
+ for (const [arg, aa] of Object.entries(fa.args)) {
275
+ const ab = fb.args[arg]
276
+ if (!ab) out.breaking(`${w}(${arg})`, 'argument removed')
277
+ else gqlTypeChange(out, `${w}(${arg})`, aa.type, ab.type, 'input')
278
+ }
279
+ for (const [arg, ab] of Object.entries(fb.args)) {
280
+ if (fa.args[arg]) continue
281
+ ;(required(ab.type) && !ab.hasDefault ? out.breaking : out.safe)(`${w}(${arg})`, required(ab.type) && !ab.hasDefault ? 'new required argument' : 'optional argument added')
282
+ }
283
+ }
284
+ for (const [f, fb] of Object.entries(tb.fields)) {
285
+ if (ta.fields[f]) continue
286
+ const breaks = position === 'input' && required(fb.type) && !fb.hasDefault
287
+ ;(breaks ? out.breaking : out.safe)(`${name}.${f}`, breaks ? 'new required input field' : 'field added')
288
+ }
289
+ }
290
+ for (const name of Object.keys(B)) if (!A[name]) out.safe(name, `${B[name].kind} added`)
291
+ return out.list
292
+ }
293
+
294
+ // ---------------------------------------------------------------------------
295
+ // Protobuf
296
+ // ---------------------------------------------------------------------------
297
+
298
+ /** Parse .proto into { messages: { Qualified: { fields: { num: {name,type,label} }, reserved:Set } }, enums, rpcs }. */
299
+ export function parseProto(src) {
300
+ const code = src.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/[^\n]*/g, '')
301
+ const res = { messages: {}, enums: {}, rpcs: {} }
302
+ const stack = []
303
+ const re = /\b(message|enum|service|oneof)\s+(\w+)\s*\{|\}|\brpc\s+(\w+)\s*\(\s*(stream\s+)?([\w.]+)\s*\)\s*returns\s*\(\s*(stream\s+)?([\w.]+)\s*\)|\breserved\s+([^;]+);|\bmap\s*<\s*([\w.]+)\s*,\s*([\w.]+)\s*>\s+(\w+)\s*=\s*(\d+)|\b(repeated\s+|optional\s+|required\s+)?([\w.]+)\s+(\w+)\s*=\s*(\d+)|\b(\w+)\s*=\s*(-?\d+)|\{/g
304
+ for (const m of code.matchAll(re)) {
305
+ const top = stack[stack.length - 1]
306
+ if (m[1]) {
307
+ if (m[1] === 'oneof') { stack.push({ kind: 'oneof', owner: top }); continue }
308
+ const qname = [...stack.filter((s) => s.kind === 'message').map((s) => s.name), m[2]].join('.')
309
+ const entry = { kind: m[1], name: qname }
310
+ if (m[1] === 'message') res.messages[qname] = { fields: {}, reserved: new Set() }
311
+ if (m[1] === 'enum') res.enums[qname] = { values: {}, reserved: new Set() }
312
+ stack.push(entry)
313
+ } else if (m[0] === '}') stack.pop()
314
+ else if (m[0] === '{') stack.push({ kind: 'block', name: top?.name, owner: top }) // rpc bodies, option literals
315
+ else if (m[3]) res.rpcs[`${top?.name}.${m[3]}`] = `${m[4] ? 'stream ' : ''}${m[5]} -> ${m[6] ? 'stream ' : ''}${m[7]}`
316
+ else if (m[8]) {
317
+ const owner = top?.kind === 'enum' ? res.enums[top.name] : res.messages[top?.name]
318
+ if (!owner) continue
319
+ for (const part of m[8].split(',').map((s) => s.trim())) {
320
+ const range = part.match(/^(\d+)\s+to\s+(\d+|max)$/)
321
+ if (range) for (let n = Number(range[1]); n <= (range[2] === 'max' ? Number(range[1]) + 1000 : Number(range[2])); n++) owner.reserved.add(n)
322
+ else if (/^\d+$/.test(part)) owner.reserved.add(Number(part))
323
+ else owner.reserved.add(part.replace(/["']/g, ''))
324
+ }
325
+ } else if (m[11]) {
326
+ const msg = res.messages[(top?.kind === 'oneof' ? top.owner : top)?.name]
327
+ if (msg) msg.fields[m[12]] = { name: m[11], type: `map<${m[9]},${m[10]}>`, label: '' }
328
+ } else if (m[15]) {
329
+ const owner = top?.kind === 'oneof' ? top.owner : top
330
+ const msg = res.messages[owner?.name]
331
+ if (msg) msg.fields[m[16]] = { name: m[15], type: m[14], label: (m[13] ?? '').trim() }
332
+ } else if (m[17] && top?.kind === 'enum') res.enums[top.name].values[m[18]] = m[17]
333
+ }
334
+ return res
335
+ }
336
+
337
+ export function diffProto(srcA, srcB) {
338
+ const out = sink()
339
+ const A = parseProto(srcA)
340
+ const B = parseProto(srcB)
341
+ for (const [name, ma] of Object.entries(A.messages)) {
342
+ const mb = B.messages[name]
343
+ if (!mb) { out.breaking(name, 'message removed'); continue }
344
+ for (const [num, fa] of Object.entries(ma.fields)) {
345
+ const fb = mb.fields[num]
346
+ const w = `${name}.${fa.name} = ${num}`
347
+ if (!fb) {
348
+ if (mb.reserved.has(Number(num))) out.safe(w, 'field removed and its number reserved')
349
+ else out.breaking(w, 'field removed without `reserved` (the number can be reused with a different meaning)')
350
+ continue
351
+ }
352
+ if (fa.type !== fb.type) out.breaking(w, `type ${fa.type} -> ${fb.type}`)
353
+ if ((fa.label === 'repeated') !== (fb.label === 'repeated')) out.breaking(w, `label ${fa.label || 'singular'} -> ${fb.label || 'singular'}`)
354
+ if (fa.name !== fb.name) out.warning(w, `renamed to ${fb.name} (wire-compatible, breaks JSON and field masks)`)
355
+ }
356
+ for (const [num, fb] of Object.entries(mb.fields)) if (!ma.fields[num]) out.safe(`${name}.${fb.name} = ${num}`, 'field added')
357
+ }
358
+ for (const [name, ea] of Object.entries(A.enums)) {
359
+ const eb = B.enums[name]
360
+ if (!eb) { out.breaking(name, 'enum removed'); continue }
361
+ for (const [num, v] of Object.entries(ea.values)) if (!(num in eb.values) && !eb.reserved.has(Number(num))) out.breaking(`${name}.${v} = ${num}`, 'enum value removed without `reserved`')
362
+ }
363
+ for (const [rpc, sig] of Object.entries(A.rpcs)) {
364
+ if (!(rpc in B.rpcs)) out.breaking(rpc, 'rpc removed')
365
+ else if (B.rpcs[rpc] !== sig) out.breaking(rpc, `signature ${sig} -> ${B.rpcs[rpc]}`)
366
+ }
367
+ for (const name of Object.keys(B.messages)) if (!A.messages[name]) out.safe(name, 'message added')
368
+ for (const rpc of Object.keys(B.rpcs)) if (!(rpc in A.rpcs)) out.safe(rpc, 'rpc added')
369
+ return out.list
370
+ }
371
+
372
+ // ---------------------------------------------------------------------------
373
+ // Loading and CLI
374
+ // ---------------------------------------------------------------------------
375
+
376
+ const onPath = (bin) => spawnSync(process.platform === 'win32' ? 'where' : 'which', [bin], { encoding: 'utf8' }).status === 0
377
+
378
+ function yamlToJson(file) {
379
+ const py = spawnSync('python3', ['-c', 'import sys,json,yaml;json.dump(yaml.safe_load(open(sys.argv[1])),sys.stdout)', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
380
+ if (py.status === 0) return py.stdout
381
+ const rb = spawnSync('ruby', ['-ryaml', '-rjson', '-e', 'print JSON.generate(YAML.safe_load(File.read(ARGV[0]), aliases: true))', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
382
+ if (rb.status === 0) return rb.stdout
383
+ throw new Error(`cannot read YAML ${file}: install oasdiff, or python3 with PyYAML, or convert the spec to JSON`)
384
+ }
385
+
386
+ function loadOpenApi(file) {
387
+ const text = /\.ya?ml$/i.test(file) ? yamlToJson(file) : fs.readFileSync(file, 'utf8')
388
+ const doc = JSON.parse(text)
389
+ if (!doc.openapi && !doc.swagger) throw new Error(`${file} does not look like an OpenAPI document`)
390
+ if (doc.swagger) throw new Error(`${file} is Swagger 2.0; convert to OpenAPI 3 or use oasdiff`)
391
+ return doc
392
+ }
393
+
394
+ function external(kind, oldFile, newFile) {
395
+ if (kind === 'openapi' && onPath('oasdiff')) return ['oasdiff', ['breaking', oldFile, newFile, '--fail-on', 'ERR']]
396
+ if (kind === 'graphql' && onPath('graphql-inspector')) return ['graphql-inspector', ['diff', oldFile, newFile]]
397
+ if (kind === 'proto' && onPath('buf')) return ['buf', ['breaking', newFile, '--against', oldFile]]
398
+ return null
399
+ }
400
+
401
+ function fromGit(ref, file) {
402
+ const rel = path.relative(process.cwd(), path.resolve(file)).split(path.sep).join('/')
403
+ const r = spawnSync('git', ['show', `${ref}:./${rel}`], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 })
404
+ if (r.status !== 0) throw new Error(`git show ${ref}:${rel} failed: ${r.stderr.trim()}`)
405
+ const tmp = path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'contract-diff-')), `base${path.extname(file)}`)
406
+ fs.writeFileSync(tmp, r.stdout)
407
+ return tmp
408
+ }
409
+
410
+ function main(argv) {
411
+ const opts = { json: false, builtin: false, base: null, files: [] }
412
+ for (let i = 0; i < argv.length; i++) {
413
+ const a = argv[i]
414
+ if (a === '-h' || a === '--help') { process.stdout.write(HELP); return 0 }
415
+ else if (a === '--json') opts.json = true
416
+ else if (a === '--builtin') opts.builtin = true
417
+ else if (a === '--base') opts.base = argv[++i]
418
+ else if (a.startsWith('--')) { process.stderr.write(`contract-diff: unknown flag ${a}\n\n${HELP}`); return 2 }
419
+ else opts.files.push(a)
420
+ }
421
+ let oldFile
422
+ let newFile
423
+ try {
424
+ if (opts.base && opts.files.length === 1) { newFile = opts.files[0]; oldFile = fromGit(opts.base, newFile) }
425
+ else if (!opts.base && opts.files.length === 2) [oldFile, newFile] = opts.files
426
+ else { process.stderr.write(HELP); return 2 }
427
+ for (const f of [oldFile, newFile]) if (!fs.existsSync(f)) throw new Error(`not found: ${f}`)
428
+ } catch (err) { process.stderr.write(`contract-diff: ${err.message}\n`); return 2 }
429
+
430
+ const kind = kindOf(newFile)
431
+ const ext = !opts.builtin && !opts.json ? external(kind, oldFile, newFile) : null
432
+ if (ext) {
433
+ process.stdout.write(`Using ${ext[0]} (pass --builtin to use the bundled checker)\n\n`)
434
+ if (kind === 'proto') process.stdout.write('Note: buf compares modules; pass directories or a buf.yaml root if single files fail.\n\n')
435
+ const r = spawnSync(ext[0], ext[1], { stdio: 'inherit' })
436
+ return r.status ?? 1
437
+ }
438
+
439
+ let findings
440
+ try {
441
+ if (kind === 'graphql') findings = diffGraphql(fs.readFileSync(oldFile, 'utf8'), fs.readFileSync(newFile, 'utf8'))
442
+ else if (kind === 'proto') findings = diffProto(fs.readFileSync(oldFile, 'utf8'), fs.readFileSync(newFile, 'utf8'))
443
+ else findings = diffOpenApi(loadOpenApi(oldFile), loadOpenApi(newFile))
444
+ } catch (err) { process.stderr.write(`contract-diff: ${err.message}\n`); return 2 }
445
+
446
+ const by = (l) => findings.filter((f) => f.level === l)
447
+ const counts = { breaking: by('breaking').length, warning: by('warning').length, safe: by('safe').length }
448
+ if (opts.json) process.stdout.write(JSON.stringify({ kind, ...counts, findings }, null, 2) + '\n')
449
+ else {
450
+ for (const level of ['breaking', 'warning', 'safe']) {
451
+ const list = by(level)
452
+ if (!list.length) continue
453
+ process.stdout.write(`\n${level.toUpperCase()} (${list.length})\n`)
454
+ for (const f of level === 'safe' && list.length > 25 ? list.slice(0, 25) : list) process.stdout.write(` ${f.where}: ${f.message}\n`)
455
+ if (level === 'safe' && list.length > 25) process.stdout.write(` ... ${list.length - 25} more (use --json)\n`)
456
+ }
457
+ process.stdout.write(`\n${kind} (builtin): ${counts.breaking} breaking, ${counts.warning} warning, ${counts.safe} safe\n`)
458
+ }
459
+ return counts.breaking ? 1 : 0
460
+ }
461
+
462
+ if (process.argv[1] && import.meta.url === pathToFileURL(path.resolve(process.argv[1])).href) {
463
+ process.exitCode = main(process.argv.slice(2))
464
+ }
@@ -0,0 +1,102 @@
1
+ ---
2
+ name: dependency-upgrade
3
+ description: Use when upgrading a library, framework, runtime or toolchain version (npm, pnpm, yarn, pip, uv, poetry, cargo, go modules, gradle), bumping outdated or vulnerable dependencies, applying a migration guide or codemod, or fixing breakage that appeared after a lockfile change.
4
+ ---
5
+
6
+ # Dependency Upgrade
7
+
8
+ Upgrades fail in two ways: the agent guesses at breaking changes from memory, or it bumps everything in one commit so no failure can be traced to its cause. Your memory of a library's API is from your training data, and the version you are upgrading to may be newer than that. Read the changelog. Move one step at a time.
9
+
10
+ Announce: "Using dependency-upgrade to move <pkg> from <old> to <new>."
11
+
12
+ **Script location.** `${CLAUDE_SKILL_DIR}/scripts/upgrade-report.mjs`. If `CLAUDE_SKILL_DIR` is not set, use the directory containing this SKILL.md. Below, `$S` stands for the scripts folder. It needs Node 20+ and git. The JS subcommands also need npm or pnpm.
13
+
14
+ ## The Rule
15
+
16
+ ```
17
+ One breaking upgrade per commit, with its changelog read and its test suite green.
18
+ ```
19
+
20
+ ## Checklist
21
+
22
+ Copy this into your reply and tick it off:
23
+
24
+ ```
25
+ - [ ] 1. Baseline: tests, build and typecheck pass BEFORE any change (or failures recorded)
26
+ - [ ] 2. Inventory: what is behind, split into safe (minor/patch) and breaking (major)
27
+ - [ ] 3. Safe batch upgraded in one commit, suite green
28
+ - [ ] 4. Per major: changelog/migration guide READ from the source, not recalled
29
+ - [ ] 5. Per major: codemod run if one exists, then usages checked against breaking list
30
+ - [ ] 6. Per major: suite green, own commit
31
+ - [ ] 7. Lockfile diff reviewed: no unexpected majors pulled in transitively
32
+ ```
33
+
34
+ ## 1. Baseline
35
+
36
+ Run the project's test, build, typecheck and lint commands *before* you touch anything. If some already fail, write down exactly which ones. Otherwise every later failure is ambiguous. If there are no tests, say so to the user, and treat `build` plus `typecheck` plus starting the app as the minimum check.
37
+
38
+ ## 2. Inventory
39
+
40
+ ```bash
41
+ node $S/upgrade-report.mjs outdated # npm / pnpm: classifies, counts importers, links release notes
42
+ ```
43
+
44
+ For other ecosystems, use the commands in `references/ecosystems.md`.
45
+
46
+ - In 0.x versions, a minor bump counts as breaking. The script already treats it that way.
47
+ - If the user asked for one package, inventory only that package and its peer dependencies (e.g. `react` means `react-dom` and `@types/react` too).
48
+
49
+ ## 3. The safe batch
50
+
51
+ Upgrade every minor and patch update in one commit within the current ranges: `npm update`, `pnpm update`, `uv lock --upgrade`, `cargo update`. Run the full suite. If it goes red, bisect the batch by halves instead of guessing. A minor release that breaks you is a real finding, so report it.
52
+
53
+ ## 4. Read the changelog, for each major
54
+
55
+ Work through the majors one at a time. Start with the ones that have the fewest importers, since those diffs are small and build confidence. For each one:
56
+
57
+ 1. **Fetch the source.** Get the migration guide or upgrade guide, the release notes for *every* major between the current version and the target (`notes:` in the report), and `CHANGELOG.md` in the package repo.
58
+ 2. **Extract a breaking-changes list:** each removed or renamed API, changed default, dropped runtime version and new peer requirement.
59
+ 3. If you can't fetch the notes, stop and tell the user. Don't reconstruct them from memory.
60
+
61
+ ## 5. Apply
62
+
63
+ 1. **Codemod first**, if the guide names one (common ones are listed in `references/ecosystems.md`). Run it, then read its diff. Codemods miss dynamic usage.
64
+ 2. **Find every call site** of the APIs that changed:
65
+ ```bash
66
+ node $S/upgrade-report.mjs usages <pkg> # files, lines and the imported names
67
+ ```
68
+ Check every imported name against the breaking-changes list, and fix the ones that match.
69
+ 3. Bump the version, install, then run the typecheck (the fastest check), then the tests, then the build.
70
+ 4. For a large jump (e.g. 3 majors), go one major at a time if intermediate guides exist. Many guides assume you are coming from the version immediately before.
71
+
72
+ ## 6. Commit
73
+
74
+ Each major gets its own commit: `chore(deps): upgrade <pkg> <old> -> <new>`. The body lists the breaking changes you handled. If the suite can't go green, stop there. Revert that major, keep the ones that already passed, and report what blocks it. Don't pin workarounds or add `// @ts-ignore` to force it through.
75
+
76
+ ## 7. Audit the lockfile
77
+
78
+ ```bash
79
+ node $S/upgrade-report.mjs diff --base <branch-point>
80
+ ```
81
+
82
+ - Every major listed must be one you meant to upgrade. An unexpected major means a transitive range moved or a peer dependency was forced, so investigate it.
83
+ - Also check for duplicate copies of singleton packages (`npm ls <pkg>`, `pnpm why <pkg>`), e.g. two copies of `react`.
84
+
85
+ ## Report
86
+
87
+ ```
88
+ Upgraded: <pkg old -> new> (commit sha)... | Deferred: <pkg: reason>
89
+ Breaking changes handled: <list per pkg>
90
+ Verification: tests <n passed>, typecheck ok, build ok (this run)
91
+ Lockfile: <n> direct changes, no unexpected majors | <exceptions>
92
+ ```
93
+
94
+ ## Red flags
95
+
96
+ | Thought | Reality |
97
+ |---|---|
98
+ | "I know what changed in v5." | You know what changed as of your training data. Fetch the notes. |
99
+ | "Bump everything, then fix what breaks." | Twenty packages failing together can't be untangled. One major per commit. |
100
+ | "Tests pass, done." | Also check the typecheck, the build and the lockfile diff. Tests rarely cover config or bundling. |
101
+ | "Add `--legacy-peer-deps` / `--force`." | That hides a real incompatibility. Find which peer is out of range. |
102
+ | "Pin it back and move on." | That's fine as a decision, as long as you report it with the reason. It isn't fine done silently. |
@@ -0,0 +1,45 @@
1
+ # Ecosystem commands and known codemods
2
+
3
+ These tools change. Treat this file as a list of starting points, and confirm each command against the tool's current docs before relying on it.
4
+
5
+ ## Inventory, update, why
6
+
7
+ | Ecosystem | What's behind | Update within ranges | Why is X installed |
8
+ |---|---|---|---|
9
+ | npm | `npm outdated` | `npm update` | `npm ls <pkg>` / `npm explain <pkg>` |
10
+ | pnpm | `pnpm outdated` (`-r` in workspaces) | `pnpm update` (`--latest` crosses majors) | `pnpm why <pkg>` |
11
+ | yarn (berry) | `yarn upgrade-interactive` | `yarn up <pkg>` | `yarn why <pkg>` |
12
+ | bun | `bun outdated` | `bun update` | `bun pm ls` |
13
+ | uv | `uv pip list --outdated`, `uv tree --outdated` | `uv lock --upgrade` / `--upgrade-package <pkg>` | `uv tree --invert --package <pkg>` |
14
+ | poetry | `poetry show --outdated` | `poetry update` | `poetry show --tree` |
15
+ | pip | `pip list --outdated` | edit requirements, then `pip install -U` | `pipdeptree -r -p <pkg>` |
16
+ | cargo | `cargo outdated` (plugin) | `cargo update` | `cargo tree -i <crate>` |
17
+ | go | `go list -m -u all` | `go get -u ./...` then `go mod tidy` | `go mod why -m <mod>` |
18
+ | gradle | `gradle dependencyUpdates` (versions plugin) | edit the version catalog | `gradle dependencyInsight --dependency <x>` |
19
+
20
+ For the lockfile diff outside JS, use `git diff <base> -- uv.lock Cargo.lock go.sum poetry.lock` and read the changed versions.
21
+
22
+ ## Codemods and official upgraders
23
+
24
+ | Target | Command |
25
+ |---|---|
26
+ | Next.js | `npx @next/codemod@latest upgrade latest` (codemods alone: `npx @next/codemod <name> <path>`) |
27
+ | React 19 | `npx codemod@latest react/19/migration-recipe` and `npx types-react-codemod@latest preset-19 ./src` |
28
+ | Angular | `npx ng update @angular/core @angular/cli` |
29
+ | Tailwind CSS v4 | `npx @tailwindcss/upgrade` |
30
+ | ESLint 9 flat config | `npx @eslint/migrate-config .eslintrc.json` |
31
+ | Storybook | `npx storybook@latest upgrade` |
32
+ | Expo / React Native | `npx expo install --fix` (Expo); React Native Upgrade Helper (react-native-community.github.io/upgrade-helper) |
33
+ | Vue 2 -> 3 | the migration build (`@vue/compat`) first, then remove it |
34
+ | Python syntax | `pyupgrade --py311-plus`, or `ruff check --select UP --fix` |
35
+ | Django | `django-upgrade --target-version 5.2` |
36
+ | Rails | `bin/rails app:update`, then `config.load_defaults` one version at a time |
37
+ | Go | `go fix ./...`; for module major versions, update the import paths (`/v2`) |
38
+ | Java / Spring | OpenRewrite recipes (`rewrite-maven-plugin` / `rewrite-gradle-plugin`) |
39
+
40
+ ## Where release notes live
41
+
42
+ - The GitHub releases page: `https://github.com/<org>/<repo>/releases`.
43
+ - `CHANGELOG.md` in the repo, or in the package folder for monorepos, e.g. `packages/<name>/CHANGELOG.md`.
44
+ - A framework's own upgrade guide, which is usually more complete than release notes. For example, the "Upgrading" section of the Next.js, Django or Rails docs.
45
+ - `npm view <pkg> repository.url homepage` gives both links for any npm package.