forked from angular/angular-cli
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathparsers.ts
More file actions
523 lines (449 loc) · 15.7 KB
/
parsers.ts
File metadata and controls
523 lines (449 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
* @fileoverview This file contains the parser functions that are used to
* interpret the output of various package manager commands. Separating these
* into their own file improves modularity and allows for focused testing.
*/
import { ErrorInfo } from './error';
import { Logger } from './logger';
import { PackageManifest, PackageMetadata } from './package-metadata';
import { InstalledPackage } from './package-tree';
const MAX_LOG_LENGTH = 1024;
function logStdout(stdout: string, logger?: Logger): void {
if (!logger) {
return;
}
let output = stdout;
if (output.length > MAX_LOG_LENGTH) {
output = `${output.slice(0, MAX_LOG_LENGTH)}... (truncated)`;
}
logger.debug(` stdout:\n${output}`);
}
/**
* A generator function that parses a string containing JSONL (newline-delimited JSON)
* and yields each successfully parsed JSON object.
* @param output The string output to parse.
* @param logger An optional logger instance.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function* parseJsonLines(output: string, logger?: Logger): Generator<any> {
for (const line of output.split('\n')) {
if (!line.trim()) {
continue;
}
try {
yield JSON.parse(line);
} catch (e) {
logger?.debug(` Ignoring non-JSON line: ${e}`);
}
}
}
interface NpmListDependency {
version: string;
path?: string;
[key: string]: unknown;
}
/**
* Parses the output of `npm list` or a compatible command.
*
* The expected JSON structure is:
* ```json
* {
* "dependencies": {
* "@angular/cli": {
* "version": "18.0.0",
* "path": "/path/to/project/node_modules/@angular/cli", // path is optional
* ... (other package.json properties)
* }
* }
* }
* ```
*
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns A map of package names to their installed package details.
*/
export function parseNpmLikeDependencies(
stdout: string,
logger?: Logger,
): Map<string, InstalledPackage> {
logger?.debug(`Parsing npm-like dependency list...`);
logStdout(stdout, logger);
const dependencies = new Map<string, InstalledPackage>();
if (!stdout) {
logger?.debug(' stdout is empty. No dependencies found.');
return dependencies;
}
let data = JSON.parse(stdout);
if (Array.isArray(data)) {
// pnpm returns an array of projects.
data = data[0];
}
const dependencyMaps = [data.dependencies, data.devDependencies, data.unsavedDependencies].filter(
(d) => !!d,
);
if (dependencyMaps.length === 0) {
logger?.debug(' `dependencies` property not found. No dependencies found.');
return dependencies;
}
for (const dependencyMap of dependencyMaps) {
for (const [name, info] of Object.entries(dependencyMap as Record<string, NpmListDependency>)) {
dependencies.set(name, {
name,
version: info.version,
path: info.path,
});
}
}
logger?.debug(` Found ${dependencies.size} dependencies.`);
return dependencies;
}
/**
* Parses the output of `yarn list` (classic).
*
* The expected output is a JSON stream (JSONL), where each line is a JSON object.
* The relevant object has a `type` of `'tree'` with a `data` property.
* Yarn classic does not provide a path, so the `path` property will be `undefined`.
*
* ```json
* {"type":"tree","data":{"trees":[{"name":"@angular/cli@18.0.0","children":[]}]}}
* ```
*
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns A map of package names to their installed package details.
*/
export function parseYarnClassicDependencies(
stdout: string,
logger?: Logger,
): Map<string, InstalledPackage> {
logger?.debug(`Parsing yarn classic dependency list...`);
logStdout(stdout, logger);
const dependencies = new Map<string, InstalledPackage>();
if (!stdout) {
logger?.debug(' stdout is empty. No dependencies found.');
return dependencies;
}
for (const json of parseJsonLines(stdout, logger)) {
if (json.type === 'tree' && json.data?.trees) {
for (const info of json.data.trees) {
const name = info.name.split('@')[0];
const version = info.name.split('@').pop();
dependencies.set(name, {
name,
version,
});
}
}
}
logger?.debug(` Found ${dependencies.size} dependencies.`);
return dependencies;
}
/**
* Parses the output of `yarn list` (modern).
*
* The expected JSON structure is a single object.
* Yarn modern does not provide a path, so the `path` property will be `undefined`.
*
* ```json
* {
* "trees": [
* { "name": "@angular/cli@18.0.0", "children": [] }
* ]
* }
* ```
*
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns A map of package names to their installed package details.
*/
export function parseYarnModernDependencies(
stdout: string,
logger?: Logger,
): Map<string, InstalledPackage> {
logger?.debug(`Parsing yarn modern dependency list...`);
logStdout(stdout, logger);
const dependencies = new Map<string, InstalledPackage>();
if (!stdout) {
logger?.debug(' stdout is empty. No dependencies found.');
return dependencies;
}
// Modern yarn `list` command outputs a single JSON object with a `trees` property.
// Each line is not a separate JSON object.
try {
const data = JSON.parse(stdout);
for (const info of data.trees) {
const name = info.name.split('@')[0];
const version = info.name.split('@').pop();
dependencies.set(name, {
name,
version,
});
}
} catch (e) {
logger?.debug(
` Failed to parse as single JSON object: ${e}. Falling back to line-by-line parsing.`,
);
// Fallback for older versions of yarn berry that might still output json lines
for (const json of parseJsonLines(stdout, logger)) {
if (json.type === 'tree' && json.data?.trees) {
for (const info of json.data.trees) {
const name = info.name.split('@')[0];
const version = info.name.split('@').pop();
dependencies.set(name, {
name,
version,
});
}
}
}
}
logger?.debug(` Found ${dependencies.size} dependencies.`);
return dependencies;
}
/**
* Parses the output of `npm view` or a compatible command to get a package manifest.
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns The package manifest object.
*/
export function parseNpmLikeManifest(stdout: string, logger?: Logger): PackageManifest | null {
logger?.debug(`Parsing npm-like manifest...`);
logStdout(stdout, logger);
if (!stdout) {
logger?.debug(' stdout is empty. No manifest found.');
return null;
}
const result = JSON.parse(stdout);
return Array.isArray(result) ? result[result.length - 1] : result;
}
/**
* Parses the output of `npm view` or a compatible command to get package metadata.
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns The package metadata object.
*/
export function parseNpmLikeMetadata(stdout: string, logger?: Logger): PackageMetadata | null {
logger?.debug(`Parsing npm-like metadata...`);
logStdout(stdout, logger);
if (!stdout) {
logger?.debug(' stdout is empty. No metadata found.');
return null;
}
return JSON.parse(stdout);
}
/**
* Parses the output of `yarn info` (classic) to get a package manifest.
*
* When `yarn info --verbose` is used, the output is a JSONL stream. This function
* iterates through the lines to find the object with `type: 'inspect'` which contains
* the package manifest.
*
* For non-verbose output, it falls back to parsing a single JSON object.
*
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns The package manifest object, or `null` if not found.
*/
export function parseYarnClassicManifest(stdout: string, logger?: Logger): PackageManifest | null {
logger?.debug(`Parsing yarn classic manifest...`);
logStdout(stdout, logger);
if (!stdout) {
logger?.debug(' stdout is empty. No manifest found.');
return null;
}
// Yarn classic outputs JSONL. We need to find the relevant object.
let manifest;
for (const json of parseJsonLines(stdout, logger)) {
// The manifest data is in a JSON object with type 'inspect'.
if (json.type === 'inspect' && json.data) {
manifest = json.data;
break;
}
}
if (!manifest) {
logger?.debug(' Failed to find manifest in yarn classic output.');
return null;
}
// Yarn classic removes any field with a falsy value
// https://github.com/yarnpkg/yarn/blob/7cafa512a777048ce0b666080a24e80aae3d66a9/src/cli/commands/info.js#L26-L29
// Add a default of 'false' for the `save` field when the `ng-add` object is present but does not have any fields.
// There is a small chance this causes an incorrect value. However, the use of `ng-add` is rare and, in the cases
// it is used, save is set to either a `false` literal or a truthy value. Special cases can be added for specific
// packages if discovered.
if (
manifest['ng-add'] &&
typeof manifest['ng-add'] === 'object' &&
Object.keys(manifest['ng-add']).length === 0
) {
manifest['ng-add'].save ??= false;
}
return manifest;
}
/**
* Parses the output of `yarn info` (classic) to get package metadata.
* @param stdout The standard output of the command.
* @param logger An optional logger instance.
* @returns The package metadata object.
*/
export function parseYarnClassicMetadata(stdout: string, logger?: Logger): PackageMetadata | null {
logger?.debug(`Parsing yarn classic metadata...`);
logStdout(stdout, logger);
if (!stdout) {
logger?.debug(' stdout is empty. No metadata found.');
return null;
}
// Yarn classic outputs JSONL. We need to find the relevant object.
let metadata;
for (const json of parseJsonLines(stdout, logger)) {
// The metadata data is in a JSON object with type 'inspect'.
if (json.type === 'inspect' && json.data) {
metadata = json.data;
break;
}
}
if (!metadata) {
logger?.debug(' Failed to find metadata in yarn classic output.');
return null;
}
return metadata;
}
/**
* Parses the `stdout` or `stderr` output of npm, pnpm, modern yarn, or bun to extract structured error information.
*
* This parser uses a multi-stage approach. It first attempts to parse the entire `output` as a
* single JSON object, which is the standard for modern tools like pnpm, yarn, and bun. If JSON
* parsing fails, it falls back to a line-by-line regex-based approach to handle the plain
* text output from older versions of npm.
*
* Example JSON output (pnpm):
* ```json
* {
* "code": "E404",
* "summary": "Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found",
* "detail": "The requested resource '@angular/non-existent@*' could not be found or you do not have permission to access it."
* }
* ```
*
* Example text output (npm):
* ```
* npm error code E404
* npm error 404 Not Found - GET https://registry.npmjs.org/@angular%2fnon-existent - Not found
* ```
*
* @param output The standard output or standard error of the command.
* @param logger An optional logger instance.
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
*/
export function parseNpmLikeError(output: string, logger?: Logger): ErrorInfo | null {
logger?.debug(`Parsing npm-like error output...`);
logStdout(output, logger); // Log output for debugging purposes
if (!output) {
logger?.debug(' output is empty. No error found.');
return null;
}
// Attempt to parse as JSON first (common for pnpm, modern yarn, bun)
try {
const jsonError = JSON.parse(output);
if (
jsonError &&
typeof jsonError.code === 'string' &&
(typeof jsonError.summary === 'string' || typeof jsonError.message === 'string')
) {
const summary = jsonError.summary || jsonError.message;
logger?.debug(` Successfully parsed JSON error with code '${jsonError.code}'.`);
return {
code: jsonError.code,
summary,
detail: jsonError.detail,
};
}
} catch (e) {
logger?.debug(` Failed to parse output as JSON: ${e}. Attempting regex fallback.`);
// Fallback to regex for plain text errors (common for npm)
}
// Regex for npm-like error codes (e.g., `npm ERR! code E404` or `npm error code E404`)
const errorCodeMatch = output.match(/npm (ERR!|error) code (E\d{3}|[A-Z_]+)/);
if (errorCodeMatch) {
const code = errorCodeMatch[2]; // Capture group 2 is the actual error code
let summary: string | undefined;
// Find the most descriptive summary line (the line after `npm ERR! code ...` or `npm error code ...`).
for (const line of output.split('\n')) {
if (line.startsWith('npm ERR!') && !line.includes(' code ')) {
summary = line.replace('npm ERR! ', '').trim();
break;
} else if (line.startsWith('npm error') && !line.includes(' code ')) {
summary = line.replace('npm error ', '').trim();
break;
}
}
logger?.debug(` Successfully parsed text error with code '${code}'.`);
return {
code,
summary: summary || `Package manager error: ${code}`,
};
}
logger?.debug(' Failed to parse npm-like error. No structured error found.');
return null;
}
/**
* Parses the `stdout` or `stderr` output of yarn classic to extract structured error information.
*
* This parser first attempts to find an HTTP status code (e.g., 404, 401) in the verbose output.
* If found, it returns a standardized error code (`E${statusCode}`).
* If no HTTP status code is found, it falls back to parsing generic JSON error lines.
*
* Example verbose output (with HTTP status code):
* ```json
* {"type":"verbose","data":"Request \"https://registry.npmjs.org/@angular%2fnon-existent\" finished with status code 404."}
* ```
*
* Example generic JSON error output:
* ```json
* {"type":"error","data":"Received invalid response from npm."}
* ```
*
* @param output The standard output or standard error of the command.
* @param logger An optional logger instance.
* @returns An `ErrorInfo` object if parsing is successful, otherwise `null`.
*/
export function parseYarnClassicError(output: string, logger?: Logger): ErrorInfo | null {
logger?.debug(`Parsing yarn classic error output...`);
logStdout(output, logger); // Log output for debugging purposes
if (!output) {
logger?.debug(' output is empty. No error found.');
return null;
}
// First, check for any HTTP status code in the verbose output.
const statusCodeMatch = output.match(/finished with status code (\d{3})/);
if (statusCodeMatch) {
const statusCode = Number(statusCodeMatch[1]);
// Status codes in the 200-299 range are successful.
if (statusCode < 200 || statusCode >= 300) {
logger?.debug(` Detected HTTP error status code '${statusCode}' in verbose output.`);
return {
code: `E${statusCode}`,
summary: `Request failed with status code ${statusCode}.`,
};
}
}
// Fallback to the JSON error type if no HTTP status code is present.
for (const json of parseJsonLines(output, logger)) {
if (json.type === 'error' && typeof json.data === 'string') {
const summary = json.data;
logger?.debug(` Successfully parsed generic yarn classic error.`);
return {
code: 'UNKNOWN_ERROR',
summary,
};
}
}
logger?.debug(' Failed to parse yarn classic error. No structured error found.');
return null;
}