@looply/core 0.5.10 → 0.5.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,826 @@
1
+ "use strict";
2
+ /**
3
+ * SCHEDULED MAINTENANCE — the shapes the server stores and the machine obeys,
4
+ * and the pure planner that turns one repository's facts into small goals.
5
+ *
6
+ * Once a week, per component that opted in (AutoRyn's "Maintenance" card, or the
7
+ * console), the machine that drives the repository looks at it — `npm outdated`,
8
+ * `npm audit`, which packages nothing imports — and proposes a handful of small
9
+ * goals: one per upgrade group, one per security tier, one dead-code pass. Each
10
+ * becomes an AutoRyn ticket of type `maintenance` and a Looply goal like any
11
+ * other, through the same gates, the same review flow and the same delivery.
12
+ *
13
+ * THREE RULES THAT ARE NOT SETTINGS:
14
+ *
15
+ * 1. A MAJOR UPGRADE IS NEVER MERGED BY LOOPLY. Whatever "When Looply finishes"
16
+ * says, a goal whose maintenance payload says `autoMerge: false` is delivered
17
+ * as a pull request and a person merges it (`maintenanceDeliverMode`).
18
+ * 2. A NATIVE MODULE IN AN EXPO APP IS NEVER TOUCHED WITHOUT A BUILD NOTE. Such
19
+ * packages go in their own group, upgraded with `npx expo install`, and the
20
+ * goal and its pull request say a new native build is needed. Never merged
21
+ * automatically either: an over-the-air update cannot carry it.
22
+ * 3. MAINTENANCE NEVER STARVES REAL WORK. Its goals run at `MAINTENANCE_PRIORITY`,
23
+ * do not age past real tickets, run one at a time and leave a slot free
24
+ * (see `schedule.ts`), and there are at most `caps.goalsPerWeek` a week and
25
+ * `caps.openGoals` open at once per component.
26
+ *
27
+ * Nothing here does I/O. The machine gathers the facts (`maintenance-facts.ts` in
28
+ * the CLI); this file decides.
29
+ */
30
+ Object.defineProperty(exports, "__esModule", { value: true });
31
+ exports.MAINTENANCE_TEXT_LIMIT = exports.EXPO_BUILD_NOTE = exports.PACKAGE_MANAGERS = exports.MAX_OPEN_GOALS = exports.MAX_GOALS_PER_WEEK = exports.DEFAULT_MAINTENANCE_SETTINGS = exports.MAINTENANCE_PRIORITY = exports.AUDIT_SEVERITIES = exports.MAINTENANCE_KINDS = void 0;
32
+ exports.validateMaintenanceSettings = validateMaintenanceSettings;
33
+ exports.isoWeek = isoWeek;
34
+ exports.lastScheduledSlot = lastScheduledSlot;
35
+ exports.maintenanceDue = maintenanceDue;
36
+ exports.validateGoalMaintenance = validateGoalMaintenance;
37
+ exports.maintenanceDeliverMode = maintenanceDeliverMode;
38
+ exports.parseVersion = parseVersion;
39
+ exports.bumpOf = bumpOf;
40
+ exports.familyOf = familyOf;
41
+ exports.expoManaged = expoManaged;
42
+ exports.fitGoalText = fitGoalText;
43
+ exports.planMaintenance = planMaintenance;
44
+ exports.parseOutdatedJson = parseOutdatedJson;
45
+ exports.parseAuditJson = parseAuditJson;
46
+ exports.changelogUrlOf = changelogUrlOf;
47
+ exports.packageManagerOf = packageManagerOf;
48
+ /* ───────────────────────────────────────────────────────────── settings ── */
49
+ exports.MAINTENANCE_KINDS = ['upgrade', 'security', 'dead-code'];
50
+ /** npm audit's severities, least to most severe. */
51
+ exports.AUDIT_SEVERITIES = ['low', 'moderate', 'high', 'critical'];
52
+ /**
53
+ * Below every goal a person or AutoRyn asks for (0 by default, AutoRyn's ticket
54
+ * priorities are small positive numbers). The server forces it on any goal that
55
+ * carries a maintenance payload, so no caller can raise one.
56
+ */
57
+ exports.MAINTENANCE_PRIORITY = -500;
58
+ exports.DEFAULT_MAINTENANCE_SETTINGS = Object.freeze({
59
+ enabled: false,
60
+ schedule: Object.freeze({ weekday: 1, hour: 3 }),
61
+ upgrades: Object.freeze({ enabled: true, major: false }),
62
+ security: Object.freeze({ enabled: true, minSeverity: 'high' }),
63
+ deadCode: Object.freeze({ enabled: false }),
64
+ caps: Object.freeze({ goalsPerWeek: 4, openGoals: 2 }),
65
+ });
66
+ exports.MAX_GOALS_PER_WEEK = 20;
67
+ exports.MAX_OPEN_GOALS = 10;
68
+ const isObj = (x) => typeof x === 'object' && x !== null && !Array.isArray(x);
69
+ /**
70
+ * Is this a maintenance setting the machine will act on? A missing section or
71
+ * field takes its default, so `{ enabled: true }` is a whole setting. Returns a
72
+ * clean, complete copy; every refusal names the key.
73
+ */
74
+ function validateMaintenanceSettings(x) {
75
+ if (!isObj(x))
76
+ return { ok: false, key: 'settings', because: 'must be an object like { "enabled": true }' };
77
+ const d = exports.DEFAULT_MAINTENANCE_SETTINGS;
78
+ const known = ['enabled', 'schedule', 'upgrades', 'security', 'deadCode', 'caps'];
79
+ for (const k of Object.keys(x))
80
+ if (!known.includes(k))
81
+ return { ok: false, key: k, because: `is not a maintenance setting (${known.join(', ')})` };
82
+ const section = (name, fields) => {
83
+ const v = x[name];
84
+ if (v === undefined || v === null)
85
+ return {};
86
+ if (!isObj(v))
87
+ return 'must be an object';
88
+ for (const k of Object.keys(v))
89
+ if (!fields.includes(k))
90
+ return `has no field "${k}" (${fields.join(', ')})`;
91
+ return v;
92
+ };
93
+ const bool = (v, dflt) => (v === undefined || v === null ? dflt : typeof v === 'boolean' ? v : null);
94
+ const int = (v, dflt, min, max) => v === undefined || v === null ? dflt : typeof v === 'number' && Number.isInteger(v) && v >= min && v <= max ? v : null;
95
+ const enabled = bool(x['enabled'], d.enabled);
96
+ if (enabled === null)
97
+ return { ok: false, key: 'enabled', because: 'must be true or false' };
98
+ const sch = section('schedule', ['weekday', 'hour']);
99
+ if (typeof sch === 'string')
100
+ return { ok: false, key: 'schedule', because: sch };
101
+ const weekday = int(sch['weekday'], d.schedule.weekday, 0, 6);
102
+ if (weekday === null)
103
+ return { ok: false, key: 'schedule.weekday', because: 'must be a whole number 0 (Sunday) to 6 (Saturday)' };
104
+ const hour = int(sch['hour'], d.schedule.hour, 0, 23);
105
+ if (hour === null)
106
+ return { ok: false, key: 'schedule.hour', because: 'must be a whole number 0 to 23 (UTC)' };
107
+ const up = section('upgrades', ['enabled', 'major']);
108
+ if (typeof up === 'string')
109
+ return { ok: false, key: 'upgrades', because: up };
110
+ const upEnabled = bool(up['enabled'], d.upgrades.enabled);
111
+ if (upEnabled === null)
112
+ return { ok: false, key: 'upgrades.enabled', because: 'must be true or false' };
113
+ const major = bool(up['major'], d.upgrades.major);
114
+ if (major === null)
115
+ return { ok: false, key: 'upgrades.major', because: 'must be true or false' };
116
+ const sec = section('security', ['enabled', 'minSeverity']);
117
+ if (typeof sec === 'string')
118
+ return { ok: false, key: 'security', because: sec };
119
+ const secEnabled = bool(sec['enabled'], d.security.enabled);
120
+ if (secEnabled === null)
121
+ return { ok: false, key: 'security.enabled', because: 'must be true or false' };
122
+ const sev = sec['minSeverity'] === undefined || sec['minSeverity'] === null ? d.security.minSeverity : sec['minSeverity'];
123
+ if (typeof sev !== 'string' || !exports.AUDIT_SEVERITIES.includes(sev)) {
124
+ return { ok: false, key: 'security.minSeverity', because: `must be one of ${exports.AUDIT_SEVERITIES.join(', ')}` };
125
+ }
126
+ const dc = section('deadCode', ['enabled']);
127
+ if (typeof dc === 'string')
128
+ return { ok: false, key: 'deadCode', because: dc };
129
+ const dcEnabled = bool(dc['enabled'], d.deadCode.enabled);
130
+ if (dcEnabled === null)
131
+ return { ok: false, key: 'deadCode.enabled', because: 'must be true or false' };
132
+ const caps = section('caps', ['goalsPerWeek', 'openGoals']);
133
+ if (typeof caps === 'string')
134
+ return { ok: false, key: 'caps', because: caps };
135
+ const perWeek = int(caps['goalsPerWeek'], d.caps.goalsPerWeek, 1, exports.MAX_GOALS_PER_WEEK);
136
+ if (perWeek === null)
137
+ return { ok: false, key: 'caps.goalsPerWeek', because: `must be a whole number 1 to ${exports.MAX_GOALS_PER_WEEK}` };
138
+ const open = int(caps['openGoals'], d.caps.openGoals, 1, exports.MAX_OPEN_GOALS);
139
+ if (open === null)
140
+ return { ok: false, key: 'caps.openGoals', because: `must be a whole number 1 to ${exports.MAX_OPEN_GOALS}` };
141
+ return {
142
+ ok: true,
143
+ settings: {
144
+ enabled,
145
+ schedule: { weekday, hour },
146
+ upgrades: { enabled: upEnabled, major },
147
+ security: { enabled: secEnabled, minSeverity: sev },
148
+ deadCode: { enabled: dcEnabled },
149
+ caps: { goalsPerWeek: perWeek, openGoals: open },
150
+ },
151
+ };
152
+ }
153
+ /* ────────────────────────────────────────────────────────────── the week ── */
154
+ /** ISO-8601 week of a UTC instant, e.g. `2026-W42`. */
155
+ function isoWeek(ms) {
156
+ const d = new Date(ms);
157
+ const day = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()));
158
+ const dow = day.getUTCDay() === 0 ? 7 : day.getUTCDay();
159
+ day.setUTCDate(day.getUTCDate() + 4 - dow); // the Thursday of this week names its year
160
+ const yearStart = Date.UTC(day.getUTCFullYear(), 0, 1);
161
+ const week = Math.ceil(((day.getTime() - yearStart) / 86_400_000 + 1) / 7);
162
+ return `${day.getUTCFullYear()}-W${String(week).padStart(2, '0')}`;
163
+ }
164
+ /** The most recent scheduled moment at or before `now` (UTC). */
165
+ function lastScheduledSlot(schedule, now) {
166
+ const d = new Date(now);
167
+ const today = Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(), schedule.hour);
168
+ const back = (d.getUTCDay() - schedule.weekday + 7) % 7;
169
+ let slot = today - back * 86_400_000;
170
+ if (slot > now)
171
+ slot -= 7 * 86_400_000;
172
+ return slot;
173
+ }
174
+ /**
175
+ * Is a weekly plan due? Due once per scheduled slot: when the latest slot has
176
+ * passed and no plan was made since it. A machine that was off at the slot plans
177
+ * when it comes back, once — never a backlog of missed weeks.
178
+ */
179
+ function maintenanceDue(settings, lastPlannedAt, now) {
180
+ if (settings === null || !settings.enabled)
181
+ return { due: false, week: isoWeek(now), because: 'maintenance is off for this project' };
182
+ if (!settings.upgrades.enabled && !settings.security.enabled && !settings.deadCode.enabled) {
183
+ return { due: false, week: isoWeek(now), because: 'maintenance is on but every kind is off' };
184
+ }
185
+ const slot = lastScheduledSlot(settings.schedule, now);
186
+ const week = isoWeek(slot);
187
+ if (lastPlannedAt !== null && lastPlannedAt >= slot)
188
+ return { due: false, week, because: `this week's plan (${week}) was made` };
189
+ return { due: true, week, because: `the weekly slot passed at ${new Date(slot).toISOString()}` };
190
+ }
191
+ /* ───────────────────────────────────────────────── what a goal carries ── */
192
+ exports.PACKAGE_MANAGERS = ['npm', 'pnpm', 'yarn', 'bun'];
193
+ const MAX_LIST = 80;
194
+ const KEY = /^[a-z0-9][a-z0-9:._/@-]{0,159}$/i;
195
+ const PKG = /^(@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/i;
196
+ const VERSION = /^[0-9A-Za-z.+-]{1,64}$/;
197
+ const WEEK = /^\d{4}-W\d{2}$/;
198
+ function str(v, max) {
199
+ return typeof v === 'string' && v.length > 0 && v.length <= max ? v : null;
200
+ }
201
+ function validateGoalMaintenance(x) {
202
+ if (!isObj(x))
203
+ return { ok: false, because: 'must be an object' };
204
+ const kind = x['kind'];
205
+ if (typeof kind !== 'string' || !exports.MAINTENANCE_KINDS.includes(kind)) {
206
+ return { ok: false, because: `kind must be one of ${exports.MAINTENANCE_KINDS.join(', ')}` };
207
+ }
208
+ const key = str(x['key'], 160);
209
+ if (key === null || !KEY.test(key))
210
+ return { ok: false, because: 'key must be a short identifier' };
211
+ const week = str(x['week'], 8);
212
+ if (week === null || !WEEK.test(week))
213
+ return { ok: false, because: 'week must look like 2026-W42' };
214
+ const root = str(x['root'], 200);
215
+ if (root === null || root.includes('..') || /^[a-z]:|^[\\/]/i.test(root))
216
+ return { ok: false, because: 'root must be a relative path inside the repository' };
217
+ const pm = x['packageManager'];
218
+ if (typeof pm !== 'string' || !exports.PACKAGE_MANAGERS.includes(pm)) {
219
+ return { ok: false, because: `packageManager must be one of ${exports.PACKAGE_MANAGERS.join(', ')}` };
220
+ }
221
+ const list = (k) => {
222
+ const v = x[k];
223
+ if (v === undefined || v === null)
224
+ return [];
225
+ return Array.isArray(v) && v.length <= MAX_LIST ? v : null;
226
+ };
227
+ const rawPkgs = list('packages');
228
+ if (rawPkgs === null)
229
+ return { ok: false, because: `packages must be a list of at most ${MAX_LIST}` };
230
+ const packages = [];
231
+ for (const p of rawPkgs) {
232
+ if (!isObj(p))
233
+ return { ok: false, because: 'every package must be an object' };
234
+ const name = str(p['name'], 214);
235
+ const from = str(p['from'], 64);
236
+ const to = str(p['to'], 64);
237
+ if (name === null || !PKG.test(name))
238
+ return { ok: false, because: 'a package name is not an npm name' };
239
+ if (from === null || !VERSION.test(from) || to === null || !VERSION.test(to))
240
+ return { ok: false, because: `${name}: from/to must be versions` };
241
+ const bump = p['bump'];
242
+ if (bump !== 'patch' && bump !== 'minor' && bump !== 'major')
243
+ return { ok: false, because: `${name}: bump must be patch, minor or major` };
244
+ packages.push({ name, from, to, bump, dev: p['dev'] === true, native: p['native'] === true });
245
+ }
246
+ const rawAdv = list('advisories');
247
+ if (rawAdv === null)
248
+ return { ok: false, because: `advisories must be a list of at most ${MAX_LIST}` };
249
+ const advisories = [];
250
+ for (const a of rawAdv) {
251
+ if (!isObj(a))
252
+ return { ok: false, because: 'every advisory must be an object' };
253
+ const id = str(a['id'], 120);
254
+ const pkg = str(a['package'], 214);
255
+ const title = str(a['title'], 300);
256
+ const sev = a['severity'];
257
+ const url = a['url'] === null || a['url'] === undefined ? null : str(a['url'], 400);
258
+ if (id === null || pkg === null || title === null)
259
+ return { ok: false, because: 'an advisory needs id, package and title' };
260
+ if (typeof sev !== 'string' || !exports.AUDIT_SEVERITIES.includes(sev))
261
+ return { ok: false, because: `${id}: severity` };
262
+ if (url !== null && !/^https:\/\/\S+$/.test(url))
263
+ return { ok: false, because: `${id}: url must be https` };
264
+ advisories.push({ id, package: pkg, title, severity: sev, url });
265
+ }
266
+ const rawLinks = list('links');
267
+ if (rawLinks === null)
268
+ return { ok: false, because: `links must be a list of at most ${MAX_LIST}` };
269
+ const links = [];
270
+ for (const l of rawLinks) {
271
+ if (!isObj(l))
272
+ return { ok: false, because: 'every link must be an object' };
273
+ const label = str(l['label'], 200);
274
+ const url = str(l['url'], 400);
275
+ if (label === null || url === null || !/^https:\/\/\S+$/.test(url))
276
+ return { ok: false, because: 'a link needs a label and an https url' };
277
+ links.push({ label, url });
278
+ }
279
+ const buildNote = x['buildNote'] === null || x['buildNote'] === undefined ? null : str(x['buildNote'], 1000);
280
+ if (x['buildNote'] !== null && x['buildNote'] !== undefined && buildNote === null)
281
+ return { ok: false, because: 'buildNote must be text of at most 1000 characters' };
282
+ const major = x['major'] === true || packages.some((p) => p.bump === 'major');
283
+ const native = x['native'] === true || packages.some((p) => p.native);
284
+ if (native && buildNote === null)
285
+ return { ok: false, because: 'a native-module change needs a buildNote' };
286
+ // Never trusted from the wire: derived, so a caller cannot ask for a major to be merged.
287
+ const autoMerge = x['autoMerge'] !== false && !major && !native;
288
+ return {
289
+ ok: true,
290
+ maintenance: { kind: kind, key, week, root, packageManager: pm, packages, advisories, links, major, native, buildNote, autoMerge },
291
+ };
292
+ }
293
+ /**
294
+ * The delivery mode a maintenance goal actually gets: the project's own, except
295
+ * that a goal Looply may not merge (major, native) is capped at `pr`.
296
+ */
297
+ function maintenanceDeliverMode(mode, maintenance) {
298
+ if (!maintenance || maintenance.autoMerge)
299
+ return { mode, capped: null };
300
+ if (mode !== 'merge' && mode !== 'deploy')
301
+ return { mode, capped: null };
302
+ return {
303
+ mode: 'pr',
304
+ capped: maintenance.major
305
+ ? 'a major upgrade is never merged automatically; a person reviews and merges it'
306
+ : 'a native-module upgrade needs a new native build, so a person merges it',
307
+ };
308
+ }
309
+ function parseVersion(v) {
310
+ const m = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(v.trim());
311
+ if (!m)
312
+ return null;
313
+ return { major: Number(m[1]), minor: Number(m[2]), patch: Number(m[3]), pre: m[4] ?? '' };
314
+ }
315
+ /**
316
+ * How big a step `from → to` is, the way a caret range reads it: below 1.0 a
317
+ * minor step is breaking, below 0.1 a patch step is. Null when `to` is not newer.
318
+ */
319
+ function bumpOf(from, to) {
320
+ const a = parseVersion(from);
321
+ const b = parseVersion(to);
322
+ if (a === null || b === null)
323
+ return null;
324
+ const cmp = b.major - a.major || b.minor - a.minor || b.patch - a.patch;
325
+ if (cmp <= 0)
326
+ return null;
327
+ if (b.major !== a.major)
328
+ return 'major';
329
+ if (a.major === 0 && b.minor !== a.minor)
330
+ return 'major';
331
+ if (a.major === 0 && a.minor === 0 && b.patch !== a.patch)
332
+ return 'major';
333
+ if (b.minor !== a.minor)
334
+ return 'minor';
335
+ return 'patch';
336
+ }
337
+ const SEVERITY_RANK = { low: 0, moderate: 1, high: 2, critical: 3 };
338
+ /** Packages that move together and are upgraded as one group. */
339
+ const FAMILIES = [
340
+ [/^(react|react-dom|@types\/react|@types\/react-dom|react-is|react-test-renderer)$/, 'react'],
341
+ [/^(prisma|@prisma\/.+)$/, 'prisma'],
342
+ [/^(eslint|eslint-.+|@eslint\/.+|@typescript-eslint\/.+|typescript-eslint)$/, 'eslint'],
343
+ [/^(jest|ts-jest|babel-jest|jest-.+|@jest\/.+|@types\/jest)$/, 'jest'],
344
+ [/^(vite|vitest|@vitejs\/.+|@vitest\/.+)$/, 'vite'],
345
+ [/^(typescript|ts-node|tsx)$/, 'typescript'],
346
+ [/^@types\//, 'types'],
347
+ ];
348
+ function familyOf(name) {
349
+ for (const [re, fam] of FAMILIES)
350
+ if (re.test(name))
351
+ return fam;
352
+ const scope = /^(@[^/]+)\//.exec(name);
353
+ return scope ? scope[1] : name;
354
+ }
355
+ /** Packages an Expo SDK pins: never upgraded past what `npx expo install` picks. */
356
+ function expoManaged(name) {
357
+ return /^(expo|expo-.+|@expo\/.+|react-native|react-native-.+|@react-native\/.+|@react-native-community\/.+|react|react-dom)$/.test(name);
358
+ }
359
+ exports.EXPO_BUILD_NOTE = 'Build note: this changes native modules in an Expo app. It needs a new native build (EAS build or a new development build) ' +
360
+ 'before it can be tested on a device; an over-the-air update cannot carry it. Versions were chosen with `npx expo install`, so they match the app\'s Expo SDK.';
361
+ /** Packages in one pull request: small enough to review, and to fit a goal's wording. */
362
+ const MAX_GROUP = 12;
363
+ /** The server's limit on a goal's wording. */
364
+ exports.MAINTENANCE_TEXT_LIMIT = 2000;
365
+ /** Never longer than a goal may be: a cut is said, and the full list is in the maintenance payload. */
366
+ function fitGoalText(text) {
367
+ if (text.length <= exports.MAINTENANCE_TEXT_LIMIT)
368
+ return text;
369
+ const tail = "\n(cut to fit; the full list is in this goal's maintenance details)";
370
+ return text.slice(0, exports.MAINTENANCE_TEXT_LIMIT - tail.length).trimEnd() + tail;
371
+ }
372
+ /** A list for a sentence: the first few, then how many more. */
373
+ function listed(xs, n = 6) {
374
+ return xs.length <= n ? xs.join(', ') : `${xs.slice(0, n).join(', ')} and ${xs.length - n} more`;
375
+ }
376
+ function clip(s, n) {
377
+ return s.length <= n ? s : `${s.slice(0, n - 1).trimEnd()}…`;
378
+ }
379
+ function installCommand(pm, specs, dev) {
380
+ const list = specs.join(' ');
381
+ if (pm === 'npm')
382
+ return `npm install ${dev ? '--save-dev ' : ''}${list}`;
383
+ if (pm === 'pnpm')
384
+ return `pnpm add ${dev ? '--save-dev ' : ''}${list}`;
385
+ if (pm === 'yarn')
386
+ return `yarn add ${dev ? '--dev ' : ''}${list}`;
387
+ return `bun add ${dev ? '--dev ' : ''}${list}`;
388
+ }
389
+ function lockfileOf(pm) {
390
+ return pm === 'npm' ? 'package-lock.json' : pm === 'pnpm' ? 'pnpm-lock.yaml' : pm === 'yarn' ? 'yarn.lock' : 'bun.lock';
391
+ }
392
+ function where(root) {
393
+ return root === '.' ? 'the repository root' : `\`${root}/\``;
394
+ }
395
+ function npmLink(name, version) {
396
+ return { label: `${name} ${version} on npm`, url: `https://www.npmjs.com/package/${name}/v/${version}` };
397
+ }
398
+ function packageLinks(facts, pkgs) {
399
+ const out = [];
400
+ for (const p of pkgs) {
401
+ const changelog = facts.changelogs[p.name];
402
+ out.push(changelog ? { label: `${p.name} changelog`, url: changelog } : npmLink(p.name, p.to));
403
+ }
404
+ return out.slice(0, MAX_LIST);
405
+ }
406
+ function ruleLines(pm, root) {
407
+ return [
408
+ `Use ${pm} only, so package.json and ${lockfileOf(pm)} in ${where(root)} change together; no other lockfile, no other package manager, no other dependency.`,
409
+ "Then make the project's checks pass, adapting the code minimally to any breaking change; a package that cannot be adapted stays at its version, with the reason.",
410
+ ];
411
+ }
412
+ function upgradeItem(facts, week, pm, group, pkgs, label) {
413
+ const native = pkgs.some((p) => p.native);
414
+ const major = pkgs.some((p) => p.bump === 'major');
415
+ const expo = facts.expo && native;
416
+ const key = `upgrade:${group}:${facts.root}`;
417
+ const title = `Maintenance: ${label}${facts.root === '.' ? '' : ` in ${facts.root}`}`;
418
+ const lines = [
419
+ `${title}`,
420
+ `Weekly maintenance, ${week}.`,
421
+ '',
422
+ `Upgrade exactly these packages in ${where(facts.root)}:`,
423
+ ...pkgs.map((p) => `- ${p.name} ${p.from} → ${p.to} (${p.bump}${p.dev ? ', dev' : ''}${p.native ? ', native' : ''})`),
424
+ '',
425
+ ];
426
+ if (expo) {
427
+ lines.push(`Upgrade them with \`npx expo install ${pkgs.map((p) => p.name).join(' ')}\` in ${where(facts.root)}, which picks the versions this app's Expo SDK supports ` +
428
+ '(they may differ from the ones above; the SDK wins). Do not upgrade the Expo SDK itself unless `expo` is listed.', exports.EXPO_BUILD_NOTE, 'Add this build note to the project\'s changelog or release notes if it keeps one.');
429
+ }
430
+ else {
431
+ const prod = pkgs.filter((p) => !p.dev).map((p) => `${p.name}@${p.to}`);
432
+ const dev = pkgs.filter((p) => p.dev).map((p) => `${p.name}@${p.to}`);
433
+ const cmds = [...(prod.length ? [installCommand(pm, prod, false)] : []), ...(dev.length ? [installCommand(pm, dev, true)] : [])];
434
+ lines.push(`Run ${cmds.map((c) => `\`${c}\``).join(' and ')} in ${where(facts.root)}.`);
435
+ }
436
+ lines.push(...ruleLines(pm, facts.root));
437
+ if (major)
438
+ lines.push('This includes a major upgrade: read its changelog for breaking changes and adapt the code to them.');
439
+ const links = packageLinks(facts, pkgs);
440
+ // The links go in the pull request's description, from the payload; the wording stays short.
441
+ if (links.length)
442
+ lines.push("The changelog links are in this goal's maintenance details; read them for breaking changes.");
443
+ return {
444
+ key,
445
+ title,
446
+ text: fitGoalText(lines.join('\n')),
447
+ maintenance: {
448
+ kind: 'upgrade',
449
+ key,
450
+ week,
451
+ root: facts.root,
452
+ packageManager: pm,
453
+ packages: pkgs,
454
+ advisories: [],
455
+ links,
456
+ major,
457
+ native,
458
+ buildNote: native ? exports.EXPO_BUILD_NOTE : null,
459
+ autoMerge: !major && !native,
460
+ },
461
+ };
462
+ }
463
+ function chunk(xs, n) {
464
+ const out = [];
465
+ for (let i = 0; i < xs.length; i += n)
466
+ out.push(xs.slice(i, i + n));
467
+ return out;
468
+ }
469
+ const byName = (a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
470
+ function planUpgrades(facts, week, pm, allowMajor, skipped) {
471
+ const native = new Set(facts.nativePackages);
472
+ const nonMajor = [];
473
+ const expoGroup = [];
474
+ const majors = new Map();
475
+ const majorsOff = [];
476
+ for (const o of [...(facts.outdated ?? [])].sort(byName)) {
477
+ const isNative = facts.expo && (native.has(o.name) || expoManaged(o.name));
478
+ // In range first: the newest version package.json already allows is never a major step.
479
+ const inRange = bumpOf(o.current, o.wanted);
480
+ const toLatest = bumpOf(o.current, o.latest);
481
+ if (parseVersion(o.latest)?.pre) {
482
+ skipped.push(`${o.name} in ${where(facts.root)}: its latest (${o.latest}) is a pre-release`);
483
+ continue;
484
+ }
485
+ if (isNative) {
486
+ // Expo picks the version; a major step here is an SDK change and needs the major setting.
487
+ const to = toLatest === 'major' && !allowMajor ? (inRange ? o.wanted : null) : o.latest;
488
+ const bump = to === null ? null : bumpOf(o.current, to);
489
+ if (to === null || bump === null) {
490
+ majorsOff.push(`${o.name} ${o.current} → ${o.latest}`);
491
+ continue;
492
+ }
493
+ expoGroup.push({ name: o.name, from: o.current, to, bump, dev: o.dev, native: true });
494
+ continue;
495
+ }
496
+ if (toLatest === 'major') {
497
+ if (inRange !== null && inRange !== 'major')
498
+ nonMajor.push({ name: o.name, from: o.current, to: o.wanted, bump: inRange, dev: o.dev, native: false });
499
+ if (allowMajor) {
500
+ const fam = familyOf(o.name);
501
+ majors.set(fam, [...(majors.get(fam) ?? []), { name: o.name, from: o.current, to: o.latest, bump: 'major', dev: o.dev, native: false }]);
502
+ }
503
+ else {
504
+ majorsOff.push(`${o.name} ${o.current} → ${o.latest}`);
505
+ }
506
+ continue;
507
+ }
508
+ const to = toLatest !== null ? o.latest : inRange !== null ? o.wanted : null;
509
+ const bump = to === null ? null : bumpOf(o.current, to);
510
+ if (to === null || bump === null)
511
+ continue;
512
+ nonMajor.push({ name: o.name, from: o.current, to, bump, dev: o.dev, native: false });
513
+ }
514
+ if (majorsOff.length > 0) {
515
+ skipped.push(`${majorsOff.length} major upgrade(s) in ${where(facts.root)}, and major upgrades are off: ${listed(majorsOff)}`);
516
+ }
517
+ const items = [];
518
+ if (nonMajor.length > 0) {
519
+ if (nonMajor.length <= MAX_GROUP) {
520
+ items.push(upgradeItem(facts, week, pm, 'non-major', nonMajor, 'patch and minor dependency upgrades'));
521
+ }
522
+ else {
523
+ // Too many for one reviewable pull request: by family, so related packages stay together.
524
+ const byFam = [...nonMajor].sort((a, b) => familyOf(a.name).localeCompare(familyOf(b.name)) || byName(a, b));
525
+ chunk(byFam, MAX_GROUP).forEach((pkgs, i) => items.push(upgradeItem(facts, week, pm, `non-major-${i + 1}`, pkgs, `patch and minor dependency upgrades (part ${i + 1})`)));
526
+ }
527
+ }
528
+ if (expoGroup.length > 0)
529
+ items.push(upgradeItem(facts, week, pm, 'expo-native', expoGroup.slice(0, MAX_GROUP), 'Expo SDK and native module upgrades'));
530
+ for (const fam of [...majors.keys()].sort()) {
531
+ const pkgs = majors.get(fam).slice(0, MAX_GROUP);
532
+ items.push(upgradeItem(facts, week, pm, `major:${fam}`, pkgs, `major upgrade of ${fam === pkgs[0].name && pkgs.length === 1 ? fam : `${fam} packages`}`));
533
+ }
534
+ return items;
535
+ }
536
+ function auditFixCommand(pm) {
537
+ return pm === 'npm' ? 'npm audit fix' : pm === 'pnpm' ? 'pnpm audit --fix' : pm === 'yarn' ? 'yarn npm audit' : 'bun audit';
538
+ }
539
+ function planSecurity(facts, week, pm, min, skipped) {
540
+ const findings = (facts.audit ?? []).filter((f) => SEVERITY_RANK[f.severity] >= SEVERITY_RANK[min]);
541
+ const below = (facts.audit ?? []).filter((f) => SEVERITY_RANK[f.severity] < SEVERITY_RANK[min]);
542
+ if (below.length > 0) {
543
+ skipped.push(`${below.length} package(s) with advisories below the ${min} threshold in ${where(facts.root)}: ${listed(below.map((f) => `${f.package} (${f.severity})`))}`);
544
+ }
545
+ const items = [];
546
+ const native = new Set(facts.nativePackages);
547
+ // Critical first, then high, and so on: each tier its own small pull request.
548
+ for (const sev of [...exports.AUDIT_SEVERITIES].reverse()) {
549
+ const tier = findings.filter((f) => f.severity === sev).sort((a, b) => (a.package < b.package ? -1 : 1));
550
+ const fixable = tier.filter((f) => f.fix !== null).slice(0, MAX_GROUP);
551
+ for (const f of tier.filter((x) => x.fix !== null).slice(MAX_GROUP)) {
552
+ skipped.push(`${f.package} (${sev}) in ${where(facts.root)}: more than ${MAX_GROUP} in one tier; it is planned again next week`);
553
+ }
554
+ for (const f of tier)
555
+ if (f.fix === null)
556
+ skipped.push(`${f.package} (${sev}) in ${where(facts.root)}: no fixed version is published yet`);
557
+ if (fixable.length === 0)
558
+ continue;
559
+ const major = fixable.some((f) => f.fix?.major === true);
560
+ const isNative = facts.expo && fixable.some((f) => native.has(f.package) || expoManaged(f.package));
561
+ const advisories = fixable
562
+ .flatMap((f) => f.advisories.map((a) => ({ id: a.id, package: f.package, title: a.title, severity: sev, url: a.url })))
563
+ .slice(0, MAX_LIST);
564
+ const key = `security:${sev}:${facts.root}`;
565
+ const title = `Maintenance: fix ${sev} security advisories${facts.root === '.' ? '' : ` in ${facts.root}`}`;
566
+ const lines = [
567
+ `${title}`,
568
+ `Weekly maintenance, ${week}.`,
569
+ '',
570
+ `${pm} audit reports these ${sev} advisories in ${where(facts.root)}:`,
571
+ ...fixable.map((f) => `- ${f.package}${f.direct ? '' : ' (indirect)'}: ${clip(f.advisories.map((a) => a.title).join('; '), 110)}${f.fix?.major ? ' (the fix is a major upgrade)' : ''}`),
572
+ '',
573
+ `Fix them with \`${auditFixCommand(pm)}\` (never with --force) where that is enough; for an indirect one it cannot reach, upgrade the direct dependency that pulls it in, ` +
574
+ 'or add an override/resolution pinning the fixed version. Fix only these advisories.',
575
+ ...ruleLines(pm, facts.root),
576
+ ...(major ? ['One fix needs a major upgrade: read its changelog for breaking changes and adapt the code to them.'] : []),
577
+ ...(isNative ? [exports.EXPO_BUILD_NOTE] : []),
578
+ "The advisory links are in this goal's maintenance details.",
579
+ ];
580
+ items.push({
581
+ key,
582
+ title,
583
+ text: fitGoalText(lines.join('\n')),
584
+ maintenance: {
585
+ kind: 'security',
586
+ key,
587
+ week,
588
+ root: facts.root,
589
+ packageManager: pm,
590
+ packages: [],
591
+ advisories,
592
+ links: advisories.filter((a) => a.url !== null).map((a) => ({ label: `${a.id} (${a.package})`, url: a.url })),
593
+ major,
594
+ native: isNative,
595
+ buildNote: isNative ? exports.EXPO_BUILD_NOTE : null,
596
+ autoMerge: !major && !isNative,
597
+ },
598
+ });
599
+ }
600
+ return items;
601
+ }
602
+ function planDeadCode(facts, week, pm) {
603
+ const unused = [...facts.unused].sort().slice(0, 30);
604
+ if (unused.length === 0)
605
+ return [];
606
+ const key = `dead-code:${facts.root}`;
607
+ const title = `Maintenance: remove unused dependencies and dead code${facts.root === '.' ? '' : ` in ${facts.root}`}`;
608
+ const lines = [
609
+ `${title}`,
610
+ `Weekly maintenance, ${week}.`,
611
+ '',
612
+ `Nothing under ${where(facts.root)} seems to import these dependencies:`,
613
+ ...unused.map((u) => `- ${u}`),
614
+ '',
615
+ 'For each one, confirm it is really unused — not loaded by a config file, a script in package.json, a CLI, a plugin name or a type-only reference — ' +
616
+ `and remove the ones that are with ${pm}, so package.json and ${lockfileOf(pm)} change together. Keep any you are not sure about and say why.`,
617
+ 'Also remove code that only existed to use a removed dependency. Do not refactor anything else, and do not change behaviour.',
618
+ "Then make the project's checks pass.",
619
+ ];
620
+ return [
621
+ {
622
+ key,
623
+ title,
624
+ text: fitGoalText(lines.join('\n')),
625
+ maintenance: {
626
+ kind: 'dead-code',
627
+ key,
628
+ week,
629
+ root: facts.root,
630
+ packageManager: pm,
631
+ packages: [],
632
+ advisories: [],
633
+ links: [],
634
+ major: false,
635
+ native: false,
636
+ buildNote: null,
637
+ autoMerge: true,
638
+ },
639
+ },
640
+ ];
641
+ }
642
+ /**
643
+ * THE WEEKLY PLAN for one repository. Deterministic: the same facts give the same
644
+ * items in the same order — security (critical first), then patch and minor
645
+ * upgrades, Expo native upgrades, majors, dead code — cut at `caps.goalsPerWeek`.
646
+ */
647
+ function planMaintenance(input) {
648
+ const { settings, week } = input;
649
+ const skipped = [];
650
+ const security = [];
651
+ const upgrades = [];
652
+ const dead = [];
653
+ const roots = [...input.roots].sort((a, b) => (a.root === '.' ? -1 : b.root === '.' ? 1 : a.root.localeCompare(b.root)));
654
+ for (const facts of roots) {
655
+ const pm = facts.packageManager;
656
+ if (pm === null) {
657
+ skipped.push(`${where(facts.root)}: ${facts.packageManagerProblem ?? 'its package manager is unknown'}; Looply does not guess one`);
658
+ continue;
659
+ }
660
+ if (settings.security.enabled) {
661
+ if (facts.audit === null)
662
+ skipped.push(`security in ${where(facts.root)}: ${facts.auditProblem ?? 'no audit report'}`);
663
+ else
664
+ security.push(...planSecurity(facts, week, pm, settings.security.minSeverity, skipped));
665
+ }
666
+ if (settings.upgrades.enabled) {
667
+ if (facts.outdated === null)
668
+ skipped.push(`upgrades in ${where(facts.root)}: ${facts.outdatedProblem ?? 'no outdated report'}`);
669
+ else
670
+ upgrades.push(...planUpgrades(facts, week, pm, settings.upgrades.major, skipped));
671
+ }
672
+ if (settings.deadCode.enabled)
673
+ dead.push(...planDeadCode(facts, week, pm));
674
+ }
675
+ // Security first across every root, critical before high; then the cheap upgrades before the risky ones.
676
+ const sevOf = (i) => SEVERITY_RANK[(i.maintenance.advisories[0]?.severity ?? 'low')];
677
+ security.sort((a, b) => sevOf(b) - sevOf(a));
678
+ const upgradeRank = (i) => (i.maintenance.major ? 2 : i.maintenance.native ? 1 : 0);
679
+ upgrades.sort((a, b) => upgradeRank(a) - upgradeRank(b));
680
+ const all = [...security, ...upgrades, ...dead];
681
+ const cap = settings.caps.goalsPerWeek;
682
+ for (const late of all.slice(cap))
683
+ skipped.push(`${late.title}: over this week's cap of ${cap} maintenance goals; it is planned again next week`);
684
+ return { week, items: all.slice(0, cap), skipped };
685
+ }
686
+ /* ─────────────────────────────────────────── parsing the tools' answers ── */
687
+ const asSeverity = (s) => typeof s === 'string' && exports.AUDIT_SEVERITIES.includes(s) ? s : s === 'info' ? 'low' : null;
688
+ /**
689
+ * `npm outdated --json --long` or `pnpm outdated --format json`. Packages that
690
+ * are not installed (`current` missing) are left out: there is no "from".
691
+ */
692
+ function parseOutdatedJson(text) {
693
+ const trimmed = text.trim();
694
+ if (trimmed === '')
695
+ return [];
696
+ const raw = JSON.parse(trimmed);
697
+ if (!isObj(raw))
698
+ throw new Error('the outdated report is not a JSON object');
699
+ const out = [];
700
+ for (const [name, v0] of Object.entries(raw)) {
701
+ const v = Array.isArray(v0) ? v0[0] : v0;
702
+ if (!isObj(v))
703
+ continue;
704
+ const current = typeof v['current'] === 'string' ? v['current'] : null;
705
+ const wanted = typeof v['wanted'] === 'string' ? v['wanted'] : null;
706
+ const latest = typeof v['latest'] === 'string' ? v['latest'] : null;
707
+ if (current === null || latest === null || !PKG.test(name))
708
+ continue;
709
+ const type = (v['type'] ?? v['dependencyType']);
710
+ out.push({ name, current, wanted: wanted ?? current, latest, dev: type === 'devDependencies' });
711
+ }
712
+ return out.sort(byName);
713
+ }
714
+ /** `npm audit --json` (npm 7+) or `pnpm audit --json`. */
715
+ function parseAuditJson(text, directNames = []) {
716
+ const raw = JSON.parse(text.trim() || '{}');
717
+ if (!isObj(raw))
718
+ throw new Error('the audit report is not a JSON object');
719
+ const direct = new Set(directNames);
720
+ const out = [];
721
+ const vulns = raw['vulnerabilities'];
722
+ if (isObj(vulns)) {
723
+ for (const [name, v] of Object.entries(vulns)) {
724
+ if (!isObj(v))
725
+ continue;
726
+ const severity = asSeverity(v['severity']);
727
+ if (severity === null)
728
+ continue;
729
+ const via = Array.isArray(v['via']) ? v['via'] : [];
730
+ // npm repeats one advisory once per affected range, under a different id: one per address.
731
+ const seen = new Set();
732
+ const advisories = via
733
+ .filter(isObj)
734
+ .map((a) => ({
735
+ id: String(a['source'] ?? a['url'] ?? a['title'] ?? 'advisory'),
736
+ title: typeof a['title'] === 'string' ? a['title'] : 'security advisory',
737
+ url: typeof a['url'] === 'string' && /^https:\/\//.test(a['url']) ? a['url'] : null,
738
+ }))
739
+ .filter((a) => {
740
+ const k = a.url ?? a.title;
741
+ if (seen.has(k))
742
+ return false;
743
+ seen.add(k);
744
+ return true;
745
+ });
746
+ // Only the advisory's own package is listed; a package flagged "via" another is fixed by fixing that one.
747
+ if (advisories.length === 0)
748
+ continue;
749
+ const fa = v['fixAvailable'];
750
+ const fix = fa === true ? { available: true, major: false, via: null } : isObj(fa) ? { available: true, major: fa['isSemVerMajor'] === true, via: typeof fa['name'] === 'string' ? fa['name'] : null } : null;
751
+ out.push({ package: name, severity, direct: v['isDirect'] === true || direct.has(name), advisories, fix });
752
+ }
753
+ return out.sort((a, b) => (a.package < b.package ? -1 : 1));
754
+ }
755
+ const advs = raw['advisories'];
756
+ if (isObj(advs)) {
757
+ const byPkg = new Map();
758
+ for (const a of Object.values(advs)) {
759
+ if (!isObj(a))
760
+ continue;
761
+ const name = typeof a['module_name'] === 'string' ? a['module_name'] : null;
762
+ const severity = asSeverity(a['severity']);
763
+ if (name === null || severity === null)
764
+ continue;
765
+ const patched = typeof a['patched_versions'] === 'string' ? a['patched_versions'] : '';
766
+ const fixable = patched !== '' && patched !== '<0.0.0';
767
+ const prev = byPkg.get(name);
768
+ const adv = {
769
+ id: String(a['github_advisory_id'] ?? a['id'] ?? 'advisory'),
770
+ title: typeof a['title'] === 'string' ? a['title'] : 'security advisory',
771
+ url: typeof a['url'] === 'string' && /^https:\/\//.test(a['url']) ? a['url'] : null,
772
+ };
773
+ if (prev) {
774
+ prev.advisories.push(adv);
775
+ if (SEVERITY_RANK[severity] > SEVERITY_RANK[prev.severity])
776
+ prev.severity = severity;
777
+ if (!fixable)
778
+ prev.fix = null;
779
+ }
780
+ else {
781
+ byPkg.set(name, { package: name, severity, direct: direct.has(name), advisories: [adv], fix: fixable ? { available: true, major: false, via: null } : null });
782
+ }
783
+ }
784
+ return [...byPkg.values()].sort((a, b) => (a.package < b.package ? -1 : 1));
785
+ }
786
+ return [];
787
+ }
788
+ /** A package.json `repository` → where its changelog is read (GitHub releases), or null. */
789
+ function changelogUrlOf(repository) {
790
+ const url = typeof repository === 'string' ? repository : isObj(repository) && typeof repository['url'] === 'string' ? repository['url'] : null;
791
+ if (url === null)
792
+ return null;
793
+ const m = /github\.com[/:]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:[#/].*)?$/.exec(url) ?? /^(?:github:)?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/.exec(url);
794
+ if (!m)
795
+ return null;
796
+ return `https://github.com/${m[1]}/${m[2]}/releases`;
797
+ }
798
+ /** Package manager from a package.json `packageManager` field and the lockfiles present. */
799
+ function packageManagerOf(field, lockfiles) {
800
+ const LOCKS = {
801
+ 'package-lock.json': 'npm',
802
+ 'npm-shrinkwrap.json': 'npm',
803
+ 'pnpm-lock.yaml': 'pnpm',
804
+ 'yarn.lock': 'yarn',
805
+ 'bun.lockb': 'bun',
806
+ 'bun.lock': 'bun',
807
+ };
808
+ const found = [...new Set(lockfiles.map((l) => LOCKS[l]).filter((x) => x !== undefined))];
809
+ if (typeof field === 'string') {
810
+ const name = field.split('@')[0];
811
+ if (exports.PACKAGE_MANAGERS.includes(name ?? '')) {
812
+ const pm = name;
813
+ if (found.length > 0 && !found.includes(pm))
814
+ return { pm: null, problem: `package.json says ${field} but the lockfile is ${found.join(' and ')}'s` };
815
+ if (found.length === 0)
816
+ return { pm: null, problem: `package.json says ${field} but there is no lockfile` };
817
+ return { pm, problem: null };
818
+ }
819
+ }
820
+ if (found.length === 1)
821
+ return { pm: found[0], problem: null };
822
+ if (found.length === 0)
823
+ return { pm: null, problem: 'there is no lockfile' };
824
+ return { pm: null, problem: `there are lockfiles for ${found.join(' and ')} and no packageManager field to say which is real` };
825
+ }
826
+ //# sourceMappingURL=maintenance.js.map