runtime-pin-check 0.0.0-stage → 0.1.1

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/dist/cli.js ADDED
@@ -0,0 +1,2779 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ bindSources,
4
+ compareSources,
5
+ describeConstraint,
6
+ dockerTagConstraint,
7
+ groupByScope,
8
+ isFloatingAlias,
9
+ manifestRuntimesOf,
10
+ parseConstraint,
11
+ projectRootsOf,
12
+ scanFiles,
13
+ scopesOf,
14
+ toRange
15
+ } from "./chunk-TRO76P2I.js";
16
+
17
+ // src/cli.ts
18
+ import { realpathSync } from "fs";
19
+ import { readFile, stat, writeFile } from "fs/promises";
20
+ import { relative, resolve, sep } from "path";
21
+ import { pathToFileURL } from "url";
22
+ import { parseArgs } from "util";
23
+
24
+ // src/eol.ts
25
+ import semver from "semver";
26
+
27
+ // data/eol.json
28
+ var eol_default = {
29
+ schema: 1,
30
+ fetchedAt: "2026-11-25",
31
+ attribution: "EOL data from endoflife.date (https://endoflife.date), MIT License, \xA9 endoflife.date contributors, fetched 2026-11-25. Node.js LTS codenames from https://nodejs.org/download/release/index.json (Node.js, MIT License).",
32
+ sources: [
33
+ {
34
+ name: "endoflife.date",
35
+ url: "https://endoflife.date/api/v1/products/",
36
+ license: "MIT",
37
+ copyright: "\xA9 2020 endoflife.date contributors (https://github.com/endoflife-date/endoflife.date)",
38
+ usedFor: "release lines, end-of-life dates, LTS start dates and latest releases of nodejs, python and go"
39
+ },
40
+ {
41
+ name: "Node.js release index",
42
+ url: "https://nodejs.org/download/release/index.json",
43
+ license: "MIT (Node.js project; no separate terms page for the index was found)",
44
+ copyright: "\xA9 Node.js contributors",
45
+ usedFor: "LTS codenames (major version to name) only"
46
+ }
47
+ ],
48
+ products: {
49
+ node: [
50
+ {
51
+ cycle: "26",
52
+ eolFrom: "2029-04-30",
53
+ ltsFrom: "2026-10-28",
54
+ latest: "26.13.1",
55
+ codename: "lithium"
56
+ },
57
+ {
58
+ cycle: "25",
59
+ eolFrom: "2026-06-01",
60
+ ltsFrom: null,
61
+ latest: "25.9.0",
62
+ codename: null
63
+ },
64
+ {
65
+ cycle: "24",
66
+ eolFrom: "2028-04-30",
67
+ ltsFrom: "2025-10-28",
68
+ latest: "24.22.3",
69
+ codename: "krypton"
70
+ },
71
+ {
72
+ cycle: "23",
73
+ eolFrom: "2025-06-01",
74
+ ltsFrom: null,
75
+ latest: "23.11.1",
76
+ codename: null
77
+ },
78
+ {
79
+ cycle: "22",
80
+ eolFrom: "2027-04-30",
81
+ ltsFrom: "2024-10-29",
82
+ latest: "22.23.5",
83
+ codename: "jod"
84
+ },
85
+ {
86
+ cycle: "21",
87
+ eolFrom: "2024-06-01",
88
+ ltsFrom: null,
89
+ latest: "21.7.3",
90
+ codename: null
91
+ },
92
+ {
93
+ cycle: "20",
94
+ eolFrom: "2026-04-30",
95
+ ltsFrom: "2023-10-24",
96
+ latest: "20.20.2",
97
+ codename: "iron"
98
+ },
99
+ {
100
+ cycle: "19",
101
+ eolFrom: "2023-06-01",
102
+ ltsFrom: null,
103
+ latest: "19.9.0",
104
+ codename: null
105
+ },
106
+ {
107
+ cycle: "18",
108
+ eolFrom: "2025-04-30",
109
+ ltsFrom: "2022-10-25",
110
+ latest: "18.20.8",
111
+ codename: "hydrogen"
112
+ },
113
+ {
114
+ cycle: "17",
115
+ eolFrom: "2022-06-01",
116
+ ltsFrom: null,
117
+ latest: "17.9.1",
118
+ codename: null
119
+ },
120
+ {
121
+ cycle: "16",
122
+ eolFrom: "2023-09-11",
123
+ ltsFrom: "2021-10-26",
124
+ latest: "16.20.2",
125
+ codename: "gallium"
126
+ },
127
+ {
128
+ cycle: "15",
129
+ eolFrom: "2021-06-01",
130
+ ltsFrom: null,
131
+ latest: "15.14.0",
132
+ codename: null
133
+ },
134
+ {
135
+ cycle: "14",
136
+ eolFrom: "2023-04-30",
137
+ ltsFrom: "2020-10-27",
138
+ latest: "14.21.3",
139
+ codename: "fermium"
140
+ },
141
+ {
142
+ cycle: "13",
143
+ eolFrom: "2020-06-01",
144
+ ltsFrom: null,
145
+ latest: "13.14.0",
146
+ codename: null
147
+ },
148
+ {
149
+ cycle: "12",
150
+ eolFrom: "2022-04-30",
151
+ ltsFrom: "2019-10-21",
152
+ latest: "12.22.12",
153
+ codename: "erbium"
154
+ },
155
+ {
156
+ cycle: "11",
157
+ eolFrom: "2019-06-30",
158
+ ltsFrom: null,
159
+ latest: "11.15.0",
160
+ codename: null
161
+ },
162
+ {
163
+ cycle: "10",
164
+ eolFrom: "2021-04-30",
165
+ ltsFrom: "2018-10-30",
166
+ latest: "10.24.1",
167
+ codename: "dubnium"
168
+ },
169
+ {
170
+ cycle: "9",
171
+ eolFrom: "2018-06-30",
172
+ ltsFrom: null,
173
+ latest: "9.11.2",
174
+ codename: null
175
+ },
176
+ {
177
+ cycle: "8",
178
+ eolFrom: "2019-12-31",
179
+ ltsFrom: "2017-10-31",
180
+ latest: "8.17.0",
181
+ codename: "carbon"
182
+ },
183
+ {
184
+ cycle: "7",
185
+ eolFrom: "2017-06-30",
186
+ ltsFrom: null,
187
+ latest: "7.10.1",
188
+ codename: null
189
+ },
190
+ {
191
+ cycle: "6",
192
+ eolFrom: "2019-04-30",
193
+ ltsFrom: "2016-10-18",
194
+ latest: "6.17.1",
195
+ codename: "boron"
196
+ },
197
+ {
198
+ cycle: "5",
199
+ eolFrom: "2016-06-30",
200
+ ltsFrom: null,
201
+ latest: "5.12.0",
202
+ codename: null
203
+ },
204
+ {
205
+ cycle: "4",
206
+ eolFrom: "2018-04-30",
207
+ ltsFrom: "2015-10-01",
208
+ latest: "4.9.1",
209
+ codename: "argon"
210
+ },
211
+ {
212
+ cycle: "3",
213
+ eolFrom: null,
214
+ ltsFrom: null,
215
+ latest: "3.3.1",
216
+ codename: null
217
+ },
218
+ {
219
+ cycle: "2",
220
+ eolFrom: null,
221
+ ltsFrom: null,
222
+ latest: "2.5.0",
223
+ codename: null
224
+ },
225
+ {
226
+ cycle: "1",
227
+ eolFrom: null,
228
+ ltsFrom: null,
229
+ latest: "1.8.4",
230
+ codename: null
231
+ }
232
+ ],
233
+ python: [
234
+ {
235
+ cycle: "3.15",
236
+ eolFrom: "2031-10-31",
237
+ ltsFrom: null,
238
+ latest: "3.15.2"
239
+ },
240
+ {
241
+ cycle: "3.14",
242
+ eolFrom: "2030-10-31",
243
+ ltsFrom: null,
244
+ latest: "3.14.10"
245
+ },
246
+ {
247
+ cycle: "3.13",
248
+ eolFrom: "2029-10-31",
249
+ ltsFrom: null,
250
+ latest: "3.13.18"
251
+ },
252
+ {
253
+ cycle: "3.12",
254
+ eolFrom: "2028-10-31",
255
+ ltsFrom: null,
256
+ latest: "3.12.16"
257
+ },
258
+ {
259
+ cycle: "3.11",
260
+ eolFrom: "2027-10-31",
261
+ ltsFrom: null,
262
+ latest: "3.11.18"
263
+ },
264
+ {
265
+ cycle: "3.10",
266
+ eolFrom: "2026-10-01",
267
+ ltsFrom: null,
268
+ latest: "3.10.22"
269
+ },
270
+ {
271
+ cycle: "3.9",
272
+ eolFrom: "2025-10-31",
273
+ ltsFrom: null,
274
+ latest: "3.9.25"
275
+ },
276
+ {
277
+ cycle: "3.8",
278
+ eolFrom: "2024-10-07",
279
+ ltsFrom: null,
280
+ latest: "3.8.20"
281
+ },
282
+ {
283
+ cycle: "3.7",
284
+ eolFrom: "2023-06-27",
285
+ ltsFrom: null,
286
+ latest: "3.7.17"
287
+ },
288
+ {
289
+ cycle: "3.6",
290
+ eolFrom: "2021-12-23",
291
+ ltsFrom: null,
292
+ latest: "3.6.15"
293
+ },
294
+ {
295
+ cycle: "3.5",
296
+ eolFrom: "2020-09-30",
297
+ ltsFrom: null,
298
+ latest: "3.5.10"
299
+ },
300
+ {
301
+ cycle: "3.4",
302
+ eolFrom: "2019-03-18",
303
+ ltsFrom: null,
304
+ latest: "3.4.10"
305
+ },
306
+ {
307
+ cycle: "3.3",
308
+ eolFrom: "2017-09-29",
309
+ ltsFrom: null,
310
+ latest: "3.3.7"
311
+ },
312
+ {
313
+ cycle: "3.2",
314
+ eolFrom: "2016-02-20",
315
+ ltsFrom: null,
316
+ latest: "3.2.6"
317
+ },
318
+ {
319
+ cycle: "2.7",
320
+ eolFrom: "2020-01-01",
321
+ ltsFrom: null,
322
+ latest: "2.7.18"
323
+ },
324
+ {
325
+ cycle: "3.1",
326
+ eolFrom: "2012-04-09",
327
+ ltsFrom: null,
328
+ latest: "3.1.5"
329
+ },
330
+ {
331
+ cycle: "3.0",
332
+ eolFrom: "2009-06-27",
333
+ ltsFrom: null,
334
+ latest: "3.0.1"
335
+ },
336
+ {
337
+ cycle: "2.6",
338
+ eolFrom: "2013-10-29",
339
+ ltsFrom: null,
340
+ latest: "2.6.9"
341
+ },
342
+ {
343
+ cycle: "2.5",
344
+ eolFrom: "2011-05-26",
345
+ ltsFrom: null,
346
+ latest: "2.5.6"
347
+ },
348
+ {
349
+ cycle: "2.4",
350
+ eolFrom: "2008-12-19",
351
+ ltsFrom: null,
352
+ latest: "2.4.6"
353
+ },
354
+ {
355
+ cycle: "2.3",
356
+ eolFrom: "2008-03-11",
357
+ ltsFrom: null,
358
+ latest: "2.3.7"
359
+ },
360
+ {
361
+ cycle: "2.2",
362
+ eolFrom: "2003-05-30",
363
+ ltsFrom: null,
364
+ latest: "2.2.3"
365
+ },
366
+ {
367
+ cycle: "2.1",
368
+ eolFrom: "2002-04-09",
369
+ ltsFrom: null,
370
+ latest: "2.1.3"
371
+ }
372
+ ],
373
+ go: [
374
+ {
375
+ cycle: "1.27",
376
+ eolFrom: null,
377
+ ltsFrom: null,
378
+ latest: "1.27.4"
379
+ },
380
+ {
381
+ cycle: "1.26",
382
+ eolFrom: null,
383
+ ltsFrom: null,
384
+ latest: "1.26.11"
385
+ },
386
+ {
387
+ cycle: "1.25",
388
+ eolFrom: "2026-08-19",
389
+ ltsFrom: null,
390
+ latest: "1.25.14"
391
+ },
392
+ {
393
+ cycle: "1.24",
394
+ eolFrom: "2026-02-10",
395
+ ltsFrom: null,
396
+ latest: "1.24.13"
397
+ },
398
+ {
399
+ cycle: "1.23",
400
+ eolFrom: "2025-08-12",
401
+ ltsFrom: null,
402
+ latest: "1.23.12"
403
+ },
404
+ {
405
+ cycle: "1.22",
406
+ eolFrom: "2025-02-11",
407
+ ltsFrom: null,
408
+ latest: "1.22.12"
409
+ },
410
+ {
411
+ cycle: "1.21",
412
+ eolFrom: "2024-08-13",
413
+ ltsFrom: null,
414
+ latest: "1.21.13"
415
+ },
416
+ {
417
+ cycle: "1.20",
418
+ eolFrom: "2024-02-06",
419
+ ltsFrom: null,
420
+ latest: "1.20.14"
421
+ },
422
+ {
423
+ cycle: "1.19",
424
+ eolFrom: "2023-09-06",
425
+ ltsFrom: null,
426
+ latest: "1.19.13"
427
+ },
428
+ {
429
+ cycle: "1.18",
430
+ eolFrom: "2023-02-01",
431
+ ltsFrom: null,
432
+ latest: "1.18.10"
433
+ },
434
+ {
435
+ cycle: "1.17",
436
+ eolFrom: "2022-08-02",
437
+ ltsFrom: null,
438
+ latest: "1.17.13"
439
+ },
440
+ {
441
+ cycle: "1.16",
442
+ eolFrom: "2022-03-15",
443
+ ltsFrom: null,
444
+ latest: "1.16.15"
445
+ },
446
+ {
447
+ cycle: "1.15",
448
+ eolFrom: "2021-08-16",
449
+ ltsFrom: null,
450
+ latest: "1.15.15"
451
+ },
452
+ {
453
+ cycle: "1.14",
454
+ eolFrom: "2021-02-16",
455
+ ltsFrom: null,
456
+ latest: "1.14.15"
457
+ },
458
+ {
459
+ cycle: "1.13",
460
+ eolFrom: "2020-08-11",
461
+ ltsFrom: null,
462
+ latest: "1.13.15"
463
+ },
464
+ {
465
+ cycle: "1.12",
466
+ eolFrom: "2020-02-25",
467
+ ltsFrom: null,
468
+ latest: "1.12.17"
469
+ },
470
+ {
471
+ cycle: "1.11",
472
+ eolFrom: "2019-09-03",
473
+ ltsFrom: null,
474
+ latest: "1.11.13"
475
+ },
476
+ {
477
+ cycle: "1.10",
478
+ eolFrom: "2019-02-25",
479
+ ltsFrom: null,
480
+ latest: "1.10.8"
481
+ },
482
+ {
483
+ cycle: "1.9",
484
+ eolFrom: "2018-08-24",
485
+ ltsFrom: null,
486
+ latest: "1.9.7"
487
+ },
488
+ {
489
+ cycle: "1.8",
490
+ eolFrom: "2018-02-16",
491
+ ltsFrom: null,
492
+ latest: "1.8.7"
493
+ },
494
+ {
495
+ cycle: "1.7",
496
+ eolFrom: "2017-08-24",
497
+ ltsFrom: null,
498
+ latest: "1.7.6"
499
+ },
500
+ {
501
+ cycle: "1.6",
502
+ eolFrom: "2017-02-16",
503
+ ltsFrom: null,
504
+ latest: "1.6.4"
505
+ },
506
+ {
507
+ cycle: "1.5",
508
+ eolFrom: "2016-08-15",
509
+ ltsFrom: null,
510
+ latest: "1.5.4"
511
+ },
512
+ {
513
+ cycle: "1.4",
514
+ eolFrom: "2016-02-17",
515
+ ltsFrom: null,
516
+ latest: "1.4.3"
517
+ },
518
+ {
519
+ cycle: "1.3",
520
+ eolFrom: "2015-08-19",
521
+ ltsFrom: null,
522
+ latest: "1.3.3"
523
+ },
524
+ {
525
+ cycle: "1.2",
526
+ eolFrom: "2014-12-10",
527
+ ltsFrom: null,
528
+ latest: "1.2.2"
529
+ }
530
+ ]
531
+ }
532
+ };
533
+
534
+ // src/eol.ts
535
+ var EOL_SOON_DAYS = 90;
536
+ var RUNTIMES = ["node", "python", "go"];
537
+ var DATE = /^\d{4}-\d{2}-\d{2}$/;
538
+ function fail(message) {
539
+ throw new TypeError(`Invalid end-of-life snapshot: ${message}`);
540
+ }
541
+ function validDate(value) {
542
+ if (!DATE.test(value)) return false;
543
+ const d = /* @__PURE__ */ new Date(`${value}T00:00:00Z`);
544
+ return !Number.isNaN(d.getTime()) && d.toISOString().slice(0, 10) === value;
545
+ }
546
+ function optionalDate(value, where) {
547
+ if (value === null) return null;
548
+ if (typeof value !== "string" || !validDate(value)) fail(`${where} must be YYYY-MM-DD or null, got ${JSON.stringify(value)}`);
549
+ return value;
550
+ }
551
+ function text(value, where) {
552
+ if (typeof value !== "string" || value === "") fail(`${where} must be a non-empty string`);
553
+ return value;
554
+ }
555
+ function parseSnapshot(data) {
556
+ if (typeof data !== "object" || data === null) return fail("the file is not an object");
557
+ const d = data;
558
+ if (d.schema !== 1) fail(`schema must be 1, got ${JSON.stringify(d.schema)}`);
559
+ const fetchedAt = text(d.fetchedAt, "fetchedAt");
560
+ if (!validDate(fetchedAt)) fail(`fetchedAt must be YYYY-MM-DD, got "${fetchedAt}"`);
561
+ const attribution = text(d.attribution, "attribution");
562
+ if (!Array.isArray(d.sources) || d.sources.length === 0) fail("sources must list at least one source");
563
+ const sources = d.sources.map((s, i) => {
564
+ const o = typeof s === "object" && s !== null ? s : {};
565
+ return {
566
+ name: text(o.name, `sources[${i}].name`),
567
+ url: text(o.url, `sources[${i}].url`),
568
+ license: text(o.license, `sources[${i}].license`),
569
+ copyright: text(o.copyright, `sources[${i}].copyright`),
570
+ usedFor: text(o.usedFor, `sources[${i}].usedFor`)
571
+ };
572
+ });
573
+ const rawProducts = typeof d.products === "object" && d.products !== null ? d.products : {};
574
+ const products = {};
575
+ for (const runtime of RUNTIMES) {
576
+ const list2 = rawProducts[runtime];
577
+ if (!Array.isArray(list2) || list2.length === 0) fail(`products.${runtime} must list at least one release line`);
578
+ products[runtime] = list2.map((c, i) => {
579
+ const where = `products.${runtime}[${i}]`;
580
+ const o = typeof c === "object" && c !== null ? c : {};
581
+ const cycle = text(o.cycle, `${where}.cycle`);
582
+ if (!/^\d+(\.\d+)?$/.test(cycle)) fail(`${where}.cycle must look like 22 or 3.12, got "${cycle}"`);
583
+ const out = {
584
+ cycle,
585
+ eolFrom: optionalDate(o.eolFrom, `${where}.eolFrom`),
586
+ ltsFrom: optionalDate(o.ltsFrom, `${where}.ltsFrom`),
587
+ latest: o.latest === null || typeof o.latest === "string" ? o.latest ?? null : fail(`${where}.latest must be a string or null`)
588
+ };
589
+ if (o.codename !== void 0) {
590
+ if (o.codename !== null && typeof o.codename !== "string") fail(`${where}.codename must be a string or null`);
591
+ out.codename = o.codename;
592
+ }
593
+ return out;
594
+ });
595
+ }
596
+ return { schema: 1, fetchedAt, attribution, sources, products };
597
+ }
598
+ var bundled;
599
+ function bundledSnapshot() {
600
+ bundled ??= parseSnapshot(eol_default);
601
+ return bundled;
602
+ }
603
+ function checkDate(input) {
604
+ if (input === void 0) return (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
605
+ if (!validDate(input)) throw new RangeError(`--date must be a real date as YYYY-MM-DD, got "${input}"`);
606
+ return input;
607
+ }
608
+ function addDays(date, days) {
609
+ const d = /* @__PURE__ */ new Date(`${date}T00:00:00Z`);
610
+ d.setUTCDate(d.getUTCDate() + days);
611
+ return d.toISOString().slice(0, 10);
612
+ }
613
+ function cycleRange(cycle) {
614
+ const parts = cycle.split(".");
615
+ const major = Number(parts[0]);
616
+ if (parts.length === 1) return `>=${major}.0.0 <${major + 1}.0.0-0`;
617
+ const minor = Number(parts[1]);
618
+ return `>=${major}.${minor}.0 <${major}.${minor + 1}.0-0`;
619
+ }
620
+ function newestBound(cycles) {
621
+ let best = "0.0.0";
622
+ for (const c of cycles) {
623
+ const upper = cycleRange(c.cycle).split(" <")[1]?.replace(/-0$/, "") ?? "0.0.0";
624
+ if (semver.gt(upper, best)) best = upper;
625
+ }
626
+ return best;
627
+ }
628
+ function byCycleDesc(a, b) {
629
+ return semver.rcompare(semver.coerce(a.cycle) ?? "0.0.0", semver.coerce(b.cycle) ?? "0.0.0");
630
+ }
631
+ function createAliasResolver(snapshot = bundledSnapshot(), date = checkDate()) {
632
+ const lts = snapshot.products.node.filter((c) => c.ltsFrom !== null && c.ltsFrom <= date).sort(byCycleDesc);
633
+ return (runtime, alias) => {
634
+ if (runtime !== "node") return void 0;
635
+ const a = alias.toLowerCase();
636
+ let line;
637
+ if (a === "lts/*" || a === "lts") line = lts[0];
638
+ else {
639
+ const back = /^lts\/-(\d+)$/.exec(a);
640
+ if (back) line = lts[Number(back[1])];
641
+ else {
642
+ const name = /^lts\/([a-z][a-z-]*)$/.exec(a)?.[1];
643
+ if (name) line = snapshot.products.node.find((c) => c.codename === name);
644
+ }
645
+ }
646
+ return line ? cycleRange(line.cycle) : void 0;
647
+ };
648
+ }
649
+ var SEVERITY = { EOL_RUNTIME: "warning", EOL_SOON: "info" };
650
+ function ref(s) {
651
+ return { file: s.file, line: s.line, raw: s.raw, constraint: s.constraint };
652
+ }
653
+ function list(cycles) {
654
+ const names = cycles.map((c) => c.cycle);
655
+ return names.length <= 4 ? names.join(", ") : `${names.slice(0, 4).join(", ")} and ${names.length - 4} more`;
656
+ }
657
+ function allowedRange(source, resolve2) {
658
+ const c = source.constraint;
659
+ if (c.kind === "unknown") return void 0;
660
+ if (c.kind === "alias") {
661
+ if (isFloatingAlias(c.alias)) return void 0;
662
+ const range2 = resolve2(source.runtime, c.alias);
663
+ return range2 && semver.validRange(range2) ? range2 : void 0;
664
+ }
665
+ const range = toRange(c);
666
+ return range !== void 0 && semver.validRange(range) ? range : void 0;
667
+ }
668
+ function judge(source, range, cycles, date) {
669
+ if (semver.intersects(range, `>=${newestBound(cycles)}`)) return void 0;
670
+ const allowed = cycles.filter((c) => semver.intersects(range, cycleRange(c.cycle))).sort(byCycleDesc);
671
+ if (allowed.length === 0) return void 0;
672
+ const pin = `${source.runtime} ${describeConstraint(source.constraint)}`;
673
+ const where = `${source.file}:${source.line}`;
674
+ const ended = (c) => c.eolFrom !== null && c.eolFrom <= date;
675
+ if (allowed.every(ended)) {
676
+ const last = allowed.map((c) => c.eolFrom).sort().at(-1);
677
+ const what = allowed.length === 1 ? `${source.runtime} ${allowed[0].cycle} reached end-of-life on ${last}` : `every ${source.runtime} line it allows (${list(allowed)}) is past end-of-life; the newest of them ended on ${last}`;
678
+ return { code: "EOL_RUNTIME", message: `${where} pins ${pin} ("${source.raw}"): ${what} (check date ${date}).` };
679
+ }
680
+ if (allowed.every((c) => c.eolFrom !== null)) {
681
+ const last = allowed.map((c) => c.eolFrom).sort().at(-1);
682
+ const limit = addDays(date, EOL_SOON_DAYS);
683
+ if (last <= limit) {
684
+ const what = allowed.length === 1 ? `${source.runtime} ${allowed[0].cycle} reaches end-of-life on ${last}` : `the newest ${source.runtime} line it allows reaches end-of-life on ${last}`;
685
+ return { code: "EOL_SOON", message: `${where} pins ${pin} ("${source.raw}"): ${what}, within ${EOL_SOON_DAYS} days of the check date ${date}.` };
686
+ }
687
+ }
688
+ return void 0;
689
+ }
690
+ function eolFindings(sources, roots = ["."], options = {}) {
691
+ const snapshot = options.snapshot ?? bundledSnapshot();
692
+ const date = checkDate(options.date);
693
+ const resolve2 = createAliasResolver(snapshot, date);
694
+ const found = /* @__PURE__ */ new Map();
695
+ for (const source of sources) {
696
+ const range = allowedRange(source, resolve2);
697
+ if (range === void 0) continue;
698
+ const verdict = judge(source, range, snapshot.products[source.runtime], date);
699
+ if (!verdict) continue;
700
+ const key = `${verdict.code}\0${source.runtime}\0${source.file}:${source.line}\0${source.raw}`;
701
+ const existing = found.get(key);
702
+ const scopes = scopesOf(source, roots);
703
+ if (existing) {
704
+ for (const s of scopes) if (!existing.scopes.includes(s)) existing.scopes.push(s);
705
+ continue;
706
+ }
707
+ found.set(key, {
708
+ code: verdict.code,
709
+ severity: SEVERITY[verdict.code],
710
+ runtime: source.runtime,
711
+ sources: [ref(source)],
712
+ scopes: [...scopes],
713
+ message: verdict.message
714
+ });
715
+ }
716
+ const order = { error: 0, warning: 1, info: 2 };
717
+ const out = [...found.values()];
718
+ for (const f of out) f.scopes.sort();
719
+ return out.sort(
720
+ (a, b) => order[a.severity] - order[b.severity] || (a.sources[0]?.file ?? "").localeCompare(b.sources[0]?.file ?? "") || (a.sources[0]?.line ?? 0) - (b.sources[0]?.line ?? 0) || a.code.localeCompare(b.code)
721
+ );
722
+ }
723
+
724
+ // src/extract/shared/yaml-util.ts
725
+ import { LineCounter, parseAllDocuments, parseDocument, isAlias, isMap, isScalar, isSeq, Scalar } from "yaml";
726
+ function loadYamlAll(text2) {
727
+ try {
728
+ const lineCounter = new LineCounter();
729
+ const docs = parseAllDocuments(text2, { lineCounter, prettyErrors: false, strict: false, uniqueKeys: false, merge: true });
730
+ const list2 = Array.isArray(docs) ? docs : [docs];
731
+ return list2.map((doc) => ({
732
+ doc,
733
+ text: text2,
734
+ pos(offset) {
735
+ const p = lineCounter.linePos(offset);
736
+ return { line: p.line, column: p.col };
737
+ }
738
+ }));
739
+ } catch {
740
+ return void 0;
741
+ }
742
+ }
743
+ function resolveNode(y, node) {
744
+ let n = node;
745
+ for (let i = 0; i < 8 && isAlias(n); i++) n = n.resolve(y.doc);
746
+ return n;
747
+ }
748
+ function scalarText(y, node) {
749
+ const n = resolveNode(y, node);
750
+ if (!isScalar(n)) return void 0;
751
+ const sc = n;
752
+ const range = sc.range;
753
+ if (!range) return void 0;
754
+ const { line, column } = y.pos(range[0]);
755
+ const type = sc.type;
756
+ const quoted = type === Scalar.QUOTE_DOUBLE || type === Scalar.QUOTE_SINGLE;
757
+ if (type === Scalar.BLOCK_FOLDED || type === Scalar.BLOCK_LITERAL) {
758
+ return { text: String(sc.value ?? "").replace(/\n$/, ""), quoted: false, line, column };
759
+ }
760
+ const raw = y.text.slice(range[0], range[1]);
761
+ const inner = quoted ? raw.slice(1, -1) : raw;
762
+ return { text: quoted ? String(sc.value ?? inner) : inner.trim(), quoted, line, column: quoted ? column + 1 : column };
763
+ }
764
+ function getPair(y, map, key) {
765
+ const m = resolveNode(y, map);
766
+ if (!isMap(m)) return void 0;
767
+ const pairs = m.items;
768
+ for (const pair of pairs) {
769
+ const k = scalarKey(pair.key);
770
+ if (k === key) {
771
+ const kn = pair.key;
772
+ const range = kn && kn.range;
773
+ const p = range ? y.pos(range[0]) : { line: 1, column: 1 };
774
+ return { value: pair.value, line: p.line, column: p.column };
775
+ }
776
+ }
777
+ for (const pair of pairs) {
778
+ if (scalarKey(pair.key) !== "<<") continue;
779
+ const v = resolveNode(y, pair.value);
780
+ const targets = isSeq(v) ? v.items : [v];
781
+ for (const t of targets) {
782
+ const found = getPair(y, t, key);
783
+ if (found) return found;
784
+ }
785
+ }
786
+ return void 0;
787
+ }
788
+ function scalarKey(key) {
789
+ if (isScalar(key)) {
790
+ const v = key.value;
791
+ return typeof v === "symbol" ? "<<" : String(v);
792
+ }
793
+ return void 0;
794
+ }
795
+ function entries(y, map) {
796
+ const m = resolveNode(y, map);
797
+ if (!isMap(m)) return [];
798
+ const out = [];
799
+ for (const pair of m.items) {
800
+ const key = scalarKey(pair.key);
801
+ if (key === void 0 || key === "<<") continue;
802
+ const kn = pair.key;
803
+ const p = kn.range ? y.pos(kn.range[0]) : { line: 1, column: 1 };
804
+ out.push({ key, value: pair.value, line: p.line, column: p.column });
805
+ }
806
+ return out;
807
+ }
808
+ function items(y, seq) {
809
+ const s = resolveNode(y, seq);
810
+ return isSeq(s) ? s.items : [];
811
+ }
812
+
813
+ // src/extract/shared/imageref.ts
814
+ function splitImageRef(ref2) {
815
+ let rest = ref2;
816
+ let digest;
817
+ const at = rest.indexOf("@");
818
+ if (at >= 0) {
819
+ digest = rest.slice(at + 1);
820
+ rest = rest.slice(0, at);
821
+ }
822
+ const colon = rest.lastIndexOf(":");
823
+ const tagColon = colon > rest.lastIndexOf("/") ? colon : -1;
824
+ const out = { image: tagColon >= 0 ? rest.slice(0, tagColon) : rest };
825
+ if (tagColon >= 0) out.tag = rest.slice(tagColon + 1);
826
+ if (digest !== void 0 && digest !== "") out.digest = digest;
827
+ return out;
828
+ }
829
+
830
+ // src/extract/shared/dockerfile.ts
831
+ function logicalLines(text2) {
832
+ const physical = text2.split(/\r?\n/);
833
+ let escape = "\\";
834
+ for (const l of physical) {
835
+ const m = /^\s*#\s*([A-Za-z]+)\s*=\s*(\S+)\s*$/.exec(l);
836
+ if (!m) break;
837
+ if (m[1].toLowerCase() === "escape" && (m[2] === "`" || m[2] === "\\")) escape = m[2];
838
+ }
839
+ const out = [];
840
+ for (let i = 0; i < physical.length; i++) {
841
+ const raw = physical[i];
842
+ if (/^\s*#/.test(raw) || raw.trim() === "") continue;
843
+ const firstColumn = raw.length - raw.trimStart().length + 1;
844
+ let joined = raw.trimStart();
845
+ const startLine = i + 1;
846
+ let continuing = joined.trimEnd().endsWith(escape);
847
+ while (continuing && i + 1 < physical.length) {
848
+ if (joined.trimEnd().endsWith(escape)) joined = joined.trimEnd().slice(0, -1);
849
+ i++;
850
+ const next = physical[i];
851
+ if (/^\s*#/.test(next)) {
852
+ joined += " ";
853
+ continue;
854
+ }
855
+ joined += ` ${next.trim()}`;
856
+ continuing = next.trimEnd().endsWith(escape);
857
+ }
858
+ if (joined.trimEnd().endsWith(escape)) joined = joined.trimEnd().slice(0, -1);
859
+ out.push({ text: joined.trim(), line: startLine, firstColumn });
860
+ }
861
+ return out;
862
+ }
863
+ function unquote(v) {
864
+ const m = /^(["'])(.*)\1$/.exec(v);
865
+ return m ? m[2] : v;
866
+ }
867
+ function substitute(s, args) {
868
+ let arg;
869
+ const text2 = s.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?-)([^}]*))?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (whole, braced, op, fallback, bare) => {
870
+ const name = braced ?? bare;
871
+ const known = args.get(name);
872
+ if (known && known.value !== void 0 && known.value !== "") {
873
+ arg ??= { name, line: known.line };
874
+ return known.value;
875
+ }
876
+ if (op !== void 0 && fallback !== void 0) return fallback;
877
+ return whole;
878
+ });
879
+ return arg ? { text: text2, arg } : { text: text2 };
880
+ }
881
+ function parseDockerfile(text2) {
882
+ try {
883
+ const out = [];
884
+ const args = /* @__PURE__ */ new Map();
885
+ let seenFrom = false;
886
+ for (const ins of logicalLines(text2)) {
887
+ const word = /^([A-Za-z]+)\b/.exec(ins.text);
888
+ const keyword = word ? word[1].toUpperCase() : "";
889
+ if (keyword === "ARG" && !seenFrom) {
890
+ for (const tok of ins.text.slice(3).trim().split(/\s+/)) {
891
+ const eq = tok.indexOf("=");
892
+ if (eq < 0) args.set(tok, { value: void 0, line: ins.line });
893
+ else args.set(tok.slice(0, eq), { value: unquote(tok.slice(eq + 1)), line: ins.line });
894
+ }
895
+ continue;
896
+ }
897
+ if (keyword !== "FROM") continue;
898
+ seenFrom = true;
899
+ const tokens = ins.text.slice(4).trim().split(/\s+/).filter((t) => t !== "");
900
+ let i = 0;
901
+ while (i < tokens.length && tokens[i].startsWith("--")) i++;
902
+ const rawRef = tokens[i];
903
+ if (rawRef === void 0) continue;
904
+ const as = (tokens[i + 1] ?? "").toUpperCase() === "AS" ? tokens[i + 2] : void 0;
905
+ const sub = substitute(rawRef, args);
906
+ const parts = splitImageRef(sub.text);
907
+ const column = ins.firstColumn + ins.text.indexOf(rawRef);
908
+ const from = { image: parts.image, line: ins.line, column, raw: rawRef };
909
+ if (parts.tag !== void 0) from.tag = parts.tag;
910
+ if (parts.digest !== void 0) from.digest = parts.digest;
911
+ if (as !== void 0) from.stage = as;
912
+ if (sub.arg) from.arg = sub.arg;
913
+ out.push(from);
914
+ }
915
+ return out;
916
+ } catch {
917
+ return [];
918
+ }
919
+ }
920
+
921
+ // src/extract/shared/gitlab.ts
922
+ function imageOf(y, node, job) {
923
+ const direct = scalarText(y, node);
924
+ const target = direct ?? scalarText(y, getPair(y, node, "name")?.value);
925
+ if (!target || target.text === "") return void 0;
926
+ const parts = splitImageRef(target.text);
927
+ const out = { image: parts.image, line: target.line, column: target.column, job, raw: target.text };
928
+ if (parts.tag !== void 0) out.tag = parts.tag;
929
+ if (parts.digest !== void 0) out.digest = parts.digest;
930
+ return out;
931
+ }
932
+ function parseGitlabCi(text2) {
933
+ try {
934
+ return (loadYamlAll(text2) ?? []).flatMap((y) => parseGitlabDocument(y));
935
+ } catch {
936
+ return [];
937
+ }
938
+ }
939
+ function parseGitlabDocument(y) {
940
+ try {
941
+ const root = resolveNode(y, y.doc.contents);
942
+ if (!isMap(root)) return [];
943
+ const out = [];
944
+ const top = getPair(y, root, "image");
945
+ if (top) {
946
+ const found = imageOf(y, top.value, "default");
947
+ if (found) out.push(found);
948
+ }
949
+ for (const { key, value } of entries(y, root)) {
950
+ if (key === "image") continue;
951
+ if (key === "default") {
952
+ const found2 = imageOf(y, getPair(y, value, "image")?.value, "default");
953
+ if (found2) out.push(found2);
954
+ continue;
955
+ }
956
+ if (["stages", "variables", "include", "workflow", "services", "cache", "before_script", "after_script"].includes(key)) continue;
957
+ const pair = getPair(y, value, "image");
958
+ if (!pair) continue;
959
+ const found = imageOf(y, pair.value, key);
960
+ if (found) out.push(found);
961
+ }
962
+ return out;
963
+ } catch {
964
+ return [];
965
+ }
966
+ }
967
+
968
+ // src/extract/shared/images.ts
969
+ var LIBRARY_HOSTS = ["docker.io", "index.docker.io", "registry-1.docker.io", "registry.hub.docker.com", "mirror.gcr.io", "public.ecr.aws/docker"];
970
+ var IMAGES = {
971
+ node: ["node", "cimg/node", "circleci/node", "public.ecr.aws/lambda/nodejs", "mcr.microsoft.com/devcontainers/javascript-node"],
972
+ python: ["python", "cimg/python", "circleci/python", "public.ecr.aws/lambda/python"],
973
+ go: ["golang", "cimg/go", "circleci/golang"]
974
+ };
975
+ function canonicalImage(image) {
976
+ let n = image.trim().toLowerCase();
977
+ for (const host of LIBRARY_HOSTS) {
978
+ if (n.startsWith(`${host}/`)) {
979
+ n = n.slice(host.length + 1);
980
+ break;
981
+ }
982
+ }
983
+ return n.startsWith("library/") ? n.slice("library/".length) : n;
984
+ }
985
+ function isRuntimeImage(image, runtime) {
986
+ return IMAGES[runtime].includes(canonicalImage(image));
987
+ }
988
+
989
+ // src/extract/shared/toml.ts
990
+ import { parse } from "smol-toml";
991
+ var HEADER = /^\s*\[(?!\[)([^\]]*)\]\s*(#.*)?$/;
992
+ function stripKey(key) {
993
+ return key.trim().replace(/^(["'])(.*)\1$/, "$2");
994
+ }
995
+ function splitDotted(path) {
996
+ const parts = [];
997
+ let cur = "";
998
+ let quote = "";
999
+ for (const ch of path) {
1000
+ if (quote) {
1001
+ if (ch === quote) quote = "";
1002
+ cur += ch;
1003
+ } else if (ch === '"' || ch === "'") {
1004
+ quote = ch;
1005
+ cur += ch;
1006
+ } else if (ch === ".") {
1007
+ parts.push(stripKey(cur));
1008
+ cur = "";
1009
+ } else cur += ch;
1010
+ }
1011
+ if (cur.trim() !== "") parts.push(stripKey(cur));
1012
+ return parts;
1013
+ }
1014
+ function locateTomlKey(text2, table, key) {
1015
+ try {
1016
+ let current = [];
1017
+ const lines = text2.split(/\r?\n/);
1018
+ for (let i = 0; i < lines.length; i++) {
1019
+ const line = lines[i];
1020
+ const header = HEADER.exec(line);
1021
+ if (header) {
1022
+ current = splitDotted(header[1].trim());
1023
+ continue;
1024
+ }
1025
+ if (/^\s*\[\[/.test(line)) {
1026
+ current = ["\0array-of-tables"];
1027
+ continue;
1028
+ }
1029
+ const kv = /^(\s*)((?:"[^"]*"|'[^']*'|[A-Za-z0-9_-]+)(?:\s*\.\s*(?:"[^"]*"|'[^']*'|[A-Za-z0-9_-]+))*)\s*=\s*(.*)$/.exec(line);
1030
+ if (!kv) continue;
1031
+ const full = [...current, ...splitDotted(kv[2])];
1032
+ const want = [...table, key];
1033
+ if (full.length === want.length && full.every((p, k) => p === want[k])) {
1034
+ const rest = kv[3];
1035
+ const column = line.length - rest.length + 1;
1036
+ return { line: i + 1, column, raw: rest.replace(/\s+#.*$/, "").trimEnd() };
1037
+ }
1038
+ }
1039
+ return void 0;
1040
+ } catch {
1041
+ return void 0;
1042
+ }
1043
+ }
1044
+ function locateTomlTable(text2, path) {
1045
+ try {
1046
+ const lines = text2.split(/\r?\n/);
1047
+ for (let i = 0; i < lines.length; i++) {
1048
+ const header = HEADER.exec(lines[i]);
1049
+ if (!header) continue;
1050
+ const got = splitDotted(header[1].trim());
1051
+ if (got.length === path.length && got.every((p, k) => p === path[k])) return i + 1;
1052
+ }
1053
+ if (path.length === 1) return locateTomlKey(text2, [], path[0])?.line;
1054
+ return void 0;
1055
+ } catch {
1056
+ return void 0;
1057
+ }
1058
+ }
1059
+ function parseToml(text2) {
1060
+ try {
1061
+ return parse(text2);
1062
+ } catch {
1063
+ return void 0;
1064
+ }
1065
+ }
1066
+ function parseTomlDetailed(text2) {
1067
+ try {
1068
+ return { data: parse(text2) };
1069
+ } catch (err) {
1070
+ const e = err;
1071
+ const first = String(e.message ?? "invalid TOML").split("\n")[0];
1072
+ return {
1073
+ error: {
1074
+ line: typeof e.line === "number" && e.line > 0 ? e.line : 1,
1075
+ column: typeof e.column === "number" && e.column > 0 ? e.column : 1,
1076
+ message: first.replace(/^Invalid TOML document:\s*/i, "")
1077
+ }
1078
+ };
1079
+ }
1080
+ }
1081
+
1082
+ // src/extract/shared/mise.ts
1083
+ function versionsOf(value) {
1084
+ if (typeof value === "string") return [value];
1085
+ if (typeof value === "number") return [String(value)];
1086
+ if (Array.isArray(value)) {
1087
+ const list2 = value.filter((v) => typeof v === "string" || typeof v === "number").map(String);
1088
+ return list2.length === value.length ? list2 : void 0;
1089
+ }
1090
+ if (value && typeof value === "object") {
1091
+ const v = value.version;
1092
+ return v === void 0 ? void 0 : versionsOf(v);
1093
+ }
1094
+ return void 0;
1095
+ }
1096
+ function parseMise(text2) {
1097
+ try {
1098
+ const data = parseToml(text2);
1099
+ const tools = data?.tools;
1100
+ if (!tools || typeof tools !== "object" || Array.isArray(tools)) return [];
1101
+ const out = [];
1102
+ for (const [tool, value] of Object.entries(tools)) {
1103
+ const where = locateTomlKey(text2, ["tools"], tool) ?? locateTomlKey(text2, ["tools", tool], "version");
1104
+ const line = where?.line ?? locateTomlTable(text2, ["tools", tool]) ?? locateTomlTable(text2, ["tools"]);
1105
+ if (line === void 0) continue;
1106
+ const entry = { tool, versions: versionsOf(value) ?? [], line };
1107
+ if (where) entry.column = where.column;
1108
+ out.push(entry);
1109
+ }
1110
+ return out;
1111
+ } catch {
1112
+ return [];
1113
+ }
1114
+ }
1115
+
1116
+ // src/extract/shared/tool-versions.ts
1117
+ function parseToolVersions(text2) {
1118
+ try {
1119
+ const out = [];
1120
+ text2.split(/\r?\n/).forEach((raw, i) => {
1121
+ const body = raw.replace(/(^|\s)#.*$/, "").trim();
1122
+ if (body === "") return;
1123
+ const [tool, ...versions] = body.split(/\s+/);
1124
+ if (tool === void 0) return;
1125
+ out.push({ tool, versions, line: i + 1 });
1126
+ });
1127
+ return out;
1128
+ } catch {
1129
+ return [];
1130
+ }
1131
+ }
1132
+
1133
+ // src/extract/shared/workflow.ts
1134
+ var PATH_INPUTS = ["cache-dependency-path", "node-version-file", "python-version-file", "go-version-file", "working-directory"];
1135
+ function cleanWorkflowPath(raw) {
1136
+ let p = raw.trim().replace(/^["']|["']$/g, "");
1137
+ if (p === "" || p.startsWith("!") || p.startsWith("/") || p.includes("${{") || p.split("/").includes("..")) return void 0;
1138
+ p = p.replace(/^(\.\/)+/, "");
1139
+ const segments = p.split("/").filter((x) => x !== "" && x !== ".");
1140
+ return segments.length === 0 ? "." : segments.join("/");
1141
+ }
1142
+ var ENV_REF = /^\$\{\{\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}$/;
1143
+ var MATRIX_REF = /^\$\{\{\s*matrix\.([A-Za-z0-9_-]+)\s*\}\}$/;
1144
+ function readMatrix(y, matrixNode) {
1145
+ const out = {};
1146
+ const add = (key, line, node) => {
1147
+ const target = out[key] ??= { values: [], lines: [], columns: [], quoted: [], line };
1148
+ const one = scalarText(y, node);
1149
+ const list2 = one ? [one] : items(y, node).map((n) => scalarText(y, n)).filter((s) => s !== void 0);
1150
+ if (one && /^\$\{\{/.test(one.text)) {
1151
+ target.expression = one.text;
1152
+ return;
1153
+ }
1154
+ for (const v of list2) {
1155
+ if (target.values.includes(v.text)) continue;
1156
+ target.values.push(v.text);
1157
+ target.lines.push(v.line);
1158
+ target.columns.push(v.column);
1159
+ target.quoted.push(v.quoted);
1160
+ }
1161
+ };
1162
+ for (const { key, value, line } of entries(y, matrixNode)) {
1163
+ if (key === "exclude") continue;
1164
+ if (key === "include") {
1165
+ for (const inc of items(y, value)) for (const e of entries(y, inc)) add(e.key, e.line, e.value);
1166
+ continue;
1167
+ }
1168
+ add(key, line, value);
1169
+ }
1170
+ return out;
1171
+ }
1172
+ function envValue(y, envNode, name) {
1173
+ const found = entries(y, envNode).find((e) => e.key === name);
1174
+ const v = found ? scalarText(y, found.value) : void 0;
1175
+ if (!v || v.text === "" || v.text.includes("${{")) return void 0;
1176
+ return { value: v.text, quoted: v.quoted, line: v.line, column: v.column };
1177
+ }
1178
+ function stepsOf(y, job, node, matrix, inherited, out, jobEnv, workflowEnv) {
1179
+ const list2 = items(y, getPair(y, node, "steps")?.value ?? node);
1180
+ const dirs = inherited === void 0 ? [] : [inherited];
1181
+ for (const step of list2) {
1182
+ const d = scalarText(y, getPair(y, step, "working-directory")?.value)?.text;
1183
+ if (d !== void 0 && !dirs.includes(d)) dirs.push(d);
1184
+ }
1185
+ for (const step of list2) {
1186
+ const uses = scalarText(y, getPair(y, step, "uses")?.value);
1187
+ if (!uses || uses.text === "") continue;
1188
+ const inputs = {};
1189
+ for (const { key, value } of entries(y, getPair(y, step, "with")?.value)) {
1190
+ const v = scalarText(y, value);
1191
+ if (!v) continue;
1192
+ const input = { value: v.text, line: v.line, column: v.column, quoted: v.quoted };
1193
+ const ref2 = MATRIX_REF.exec(v.text);
1194
+ const hit = ref2 ? matrix[ref2[1]] : void 0;
1195
+ if (ref2 && hit && hit.values.length > 0) {
1196
+ input.matrixKey = ref2[1];
1197
+ input.resolved = hit;
1198
+ }
1199
+ const envRef = ENV_REF.exec(v.text);
1200
+ if (envRef) {
1201
+ const name = envRef[1];
1202
+ const hitEnv = envValue(y, getPair(y, step, "env")?.value, name) ?? envValue(y, jobEnv, name) ?? envValue(y, workflowEnv, name);
1203
+ if (hitEnv) input.env = { name, ...hitEnv };
1204
+ }
1205
+ inputs[key] = input;
1206
+ }
1207
+ const own = scalarText(y, getPair(y, step, "working-directory")?.value);
1208
+ const wd = own?.text ?? scalarText(y, getPair(y, step, "with")?.value && getPair(y, getPair(y, step, "with")?.value, "working-directory")?.value)?.text ?? inherited;
1209
+ const paths = [];
1210
+ for (const [key, input] of Object.entries(inputs)) {
1211
+ if (!PATH_INPUTS.includes(key)) continue;
1212
+ for (const piece of input.value.split(/\r?\n/)) {
1213
+ const cleaned = cleanWorkflowPath(piece);
1214
+ if (cleaned !== void 0 && !paths.includes(cleaned)) paths.push(cleaned);
1215
+ }
1216
+ }
1217
+ const ownDir = own?.text === void 0 ? void 0 : cleanWorkflowPath(own.text);
1218
+ if (ownDir !== void 0 && !paths.includes(ownDir)) paths.push(ownDir);
1219
+ const entry = { uses: uses.text, line: uses.line, column: uses.column, job, with: inputs, matrix, jobWorkingDirectories: dirs, paths };
1220
+ if (wd !== void 0) entry.workingDirectory = wd;
1221
+ out.push(entry);
1222
+ }
1223
+ }
1224
+ function defaultsWd(y, node) {
1225
+ return scalarText(y, getPair(y, getPair(y, getPair(y, node, "defaults")?.value, "run")?.value, "working-directory")?.value)?.text;
1226
+ }
1227
+ function parseWorkflow(text2) {
1228
+ try {
1229
+ return (loadYamlAll(text2) ?? []).flatMap((y) => parseWorkflowDocument(y));
1230
+ } catch {
1231
+ return [];
1232
+ }
1233
+ }
1234
+ function parseWorkflowDocument(y) {
1235
+ try {
1236
+ const root = resolveNode(y, y.doc.contents);
1237
+ if (!isMap(root)) return [];
1238
+ const out = [];
1239
+ const topWd = defaultsWd(y, root);
1240
+ const topEnv = getPair(y, root, "env")?.value;
1241
+ for (const { key, value } of entries(y, getPair(y, root, "jobs")?.value)) {
1242
+ const matrixNode = getPair(y, getPair(y, value, "strategy")?.value, "matrix")?.value;
1243
+ const matrix = isScalar(resolveNode(y, matrixNode)) ? {} : readMatrix(y, matrixNode);
1244
+ stepsOf(y, key, getPair(y, value, "steps")?.value, matrix, defaultsWd(y, value) ?? topWd, out, getPair(y, value, "env")?.value, topEnv);
1245
+ }
1246
+ const composite = getPair(y, getPair(y, root, "runs")?.value, "steps")?.value;
1247
+ if (composite) stepsOf(y, "", composite, {}, void 0, out);
1248
+ return out;
1249
+ } catch {
1250
+ return [];
1251
+ }
1252
+ }
1253
+ function workflowSourcePaths(step) {
1254
+ const out = [...step.paths];
1255
+ for (const dir of step.jobWorkingDirectories) {
1256
+ const cleaned = cleanWorkflowPath(dir);
1257
+ if (cleaned !== void 0 && !out.includes(cleaned)) out.push(cleaned);
1258
+ }
1259
+ return out;
1260
+ }
1261
+
1262
+ // src/extract/diagnose.ts
1263
+ var WORKFLOW_YAML = /(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/i;
1264
+ var ACTION_YAML = /(^|\/)action\.ya?ml$/i;
1265
+ var GITLAB_YAML = /(^|\/)\.gitlab-ci\.ya?ml$/i;
1266
+ var MISE_TOML = /(^|\/)(\.?mise(\..+)?\.toml|\.config\/mise\/config(\..+)?\.toml|\.config\/mise\.toml)$/i;
1267
+ function firstLine(text2) {
1268
+ return (text2.split("\n")[0] ?? "").trim();
1269
+ }
1270
+ function yamlDiagnostic(file, text2) {
1271
+ const docs = loadYamlAll(text2);
1272
+ if (!docs) return { file, line: 1, message: "YAML could not be parsed at all; no pins were read from this file." };
1273
+ const errors = docs.flatMap((y) => y.doc.errors.map((e) => ({ e, y })));
1274
+ const first = errors[0];
1275
+ if (!first) return void 0;
1276
+ const { line, column } = first.y.pos(first.e.pos[0]);
1277
+ const more = errors.length > 1 ? ` (${errors.length - 1} more error${errors.length === 2 ? "" : "s"} in this file)` : "";
1278
+ return {
1279
+ file,
1280
+ line,
1281
+ column,
1282
+ message: `YAML syntax error: ${firstLine(first.e.message)}${more}. Pins before this point were read; pins after it may not have been.`
1283
+ };
1284
+ }
1285
+ function tomlDiagnostic(file, text2) {
1286
+ const r = parseTomlDetailed(text2);
1287
+ if (!("error" in r)) return void 0;
1288
+ return { file, line: r.error.line, column: r.error.column, message: `TOML syntax error: ${r.error.message}. No pins were read from this file.` };
1289
+ }
1290
+ function jsonDiagnostic(file, text2) {
1291
+ try {
1292
+ JSON.parse(text2);
1293
+ return void 0;
1294
+ } catch (err) {
1295
+ const message = err instanceof Error ? err.message : String(err);
1296
+ let line = 1;
1297
+ let column;
1298
+ const lc = /\(line (\d+) column (\d+)\)/.exec(message);
1299
+ const pos = /position (\d+)/.exec(message);
1300
+ if (lc) {
1301
+ line = Number(lc[1]);
1302
+ column = Number(lc[2]);
1303
+ } else if (pos) {
1304
+ const before = text2.slice(0, Number(pos[1]));
1305
+ line = before.split("\n").length;
1306
+ column = Number(pos[1]) - (before.lastIndexOf("\n") + 1) + 1;
1307
+ }
1308
+ const d = { file, line, message: `JSON syntax error: ${message.replace(/\s*\(line \d+ column \d+\)/, "")}. No pins were read from this file.` };
1309
+ if (column !== void 0) d.column = column;
1310
+ return d;
1311
+ }
1312
+ }
1313
+ function diagnoseFile(file, text2, runtimes = ["node", "python", "go"]) {
1314
+ try {
1315
+ const base = file.slice(file.lastIndexOf("/") + 1);
1316
+ let d;
1317
+ if (WORKFLOW_YAML.test(file) || ACTION_YAML.test(file) || GITLAB_YAML.test(file)) d = yamlDiagnostic(file, text2);
1318
+ else if (base === "package.json" && runtimes.includes("node")) d = jsonDiagnostic(file, text2);
1319
+ else if (base === "pyproject.toml" && runtimes.includes("python")) d = tomlDiagnostic(file, text2);
1320
+ else if (MISE_TOML.test(file)) d = tomlDiagnostic(file, text2);
1321
+ return d ? [d] : [];
1322
+ } catch {
1323
+ return [];
1324
+ }
1325
+ }
1326
+
1327
+ // src/extract/python/adapters.ts
1328
+ function baseName(file) {
1329
+ return file.slice(file.lastIndexOf("/") + 1);
1330
+ }
1331
+ function isDockerfile(file) {
1332
+ return /^(.+\.)?dockerfile(\..+)?$/i.test(baseName(file));
1333
+ }
1334
+ function isWorkflowFile(file) {
1335
+ return /^\.github\/(workflows\/([^/]+|.+\/action)|actions\/.+\/action)\.ya?ml$/i.test(file);
1336
+ }
1337
+ function isMiseFile(file) {
1338
+ if (/^\.?mise(\..+)?\.toml$/i.test(baseName(file))) return true;
1339
+ return /(^|\/)\.config\/mise(\/config(\..+)?)?\.toml$/i.test(file) || /(^|\/)\.config\/mise\/config(\..+)?\.toml$/i.test(file);
1340
+ }
1341
+ function isToolVersions(file) {
1342
+ return baseName(file) === ".tool-versions";
1343
+ }
1344
+ function yamlNumberPitfall(text2, quoted) {
1345
+ if (quoted) return void 0;
1346
+ if (/^\d+\.\d*0$/.test(text2)) {
1347
+ const read = String(Number(text2));
1348
+ return `unquoted ${text2} is read by YAML as the number ${read}; write it in quotes ('${text2}')`;
1349
+ }
1350
+ return void 0;
1351
+ }
1352
+ function ciConstraint(text2, quoted, runtime) {
1353
+ const pitfall = yamlNumberPitfall(text2, quoted);
1354
+ return pitfall ? { kind: "unknown", reason: pitfall } : parseConstraint(text2, runtime);
1355
+ }
1356
+ function cleanDirectory(dir) {
1357
+ const d = dir.trim().replace(/^\.\//, "").replace(/\/+$/, "");
1358
+ if (d === "" || d === ".") return ".";
1359
+ if (d.startsWith("/") || d.includes("${{") || d.includes("..")) return void 0;
1360
+ return d;
1361
+ }
1362
+ function dockerConstraint(tag, digest, runtime) {
1363
+ if (tag === void 0 && digest !== void 0) {
1364
+ return { kind: "unknown", reason: "image is pinned by digest only, so its version cannot be read" };
1365
+ }
1366
+ return dockerTagConstraint(tag, runtime);
1367
+ }
1368
+ function dockerfileSources(file, text2, runtime) {
1369
+ const out = [];
1370
+ for (const from of parseDockerfile(text2)) {
1371
+ if (!isRuntimeImage(from.image, runtime)) continue;
1372
+ const written = splitImageRef(from.raw);
1373
+ const raw = written.tag ?? from.raw;
1374
+ const tagOffset = written.tag === void 0 ? 0 : written.image.length + 1;
1375
+ out.push({
1376
+ runtime,
1377
+ file,
1378
+ line: from.line,
1379
+ column: from.column + tagOffset,
1380
+ raw,
1381
+ kind: "dockerfile",
1382
+ constraint: dockerConstraint(from.tag, from.digest, runtime)
1383
+ });
1384
+ }
1385
+ return out;
1386
+ }
1387
+ function isGitlabCi(file) {
1388
+ return /^\.gitlab-ci\.ya?ml$/i.test(baseName(file));
1389
+ }
1390
+ function gitlabSources(file, text2, runtime) {
1391
+ const out = [];
1392
+ for (const img of parseGitlabCi(text2)) {
1393
+ if (!isRuntimeImage(img.image, runtime)) continue;
1394
+ const written = splitImageRef(img.raw);
1395
+ const raw = written.tag ?? img.raw;
1396
+ const tagOffset = written.tag === void 0 ? 0 : written.image.length + 1;
1397
+ out.push({
1398
+ runtime,
1399
+ file,
1400
+ line: img.line,
1401
+ column: img.column + tagOffset,
1402
+ raw,
1403
+ kind: "gitlab-ci",
1404
+ constraint: dockerConstraint(img.tag, img.digest, runtime)
1405
+ });
1406
+ }
1407
+ return out;
1408
+ }
1409
+ function toolVersionsSources(file, text2, runtime, tools) {
1410
+ const out = [];
1411
+ const lines = text2.split(/\r?\n/);
1412
+ for (const entry of parseToolVersions(text2)) {
1413
+ if (!tools.includes(entry.tool)) continue;
1414
+ const raw = entry.versions[0];
1415
+ const source = {
1416
+ runtime,
1417
+ file,
1418
+ line: entry.line,
1419
+ raw: raw ?? "",
1420
+ kind: "tool-versions",
1421
+ constraint: raw === void 0 ? { kind: "unknown", reason: "no version after the tool name" } : parseConstraint(raw, runtime)
1422
+ };
1423
+ const lineText = lines[entry.line - 1] ?? "";
1424
+ const toolEnd = lineText.indexOf(entry.tool) + entry.tool.length;
1425
+ const at = raw === void 0 ? -1 : lineText.indexOf(raw, toolEnd);
1426
+ if (at >= 0) source.column = at + 1;
1427
+ out.push(source);
1428
+ }
1429
+ return out;
1430
+ }
1431
+ function miseRawPosition(lines, line, column, raw) {
1432
+ for (let k = 0; k < 20 && line - 1 + k < lines.length; k++) {
1433
+ const text2 = lines[line - 1 + k];
1434
+ const from = k === 0 && column !== void 0 ? column - 1 : 0;
1435
+ let rest = text2.slice(from);
1436
+ let offset = from;
1437
+ if (k === 0 && rest.startsWith("{")) {
1438
+ const m = /version\s*=\s*["']?/.exec(rest);
1439
+ if (m) {
1440
+ offset += m.index + m[0].length;
1441
+ rest = text2.slice(offset);
1442
+ }
1443
+ }
1444
+ const at = rest.indexOf(raw);
1445
+ if (at >= 0) return { line: line + k, column: offset + at + 1 };
1446
+ }
1447
+ return column === void 0 ? { line } : { line, column };
1448
+ }
1449
+ function miseSources(file, text2, runtime, tools) {
1450
+ const out = [];
1451
+ const lines = text2.split(/\r?\n/);
1452
+ for (const entry of parseMise(text2)) {
1453
+ if (!tools.includes(entry.tool)) continue;
1454
+ const raw = entry.versions[0];
1455
+ const where = raw === void 0 ? miseRawPosition([], entry.line, entry.column, "") : miseRawPosition(lines, entry.line, entry.column, raw);
1456
+ const source = {
1457
+ runtime,
1458
+ file,
1459
+ line: where.line,
1460
+ raw: raw ?? "",
1461
+ kind: "mise",
1462
+ constraint: raw === void 0 ? { kind: "unknown", reason: "no version in the mise tool entry" } : parseConstraint(raw, runtime)
1463
+ };
1464
+ if (where.column !== void 0) source.column = where.column;
1465
+ out.push(source);
1466
+ }
1467
+ return out;
1468
+ }
1469
+ function stepDirectory(step) {
1470
+ return step.workingDirectory === void 0 ? void 0 : cleanDirectory(step.workingDirectory);
1471
+ }
1472
+ function inputSources(step, input, file, runtime, kind, dir) {
1473
+ const base = { runtime, file, kind };
1474
+ const paths = workflowSourcePaths(step);
1475
+ const withDir = (s) => {
1476
+ if (dir !== void 0) s.workingDirectory = dir;
1477
+ if (paths.length > 0) s.paths = paths;
1478
+ return s;
1479
+ };
1480
+ const resolved = input.resolved;
1481
+ if (resolved) {
1482
+ return resolved.values.map(
1483
+ (value, i) => withDir({
1484
+ ...base,
1485
+ line: resolved.lines[i],
1486
+ column: resolved.columns[i],
1487
+ raw: value,
1488
+ constraint: ciConstraint(value, resolved.quoted[i], runtime),
1489
+ matrix: true
1490
+ })
1491
+ );
1492
+ }
1493
+ if (input.env) {
1494
+ return [withDir({ ...base, line: input.line, column: input.column, raw: input.value, constraint: ciConstraint(input.env.value, input.env.quoted, runtime) })];
1495
+ }
1496
+ if (/^\$\{\{/.test(input.value) || input.value.includes("${{") && !input.quoted) {
1497
+ return [withDir({ ...base, line: input.line, column: input.column, raw: input.value, constraint: { kind: "unknown", reason: "value is a workflow expression that cannot be read statically" } })];
1498
+ }
1499
+ if (!input.quoted && input.value.includes("\n")) {
1500
+ return input.value.split("\n").map((v, i) => ({ v: v.trim(), i })).filter(({ v }) => v !== "").map(({ v, i }) => withDir({ ...base, line: input.line + 1 + i, raw: v, constraint: parseConstraint(v, runtime) }));
1501
+ }
1502
+ return [withDir({ ...base, line: input.line, column: input.column, raw: input.value, constraint: ciConstraint(input.value, input.quoted, runtime) })];
1503
+ }
1504
+ function workflowSources(file, text2, runtime, action, input) {
1505
+ const out = [];
1506
+ const name = action.toLowerCase();
1507
+ for (const step of parseWorkflow(text2)) {
1508
+ const used = step.uses.toLowerCase();
1509
+ if (used !== name && !used.startsWith(`${name}@`)) continue;
1510
+ const value = step.with[input];
1511
+ if (!value) continue;
1512
+ out.push(...inputSources(step, value, file, runtime, action.slice(action.lastIndexOf("/") + 1), stepDirectory(step)));
1513
+ }
1514
+ const lines = text2.split(/\r?\n/);
1515
+ for (const source of out) {
1516
+ if (source.raw === "") continue;
1517
+ if (source.column !== void 0 && lines[source.line - 1]?.startsWith(source.raw, source.column - 1)) continue;
1518
+ delete source.column;
1519
+ const own = lines[source.line - 1] ?? "";
1520
+ if (own.trim() === source.raw) {
1521
+ source.column = own.indexOf(source.raw) + 1;
1522
+ continue;
1523
+ }
1524
+ const header = lines[source.line - 1] ?? "";
1525
+ if (/[|>][+-]?\d*\s*(#.*)?$/.test(header)) {
1526
+ for (let k = 1; k <= 20; k++) {
1527
+ const below = lines[source.line - 1 + k];
1528
+ if (below === void 0) break;
1529
+ if (below.trim() === source.raw) {
1530
+ source.line += k;
1531
+ source.column = below.indexOf(source.raw) + 1;
1532
+ break;
1533
+ }
1534
+ }
1535
+ }
1536
+ }
1537
+ return out;
1538
+ }
1539
+ function guardColumns(text2, sources) {
1540
+ const lines = text2.split(/\r?\n/);
1541
+ for (const source of sources) {
1542
+ if (source.column === void 0) continue;
1543
+ if (!(lines[source.line - 1] ?? "").startsWith(source.raw, source.column - 1)) delete source.column;
1544
+ }
1545
+ return sources;
1546
+ }
1547
+
1548
+ // src/extract/go/gomod.ts
1549
+ function goModSources(file, text2) {
1550
+ const out = [];
1551
+ let depth = 0;
1552
+ text2.split(/\r?\n/).forEach((line, i) => {
1553
+ const code = line.replace(/\/\/.*$/, "");
1554
+ const openers = (code.match(/\(/g) ?? []).length;
1555
+ const closers = (code.match(/\)/g) ?? []).length;
1556
+ const inBlock = depth > 0;
1557
+ depth = Math.max(0, depth + openers - closers);
1558
+ if (inBlock) return;
1559
+ const m = /^(\s*)(go|toolchain)\s+(\S+)\s*$/.exec(code);
1560
+ if (!m) return;
1561
+ const directive = m[2];
1562
+ const raw = m[3];
1563
+ const column = m[1].length + directive.length + (code.slice(m[1].length + directive.length).length - code.slice(m[1].length + directive.length).trimStart().length) + 1;
1564
+ let constraint;
1565
+ if (directive === "go") {
1566
+ const exact = /^\d+\.\d+(\.\d+)?$/.test(raw);
1567
+ constraint = exact ? parseConstraint(`>=${raw}`, "go") : { kind: "unknown", reason: `go directive ${raw} is not a plain version` };
1568
+ } else if (raw === "default" || raw === "local") {
1569
+ constraint = { kind: "unknown", reason: `toolchain ${raw} selects the toolchain at build time` };
1570
+ } else {
1571
+ constraint = parseConstraint(raw, "go");
1572
+ }
1573
+ out.push({ runtime: "go", file, line: i + 1, column, raw, kind: directive === "go" ? "go-mod" : "go-toolchain", constraint });
1574
+ });
1575
+ return out;
1576
+ }
1577
+
1578
+ // src/extract/go/index.ts
1579
+ var GO_TOOLS = ["golang", "go"];
1580
+ function dispatch(file, text2) {
1581
+ if (baseName(file) === "go.mod") return goModSources(file, text2);
1582
+ if (isToolVersions(file)) return toolVersionsSources(file, text2, "go", GO_TOOLS);
1583
+ if (isMiseFile(file)) return miseSources(file, text2, "go", GO_TOOLS);
1584
+ if (isDockerfile(file)) return dockerfileSources(file, text2, "go");
1585
+ if (isGitlabCi(file)) return gitlabSources(file, text2, "go");
1586
+ if (isWorkflowFile(file)) return workflowSources(file, text2, "go", "actions/setup-go", "go-version");
1587
+ return [];
1588
+ }
1589
+ function extractGo(file, text2) {
1590
+ try {
1591
+ return guardColumns(text2, dispatch(file, text2));
1592
+ } catch {
1593
+ return [];
1594
+ }
1595
+ }
1596
+
1597
+ // src/extract/node/util.ts
1598
+ function nodeSource(file, kind, line, raw, constraint, extra = {}) {
1599
+ const source = { runtime: "node", file, line, raw, kind, constraint };
1600
+ if (extra.column !== void 0) source.column = extra.column;
1601
+ if (extra.matrix) source.matrix = true;
1602
+ if (extra.workingDirectory !== void 0) source.workingDirectory = extra.workingDirectory;
1603
+ if (extra.paths !== void 0 && extra.paths.length > 0) source.paths = extra.paths;
1604
+ return source;
1605
+ }
1606
+ function nodeConstraint(raw) {
1607
+ return parseConstraint(raw, "node");
1608
+ }
1609
+ function isNodeImage(image) {
1610
+ return isRuntimeImage(image, "node");
1611
+ }
1612
+ function columnOf(text2, line, needle, from = 0) {
1613
+ const l = text2.split(/\r?\n/)[line - 1];
1614
+ if (l === void 0) return void 0;
1615
+ const i = l.indexOf(needle, from);
1616
+ return i < 0 ? void 0 : i + 1;
1617
+ }
1618
+
1619
+ // src/extract/node/ci.ts
1620
+ function tagConstraint(tag, digest) {
1621
+ if (tag === void 0 && digest !== void 0) return { kind: "unknown", reason: "pinned by digest, the version is not in the reference" };
1622
+ if (tag !== void 0 && /\$/.test(tag)) return { kind: "unknown", reason: "tag contains an unresolved variable" };
1623
+ return dockerTagConstraint(tag, "node");
1624
+ }
1625
+ function extractDockerfile(file, text2) {
1626
+ const out = [];
1627
+ const stages = /* @__PURE__ */ new Set();
1628
+ const seenArgs = /* @__PURE__ */ new Set();
1629
+ for (const from of parseDockerfile(text2)) {
1630
+ const isStage = from.tag === void 0 && from.digest === void 0 && stages.has(from.image.toLowerCase());
1631
+ if (from.stage) stages.add(from.stage.toLowerCase());
1632
+ if (isStage || !isNodeImage(from.image)) continue;
1633
+ const constraint = tagConstraint(from.tag, from.digest);
1634
+ if (from.arg) {
1635
+ const value = new RegExp(`\\b${from.arg.name}=(["']?)([^\\s"']*)`).exec(text2.split(/\r?\n/)[from.arg.line - 1] ?? "");
1636
+ if (value) {
1637
+ const line = text2.split(/\r?\n/)[from.arg.line - 1];
1638
+ const column2 = value.index + value[0].length - value[2].length + 1;
1639
+ const key = `${from.arg.line}:${column2}`;
1640
+ if (!seenArgs.has(key)) {
1641
+ seenArgs.add(key);
1642
+ out.push(nodeSource(file, "dockerfile", from.arg.line, value[2], constraint, { column: Math.min(column2, line.length + 1) }));
1643
+ }
1644
+ continue;
1645
+ }
1646
+ }
1647
+ const raw = from.tag ?? from.raw;
1648
+ const column = from.tag !== void 0 && !from.arg && from.raw.startsWith(`${from.image}:`) ? from.column + from.image.length + 1 : from.column;
1649
+ out.push(nodeSource(file, "dockerfile", from.line, raw, constraint, { column }));
1650
+ }
1651
+ return out;
1652
+ }
1653
+ function projectRoot(dir) {
1654
+ if (dir === void 0 || /\$\{\{/.test(dir) || dir.startsWith("/")) return void 0;
1655
+ const clean = dir.replace(/^(\.\/)+/, "").replace(/\/+$/, "");
1656
+ return clean === "" ? "." : clean;
1657
+ }
1658
+ function extractWorkflow(file, text2) {
1659
+ const out = [];
1660
+ for (const step of parseWorkflow(text2)) {
1661
+ if (!/^actions\/setup-node(@|$)/i.test(step.uses)) continue;
1662
+ const input = step.with["node-version"];
1663
+ if (!input) continue;
1664
+ const dir = projectRoot(step.workingDirectory);
1665
+ const paths = workflowSourcePaths(step);
1666
+ const base = dir === void 0 ? { paths } : { workingDirectory: dir, paths };
1667
+ const ref2 = /^\$\{\{\s*matrix\.([A-Za-z0-9_-]+)\s*\}\}$/.exec(input.value.trim());
1668
+ const m = input.resolved ?? (ref2 ? step.matrix[ref2[1]] : void 0);
1669
+ if (m) {
1670
+ if (m.expression !== void 0 || m.values.length === 0) {
1671
+ out.push(nodeSource(file, "setup-node", input.line, input.value, { kind: "unknown", reason: "matrix is computed by an expression" }, { ...base, matrix: true, column: input.column }));
1672
+ continue;
1673
+ }
1674
+ m.values.forEach((value, i) => {
1675
+ out.push(nodeSource(file, "setup-node", m.lines[i], value, nodeConstraint(value), { ...base, matrix: true, column: m.columns[i] }));
1676
+ });
1677
+ continue;
1678
+ }
1679
+ out.push(nodeSource(file, "setup-node", input.line, input.value, nodeConstraint(input.env?.value ?? input.value), { ...base, column: input.column }));
1680
+ }
1681
+ return out;
1682
+ }
1683
+ function extractGitlabCi(file, text2) {
1684
+ const out = [];
1685
+ for (const img of parseGitlabCi(text2)) {
1686
+ if (!isNodeImage(img.image)) continue;
1687
+ const constraint = tagConstraint(img.tag, img.digest);
1688
+ const raw = img.tag ?? img.raw;
1689
+ const column = img.tag !== void 0 && img.raw.startsWith(`${img.image}:`) ? img.column + img.image.length + 1 : img.column;
1690
+ out.push(nodeSource(file, "gitlab-ci", img.line, raw, constraint, { column }));
1691
+ }
1692
+ return out;
1693
+ }
1694
+
1695
+ // src/extract/node/package-json.ts
1696
+ function isObject(v) {
1697
+ return typeof v === "object" && v !== null && !Array.isArray(v);
1698
+ }
1699
+ function position(text2, offset) {
1700
+ const before = text2.slice(0, offset);
1701
+ const line = before.split("\n").length;
1702
+ return { line, column: offset - (before.lastIndexOf("\n") + 1) + 1 };
1703
+ }
1704
+ function findValue(text2, from, key, raw, within) {
1705
+ const re = new RegExp(`"${key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}"\\s*:\\s*"`, "g");
1706
+ re.lastIndex = from;
1707
+ const escaped = JSON.stringify(raw).slice(1, -1);
1708
+ for (let m = re.exec(text2); m; m = re.exec(text2)) {
1709
+ const at = m.index + m[0].length;
1710
+ if (within && at > within.end) return void 0;
1711
+ if (text2.startsWith(escaped, at) && text2[at + escaped.length] === '"') return at;
1712
+ }
1713
+ return void 0;
1714
+ }
1715
+ function objectStart(text2, key) {
1716
+ const m = new RegExp(`"${key}"\\s*:\\s*[\\[{]`).exec(text2);
1717
+ return m ? m.index : void 0;
1718
+ }
1719
+ function extractPackageJson(file, text2) {
1720
+ let json;
1721
+ try {
1722
+ json = JSON.parse(text2);
1723
+ } catch {
1724
+ return [];
1725
+ }
1726
+ if (!isObject(json)) return [];
1727
+ const out = [];
1728
+ const add = (kind, parentKey, key, value, near) => {
1729
+ const parent = objectStart(text2, parentKey) ?? 0;
1730
+ if (typeof value === "string") {
1731
+ let at = findValue(text2, parent, key, value);
1732
+ if (near) {
1733
+ let from = parent;
1734
+ for (let n = 0; n < 50; n++) {
1735
+ at = findValue(text2, from, key, value);
1736
+ if (at === void 0 || near(at)) break;
1737
+ from = at;
1738
+ }
1739
+ }
1740
+ const pos = position(text2, at ?? parent);
1741
+ out.push(nodeSource(file, kind, pos.line, value, nodeConstraint(value), at === void 0 ? {} : { column: pos.column }));
1742
+ } else {
1743
+ const pos = position(text2, parent);
1744
+ out.push(nodeSource(file, kind, pos.line, JSON.stringify(value), { kind: "unknown", reason: "expected a string" }));
1745
+ }
1746
+ };
1747
+ const engines = json.engines;
1748
+ if (isObject(engines) && engines.node !== void 0) add("engines", "engines", "node", engines.node);
1749
+ const volta = json.volta;
1750
+ if (isObject(volta) && volta.node !== void 0) add("volta", "volta", "node", volta.node);
1751
+ const dev = json.devEngines;
1752
+ if (isObject(dev) && dev.runtime !== void 0) {
1753
+ const runtimes = Array.isArray(dev.runtime) ? dev.runtime : [dev.runtime];
1754
+ for (const rt of runtimes) {
1755
+ if (!isObject(rt) || rt.name !== "node" || rt.version === void 0) continue;
1756
+ const inNodeObject = (at) => {
1757
+ const open = text2.lastIndexOf("{", at);
1758
+ const close = text2.indexOf("}", at);
1759
+ return /"name"\s*:\s*"node"/.test(text2.slice(open, close < 0 ? void 0 : close));
1760
+ };
1761
+ add("dev-engines", "devEngines", "version", rt.version, inNodeObject);
1762
+ }
1763
+ }
1764
+ return out;
1765
+ }
1766
+
1767
+ // src/extract/node/version-files.ts
1768
+ function extractVersionFile(file, text2, kind) {
1769
+ const lines = text2.split(/\r?\n/);
1770
+ for (let i = 0; i < lines.length; i++) {
1771
+ const raw = lines[i].trim();
1772
+ if (raw === "" || raw.startsWith("#")) continue;
1773
+ const column = lines[i].indexOf(raw) + 1;
1774
+ return [nodeSource(file, kind, i + 1, raw, nodeConstraint(raw), { column })];
1775
+ }
1776
+ return [];
1777
+ }
1778
+ function extractToolVersions(file, text2) {
1779
+ const out = [];
1780
+ for (const entry of parseToolVersions(text2)) {
1781
+ if (entry.tool !== "nodejs" && entry.tool !== "node") continue;
1782
+ const raw = entry.versions[0];
1783
+ if (raw === void 0) {
1784
+ out.push(nodeSource(file, "tool-versions", entry.line, entry.tool, { kind: "unknown", reason: "no version on the line" }));
1785
+ continue;
1786
+ }
1787
+ const column = columnOf(text2, entry.line, raw, (text2.split(/\r?\n/)[entry.line - 1] ?? "").indexOf(entry.tool) + entry.tool.length);
1788
+ out.push(nodeSource(file, "tool-versions", entry.line, raw, nodeConstraint(raw), column === void 0 ? {} : { column }));
1789
+ }
1790
+ return out;
1791
+ }
1792
+ function miseColumn(text2, line, valueColumn, raw) {
1793
+ if (valueColumn === void 0) return {};
1794
+ const l = text2.split(/\r?\n/)[line - 1] ?? "";
1795
+ let from = valueColumn - 1;
1796
+ if (l[from] === "{") from += Math.max(l.slice(from).search(/\bversion\b/), 0);
1797
+ const column = columnOf(text2, line, raw, from);
1798
+ return column === void 0 ? {} : { column };
1799
+ }
1800
+ function extractMise(file, text2) {
1801
+ const out = [];
1802
+ for (const tool of parseMise(text2)) {
1803
+ if (!["node", "nodejs", "core:node"].includes(tool.tool)) continue;
1804
+ const raw = tool.versions[0];
1805
+ if (raw === void 0) continue;
1806
+ out.push(nodeSource(file, "mise", tool.line, raw, nodeConstraint(raw), miseColumn(text2, tool.line, tool.column, raw)));
1807
+ }
1808
+ return out;
1809
+ }
1810
+
1811
+ // src/extract/node/index.ts
1812
+ var WORKFLOW = /(^|\/)\.github\/(workflows\/[^/]+|actions\/.+\/action)\.ya?ml$/i;
1813
+ var ACTION = /(^|\/)action\.ya?ml$/i;
1814
+ var GITLAB = /(^|\/)\.gitlab-ci\.ya?ml$/i;
1815
+ var MISE = /(^|\/)(\.?mise(\.[\w-]+)?\.toml|\.config\/mise(\/config)?\.toml|mise\/config\.toml)$/i;
1816
+ var DOCKERFILE = /^(Dockerfile(\..+)?|.+\.Dockerfile)$/i;
1817
+ var NOT_DOCKERFILE = /\.(md|markdown|txt|rst|json|ya?ml|toml|sh|bak|orig)$/i;
1818
+ function extractNode(file, text2) {
1819
+ try {
1820
+ const base = file.slice(file.lastIndexOf("/") + 1);
1821
+ if (base === ".nvmrc") return extractVersionFile(file, text2, "nvmrc");
1822
+ if (base === ".node-version") return extractVersionFile(file, text2, "node-version");
1823
+ if (base === "package.json") return extractPackageJson(file, text2);
1824
+ if (base === ".tool-versions") return extractToolVersions(file, text2);
1825
+ if (MISE.test(file)) return extractMise(file, text2);
1826
+ if (DOCKERFILE.test(base) && !NOT_DOCKERFILE.test(base)) return extractDockerfile(file, text2);
1827
+ if (GITLAB.test(file)) return extractGitlabCi(file, text2);
1828
+ if (WORKFLOW.test(file) || ACTION.test(file)) return extractWorkflow(file, text2);
1829
+ return [];
1830
+ } catch {
1831
+ return [];
1832
+ }
1833
+ }
1834
+
1835
+ // src/extract/python/files.ts
1836
+ function pythonVersionFile(file, text2) {
1837
+ const out = [];
1838
+ text2.split(/\r?\n/).forEach((line, i) => {
1839
+ const body = line.replace(/(^|\s)#.*$/, "").trim();
1840
+ if (body === "") return;
1841
+ out.push({
1842
+ runtime: "python",
1843
+ file,
1844
+ line: i + 1,
1845
+ column: line.indexOf(body) + 1,
1846
+ raw: body,
1847
+ kind: "python-version",
1848
+ constraint: parseConstraint(body, "python")
1849
+ });
1850
+ });
1851
+ return out;
1852
+ }
1853
+ function runtimeTxtSources(file, text2) {
1854
+ const lines = text2.split(/\r?\n/);
1855
+ const index = lines.findIndex((l) => l.trim() !== "");
1856
+ if (index < 0) return [];
1857
+ const body = lines[index].trim();
1858
+ if (!/^python-/i.test(body)) return [];
1859
+ return [
1860
+ {
1861
+ runtime: "python",
1862
+ file,
1863
+ line: index + 1,
1864
+ column: lines[index].indexOf(body) + 1,
1865
+ raw: body,
1866
+ kind: "runtime-txt",
1867
+ constraint: parseConstraint(body, "python")
1868
+ }
1869
+ ];
1870
+ }
1871
+ function fallbackLocation(text2, key, tableKey) {
1872
+ const lines = text2.split(/\r?\n/);
1873
+ const escaped = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1874
+ const re = new RegExp(`(^|[\\s{,])"?${escaped}"?\\s*=\\s*(["'])`);
1875
+ for (let i = 0; i < lines.length; i++) {
1876
+ const m = re.exec(lines[i]);
1877
+ if (m) {
1878
+ const column = m.index + m[0].length + 1;
1879
+ return { line: i + 1, column, raw: lines[i].slice(column - 1) };
1880
+ }
1881
+ }
1882
+ const owner = locateTomlKey(text2, [], tableKey);
1883
+ return { line: owner?.line ?? 1, column: owner?.column ?? 1, raw: "" };
1884
+ }
1885
+ function tomlString(raw) {
1886
+ const m = /^(["'])(.*)\1$/.exec(raw.trim());
1887
+ return m ? { text: m[2], quoted: true } : void 0;
1888
+ }
1889
+ function pyprojectSources(file, text2) {
1890
+ const data = parseToml(text2);
1891
+ if (data === void 0) return [];
1892
+ const out = [];
1893
+ const fields = [
1894
+ { table: ["project"], key: "requires-python", kind: "requires-python", value: data?.project?.["requires-python"] },
1895
+ {
1896
+ table: ["tool", "poetry", "dependencies"],
1897
+ key: "python",
1898
+ kind: "poetry-python",
1899
+ value: data?.tool?.poetry?.dependencies ? (data?.tool).poetry.dependencies.python : void 0
1900
+ }
1901
+ ];
1902
+ for (const f of fields) {
1903
+ if (f.value === void 0) continue;
1904
+ const located = locateTomlKey(text2, f.table, f.key);
1905
+ const where = located ?? fallbackLocation(text2, f.key, f.table[0]);
1906
+ if (!where) continue;
1907
+ const written = tomlString(where.raw);
1908
+ const raw = written ? written.text : where.raw;
1909
+ const column = located ? where.column + (written ? 1 : 0) : where.column;
1910
+ const base = { runtime: "python", file, line: where.line, column, raw, kind: f.kind };
1911
+ if (typeof f.value !== "string") {
1912
+ out.push({ ...base, constraint: { kind: "unknown", reason: `${f.table.join(".")}.${f.key} is not a plain string` } });
1913
+ } else {
1914
+ out.push({ ...base, raw: f.value, constraint: parseConstraint(f.value, "python") });
1915
+ }
1916
+ }
1917
+ return out;
1918
+ }
1919
+
1920
+ // src/extract/python/index.ts
1921
+ function dispatch2(file, text2) {
1922
+ const name = baseName(file);
1923
+ if (name === ".python-version") return pythonVersionFile(file, text2);
1924
+ if (name === "pyproject.toml") return pyprojectSources(file, text2);
1925
+ if (name === "runtime.txt") return runtimeTxtSources(file, text2);
1926
+ if (isToolVersions(file)) return toolVersionsSources(file, text2, "python", ["python"]);
1927
+ if (isMiseFile(file)) return miseSources(file, text2, "python", ["python"]);
1928
+ if (isDockerfile(file)) return dockerfileSources(file, text2, "python");
1929
+ if (isGitlabCi(file)) return gitlabSources(file, text2, "python");
1930
+ if (isWorkflowFile(file)) return workflowSources(file, text2, "python", "actions/setup-python", "python-version");
1931
+ return [];
1932
+ }
1933
+ function extractPython(file, text2) {
1934
+ try {
1935
+ return guardColumns(text2, dispatch2(file, text2));
1936
+ } catch {
1937
+ return [];
1938
+ }
1939
+ }
1940
+
1941
+ // src/fix.ts
1942
+ import semver2 from "semver";
1943
+ var FixError = class extends Error {
1944
+ name = "FixError";
1945
+ };
1946
+ var LOCKFILES = /* @__PURE__ */ new Set([
1947
+ "package-lock.json",
1948
+ "npm-shrinkwrap.json",
1949
+ "yarn.lock",
1950
+ "pnpm-lock.yaml",
1951
+ "bun.lock",
1952
+ "bun.lockb",
1953
+ "poetry.lock",
1954
+ "uv.lock",
1955
+ "pdm.lock",
1956
+ "Pipfile.lock",
1957
+ "go.sum",
1958
+ "go.work.sum"
1959
+ ]);
1960
+ function isLockfile(file) {
1961
+ const base = file.slice(file.lastIndexOf("/") + 1);
1962
+ return LOCKFILES.has(base) || /\.lock$|-lock\.(json|ya?ml)$/i.test(base);
1963
+ }
1964
+ var MULTI_VERSION_KINDS = /* @__PURE__ */ new Set(["python-version", "nvmrc", "node-version"]);
1965
+ var SHAPE = /^([A-Za-z-]*)(\d+(?:\.\d+){0,2})(\.[xX*])?(.*)$/s;
1966
+ function shapeOf(raw) {
1967
+ const m = SHAPE.exec(raw);
1968
+ if (!m) return void 0;
1969
+ return { prefix: m[1], numbers: m[2].split("."), wildcard: m[3] ?? "", suffix: m[4] };
1970
+ }
1971
+ function targetParts(to) {
1972
+ return to.kind === "exact" || to.kind === "partial" ? to.version.split(".") : [];
1973
+ }
1974
+ function restyle(raw, target) {
1975
+ const shape = shapeOf(raw);
1976
+ if (!shape || shape.numbers.length > target.length) return void 0;
1977
+ return `${shape.prefix}${target.slice(0, shape.numbers.length).join(".")}${shape.wildcard}${shape.suffix}`;
1978
+ }
1979
+ function rangeText(runtime, target) {
1980
+ const parts = runtime === "node" ? 1 : 2;
1981
+ return target.length < parts ? void 0 : `>=${target.slice(0, parts).join(".")}`;
1982
+ }
1983
+ function yamlHazard(text2) {
1984
+ if (text2.startsWith(">") || text2.startsWith("|")) return 'cannot start with ">" or "|" in unquoted YAML (it opens a block scalar)';
1985
+ if (/^\d+\.\d+$/.test(text2) && String(Number(text2)) !== text2) return `would be read by YAML as the number ${Number(text2)}`;
1986
+ return void 0;
1987
+ }
1988
+ function decide(source, to, target, toText, fixRanges) {
1989
+ if (source.matrix === true) {
1990
+ return { skip: "matrix", detail: "a CI matrix entry is a deliberate multi-version test; edit it by hand" };
1991
+ }
1992
+ const c = source.constraint;
1993
+ switch (c.kind) {
1994
+ case "alias":
1995
+ return { skip: "alias", detail: `"${source.raw}" names no fixed version` };
1996
+ case "unknown":
1997
+ return { skip: "unparseable", detail: `the value could not be read (${c.reason})` };
1998
+ case "exact":
1999
+ case "partial": {
2000
+ const next = restyle(source.raw, target);
2001
+ if (next === void 0) {
2002
+ const need = c.kind === "exact" ? "a full version such as 24.1.0" : "major.minor such as 24.1";
2003
+ return { skip: "precision", detail: `"${source.raw}" needs --to to be ${need}` };
2004
+ }
2005
+ return next === source.raw ? { same: true } : { edit: next };
2006
+ }
2007
+ case "range": {
2008
+ if (!fixRanges) return { skip: "range", detail: `"${source.raw}" is a range; pass --fix-ranges to rewrite it` };
2009
+ const targetRange = toRange(to);
2010
+ if (targetRange !== void 0 && semver2.subset(targetRange, c.range)) {
2011
+ return { skip: "range-allows-target", detail: `"${source.raw}" already allows ${toText}` };
2012
+ }
2013
+ const text2 = source.kind === "go-mod" ? restyle(source.raw, target) : rangeText(source.runtime, target);
2014
+ if (text2 === void 0) {
2015
+ return { skip: "precision", detail: `"${source.raw}" needs --to to have more parts (for example 1.27)` };
2016
+ }
2017
+ return text2 === source.raw ? { same: true } : { edit: text2 };
2018
+ }
2019
+ }
2020
+ }
2021
+ function lineStarts(text2) {
2022
+ const starts = [0];
2023
+ for (let i = 0; i < text2.length; i++) if (text2.charCodeAt(i) === 10) starts.push(i + 1);
2024
+ return starts;
2025
+ }
2026
+ function offsetOf(starts, text2, line, column) {
2027
+ const start = starts[line - 1];
2028
+ if (start === void 0 || column < 1) return void 0;
2029
+ const end = line < starts.length ? starts[line] - 1 : text2.length;
2030
+ const at = start + column - 1;
2031
+ return at <= end ? at : void 0;
2032
+ }
2033
+ function extractAll(file, text2) {
2034
+ return [...extractNode(file, text2), ...extractPython(file, text2), ...extractGo(file, text2)];
2035
+ }
2036
+ var keyOf = (s) => `${s.file}\0${s.line}\0${s.column ?? ""}\0${s.kind}\0${s.runtime}`;
2037
+ function applyEdits(text2, edits) {
2038
+ const starts = lineStarts(text2);
2039
+ const placed = edits.map((e) => {
2040
+ const at = offsetOf(starts, text2, e.line, e.column);
2041
+ if (at === void 0 || !text2.startsWith(e.from, at) || e.from.includes("\n")) {
2042
+ throw new RangeError(`line ${e.line}, column ${e.column} does not hold "${e.from}"`);
2043
+ }
2044
+ return { at, e };
2045
+ }).sort((a, b) => a.at - b.at);
2046
+ for (let i = 1; i < placed.length; i++) {
2047
+ const before = placed[i - 1];
2048
+ if (before.at + before.e.from.length > placed[i].at) {
2049
+ throw new RangeError(`edits at line ${before.e.line} overlap`);
2050
+ }
2051
+ }
2052
+ let out = "";
2053
+ let cursor = 0;
2054
+ for (const { at, e } of placed) {
2055
+ out += text2.slice(cursor, at) + e.to;
2056
+ cursor = at + e.from.length;
2057
+ }
2058
+ return out + text2.slice(cursor);
2059
+ }
2060
+ function parseTarget(to) {
2061
+ const constraint = parseConstraint(to.trim(), "node");
2062
+ const parts = targetParts(constraint);
2063
+ if (parts.length === 0) {
2064
+ throw new FixError(`--to must be a version such as 24 or 24.1.0, got "${to}"`);
2065
+ }
2066
+ return { constraint, parts };
2067
+ }
2068
+ function planFix(options) {
2069
+ const { constraint: to, parts } = parseTarget(options.to);
2070
+ const toText = options.to.trim();
2071
+ const fixRanges = options.fixRanges === true;
2072
+ const considered = options.sources.filter((s) => options.runtime === void 0 || s.runtime === options.runtime);
2073
+ const skipped = [];
2074
+ const skip = (source, reason, detail) => {
2075
+ skipped.push({ source, reason, detail });
2076
+ };
2077
+ if (options.runtime === void 0) {
2078
+ const fixable = new Set(
2079
+ considered.filter((s) => s.matrix !== true && (s.constraint.kind === "exact" || s.constraint.kind === "partial" || fixRanges && s.constraint.kind === "range")).map((s) => s.runtime)
2080
+ );
2081
+ if (fixable.size > 1) {
2082
+ throw new FixError(`pins of several runtimes (${[...fixable].sort().join(", ")}) could be fixed: --to ${toText} cannot fit all of them; pass --runtime <one>`);
2083
+ }
2084
+ }
2085
+ const perFile = /* @__PURE__ */ new Map();
2086
+ for (const s of considered) perFile.set(`${s.file}\0${s.kind}`, (perFile.get(`${s.file}\0${s.kind}`) ?? 0) + 1);
2087
+ const unchanged = [];
2088
+ const wanted = /* @__PURE__ */ new Map();
2089
+ const textStarts = /* @__PURE__ */ new Map();
2090
+ for (const source of considered) {
2091
+ if (isLockfile(source.file)) {
2092
+ skip(source, "lockfile", "lockfiles are never edited");
2093
+ continue;
2094
+ }
2095
+ const text2 = options.files.get(source.file);
2096
+ if (text2 === void 0) {
2097
+ skip(source, "file-unreadable", "the file could not be read as UTF-8 text");
2098
+ continue;
2099
+ }
2100
+ if (MULTI_VERSION_KINDS.has(source.kind) && (perFile.get(`${source.file}\0${source.kind}`) ?? 0) > 1) {
2101
+ skip(source, "multi-version-file", "the file lists several versions on purpose; edit it by hand");
2102
+ continue;
2103
+ }
2104
+ const decision = decide(source, to, parts, toText, fixRanges);
2105
+ if ("same" in decision) {
2106
+ unchanged.push(source);
2107
+ continue;
2108
+ }
2109
+ if ("skip" in decision) {
2110
+ skip(source, decision.skip, decision.detail);
2111
+ continue;
2112
+ }
2113
+ if (source.column === void 0) {
2114
+ skip(source, "no-column", "the extractor gave no column, so the exact position is unknown");
2115
+ continue;
2116
+ }
2117
+ let starts = textStarts.get(source.file);
2118
+ if (!starts) {
2119
+ starts = lineStarts(text2);
2120
+ textStarts.set(source.file, starts);
2121
+ }
2122
+ const at = offsetOf(starts, text2, source.line, source.column);
2123
+ if (at === void 0 || source.raw === "" || !text2.startsWith(source.raw, at) || source.raw.includes("\n")) {
2124
+ skip(source, "raw-not-at-column", `"${source.raw}" is not at line ${source.line}, column ${source.column}`);
2125
+ continue;
2126
+ }
2127
+ if (text2.charAt(at + source.raw.length) === "@") {
2128
+ skip(source, "digest", "the reference is pinned by a digest (@sha256:...); a new version needs a new digest");
2129
+ continue;
2130
+ }
2131
+ const quoted = text2.charAt(at - 1) === '"' || text2.charAt(at - 1) === "'";
2132
+ if (/\.ya?ml$/i.test(source.file) && !quoted) {
2133
+ const hazard = yamlHazard(decision.edit);
2134
+ if (hazard !== void 0) {
2135
+ skip(source, "syntax", `"${decision.edit}" ${hazard}; quote the value first, then run --fix again`);
2136
+ continue;
2137
+ }
2138
+ }
2139
+ const key = `${source.file}\0${source.line}\0${source.column}`;
2140
+ const known = wanted.get(key);
2141
+ if (known === void 0) wanted.set(key, { source, to: decision.edit, sources: [source] });
2142
+ else if (known.to === decision.edit && known.source.raw === source.raw) known.sources.push(source);
2143
+ else {
2144
+ skip(source, "conflict", "two pins at the same place want different values");
2145
+ skip(known.source, "conflict", "two pins at the same place want different values");
2146
+ wanted.delete(key);
2147
+ }
2148
+ }
2149
+ const byFile = /* @__PURE__ */ new Map();
2150
+ for (const { source, to: next, sources } of wanted.values()) {
2151
+ const edit = { file: source.file, line: source.line, column: source.column, from: source.raw, to: next, sources };
2152
+ byFile.set(source.file, [...byFile.get(source.file) ?? [], edit]);
2153
+ }
2154
+ const edits = [];
2155
+ const files = /* @__PURE__ */ new Map();
2156
+ for (const [file, fileEdits] of [...byFile].sort(([a], [b]) => a.localeCompare(b))) {
2157
+ const before = options.files.get(file);
2158
+ let after;
2159
+ try {
2160
+ after = applyEdits(before, fileEdits);
2161
+ } catch (err) {
2162
+ for (const e of fileEdits) for (const s of e.sources) skip(s, "conflict", err.message);
2163
+ continue;
2164
+ }
2165
+ const problem = rereadProblem(file, before, after, fileEdits);
2166
+ if (problem !== void 0) {
2167
+ for (const e of fileEdits) for (const s of e.sources) skip(s, "reread", problem);
2168
+ continue;
2169
+ }
2170
+ edits.push(...fileEdits.sort((a, b) => a.line - b.line || a.column - b.column));
2171
+ files.set(file, after);
2172
+ }
2173
+ skipped.sort((a, b) => a.source.file.localeCompare(b.source.file) || a.source.line - b.source.line);
2174
+ return { target: toText, edits, unchanged, skipped, files };
2175
+ }
2176
+ function rereadProblem(file, before, after, edits) {
2177
+ const was = extractAll(file, before);
2178
+ const now = extractAll(file, after);
2179
+ if (was.length !== now.length) return `the file read as ${was.length} pins before and ${now.length} after the edit`;
2180
+ const edited = /* @__PURE__ */ new Map();
2181
+ for (const e of edits) for (const s of e.sources) edited.set(keyOf(s), e);
2182
+ const nowByKey = new Map(now.map((s) => [keyOf(s), s]));
2183
+ for (const s of was) {
2184
+ const key = keyOf(s);
2185
+ const found = nowByKey.get(key);
2186
+ if (found === void 0) return `the pin at line ${s.line} was no longer found after the edit`;
2187
+ const edit = edited.get(key);
2188
+ if (edit === void 0) {
2189
+ if (found.raw !== s.raw || found.constraint.kind !== s.constraint.kind) return `the pin at line ${s.line} changed although it was not edited`;
2190
+ } else if (found.raw !== edit.to) {
2191
+ return `line ${s.line} reads as "${found.raw}" after the edit, not "${edit.to}"`;
2192
+ } else if (found.constraint.kind !== s.constraint.kind) {
2193
+ const why = found.constraint.kind === "unknown" ? `: ${found.constraint.reason}` : "";
2194
+ return `line ${s.line} still reads "${found.raw}" after the edit, but no longer as a ${s.constraint.kind} version (now ${found.constraint.kind}${why})`;
2195
+ }
2196
+ }
2197
+ return void 0;
2198
+ }
2199
+ var BOM = "\uFEFF";
2200
+ function splitBom(text2) {
2201
+ return text2.startsWith(BOM) ? { bom: BOM, body: text2.slice(1) } : { bom: "", body: text2 };
2202
+ }
2203
+ function exactUtf8(bytes) {
2204
+ const text2 = bytes.toString("utf8");
2205
+ return Buffer.from(text2, "utf8").equals(bytes) ? text2 : void 0;
2206
+ }
2207
+ function linesOf(text2) {
2208
+ const lines = text2.split("\n");
2209
+ const finalNewline = lines.length > 1 && lines[lines.length - 1] === "";
2210
+ if (finalNewline) lines.pop();
2211
+ return { lines, finalNewline };
2212
+ }
2213
+ function unifiedDiff(file, before, after, context = 3) {
2214
+ const a = linesOf(before);
2215
+ const b = linesOf(after);
2216
+ if (a.lines.length !== b.lines.length) throw new RangeError("unifiedDiff compares texts with the same number of lines");
2217
+ const changed = [];
2218
+ a.lines.forEach((line, i) => {
2219
+ if (line !== b.lines[i]) changed.push(i);
2220
+ });
2221
+ if (changed.length === 0) return "";
2222
+ const groups = [];
2223
+ for (const i of changed) {
2224
+ const last = groups[groups.length - 1];
2225
+ if (last && i - last[1] <= 2 * context) last[1] = i;
2226
+ else groups.push([i, i]);
2227
+ }
2228
+ const noEol = "\";
2229
+ const out = [`--- a/${file}`, `+++ b/${file}`];
2230
+ const total = a.lines.length;
2231
+ const range = (start, len) => len === 1 ? `${start}` : `${start},${len}`;
2232
+ for (const [first, lastChange] of groups) {
2233
+ const from = Math.max(0, first - context);
2234
+ const to = Math.min(total - 1, lastChange + context);
2235
+ const len = to - from + 1;
2236
+ out.push(`@@ -${range(from + 1, len)} +${range(from + 1, len)} @@`);
2237
+ for (let i = from; i <= to; ) {
2238
+ if (a.lines[i] === b.lines[i]) {
2239
+ out.push(` ${a.lines[i]}`);
2240
+ if (i === total - 1 && !a.finalNewline) out.push(noEol);
2241
+ i++;
2242
+ continue;
2243
+ }
2244
+ let end = i;
2245
+ while (end + 1 <= to && a.lines[end + 1] !== b.lines[end + 1]) end++;
2246
+ const endsFile = end === total - 1 && !a.finalNewline;
2247
+ for (let k = i; k <= end; k++) out.push(`-${a.lines[k]}`);
2248
+ if (endsFile) out.push(noEol);
2249
+ for (let k = i; k <= end; k++) out.push(`+${b.lines[k]}`);
2250
+ if (endsFile) out.push(noEol);
2251
+ i = end + 1;
2252
+ }
2253
+ }
2254
+ return `${out.join("\n")}
2255
+ `;
2256
+ }
2257
+
2258
+ // src/report.ts
2259
+ var RANK = { error: 0, warning: 1, info: 2 };
2260
+ function failsAt(findings, failOn) {
2261
+ return findings.some((f) => RANK[f.severity] <= RANK[failOn]);
2262
+ }
2263
+ function countBySeverity(findings) {
2264
+ const counts = { error: 0, warning: 0, info: 0 };
2265
+ for (const f of findings) counts[f.severity]++;
2266
+ return counts;
2267
+ }
2268
+ function humanRange(range) {
2269
+ const major = /^>=(\d+)\.0\.0 <(\d+)\.0\.0-0$/.exec(range);
2270
+ if (major && Number(major[2]) === Number(major[1]) + 1) return `${major[1]}.x`;
2271
+ const minor = /^>=(\d+)\.(\d+)\.0 <(\d+)\.(\d+)\.0-0$/.exec(range);
2272
+ if (minor && minor[1] === minor[3] && Number(minor[4]) === Number(minor[2]) + 1) return `${minor[1]}.${minor[2]}.x`;
2273
+ return range;
2274
+ }
2275
+ function aliasNote(runtime, alias, date, resolve2) {
2276
+ if (isFloatingAlias(alias)) return void 0;
2277
+ const range = resolve2(runtime, alias);
2278
+ if (!range) return void 0;
2279
+ return `${alias} means ${runtime} ${humanRange(range)} on ${date}, per the bundled release data; it moves when a new line becomes LTS`;
2280
+ }
2281
+ function scopeLabel(scopes, roots) {
2282
+ if (scopes.length === 0) return "not tied to a project";
2283
+ if (roots.length > 1 && scopes.length === roots.length) return "every project root";
2284
+ return scopes.map((s) => s === "." ? ". (repo root)" : s).join(", ");
2285
+ }
2286
+ function pad(text2, width) {
2287
+ return text2.length >= width ? `${text2} ` : text2 + " ".repeat(width - text2.length);
2288
+ }
2289
+ function unboundSources(sources) {
2290
+ return sources.filter((s) => s.boundTo !== void 0 && s.boundTo.length === 0).sort((a, b) => a.file === b.file ? a.line - b.line : a.file < b.file ? -1 : 1);
2291
+ }
2292
+ function formatText(report) {
2293
+ const lines = [];
2294
+ const counts = countBySeverity(report.findings);
2295
+ const pins = report.sources.length;
2296
+ lines.push(
2297
+ `runtime-pin-check: ${pins} pin${pins === 1 ? "" : "s"} in ${report.roots.length} project root${report.roots.length === 1 ? "" : "s"}, checked on ${report.date} (end-of-life data from ${report.dataDate})`
2298
+ );
2299
+ lines.push("");
2300
+ if (report.findings.length === 0) {
2301
+ lines.push(pins === 0 ? "No Node, Python or Go version pins found." : "No problems found.");
2302
+ } else {
2303
+ const groups = /* @__PURE__ */ new Map();
2304
+ for (const f of report.findings) {
2305
+ const key = scopeLabel(f.scopes, report.roots);
2306
+ const list2 = groups.get(key);
2307
+ if (list2) list2.push(f);
2308
+ else groups.set(key, [f]);
2309
+ }
2310
+ for (const [label, findings] of groups) {
2311
+ lines.push(label);
2312
+ for (const f of findings) {
2313
+ lines.push(` ${pad(f.severity, 8)}${pad(f.code, 19)}${f.runtime}`);
2314
+ lines.push(` ${f.message}`);
2315
+ const width = Math.max(...f.sources.map((s) => `${s.file}:${s.line}`.length)) + 2;
2316
+ for (const s of f.sources) {
2317
+ lines.push(` ${pad(`${s.file}:${s.line}`, width)}${s.raw}`);
2318
+ if (s.constraint.kind === "alias") {
2319
+ const note = aliasNote(f.runtime, s.constraint.alias, report.date, report.resolveAlias);
2320
+ if (note) lines.push(` ${" ".repeat(width)}(${note})`);
2321
+ }
2322
+ }
2323
+ }
2324
+ lines.push("");
2325
+ }
2326
+ if (lines[lines.length - 1] === "") lines.pop();
2327
+ }
2328
+ const unbound = unboundSources(report.sources);
2329
+ if (unbound.length > 0) {
2330
+ lines.push("");
2331
+ lines.push("Not tied to a project (no working-directory, no root manifest, no path naming a project; compared with nothing):");
2332
+ for (const s of unbound) lines.push(` ${s.runtime} ${s.raw} ${s.file}:${s.line}`);
2333
+ }
2334
+ if (report.singleSource.length > 0) {
2335
+ lines.push("");
2336
+ lines.push("Pinned in one place only (nothing to compare):");
2337
+ for (const s of report.singleSource) {
2338
+ lines.push(` ${s.root === "." ? ". (repo root)" : s.root} ${s.runtime} ${s.raw} ${s.file}:${s.line}`);
2339
+ }
2340
+ }
2341
+ if (report.diagnostics.length > 0) {
2342
+ lines.push("");
2343
+ lines.push("Could not fully read (syntax errors; they do not change the exit code):");
2344
+ for (const d of report.diagnostics) lines.push(` ${d.file}:${d.line}${d.column === void 0 ? "" : `:${d.column}`} ${d.message}`);
2345
+ }
2346
+ lines.push("");
2347
+ lines.push(`${counts.error} error${counts.error === 1 ? "" : "s"}, ${counts.warning} warning${counts.warning === 1 ? "" : "s"}, ${counts.info} info`);
2348
+ if (report.excludedFiles > 0) {
2349
+ const n = report.excludedFiles;
2350
+ lines.push(`${n} file${n === 1 ? "" : "s"} skipped by exclusion (fixture folders and --exclude; --include-fixtures scans fixtures)`);
2351
+ }
2352
+ return `${lines.join("\n")}
2353
+ `;
2354
+ }
2355
+ function formatJson(report) {
2356
+ const counts = countBySeverity(report.findings);
2357
+ const doc = {
2358
+ schema: 1,
2359
+ directory: report.directory,
2360
+ date: report.date,
2361
+ eolDataDate: report.dataDate,
2362
+ roots: report.roots,
2363
+ summary: {
2364
+ ...counts,
2365
+ sources: report.sources.length,
2366
+ excludedFiles: report.excludedFiles,
2367
+ singleSource: report.singleSource,
2368
+ unbound: unboundSources(report.sources).map((s) => ({ runtime: s.runtime, file: s.file, line: s.line, raw: s.raw })),
2369
+ unreadable: report.diagnostics.length
2370
+ },
2371
+ diagnostics: report.diagnostics,
2372
+ findings: report.findings.map((f) => ({
2373
+ ...f,
2374
+ sources: f.sources.map((s) => {
2375
+ const note = s.constraint.kind === "alias" ? aliasNote(f.runtime, s.constraint.alias, report.date, report.resolveAlias) : void 0;
2376
+ return note ? { ...s, note } : s;
2377
+ })
2378
+ })),
2379
+ sources: report.sources.map((s) => ({ ...s, constraintText: describeConstraint(s.constraint) }))
2380
+ };
2381
+ return `${JSON.stringify(doc, null, 2)}
2382
+ `;
2383
+ }
2384
+ function escapeData(text2) {
2385
+ return text2.replace(/%/g, "%25").replace(/\r/g, "%0D").replace(/\n/g, "%0A");
2386
+ }
2387
+ function escapeProperty(text2) {
2388
+ return escapeData(text2).replace(/:/g, "%3A").replace(/,/g, "%2C");
2389
+ }
2390
+ var COMMAND = { error: "error", warning: "warning", info: "notice" };
2391
+ function formatAnnotations(findings, pathOf = (f) => f) {
2392
+ const lines = findings.map((f) => {
2393
+ const first = f.sources[0];
2394
+ const props = first ? `file=${escapeProperty(pathOf(first.file))},line=${first.line},title=${escapeProperty(f.code)}` : `title=${escapeProperty(f.code)}`;
2395
+ return `::${COMMAND[f.severity]} ${props}::${escapeData(f.message)}`;
2396
+ });
2397
+ return lines.length > 0 ? `${lines.join("\n")}
2398
+ ` : "";
2399
+ }
2400
+ function formatDiagnosticAnnotations(diagnostics, pathOf = (f) => f) {
2401
+ const lines = diagnostics.map((d) => {
2402
+ const col = d.column === void 0 ? "" : `,col=${d.column}`;
2403
+ return `::warning file=${escapeProperty(pathOf(d.file))},line=${d.line}${col},title=UNREADABLE_FILE::${escapeData(d.message)}`;
2404
+ });
2405
+ return lines.length > 0 ? `${lines.join("\n")}
2406
+ ` : "";
2407
+ }
2408
+
2409
+ // package.json
2410
+ var package_default = {
2411
+ name: "runtime-pin-check",
2412
+ version: "0.1.1",
2413
+ description: "Find Node, Python and Go version pins that disagree across a repo's files, with file and line.",
2414
+ license: "MIT",
2415
+ type: "module",
2416
+ engines: {
2417
+ node: ">=22"
2418
+ },
2419
+ files: [
2420
+ "dist"
2421
+ ],
2422
+ bin: {
2423
+ "runtime-pin-check": "dist/cli.js"
2424
+ },
2425
+ main: "./dist/index.js",
2426
+ types: "./dist/index.d.ts",
2427
+ exports: {
2428
+ ".": {
2429
+ types: "./dist/index.d.ts",
2430
+ import: "./dist/index.js"
2431
+ },
2432
+ "./package.json": "./package.json"
2433
+ },
2434
+ sideEffects: false,
2435
+ scripts: {
2436
+ typecheck: "tsc --noEmit",
2437
+ test: "vitest run",
2438
+ build: "tsup",
2439
+ prepublishOnly: "npm run typecheck && npm test && npm run build"
2440
+ },
2441
+ keywords: [
2442
+ "node-version",
2443
+ "nvmrc",
2444
+ "engines",
2445
+ "python-version",
2446
+ "go-version",
2447
+ "ci",
2448
+ "monorepo"
2449
+ ],
2450
+ dependencies: {
2451
+ semver: "7.7.2",
2452
+ "smol-toml": "1.9.1",
2453
+ yaml: "2.9.1"
2454
+ },
2455
+ devDependencies: {
2456
+ "@types/node": "22.20.5",
2457
+ "@types/semver": "7.7.0",
2458
+ tsup: "8.5.0",
2459
+ typescript: "5.9.3",
2460
+ vitest: "3.2.4"
2461
+ },
2462
+ repository: {
2463
+ type: "git",
2464
+ url: "git+https://github.com/Mammost1/runtime-pin-check.git"
2465
+ },
2466
+ homepage: "https://github.com/Mammost1/runtime-pin-check#readme",
2467
+ bugs: {
2468
+ url: "https://github.com/Mammost1/runtime-pin-check/issues"
2469
+ }
2470
+ };
2471
+
2472
+ // src/cli.ts
2473
+ var VERSION = package_default.version;
2474
+ var RUNTIMES2 = ["node", "python", "go"];
2475
+ var SEVERITIES = ["error", "warning", "info"];
2476
+ var RANK2 = { error: 0, warning: 1, info: 2 };
2477
+ var MAX_FILE_BYTES = 1024 * 1024;
2478
+ var CANDIDATE = /(^|\/)(\.nvmrc|\.node-version|\.python-version|\.tool-versions|package\.json|pyproject\.toml|runtime\.txt|go\.mod|[^/]*mise[^/]*\.toml|config\.toml|[^/]*dockerfile[^/]*|\.gitlab-ci\.ya?ml|action\.ya?ml)$/i;
2479
+ var GITHUB_YAML = /^\.github\/.+\.ya?ml$/i;
2480
+ var USAGE = `Usage: runtime-pin-check [dir] [options]
2481
+
2482
+ Finds Node, Python and Go version pins that disagree across a repo's files.
2483
+
2484
+ Options:
2485
+ --json print the result as JSON
2486
+ --runtime node,python,go only these runtimes (default: all)
2487
+ --fail-on error|warning|info exit 1 when a finding is at or above this level (default: error)
2488
+ --date YYYY-MM-DD check end-of-life and LTS aliases as of this date (default: today, UTC)
2489
+ --include-fixtures also scan fixture folders (skipped by default: fixtures/, fixture/,
2490
+ __fixtures__/, test_fixtures/, test-fixtures/, testdata/, test_data/ ...)
2491
+ --exclude <glob> skip matching paths (repeatable; 'examples', 'docs/**', '*.Dockerfile')
2492
+ --fix --to <version> rewrite pins to <version> (with --runtime <one>, --dry-run, --fix-ranges)
2493
+ -v, --version print the version
2494
+ -h, --help show this help
2495
+
2496
+ Exit codes: 0 no finding at or above --fail-on, 1 findings, 2 usage or I/O error.
2497
+ `;
2498
+ var UsageError = class extends Error {
2499
+ };
2500
+ function parseCliArgs(argv) {
2501
+ let parsed;
2502
+ try {
2503
+ parsed = parseArgs({
2504
+ args: [...argv],
2505
+ allowPositionals: true,
2506
+ strict: true,
2507
+ options: {
2508
+ json: { type: "boolean" },
2509
+ runtime: { type: "string" },
2510
+ "fail-on": { type: "string" },
2511
+ date: { type: "string" },
2512
+ "include-fixtures": { type: "boolean" },
2513
+ exclude: { type: "string", multiple: true },
2514
+ fix: { type: "boolean" },
2515
+ to: { type: "string" },
2516
+ "dry-run": { type: "boolean" },
2517
+ "fix-ranges": { type: "boolean" },
2518
+ help: { type: "boolean", short: "h" },
2519
+ version: { type: "boolean", short: "v" }
2520
+ }
2521
+ });
2522
+ } catch (err) {
2523
+ throw new UsageError(err instanceof Error ? err.message : String(err));
2524
+ }
2525
+ const v = parsed.values;
2526
+ if (parsed.positionals.length > 1) throw new UsageError(`expected one directory, got ${parsed.positionals.length}`);
2527
+ let runtimes = [...RUNTIMES2];
2528
+ if (v.runtime !== void 0) {
2529
+ const list2 = v.runtime.split(",").map((r) => r.trim().toLowerCase()).filter((r) => r !== "");
2530
+ const bad = list2.filter((r) => !RUNTIMES2.includes(r));
2531
+ if (list2.length === 0 || bad.length > 0) throw new UsageError(`--runtime takes node, python and/or go, got "${v.runtime}"`);
2532
+ runtimes = [...new Set(list2)];
2533
+ }
2534
+ const failOn = (v["fail-on"] ?? "error").toLowerCase();
2535
+ if (!SEVERITIES.includes(failOn)) throw new UsageError(`--fail-on takes error, warning or info, got "${v["fail-on"]}"`);
2536
+ const fix = v.fix === true;
2537
+ if (!fix) {
2538
+ for (const flag of ["to", "dry-run", "fix-ranges"]) {
2539
+ if (v[flag] !== void 0) throw new UsageError(`--${flag} only works together with --fix`);
2540
+ }
2541
+ } else {
2542
+ if (v.to === void 0 || v.to.trim() === "") throw new UsageError("--fix needs --to <version>");
2543
+ if (v.json) throw new UsageError("--fix cannot be combined with --json");
2544
+ }
2545
+ return {
2546
+ dir: parsed.positionals[0] ?? ".",
2547
+ json: v.json === true,
2548
+ runtimes,
2549
+ failOn,
2550
+ date: v.date,
2551
+ includeFixtures: v["include-fixtures"] === true,
2552
+ exclude: v.exclude ?? [],
2553
+ fix,
2554
+ to: v.to,
2555
+ dryRun: v["dry-run"] === true,
2556
+ fixRanges: v["fix-ranges"] === true,
2557
+ help: v.help === true,
2558
+ version: v.version === true
2559
+ };
2560
+ }
2561
+ async function readDirectory(dir, files, runtimes = RUNTIMES2) {
2562
+ const sources = [];
2563
+ const diagnostics = [];
2564
+ for (const file of files) {
2565
+ if (!CANDIDATE.test(file) && !GITHUB_YAML.test(file)) continue;
2566
+ const path = resolve(dir, file);
2567
+ const info = await stat(path);
2568
+ if (info.size > MAX_FILE_BYTES) continue;
2569
+ const text2 = splitBom(await readFile(path, "utf8")).body;
2570
+ sources.push(...extractNode(file, text2), ...extractPython(file, text2), ...extractGo(file, text2));
2571
+ diagnostics.push(...diagnoseFile(file, text2, runtimes));
2572
+ }
2573
+ return { sources, diagnostics };
2574
+ }
2575
+ async function collectSources(dir, files) {
2576
+ return (await readDirectory(dir, files)).sources;
2577
+ }
2578
+ function sortFindings(findings) {
2579
+ return findings.sort(
2580
+ (a, b) => RANK2[a.severity] - RANK2[b.severity] || (a.sources[0]?.file ?? "").localeCompare(b.sources[0]?.file ?? "") || (a.sources[0]?.line ?? 0) - (b.sources[0]?.line ?? 0) || a.code.localeCompare(b.code)
2581
+ );
2582
+ }
2583
+ async function checkDirectory(dir, options = {}) {
2584
+ const runtimes = options.runtimes ?? RUNTIMES2;
2585
+ const date = checkDate(options.date);
2586
+ const snapshot = bundledSnapshot();
2587
+ const resolveAlias = createAliasResolver(snapshot, date);
2588
+ const scan = await scanFiles(dir, { includeFixtures: options.includeFixtures, exclude: options.exclude });
2589
+ const files = scan.files;
2590
+ const roots = projectRootsOf(files);
2591
+ const read = await readDirectory(dir, files, runtimes);
2592
+ const sources = bindSources(
2593
+ read.sources.filter((s) => runtimes.includes(s.runtime)),
2594
+ roots,
2595
+ manifestRuntimesOf(files)
2596
+ );
2597
+ const findings = sortFindings([
2598
+ ...compareSources(sources, roots, { resolveAlias }),
2599
+ ...eolFindings(sources, roots, { snapshot, date })
2600
+ ]);
2601
+ const singleSource = groupByScope(sources, roots).filter((g) => g.sources.length === 1).filter((g) => {
2602
+ const c = g.sources[0].constraint;
2603
+ return c.kind !== "unknown" && !(c.kind === "alias" && isFloatingAlias(c.alias));
2604
+ }).map((g) => {
2605
+ const s = g.sources[0];
2606
+ return { root: g.root, runtime: g.runtime, file: s.file, line: s.line, raw: s.raw };
2607
+ });
2608
+ return { directory: dir, date, dataDate: snapshot.fetchedAt, roots, sources, findings, singleSource, excludedFiles: scan.excluded, diagnostics: read.diagnostics, resolveAlias };
2609
+ }
2610
+ var defaultIo = () => ({
2611
+ stdout: (t) => process.stdout.write(t),
2612
+ stderr: (t) => process.stderr.write(t),
2613
+ env: process.env,
2614
+ cwd: process.cwd()
2615
+ });
2616
+ function formatFixSummary(plan, options, dryRun) {
2617
+ const files = plan.files.size;
2618
+ const lines = [
2619
+ `runtime-pin-check --fix --to ${plan.target}${options.fixRanges ? " --fix-ranges" : ""}${dryRun ? " (dry run: nothing written)" : ""}`,
2620
+ plan.edits.length === 0 ? "nothing to change" : `${dryRun ? "would change" : "changed"} ${plan.edits.length} pin${plan.edits.length === 1 ? "" : "s"} in ${files} file${files === 1 ? "" : "s"}:`
2621
+ ];
2622
+ for (const e of plan.edits) lines.push(` ${e.file}:${e.line} ${e.from} -> ${e.to}`);
2623
+ if (plan.unchanged.length > 0) lines.push(`already at ${plan.target}: ${plan.unchanged.length} pin${plan.unchanged.length === 1 ? "" : "s"}`);
2624
+ if (plan.skipped.length > 0) {
2625
+ lines.push(`left alone (${plan.skipped.length}); nothing is guessed:`);
2626
+ const groups = /* @__PURE__ */ new Map();
2627
+ for (const s of plan.skipped) {
2628
+ const key = `${s.source.file}\0${s.source.line}\0${s.reason}`;
2629
+ const group = groups.get(key);
2630
+ if (group) group.raws.push(s.source.raw);
2631
+ else groups.set(key, { file: s.source.file, line: s.source.line, raws: [s.source.raw], reason: s.reason, detail: s.detail });
2632
+ }
2633
+ for (const g of groups.values()) lines.push(` ${g.file}:${g.line} ${g.raws.map((r) => `"${r}"`).join(", ")} (${g.reason}): ${g.detail}`);
2634
+ }
2635
+ return `${lines.join("\n")}
2636
+ `;
2637
+ }
2638
+ async function runFix(options, io) {
2639
+ const dir = resolve(io.cwd, options.dir);
2640
+ try {
2641
+ if (!(await stat(dir)).isDirectory()) throw new Error(`${options.dir} is not a directory`);
2642
+ } catch (err) {
2643
+ io.stderr(`runtime-pin-check: cannot read ${options.dir}: ${err.message}
2644
+ `);
2645
+ return 2;
2646
+ }
2647
+ const written = [];
2648
+ try {
2649
+ const scan = await scanFiles(dir, { includeFixtures: options.includeFixtures, exclude: options.exclude });
2650
+ const sources = (await collectSources(dir, scan.files)).filter((s) => options.runtimes.includes(s.runtime));
2651
+ const originals = /* @__PURE__ */ new Map();
2652
+ const texts = /* @__PURE__ */ new Map();
2653
+ const boms = /* @__PURE__ */ new Map();
2654
+ for (const file of new Set(sources.map((s) => s.file))) {
2655
+ const bytes = await readFile(resolve(dir, file));
2656
+ const text2 = exactUtf8(bytes);
2657
+ originals.set(file, bytes);
2658
+ if (text2 === void 0) continue;
2659
+ const { bom, body } = splitBom(text2);
2660
+ texts.set(file, body);
2661
+ boms.set(file, bom);
2662
+ }
2663
+ const plan = planFix({
2664
+ sources,
2665
+ files: texts,
2666
+ to: options.to,
2667
+ ...options.runtimes.length === 1 ? { runtime: options.runtimes[0] } : {},
2668
+ fixRanges: options.fixRanges
2669
+ });
2670
+ if (options.dryRun) {
2671
+ for (const [file, after] of plan.files) {
2672
+ const bom = boms.get(file);
2673
+ io.stdout(unifiedDiff(file, bom + texts.get(file), bom + after));
2674
+ }
2675
+ io.stderr(formatFixSummary(plan, options, true));
2676
+ return 0;
2677
+ }
2678
+ for (const [file, after] of plan.files) {
2679
+ const path = resolve(dir, file);
2680
+ if (!(await readFile(path)).equals(originals.get(file))) {
2681
+ throw new Error(`${file} changed while --fix was running; nothing more was written, run it again`);
2682
+ }
2683
+ await writeFile(path, boms.get(file) + after, "utf8");
2684
+ written.push(file);
2685
+ }
2686
+ io.stdout(formatFixSummary(plan, options, false));
2687
+ return 0;
2688
+ } catch (err) {
2689
+ const done = written.length > 0 ? ` (already written: ${written.join(", ")})` : "";
2690
+ io.stderr(`runtime-pin-check: ${err instanceof FixError ? err.message : err.message}${done}
2691
+ `);
2692
+ return 2;
2693
+ }
2694
+ }
2695
+ async function run(argv, io = defaultIo()) {
2696
+ let options;
2697
+ try {
2698
+ options = parseCliArgs(argv);
2699
+ } catch (err) {
2700
+ io.stderr(`runtime-pin-check: ${err.message}
2701
+
2702
+ ${USAGE}`);
2703
+ return 2;
2704
+ }
2705
+ if (options.version) {
2706
+ io.stdout(`${VERSION}
2707
+ `);
2708
+ return 0;
2709
+ }
2710
+ if (options.help) {
2711
+ io.stdout(USAGE);
2712
+ return 0;
2713
+ }
2714
+ if (options.fix) return runFix(options, io);
2715
+ const dir = resolve(io.cwd, options.dir);
2716
+ try {
2717
+ const info = await stat(dir);
2718
+ if (!info.isDirectory()) throw new Error(`${options.dir} is not a directory`);
2719
+ } catch (err) {
2720
+ io.stderr(`runtime-pin-check: cannot read ${options.dir}: ${err.message}
2721
+ `);
2722
+ return 2;
2723
+ }
2724
+ let report;
2725
+ try {
2726
+ report = await checkDirectory(dir, {
2727
+ runtimes: options.runtimes,
2728
+ date: options.date,
2729
+ includeFixtures: options.includeFixtures,
2730
+ exclude: options.exclude
2731
+ });
2732
+ } catch (err) {
2733
+ io.stderr(`runtime-pin-check: ${err.message}
2734
+ `);
2735
+ return 2;
2736
+ }
2737
+ report.directory = options.dir;
2738
+ const text2 = options.json ? formatJson(report) : formatText(report);
2739
+ io.stdout(text2);
2740
+ if (io.env.GITHUB_ACTIONS === "true") {
2741
+ const pathOf = (file) => relative(io.cwd, resolve(dir, file)).split(sep).join("/");
2742
+ const annotations = formatAnnotations(report.findings, pathOf) + formatDiagnosticAnnotations(report.diagnostics, pathOf);
2743
+ if (options.json) io.stderr(annotations);
2744
+ else io.stdout(annotations);
2745
+ }
2746
+ return failsAt(report.findings, options.failOn) ? 1 : 0;
2747
+ }
2748
+ function isMain() {
2749
+ const entry = process.argv[1];
2750
+ if (entry === void 0) return false;
2751
+ try {
2752
+ return import.meta.url === pathToFileURL(realpathSync(entry)).href;
2753
+ } catch {
2754
+ return false;
2755
+ }
2756
+ }
2757
+ if (isMain()) {
2758
+ run(process.argv.slice(2)).then(
2759
+ (code) => {
2760
+ process.exitCode = code;
2761
+ },
2762
+ (err) => {
2763
+ process.stderr.write(`runtime-pin-check: ${err instanceof Error ? err.message : String(err)}
2764
+ `);
2765
+ process.exitCode = 2;
2766
+ }
2767
+ );
2768
+ }
2769
+ export {
2770
+ USAGE,
2771
+ VERSION,
2772
+ checkDirectory,
2773
+ collectSources,
2774
+ parseCliArgs,
2775
+ readDirectory,
2776
+ run,
2777
+ runFix
2778
+ };
2779
+ //# sourceMappingURL=cli.js.map