@imenam/mcp-dependabot-tracker 1.0.30 → 1.0.32

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.
Files changed (48) hide show
  1. package/README.md +41 -28
  2. package/dist/shared/schemas/model.schema.d.ts +64 -8
  3. package/dist/shared/schemas/model.schema.js +23 -8
  4. package/dist/src/core/commands.d.ts +5 -7
  5. package/dist/src/core/commands.js +7 -11
  6. package/dist/src/core/containers.d.ts +82 -0
  7. package/dist/src/core/containers.js +144 -0
  8. package/dist/src/core/managers/composer.d.ts +15 -0
  9. package/dist/src/core/managers/composer.js +234 -0
  10. package/dist/src/core/managers/index.d.ts +14 -0
  11. package/dist/src/core/managers/index.js +46 -0
  12. package/dist/src/core/managers/npm.d.ts +25 -0
  13. package/dist/src/core/managers/npm.js +203 -0
  14. package/dist/src/core/managers/php-version.d.ts +18 -0
  15. package/dist/src/core/managers/php-version.js +113 -0
  16. package/dist/src/core/managers/pnpm.d.ts +28 -0
  17. package/dist/src/core/managers/pnpm.js +249 -0
  18. package/dist/src/core/managers/tool-args.d.ts +17 -0
  19. package/dist/src/core/managers/tool-args.js +26 -0
  20. package/dist/src/core/managers/types.d.ts +61 -0
  21. package/dist/src/core/managers/types.js +11 -0
  22. package/dist/src/core/operations.d.ts +8 -5
  23. package/dist/src/core/operations.js +106 -77
  24. package/dist/src/core/repair.d.ts +20 -13
  25. package/dist/src/core/repair.js +110 -84
  26. package/dist/src/core/repos.d.ts +1 -1
  27. package/dist/src/core/repos.js +1 -1
  28. package/dist/src/core/sandbox.d.ts +7 -0
  29. package/dist/src/core/sandbox.js +31 -0
  30. package/dist/src/core/settings.d.ts +1 -1
  31. package/dist/src/core/settings.js +2 -2
  32. package/dist/src/core/store.js +3 -0
  33. package/dist/src/mcp.js +6 -5
  34. package/dist/src/package-tools.d.ts +13 -0
  35. package/dist/src/package-tools.js +92 -0
  36. package/dist/src/server/serve.js +2 -0
  37. package/dist/src/tools/format.js +11 -11
  38. package/dist/src/tools/tools.js +4 -4
  39. package/gui/dist/assets/index-DrVmedqf.js +71 -0
  40. package/gui/dist/index.html +1 -1
  41. package/package.json +2 -2
  42. package/dist/src/core/npm-audit.d.ts +0 -26
  43. package/dist/src/core/npm-audit.js +0 -76
  44. package/dist/src/core/npm-sandbox.d.ts +0 -33
  45. package/dist/src/core/npm-sandbox.js +0 -159
  46. package/dist/src/npm-tools.d.ts +0 -10
  47. package/dist/src/npm-tools.js +0 -136
  48. package/gui/dist/assets/index-CAOy2g1q.js +0 -71
@@ -0,0 +1,203 @@
1
+ import { NPM_SEVERITIES } from "../../../shared/schemas/model.schema.js";
2
+ import { CACHE_MOUNT, projectDir } from "../containers.js";
3
+ import { TrackerError } from "../errors.js";
4
+ import { PACKAGES_PROPERTY, nameArg, onlyFields, packagesArg } from "./tool-args.js";
5
+ import { projectLabel, runManager } from "./types.js";
6
+ /** Image des commandes npm : Node.js LTS, npm compris. */
7
+ export const NODE_IMAGE = "docker.io/library/node:26-slim";
8
+ /**
9
+ * Variables des commandes npm : cache de l'opération, ni avis de mise à jour
10
+ * ni appel aux dons. `allow_remote` autorise le téléchargement des archives de
11
+ * paquets à `bundleDependencies` (ex. `@tailwindcss/oxide-wasm32-wasi`), que
12
+ * npm 12 classe en dépendances distantes avec `--package-lock-only`.
13
+ */
14
+ const NPM_ENV = {
15
+ npm_config_cache: `${CACHE_MOUNT}/npm`,
16
+ npm_config_update_notifier: "false",
17
+ npm_config_fund: "false",
18
+ npm_config_allow_remote: "all",
19
+ };
20
+ /** Chemins d'installation gardés par vulnérabilité dans les faits transmis à Claude. */
21
+ const MAX_NODES = 5;
22
+ /** Options npm qui limitent l'audit et ses corrections au périmètre `scope`. */
23
+ export function npmScopeArgs(scope) {
24
+ return scope === "production" ? ["--omit=dev"] : [];
25
+ }
26
+ /** Lit la sortie JSON d'un appel npm ; une sortie qui n'est pas du JSON, ou qui porte une erreur npm, lève une erreur. */
27
+ export function parseNpmJson(stdout, stderr, what) {
28
+ let json;
29
+ try {
30
+ json = JSON.parse(stdout);
31
+ }
32
+ catch {
33
+ const detail = stderr.trim() || stdout.trim() || "no output";
34
+ throw new TrackerError(`${what} did not return JSON: ${detail.slice(-1500)}`);
35
+ }
36
+ if (json && typeof json === "object" && json.error) {
37
+ const summary = json.error.summary ?? json.error.message ?? JSON.stringify(json.error);
38
+ const detail = json.error.detail ? ` ${json.error.detail}` : "";
39
+ throw new TrackerError(`${what} failed: ${summary}${detail}`.trim());
40
+ }
41
+ return json;
42
+ }
43
+ /**
44
+ * Vulnérabilités d'un rapport `npm audit --json` (format `auditReportVersion` 2).
45
+ * `fixAvailable` vaut false (aucune correction), true (dans les plages déclarées)
46
+ * ou un objet `{ name, version, isSemVerMajor }` qui désigne le paquet à mettre à
47
+ * jour, éventuellement d'une version majeure.
48
+ */
49
+ export function parseAuditReport(report, project) {
50
+ if (report?.auditReportVersion !== 2 || typeof report.vulnerabilities !== "object" || report.vulnerabilities === null) {
51
+ throw new TrackerError(`Unsupported npm audit report for ${projectLabel(project)}package-lock.json: expected auditReportVersion 2 (npm 7 or later).`);
52
+ }
53
+ return Object.values(report.vulnerabilities).map((entry) => {
54
+ const severity = NPM_SEVERITIES.includes(entry.severity) ? entry.severity : "info";
55
+ const fixAvailable = entry.fixAvailable;
56
+ const base = { project, manager: "npm", name: entry.name, severity };
57
+ if (fixAvailable === true)
58
+ return { ...base, fix: "available" };
59
+ if (fixAvailable && typeof fixAvailable === "object")
60
+ return { ...base, fix: fixAvailable.isSemVerMajor ? "major" : "available" };
61
+ return { ...base, fix: "none" };
62
+ });
63
+ }
64
+ /** Vulnérabilités d'un rapport `npm audit --json`, réduites à ce qui sert les corrections. */
65
+ export function auditFacts(report, project) {
66
+ return Object.values((report?.vulnerabilities ?? {})).map((entry) => ({
67
+ manager: "npm",
68
+ project: project === "" ? "." : project,
69
+ name: entry.name,
70
+ severity: entry.severity,
71
+ isDirect: entry.isDirect,
72
+ range: entry.range,
73
+ via: (Array.isArray(entry.via) ? entry.via : []).map((via) => typeof via === "string" ? via : { title: via?.title, url: via?.url, range: via?.range, severity: via?.severity }),
74
+ effects: entry.effects,
75
+ fixAvailable: entry.fixAvailable,
76
+ nodes: (Array.isArray(entry.nodes) ? entry.nodes : []).slice(0, MAX_NODES),
77
+ }));
78
+ }
79
+ /**
80
+ * Lit un `package-lock.json` : version de chaque paquet installé, par chemin
81
+ * d'installation sans le premier `node_modules/` (`lodash`, ou
82
+ * `d3-sankey/node_modules/d3-array` pour une copie imbriquée). Un lockfile v1
83
+ * (npm 6), sans `packages`, est refusé.
84
+ */
85
+ export function readPackageLock(text, project) {
86
+ let json;
87
+ try {
88
+ json = JSON.parse(text);
89
+ }
90
+ catch (err) {
91
+ throw new TrackerError(`${projectLabel(project)}package-lock.json is not valid JSON: ${err.message}`);
92
+ }
93
+ if (!json || typeof json.packages !== "object" || json.packages === null) {
94
+ throw new TrackerError(`${projectLabel(project)}package-lock.json has no "packages" section: lockfile version 2 or 3 (npm 7 or later) is required.`);
95
+ }
96
+ const versions = {};
97
+ for (const [key, entry] of Object.entries(json.packages)) {
98
+ if (key.startsWith("node_modules/") && typeof entry?.version === "string")
99
+ versions[key.slice("node_modules/".length)] = entry.version;
100
+ }
101
+ return versions;
102
+ }
103
+ async function audit(ctx, project) {
104
+ const args = ["audit", ...npmScopeArgs(ctx.scope), "--json"];
105
+ const result = await runManager(npm, ctx, project, args);
106
+ return parseNpmJson(result.stdout, result.stderr, `npm audit in ${projectLabel(project) || "./"}`);
107
+ }
108
+ export const npm = {
109
+ id: "npm",
110
+ lockfile: "package-lock.json",
111
+ manifest: "package.json",
112
+ image: () => ({ name: NODE_IMAGE }),
113
+ command: (ctx, project, args) => {
114
+ projectDir(ctx.workspace, project, "package.json");
115
+ return { image: NODE_IMAGE, cwd: project, command: ["npm", ...args], env: NPM_ENV };
116
+ },
117
+ audit: async (ctx, project) => {
118
+ const report = await audit(ctx, project);
119
+ return { vulnerabilities: parseAuditReport(report, project), facts: auditFacts(report, project) };
120
+ },
121
+ fix: async (ctx, project) => {
122
+ const result = await runManager(npm, ctx, project, ["audit", "fix", ...npmScopeArgs(ctx.scope), "--package-lock-only", "--ignore-scripts", "--json"]);
123
+ parseNpmJson(result.stdout, result.stderr, `npm audit fix in ${projectLabel(project) || "./"}`);
124
+ },
125
+ readLock: readPackageLock,
126
+ fixCommand: (scope) => ["npm audit fix", ...npmScopeArgs(scope), "--package-lock-only --ignore-scripts"].join(" "),
127
+ tools: [
128
+ {
129
+ name: "npm_install_lockfile",
130
+ description: "Run npm install --package-lock-only --ignore-scripts in an npm project: updates package-lock.json (and package.json for the packages given, e.g. mermaid@12.0.1) without installing node_modules. Use it after changing package.json or its overrides.",
131
+ properties: { packages: PACKAGES_PROPERTY },
132
+ required: [],
133
+ args: (args) => {
134
+ onlyFields(args, ["packages"]);
135
+ return ["install", "--package-lock-only", "--ignore-scripts", ...packagesArg(args)];
136
+ },
137
+ },
138
+ {
139
+ name: "npm_audit",
140
+ description: "Run npm audit in an npm project, with the scope of the operation.",
141
+ properties: {},
142
+ required: [],
143
+ args: (args, scope) => {
144
+ onlyFields(args);
145
+ return ["audit", ...npmScopeArgs(scope)];
146
+ },
147
+ },
148
+ {
149
+ name: "npm_ci",
150
+ description: "Run npm ci in an npm project: installs node_modules from package-lock.json, install scripts included.",
151
+ properties: {},
152
+ required: [],
153
+ args: (args) => {
154
+ onlyFields(args);
155
+ return ["ci"];
156
+ },
157
+ },
158
+ {
159
+ name: "npm_test",
160
+ description: "Run npm test in an npm project.",
161
+ properties: {},
162
+ required: [],
163
+ args: (args) => {
164
+ onlyFields(args);
165
+ return ["test"];
166
+ },
167
+ },
168
+ {
169
+ name: "npm_run",
170
+ description: "Run a script of package.json in an npm project (npm run <script>).",
171
+ properties: { script: { type: "string", description: "Name of the script." } },
172
+ required: ["script"],
173
+ args: (args) => {
174
+ onlyFields(args, ["script"]);
175
+ return ["run", nameArg(args, "script")];
176
+ },
177
+ },
178
+ {
179
+ name: "npm_ls",
180
+ description: "Show where a package is installed in the dependency tree of an npm project (npm ls <package> --all).",
181
+ properties: { package: { type: "string", description: "Name of the package." } },
182
+ required: ["package"],
183
+ args: (args) => {
184
+ onlyFields(args, ["package"]);
185
+ return ["ls", nameArg(args, "package"), "--all"];
186
+ },
187
+ },
188
+ {
189
+ name: "tsc",
190
+ description: "Type-check an npm project with its own TypeScript (npm exec --no -- tsc --noEmit).",
191
+ properties: {},
192
+ required: [],
193
+ args: (args) => {
194
+ onlyFields(args);
195
+ return ["exec", "--no", "--", "tsc", "--noEmit"];
196
+ },
197
+ },
198
+ ],
199
+ guide: (scope, server) => [
200
+ `- npm projects (package-lock.json): upgrade a dependency in package.json, or pin a transitive one with an \`overrides\` entry, with Edit, then update the lockfile with the ${server} tool npm_install_lockfile.`,
201
+ ` Check with npm_audit${scope === "production" ? " (it runs `npm audit --omit=dev`)" : ""}; npm_ci to install the dependencies, then npm_test (or npm_run with the test script of package.json) when the project has some; npm_ls and tsc when useful.`,
202
+ ].join("\n"),
203
+ };
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Choix de la version de PHP d'un projet Composer, parmi celles des images
3
+ * officielles, d'après `config.platform.php` (la version que Composer suppose
4
+ * pour résoudre les dépendances) ou, à défaut, la contrainte `require.php`.
5
+ */
6
+ /** Versions de PHP des images officielles `php:<version>-cli`, de la plus ancienne à la plus récente. */
7
+ export declare const PHP_VERSIONS: readonly ["8.2", "8.3", "8.4", "8.5"];
8
+ type Version = [number, number, number];
9
+ /** Vrai si `version` satisfait une contrainte Composer (`||` ou `|` entre alternatives, espace ou virgule entre conditions, intervalles `a - b`). */
10
+ export declare function satisfies(version: Version, constraint: string): boolean;
11
+ /**
12
+ * Version de PHP de l'image d'un projet, d'après son `composer.json` : la
13
+ * série de `config.platform.php`, sinon la plus ancienne série qui satisfait
14
+ * `require.php`, sinon la plus récente. Lève une erreur quand aucune image
15
+ * officielle ne convient.
16
+ */
17
+ export declare function phpVersionFor(manifest: any): string;
18
+ export {};
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Choix de la version de PHP d'un projet Composer, parmi celles des images
3
+ * officielles, d'après `config.platform.php` (la version que Composer suppose
4
+ * pour résoudre les dépendances) ou, à défaut, la contrainte `require.php`.
5
+ */
6
+ /** Versions de PHP des images officielles `php:<version>-cli`, de la plus ancienne à la plus récente. */
7
+ export const PHP_VERSIONS = ["8.2", "8.3", "8.4", "8.5"];
8
+ /** Correctifs essayés pour décider si une version mineure satisfait une contrainte. */
9
+ const MAX_PATCH = 99;
10
+ function parseVersion(text) {
11
+ const match = /^v?(\d+)(?:\.(\d+|\*|x))?(?:\.(\d+|\*|x))?/i.exec(text.trim());
12
+ if (!match)
13
+ return null;
14
+ const numbers = [match[1], match[2], match[3]].filter((part) => part !== undefined && /^\d+$/.test(part)).map(Number);
15
+ return { version: [numbers[0] ?? 0, numbers[1] ?? 0, numbers[2] ?? 0], parts: numbers.length };
16
+ }
17
+ function compare(a, b) {
18
+ for (let index = 0; index < 3; index++)
19
+ if (a[index] !== b[index])
20
+ return a[index] - b[index];
21
+ return 0;
22
+ }
23
+ /** Plus petite version au-delà de toutes celles qui commencent par les `parts` premiers nombres de `version`. */
24
+ function nextAfter(version, parts) {
25
+ if (parts <= 1)
26
+ return [version[0] + 1, 0, 0];
27
+ if (parts === 2)
28
+ return [version[0], version[1] + 1, 0];
29
+ return [version[0], version[1], version[2] + 1];
30
+ }
31
+ /** Vrai si `version` satisfait une contrainte simple (`^8.1`, `>=8.2`, `8.3.*`, `~8.2.1`, `8.4`…). */
32
+ function satisfiesTerm(version, term) {
33
+ const text = term.replace(/@\w+$/, "").trim();
34
+ if (text === "" || text === "*")
35
+ return true;
36
+ const operator = /^(\^|~|>=|<=|>|<|!=|==|=)?\s*(.*)$/.exec(text);
37
+ const parsed = parseVersion(operator[2]);
38
+ if (!parsed)
39
+ return false;
40
+ const { version: bound, parts } = parsed;
41
+ const wildcard = /\.(\*|x)/i.test(operator[2]);
42
+ switch (operator[1]) {
43
+ case "^": {
44
+ const upper = bound[0] > 0 ? [bound[0] + 1, 0, 0] : bound[1] > 0 || parts < 3 ? [0, bound[1] + 1, 0] : [0, 0, bound[2] + 1];
45
+ return compare(version, bound) >= 0 && compare(version, upper) < 0;
46
+ }
47
+ case "~":
48
+ return compare(version, bound) >= 0 && compare(version, nextAfter(bound, Math.max(parts - 1, 1))) < 0;
49
+ case ">=":
50
+ return compare(version, bound) >= 0;
51
+ case ">":
52
+ return compare(version, bound) > 0;
53
+ case "<=":
54
+ return compare(version, bound) <= 0;
55
+ case "<":
56
+ return compare(version, bound) < 0;
57
+ case "!=":
58
+ return compare(version, bound) !== 0;
59
+ default:
60
+ if (wildcard || parts < 3)
61
+ return compare(version, bound) >= 0 && compare(version, nextAfter(bound, parts)) < 0;
62
+ return compare(version, bound) === 0;
63
+ }
64
+ }
65
+ /** Vrai si `version` satisfait une contrainte Composer (`||` ou `|` entre alternatives, espace ou virgule entre conditions, intervalles `a - b`). */
66
+ export function satisfies(version, constraint) {
67
+ return constraint.split(/\s*\|\|?\s*/).some((alternative) => {
68
+ const range = /^(\S+)\s+-\s+(\S+)$/.exec(alternative.trim());
69
+ if (range) {
70
+ const upper = parseVersion(range[2]);
71
+ if (!upper)
72
+ return false;
73
+ return satisfiesTerm(version, `>=${range[1]}`) && (upper.parts < 3 ? compare(version, nextAfter(upper.version, upper.parts)) < 0 : compare(version, upper.version) <= 0);
74
+ }
75
+ const terms = alternative
76
+ .replace(/(>=|<=|>|<|!=|==|=|\^|~)\s+/g, "$1")
77
+ .split(/[\s,]+/)
78
+ .filter(Boolean);
79
+ return terms.every((term) => satisfiesTerm(version, term));
80
+ });
81
+ }
82
+ /** Vrai si une version de la série `minor` (`8.3`) satisfait la contrainte. */
83
+ function minorSatisfies(minor, constraint) {
84
+ const [major, minorNumber] = minor.split(".").map(Number);
85
+ for (let patch = 0; patch <= MAX_PATCH; patch++)
86
+ if (satisfies([major, minorNumber, patch], constraint))
87
+ return true;
88
+ return false;
89
+ }
90
+ /**
91
+ * Version de PHP de l'image d'un projet, d'après son `composer.json` : la
92
+ * série de `config.platform.php`, sinon la plus ancienne série qui satisfait
93
+ * `require.php`, sinon la plus récente. Lève une erreur quand aucune image
94
+ * officielle ne convient.
95
+ */
96
+ export function phpVersionFor(manifest) {
97
+ const platform = manifest?.config?.platform?.php;
98
+ if (typeof platform === "string") {
99
+ const parsed = parseVersion(platform);
100
+ const minor = parsed ? `${parsed.version[0]}.${parsed.version[1]}` : platform;
101
+ if (!PHP_VERSIONS.includes(minor)) {
102
+ throw new Error(`composer.json sets config.platform.php to ${platform}: the official PHP images cover ${PHP_VERSIONS.join(", ")}.`);
103
+ }
104
+ return minor;
105
+ }
106
+ const required = manifest?.require?.php;
107
+ if (typeof required !== "string")
108
+ return PHP_VERSIONS[PHP_VERSIONS.length - 1];
109
+ const minor = PHP_VERSIONS.find((candidate) => minorSatisfies(candidate, required));
110
+ if (!minor)
111
+ throw new Error(`composer.json requires PHP ${required}: the official PHP images cover ${PHP_VERSIONS.join(", ")}.`);
112
+ return minor;
113
+ }
@@ -0,0 +1,28 @@
1
+ import { type Vulnerability } from "../../../shared/schemas/model.schema.js";
2
+ import { type Lockfile, type PackageManager } from "./types.js";
3
+ /**
4
+ * Version de pnpm quand le projet n'en demande pas une plus récente : pnpm 11
5
+ * est la première à interroger l'API d'audit du registre npm encore en service
6
+ * (`/-/npm/v1/security/advisories/bulk`).
7
+ */
8
+ export declare const PNPM_DEFAULT = "11";
9
+ /**
10
+ * Version de pnpm à lancer pour un projet : celle de son champ `packageManager`
11
+ * (`pnpm@12.1.0`) si elle sait auditer, `PNPM_DEFAULT` sinon.
12
+ */
13
+ export declare function pnpmVersion(manifest: unknown): string;
14
+ /**
15
+ * Vulnérabilités d'un rapport `pnpm audit --json`, une par paquet, par nom : la gravité
16
+ * la plus haute de ses avis, et la correction la plus difficile parmi eux.
17
+ */
18
+ export declare function parsePnpmAudit(report: any, project: string): Vulnerability[];
19
+ /** Avis d'un rapport `pnpm audit --json`, regroupés par paquet et réduits à ce qui sert les corrections. */
20
+ export declare function pnpmFacts(report: any, project: string): unknown[];
21
+ /**
22
+ * Lit un `pnpm-lock.yaml` (format 9) : versions de chaque paquet de la section
23
+ * `packages`, dont les clés sont `<nom>@<version>` ; les versions d'un paquet
24
+ * installé en plusieurs exemplaires sont jointes, triées. Un autre format est
25
+ * refusé.
26
+ */
27
+ export declare function readPnpmLock(text: string, project: string): Lockfile;
28
+ export declare const pnpm: PackageManager;
@@ -0,0 +1,249 @@
1
+ import fs from "fs";
2
+ import path from "path";
3
+ import { NPM_SEVERITIES } from "../../../shared/schemas/model.schema.js";
4
+ import { tail } from "../commands.js";
5
+ import { CACHE_MOUNT, projectDir } from "../containers.js";
6
+ import { TrackerError } from "../errors.js";
7
+ import { NODE_IMAGE } from "./npm.js";
8
+ import { nameArg, onlyFields } from "./tool-args.js";
9
+ import { projectLabel, runManager } from "./types.js";
10
+ /**
11
+ * Version de pnpm quand le projet n'en demande pas une plus récente : pnpm 11
12
+ * est la première à interroger l'API d'audit du registre npm encore en service
13
+ * (`/-/npm/v1/security/advisories/bulk`).
14
+ */
15
+ export const PNPM_DEFAULT = "11";
16
+ /** Plus petite version majeure de pnpm qui sait auditer. */
17
+ const PNPM_MIN_MAJOR = 11;
18
+ /** Avis gardés par paquet dans les faits transmis à Claude, et chemins par avis. */
19
+ const MAX_ADVISORIES = 5;
20
+ const MAX_PATHS = 5;
21
+ /**
22
+ * Variables des commandes pnpm : caches de l'opération, et la version de pnpm
23
+ * choisie par le tracker, même quand `packageManager` en demande une autre
24
+ * (`pm-on-fail=ignore`).
25
+ */
26
+ const PNPM_ENV = {
27
+ npm_config_cache: `${CACHE_MOUNT}/npm`,
28
+ npm_config_update_notifier: "false",
29
+ pnpm_config_store_dir: `${CACHE_MOUNT}/pnpm-store`,
30
+ pnpm_config_pm_on_fail: "ignore",
31
+ pnpm_config_update_notifier: "false",
32
+ };
33
+ /**
34
+ * Version de pnpm à lancer pour un projet : celle de son champ `packageManager`
35
+ * (`pnpm@12.1.0`) si elle sait auditer, `PNPM_DEFAULT` sinon.
36
+ */
37
+ export function pnpmVersion(manifest) {
38
+ const field = manifest?.packageManager;
39
+ const match = typeof field === "string" ? /^pnpm@(\d+)(\.\d+\.\d+[^+]*)?/.exec(field) : null;
40
+ if (!match || Number(match[1]) < PNPM_MIN_MAJOR)
41
+ return PNPM_DEFAULT;
42
+ return `${match[1]}${match[2] ?? ""}`;
43
+ }
44
+ function readManifest(dir) {
45
+ try {
46
+ return JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf-8"));
47
+ }
48
+ catch (err) {
49
+ throw new TrackerError(`package.json cannot be read: ${err.message}`);
50
+ }
51
+ }
52
+ /** Options pnpm qui limitent l'audit et ses corrections au périmètre `scope`. */
53
+ function pnpmScopeArgs(scope) {
54
+ return scope === "production" ? ["--prod"] : [];
55
+ }
56
+ /** Version majeure de la plus petite version corrigée d'une plage `>=2.0.1`, ou null. */
57
+ function patchedMajor(patched) {
58
+ const match = />=\s*v?(\d+)/.exec(patched);
59
+ return match ? Number(match[1]) : null;
60
+ }
61
+ /** Correction d'un avis pour la version installée : aucune, dans la même version majeure, ou par une version majeure. */
62
+ function fixOf(advisory) {
63
+ if (typeof advisory.patched_versions !== "string" || advisory.patched_versions.trim() === "" || advisory.patched_versions.trim() === "<0.0.0")
64
+ return "none";
65
+ const target = patchedMajor(advisory.patched_versions);
66
+ const installed = (advisory.findings ?? []).map((finding) => Number(String(finding.version).split(".")[0]));
67
+ return target !== null && installed.some((major) => major < target) ? "major" : "available";
68
+ }
69
+ /** Avis d'un rapport `pnpm audit --json` ; lève une erreur sur un autre format. */
70
+ function advisoriesOf(report, project) {
71
+ if (!report || typeof report.advisories !== "object" || report.advisories === null) {
72
+ throw new TrackerError(`Unsupported pnpm audit report for ${projectLabel(project)}pnpm-lock.yaml: expected an "advisories" object (pnpm 11 or later).`);
73
+ }
74
+ return Object.values(report.advisories);
75
+ }
76
+ /**
77
+ * Vulnérabilités d'un rapport `pnpm audit --json`, une par paquet, par nom : la gravité
78
+ * la plus haute de ses avis, et la correction la plus difficile parmi eux.
79
+ */
80
+ export function parsePnpmAudit(report, project) {
81
+ const byName = new Map();
82
+ const rank = (fix) => ["available", "major", "none"].indexOf(fix);
83
+ for (const advisory of advisoriesOf(report, project)) {
84
+ const severity = NPM_SEVERITIES.includes(advisory.severity) ? advisory.severity : "info";
85
+ const fix = fixOf(advisory);
86
+ const current = byName.get(advisory.module_name);
87
+ if (!current) {
88
+ byName.set(advisory.module_name, { project, manager: "pnpm", name: advisory.module_name, severity, fix });
89
+ continue;
90
+ }
91
+ if (NPM_SEVERITIES.indexOf(severity) < NPM_SEVERITIES.indexOf(current.severity))
92
+ current.severity = severity;
93
+ if (rank(fix) > rank(current.fix))
94
+ current.fix = fix;
95
+ }
96
+ return [...byName.values()].sort((a, b) => a.name.localeCompare(b.name));
97
+ }
98
+ /** Avis d'un rapport `pnpm audit --json`, regroupés par paquet et réduits à ce qui sert les corrections. */
99
+ export function pnpmFacts(report, project) {
100
+ const byName = new Map();
101
+ for (const advisory of advisoriesOf(report, project))
102
+ byName.set(advisory.module_name, [...(byName.get(advisory.module_name) ?? []), advisory]);
103
+ return [...byName.entries()].sort(([a], [b]) => a.localeCompare(b)).map(([name, advisories]) => ({
104
+ manager: "pnpm",
105
+ project: project === "" ? "." : project,
106
+ name,
107
+ versions: [...new Set(advisories.flatMap((advisory) => (advisory.findings ?? []).map((finding) => finding.version)))],
108
+ advisories: advisories.slice(0, MAX_ADVISORIES).map((advisory) => ({
109
+ title: advisory.title,
110
+ url: advisory.url,
111
+ severity: advisory.severity,
112
+ vulnerable: advisory.vulnerable_versions,
113
+ patched: advisory.patched_versions ?? null,
114
+ paths: (advisory.findings ?? []).flatMap((finding) => finding.paths ?? []).slice(0, MAX_PATHS),
115
+ dev: (advisory.findings ?? []).some((finding) => finding.dev),
116
+ })),
117
+ }));
118
+ }
119
+ /**
120
+ * Lit un `pnpm-lock.yaml` (format 9) : versions de chaque paquet de la section
121
+ * `packages`, dont les clés sont `<nom>@<version>` ; les versions d'un paquet
122
+ * installé en plusieurs exemplaires sont jointes, triées. Un autre format est
123
+ * refusé.
124
+ */
125
+ export function readPnpmLock(text, project) {
126
+ const lines = text.split(/\r?\n/);
127
+ const version = /^lockfileVersion:\s*'?"?([\d.]+)/m.exec(text)?.[1];
128
+ if (!version || Number(version.split(".")[0]) < 9) {
129
+ throw new TrackerError(`${projectLabel(project)}pnpm-lock.yaml has lockfile version ${version ?? "unknown"}: version 9 (pnpm 9 or later) is required.`);
130
+ }
131
+ const all = new Map();
132
+ const start = lines.indexOf("packages:");
133
+ for (let index = start + 1; start !== -1 && index < lines.length; index++) {
134
+ const line = lines[index];
135
+ if (/^\S/.test(line))
136
+ break;
137
+ const key = /^ {2}(\S.*):\s*(\{\})?$/.exec(line)?.[1];
138
+ if (!key)
139
+ continue;
140
+ const id = key.replace(/^['"]|['"]$/g, "");
141
+ const at = id.lastIndexOf("@");
142
+ if (at <= 0)
143
+ continue;
144
+ const name = id.slice(0, at);
145
+ all.set(name, (all.get(name) ?? new Set()).add(id.slice(at + 1)));
146
+ }
147
+ return Object.fromEntries([...all.entries()].map(([name, versions]) => [name, [...versions].sort().join(", ")]));
148
+ }
149
+ async function audit(ctx, project) {
150
+ const result = await runManager(pnpm, ctx, project, ["audit", ...pnpmScopeArgs(ctx.scope), "--json"]);
151
+ try {
152
+ return JSON.parse(result.stdout);
153
+ }
154
+ catch {
155
+ throw new TrackerError(`pnpm audit in ${projectLabel(project) || "./"} did not return JSON: ${tail(result.stderr) || tail(result.stdout) || "no output"}`);
156
+ }
157
+ }
158
+ export const pnpm = {
159
+ id: "pnpm",
160
+ lockfile: "pnpm-lock.yaml",
161
+ manifest: "package.json",
162
+ image: () => ({ name: NODE_IMAGE }),
163
+ command: (ctx, project, args) => {
164
+ const dir = projectDir(ctx.workspace, project, "package.json");
165
+ return { image: NODE_IMAGE, cwd: project, command: ["npm", "exec", "--yes", `--package=pnpm@${pnpmVersion(readManifest(dir))}`, "--", "pnpm", ...args], env: PNPM_ENV };
166
+ },
167
+ audit: async (ctx, project) => {
168
+ const report = await audit(ctx, project);
169
+ return { vulnerabilities: parsePnpmAudit(report, project), facts: pnpmFacts(report, project) };
170
+ },
171
+ fix: async (ctx, project) => {
172
+ const result = await runManager(pnpm, ctx, project, ["audit", "--fix=update", ...pnpmScopeArgs(ctx.scope), "--lockfile-only", "--ignore-scripts"]);
173
+ if (!/\d+ vulnerabilit(y|ies) (was|were) fixed/.test(result.stdout)) {
174
+ throw new TrackerError(`pnpm audit --fix=update failed in ${projectLabel(project) || "./"}: ${tail(result.stderr) || tail(result.stdout) || "no output"}`);
175
+ }
176
+ },
177
+ readLock: readPnpmLock,
178
+ fixCommand: (scope) => ["pnpm audit --fix=update", ...pnpmScopeArgs(scope), "--lockfile-only --ignore-scripts"].join(" "),
179
+ tools: [
180
+ {
181
+ name: "pnpm_install_lockfile",
182
+ description: "Run pnpm install --lockfile-only --ignore-scripts in a pnpm project: updates pnpm-lock.yaml after a change of a package.json or of the overrides, without installing node_modules.",
183
+ properties: {},
184
+ required: [],
185
+ args: (args) => {
186
+ onlyFields(args);
187
+ return ["install", "--lockfile-only", "--ignore-scripts"];
188
+ },
189
+ },
190
+ {
191
+ name: "pnpm_audit",
192
+ description: "Run pnpm audit in a pnpm project, with the scope of the operation.",
193
+ properties: {},
194
+ required: [],
195
+ args: (args, scope) => {
196
+ onlyFields(args);
197
+ return ["audit", ...pnpmScopeArgs(scope)];
198
+ },
199
+ },
200
+ {
201
+ name: "pnpm_install",
202
+ description: "Run pnpm install --frozen-lockfile in a pnpm project: installs node_modules of every workspace package from pnpm-lock.yaml.",
203
+ properties: {},
204
+ required: [],
205
+ args: (args) => {
206
+ onlyFields(args);
207
+ return ["install", "--frozen-lockfile"];
208
+ },
209
+ },
210
+ {
211
+ name: "pnpm_test",
212
+ description: "Run the test script of every workspace package that has one (pnpm -r --if-present run test).",
213
+ properties: {},
214
+ required: [],
215
+ args: (args) => {
216
+ onlyFields(args);
217
+ return ["-r", "--if-present", "run", "test"];
218
+ },
219
+ },
220
+ {
221
+ name: "pnpm_run",
222
+ description: "Run a script of a package.json of a pnpm project: of the root package, or of the workspace package named by filter (pnpm --filter <filter> run <script>).",
223
+ properties: {
224
+ script: { type: "string", description: "Name of the script." },
225
+ filter: { type: "string", description: "Name of a workspace package (optional)." },
226
+ },
227
+ required: ["script"],
228
+ args: (args) => {
229
+ onlyFields(args, ["script", "filter"]);
230
+ const filter = args?.filter === undefined ? [] : ["--filter", nameArg(args, "filter")];
231
+ return [...filter, "run", nameArg(args, "script")];
232
+ },
233
+ },
234
+ {
235
+ name: "pnpm_why",
236
+ description: "Show which workspace packages depend on a package, and through which dependencies (pnpm why -r <package>).",
237
+ properties: { package: { type: "string", description: "Name of the package." } },
238
+ required: ["package"],
239
+ args: (args) => {
240
+ onlyFields(args, ["package"]);
241
+ return ["why", "-r", nameArg(args, "package")];
242
+ },
243
+ },
244
+ ],
245
+ guide: (scope, server) => [
246
+ `- pnpm projects (pnpm-lock.yaml, one per workspace): upgrade a dependency in the package.json of its workspace package, or pin a transitive one with an \`overrides\` entry of pnpm-workspace.yaml, with Edit, then update the lockfile with the ${server} tool pnpm_install_lockfile.`,
247
+ ` Check with pnpm_audit${scope === "production" ? " (it runs `pnpm audit --prod`)" : ""}; pnpm_install to install the dependencies, then pnpm_test (or pnpm_run) when the packages have tests; pnpm_why when useful.`,
248
+ ].join("\n"),
249
+ };
@@ -0,0 +1,17 @@
1
+ import { type Args } from "../../tools/types.js";
2
+ /** Lit un nom de paquet ou de script ; lève une erreur s'il contient autre chose. */
3
+ export declare function checkedName(value: string, field: string): string;
4
+ /** Lit l'argument `field`, nom de paquet ou de script obligatoire. */
5
+ export declare function nameArg(args: Args, field: string): string;
6
+ /** Lit l'argument facultatif `packages`, liste de noms de paquets. */
7
+ export declare function packagesArg(args: Args): string[];
8
+ /** Refuse tout champ hors de `project` et de `fields`. */
9
+ export declare function onlyFields(args: Args, fields?: string[]): void;
10
+ /** Propriété `packages` des outils qui ajoutent ou montent des paquets. */
11
+ export declare const PACKAGES_PROPERTY: {
12
+ type: string;
13
+ items: {
14
+ type: string;
15
+ };
16
+ description: string;
17
+ };
@@ -0,0 +1,26 @@
1
+ import { requireString, rejectUnknownFields } from "../../tools/types.js";
2
+ /** Nom de paquet, contrainte de version ou nom de script : pas d'option, pas d'espace. */
3
+ const NAME = /^[A-Za-z0-9@/._^~<>=*:+|-]+$/;
4
+ /** Lit un nom de paquet ou de script ; lève une erreur s'il contient autre chose. */
5
+ export function checkedName(value, field) {
6
+ if (!NAME.test(value) || value.startsWith("-"))
7
+ throw new Error(`"${field}" must be a package or script name (got ${JSON.stringify(value)}).`);
8
+ return value;
9
+ }
10
+ /** Lit l'argument `field`, nom de paquet ou de script obligatoire. */
11
+ export function nameArg(args, field) {
12
+ return checkedName(requireString(args, field), field);
13
+ }
14
+ /** Lit l'argument facultatif `packages`, liste de noms de paquets. */
15
+ export function packagesArg(args) {
16
+ const packages = args?.packages ?? [];
17
+ if (!Array.isArray(packages) || packages.some((item) => typeof item !== "string"))
18
+ throw new Error('"packages" must be a list of package names.');
19
+ return packages.map((item) => checkedName(item.trim(), "packages"));
20
+ }
21
+ /** Refuse tout champ hors de `project` et de `fields`. */
22
+ export function onlyFields(args, fields = []) {
23
+ rejectUnknownFields(args, ["project", ...fields]);
24
+ }
25
+ /** Propriété `packages` des outils qui ajoutent ou montent des paquets. */
26
+ export const PACKAGES_PROPERTY = { type: "array", items: { type: "string" }, description: "Packages to add or upgrade (optional)." };