browser-requirements 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +15 -0
- package/README.md +248 -2
- package/dist/analysis/analyze.d.ts +14 -0
- package/dist/analysis/analyze.js +67 -0
- package/dist/analysis/analyze.js.map +1 -0
- package/dist/analysis/ast.d.ts +12 -0
- package/dist/analysis/ast.js +21 -0
- package/dist/analysis/ast.js.map +1 -0
- package/dist/analysis/context.d.ts +17 -0
- package/dist/analysis/context.js +2 -0
- package/dist/analysis/context.js.map +1 -0
- package/dist/analysis/detectors/builtins.d.ts +8 -0
- package/dist/analysis/detectors/builtins.js +68 -0
- package/dist/analysis/detectors/builtins.js.map +1 -0
- package/dist/analysis/detectors/syntax.d.ts +6 -0
- package/dist/analysis/detectors/syntax.js +79 -0
- package/dist/analysis/detectors/syntax.js.map +1 -0
- package/dist/analysis/detectors/web-apis.d.ts +12 -0
- package/dist/analysis/detectors/web-apis.js +30 -0
- package/dist/analysis/detectors/web-apis.js.map +1 -0
- package/dist/analysis/files.d.ts +9 -0
- package/dist/analysis/files.js +60 -0
- package/dist/analysis/files.js.map +1 -0
- package/dist/analysis/guards.d.ts +9 -0
- package/dist/analysis/guards.js +41 -0
- package/dist/analysis/guards.js.map +1 -0
- package/dist/analysis/parse.d.ts +21 -0
- package/dist/analysis/parse.js +43 -0
- package/dist/analysis/parse.js.map +1 -0
- package/dist/analysis/scope.d.ts +11 -0
- package/dist/analysis/scope.js +31 -0
- package/dist/analysis/scope.js.map +1 -0
- package/dist/analysis/walk.d.ts +9 -0
- package/dist/analysis/walk.js +168 -0
- package/dist/analysis/walk.js.map +1 -0
- package/dist/analysis/writes.d.ts +6 -0
- package/dist/analysis/writes.js +16 -0
- package/dist/analysis/writes.js.map +1 -0
- package/dist/bin/cli.d.ts +2 -0
- package/dist/bin/cli.js +114 -0
- package/dist/bin/cli.js.map +1 -0
- package/dist/config/load.d.ts +14 -0
- package/dist/config/load.js +95 -0
- package/dist/config/load.js.map +1 -0
- package/dist/config/suppressions.d.ts +16 -0
- package/dist/config/suppressions.js +60 -0
- package/dist/config/suppressions.js.map +1 -0
- package/dist/data/browsers.d.ts +8 -0
- package/dist/data/browsers.js +49 -0
- package/dist/data/browsers.js.map +1 -0
- package/dist/data/features.d.ts +14 -0
- package/dist/data/features.js +46 -0
- package/dist/data/features.js.map +1 -0
- package/dist/data/generated/features.json +1 -0
- package/dist/data/globals.d.ts +5 -0
- package/dist/data/globals.js +22 -0
- package/dist/data/globals.js.map +1 -0
- package/dist/data/syntax-map.d.ts +10 -0
- package/dist/data/syntax-map.js +34 -0
- package/dist/data/syntax-map.js.map +1 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/model/baseline.d.ts +7 -0
- package/dist/model/baseline.js +15 -0
- package/dist/model/baseline.js.map +1 -0
- package/dist/model/compare.d.ts +5 -0
- package/dist/model/compare.js +61 -0
- package/dist/model/compare.js.map +1 -0
- package/dist/model/minimums.d.ts +5 -0
- package/dist/model/minimums.js +45 -0
- package/dist/model/minimums.js.map +1 -0
- package/dist/model/targets.d.ts +12 -0
- package/dist/model/targets.js +89 -0
- package/dist/model/targets.js.map +1 -0
- package/dist/model/types.d.ts +165 -0
- package/dist/model/types.js +2 -0
- package/dist/model/types.js.map +1 -0
- package/dist/model/version.d.ts +9 -0
- package/dist/model/version.js +39 -0
- package/dist/model/version.js.map +1 -0
- package/dist/output/comparison.d.ts +2 -0
- package/dist/output/comparison.js +7 -0
- package/dist/output/comparison.js.map +1 -0
- package/dist/output/index.d.ts +3 -0
- package/dist/output/index.js +6 -0
- package/dist/output/index.js.map +1 -0
- package/dist/output/json.d.ts +3 -0
- package/dist/output/json.js +5 -0
- package/dist/output/json.js.map +1 -0
- package/dist/output/markdown.d.ts +9 -0
- package/dist/output/markdown.js +59 -0
- package/dist/output/markdown.js.map +1 -0
- package/dist/output/style.d.ts +5 -0
- package/dist/output/style.js +14 -0
- package/dist/output/style.js.map +1 -0
- package/dist/output/text.d.ts +9 -0
- package/dist/output/text.js +115 -0
- package/dist/output/text.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +5 -0
- package/dist/version.js.map +1 -0
- package/package.json +78 -4
- package/schemas/comparison-1.json +44 -0
- package/schemas/config-1.json +24 -0
- package/schemas/report-1.json +114 -0
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { globalApi, staticMember } from '../../data/features.js';
|
|
2
|
+
import { GLOBAL_SINGLETONS } from '../../data/globals.js';
|
|
3
|
+
const GLOBAL_OBJECTS = new Set(['globalThis', 'window', 'self']);
|
|
4
|
+
/**
|
|
5
|
+
* A reference to a global (resolved by scope analysis): Web API functions and interfaces
|
|
6
|
+
* (`structuredClone`, `new Response()`) and global built-ins (`WeakRef`).
|
|
7
|
+
*/
|
|
8
|
+
export function detectGlobalIdentifier(node, ctx) {
|
|
9
|
+
const feature = globalApi(node.name);
|
|
10
|
+
if (feature)
|
|
11
|
+
ctx.report(feature, node, 'certain', node.name);
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* A member of a global object: `globalThis.fetch`, members of singletons (`navigator.share`),
|
|
15
|
+
* static members of built-ins (`Object.groupBy`) and Web API interfaces (`URL.canParse`).
|
|
16
|
+
*/
|
|
17
|
+
export function detectGlobalMember(objectName, property, node, ctx) {
|
|
18
|
+
if (GLOBAL_OBJECTS.has(objectName)) {
|
|
19
|
+
const viaGlobal = globalApi(property);
|
|
20
|
+
if (viaGlobal) {
|
|
21
|
+
ctx.report(viaGlobal, node, 'certain', property);
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const singleton = GLOBAL_SINGLETONS[objectName];
|
|
26
|
+
const feature = singleton ? staticMember(singleton, property) : staticMember(objectName, property);
|
|
27
|
+
if (feature)
|
|
28
|
+
ctx.report(feature, node, 'certain', property);
|
|
29
|
+
}
|
|
30
|
+
//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AAE,SAAS,EAAE,QAAQ,CAAC,CAAC;AAC9D,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export interface DiscoverOptions {
|
|
2
|
+
root: string;
|
|
3
|
+
kind: 'source' | 'output';
|
|
4
|
+
ignore?: readonly string[];
|
|
5
|
+
}
|
|
6
|
+
/** Converts a glob (`**`, `*`, `?`) into a regular expression matched against POSIX relative paths. */
|
|
7
|
+
export declare function globToRegExp(glob: string): RegExp;
|
|
8
|
+
/** Expands files and directories into sorted POSIX paths relative to the root. */
|
|
9
|
+
export declare function discoverFiles(paths: readonly string[], options: DiscoverOptions): string[];
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { SUPPORTED_EXTENSIONS } from './parse.js';
|
|
4
|
+
const ALWAYS_IGNORED = new Set(['.git']);
|
|
5
|
+
const SOURCE_IGNORED = new Set(['node_modules']);
|
|
6
|
+
/** Converts a glob (`**`, `*`, `?`) into a regular expression matched against POSIX relative paths. */
|
|
7
|
+
export function globToRegExp(glob) {
|
|
8
|
+
let re = '';
|
|
9
|
+
for (let i = 0; i < glob.length; i++) {
|
|
10
|
+
const c = glob[i];
|
|
11
|
+
if (c === '*') {
|
|
12
|
+
if (glob[i + 1] === '*') {
|
|
13
|
+
const slash = glob[i + 2] === '/';
|
|
14
|
+
re += slash ? '(?:.*/)?' : '.*';
|
|
15
|
+
i += slash ? 2 : 1;
|
|
16
|
+
}
|
|
17
|
+
else {
|
|
18
|
+
re += '[^/]*';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
else if (c === '?') {
|
|
22
|
+
re += '[^/]';
|
|
23
|
+
}
|
|
24
|
+
else {
|
|
25
|
+
re += /[.+^${}()|[\]\\]/.test(c) ? `\\${c}` : c;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return new RegExp(`^${re}(?:/.*)?$`);
|
|
29
|
+
}
|
|
30
|
+
const isSupported = (file) => !file.endsWith('.d.ts') && !file.endsWith('.d.mts') && !file.endsWith('.d.cts') && SUPPORTED_EXTENSIONS.includes(path.extname(file).toLowerCase());
|
|
31
|
+
/** Expands files and directories into sorted POSIX paths relative to the root. */
|
|
32
|
+
export function discoverFiles(paths, options) {
|
|
33
|
+
const ignore = (options.ignore ?? []).map(globToRegExp);
|
|
34
|
+
const skipDir = (name) => ALWAYS_IGNORED.has(name) || (options.kind === 'source' && SOURCE_IGNORED.has(name));
|
|
35
|
+
const found = new Set();
|
|
36
|
+
const toRelative = (absolute) => path.relative(options.root, absolute).split(path.sep).join('/');
|
|
37
|
+
const ignored = (relative) => ignore.some((re) => re.test(relative));
|
|
38
|
+
const walk = (absolute) => {
|
|
39
|
+
const relative = toRelative(absolute);
|
|
40
|
+
if (relative && ignored(relative))
|
|
41
|
+
return;
|
|
42
|
+
const stat = fs.statSync(absolute);
|
|
43
|
+
if (stat.isFile()) {
|
|
44
|
+
if (isSupported(absolute))
|
|
45
|
+
found.add(relative);
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
if (!stat.isDirectory())
|
|
49
|
+
return;
|
|
50
|
+
for (const entry of fs.readdirSync(absolute, { withFileTypes: true })) {
|
|
51
|
+
if (entry.isDirectory() && skipDir(entry.name))
|
|
52
|
+
continue;
|
|
53
|
+
walk(path.join(absolute, entry.name));
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
for (const p of paths)
|
|
57
|
+
walk(path.resolve(options.root, p));
|
|
58
|
+
return [...found].sort();
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=files.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"files.js","sourceRoot":"","sources":["../../src/analysis/files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,SAAS,CAAC;AACzB,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC;AAQlD,MAAM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YAClB,IAAI,WAAW,CAAC,QAAQ,CAAC;gBAAE,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;YAC/C,OAAO;QACT,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,WAAW,EAAE;YAAE,OAAO;QAChC,KAAK,MAAM,KAAK,IAAI,EAAE,CAAC,WAAW,CAAC,QAAQ,EAAE,EAAE,aAAa,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC;YACtE,IAAI,KAAK,CAAC,WAAW,EAAE,IAAI,OAAO,CAAC,KAAK,CAAC,IAAI,CAAC;gBAAE,SAAS;YACzD,IAAI,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,EAAE,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;QACxC,CAAC;IACH,CAAC,CAAC;IAEF,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;IAC3D,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,IAAI,EAAE,CAAC;AAC3B,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type AstNode } from './ast.js';
|
|
2
|
+
/**
|
|
3
|
+
* Names checked by a feature-detection test (research R6). A finding is guarded when it is
|
|
4
|
+
* evaluated inside the truthy branch of a test that checks the same member or global name.
|
|
5
|
+
*
|
|
6
|
+
* Recognised: `'m' in X`, `typeof X.m !== 'undefined'` (and `!=`), `typeof X.m === 'function' |
|
|
7
|
+
* 'object' | 'symbol'` (and `==`), truthiness `X.m` / `g`, and `&&` combinations of those.
|
|
8
|
+
*/
|
|
9
|
+
export declare function guardedNames(test: AstNode): string[];
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { memberName, unwrap } from './ast.js';
|
|
2
|
+
/**
|
|
3
|
+
* Names checked by a feature-detection test (research R6). A finding is guarded when it is
|
|
4
|
+
* evaluated inside the truthy branch of a test that checks the same member or global name.
|
|
5
|
+
*
|
|
6
|
+
* Recognised: `'m' in X`, `typeof X.m !== 'undefined'` (and `!=`), `typeof X.m === 'function' |
|
|
7
|
+
* 'object' | 'symbol'` (and `==`), truthiness `X.m` / `g`, and `&&` combinations of those.
|
|
8
|
+
*/
|
|
9
|
+
export function guardedNames(test) {
|
|
10
|
+
const node = unwrap(test.type === 'ChainExpression' ? test.expression : test);
|
|
11
|
+
if (node.type === 'LogicalExpression' && node.operator === '&&') {
|
|
12
|
+
return [...guardedNames(node.left), ...guardedNames(node.right)];
|
|
13
|
+
}
|
|
14
|
+
if (node.type === 'BinaryExpression') {
|
|
15
|
+
if (node.operator === 'in' && node.left?.type === 'Literal' && typeof node.left.value === 'string') {
|
|
16
|
+
return [node.left.value];
|
|
17
|
+
}
|
|
18
|
+
const typeofSide = [node.left, node.right].find((s) => s?.type === 'UnaryExpression' && s.operator === 'typeof');
|
|
19
|
+
const literalSide = [node.left, node.right].find((s) => s?.type === 'Literal' && typeof s.value === 'string');
|
|
20
|
+
if (typeofSide && literalSide) {
|
|
21
|
+
const negative = node.operator === '!==' || node.operator === '!=';
|
|
22
|
+
const positive = node.operator === '===' || node.operator === '==';
|
|
23
|
+
const value = literalSide.value;
|
|
24
|
+
if ((negative && value === 'undefined') || (positive && ['function', 'object', 'symbol'].includes(value))) {
|
|
25
|
+
return checkedName(typeofSide.argument);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return [];
|
|
29
|
+
}
|
|
30
|
+
return checkedName(node);
|
|
31
|
+
}
|
|
32
|
+
function checkedName(expr) {
|
|
33
|
+
if (!expr)
|
|
34
|
+
return [];
|
|
35
|
+
const node = unwrap(expr.type === 'ChainExpression' ? expr.expression : expr);
|
|
36
|
+
if (node.type === 'Identifier')
|
|
37
|
+
return [node.name];
|
|
38
|
+
const name = memberName(node);
|
|
39
|
+
return name ? [name] : [];
|
|
40
|
+
}
|
|
41
|
+
//# sourceMappingURL=guards.js.map
|
|
@@ -0,0 +1 @@
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
|
3
|
+
message: string;
|
|
4
|
+
line: number;
|
|
5
|
+
column: number;
|
|
6
|
+
}
|
|
7
|
+
export interface ParsedFile {
|
|
8
|
+
program: Program;
|
|
9
|
+
comments: Comment[];
|
|
10
|
+
errors: ParseError[];
|
|
11
|
+
/** Converts a source offset into a 1-based line and column. */
|
|
12
|
+
locate(offset: number): {
|
|
13
|
+
line: number;
|
|
14
|
+
column: number;
|
|
15
|
+
};
|
|
16
|
+
/** Text of a 1-based line, without its line terminator. */
|
|
17
|
+
lineText(line: number): string;
|
|
18
|
+
}
|
|
19
|
+
export declare const SUPPORTED_EXTENSIONS: readonly ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'];
|
|
20
|
+
/** Parses JavaScript or TypeScript source with oxc-parser. Never throws on syntax errors. */
|
|
21
|
+
export declare function parseFile(file: string, code: string): ParsedFile;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { parseSync } from 'oxc-parser';
|
|
3
|
+
export const SUPPORTED_EXTENSIONS = ['.js', '.mjs', '.cjs', '.jsx', '.ts', '.mts', '.cts', '.tsx'];
|
|
4
|
+
function optionsFor(file) {
|
|
5
|
+
const ext = path.extname(file).toLowerCase();
|
|
6
|
+
const lang = ext === '.tsx' ? 'tsx' : ext === '.ts' || ext === '.mts' || ext === '.cts' ? 'ts' : 'jsx';
|
|
7
|
+
const sourceType = ext === '.mjs' || ext === '.mts' ? 'module' : ext === '.cjs' || ext === '.cts' ? 'commonjs' : 'unambiguous';
|
|
8
|
+
// One AST shape (TS-ESTree with ranges) for every file, as required by the scope manager (research R1, R3).
|
|
9
|
+
return { lang, sourceType, astType: 'ts', range: true, preserveParens: false };
|
|
10
|
+
}
|
|
11
|
+
/** Parses JavaScript or TypeScript source with oxc-parser. Never throws on syntax errors. */
|
|
12
|
+
export function parseFile(file, code) {
|
|
13
|
+
const result = parseSync(file, code, optionsFor(file));
|
|
14
|
+
const lineStarts = [0];
|
|
15
|
+
for (let i = 0; i < code.length; i++) {
|
|
16
|
+
if (code.charCodeAt(i) === 10)
|
|
17
|
+
lineStarts.push(i + 1);
|
|
18
|
+
}
|
|
19
|
+
const locate = (offset) => {
|
|
20
|
+
let lo = 0;
|
|
21
|
+
let hi = lineStarts.length - 1;
|
|
22
|
+
while (lo < hi) {
|
|
23
|
+
const mid = (lo + hi + 1) >> 1;
|
|
24
|
+
if ((lineStarts[mid] ?? 0) <= offset)
|
|
25
|
+
lo = mid;
|
|
26
|
+
else
|
|
27
|
+
hi = mid - 1;
|
|
28
|
+
}
|
|
29
|
+
return { line: lo + 1, column: offset - (lineStarts[lo] ?? 0) + 1 };
|
|
30
|
+
};
|
|
31
|
+
const lineText = (line) => {
|
|
32
|
+
const start = lineStarts[line - 1];
|
|
33
|
+
if (start === undefined)
|
|
34
|
+
return '';
|
|
35
|
+
const next = lineStarts[line];
|
|
36
|
+
return code.slice(start, next === undefined ? code.length : next).replace(/\r?\n$/, '');
|
|
37
|
+
};
|
|
38
|
+
const errors = result.errors
|
|
39
|
+
.filter((e) => e.severity === 'Error')
|
|
40
|
+
.map((e) => ({ message: e.message, ...locate(e.labels[0]?.start ?? 0) }));
|
|
41
|
+
return { program: result.program, comments: result.comments, errors, locate, lineText };
|
|
42
|
+
}
|
|
43
|
+
//# sourceMappingURL=parse.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parse.js","sourceRoot":"","sources":["../../src/analysis/parse.ts"],"names":[],"mappings":"AAAA,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAkD,MAAM,YAAY,CAAC;AAkBvF,MAAM,CAAC,MAAM,oBAAoB,GAAG,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAU,CAAC;AAE5G,SAAS,UAAU,CAAC,IAAY;IAC9B,MAAM,GAAG,GAAG,IAA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AO,EAAE,QAAQ,EAAE,MAAM,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC;AAC1F,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Program } from 'oxc-parser';
|
|
2
|
+
export interface ScopeInfo {
|
|
3
|
+
/** Identifier start offset → name, for value references that resolve to the global scope. */
|
|
4
|
+
globals: Map<number, string>;
|
|
5
|
+
/** How many declarations each name has across all scopes of the file. */
|
|
6
|
+
declarationCounts: Map<string, number>;
|
|
7
|
+
}
|
|
8
|
+
/** Scope analysis with the TypeScript scope manager (research R3). Type-only references are excluded. */
|
|
9
|
+
export declare function analyzeScopes(program: Program, file: string): ScopeInfo;
|
|
10
|
+
/** Identifier start offset → name, for value references that resolve to the global scope. */
|
|
11
|
+
export declare function findGlobalReferences(program: Program, file: string): Map<number, string>;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { analyze } from '@typescript-eslint/scope-manager';
|
|
2
|
+
/** Scope analysis with the TypeScript scope manager (research R3). Type-only references are excluded. */
|
|
3
|
+
export function analyzeScopes(program, file) {
|
|
4
|
+
const isModule = program.sourceType === 'module' || /\.m[jt]s$/i.test(file);
|
|
5
|
+
const manager = analyze(program, {
|
|
6
|
+
sourceType: isModule ? 'module' : 'script',
|
|
7
|
+
jsxPragma: null,
|
|
8
|
+
// No implicit lib globals: built-ins like Promise or structuredClone must stay unresolved.
|
|
9
|
+
lib: [],
|
|
10
|
+
});
|
|
11
|
+
const globals = new Map();
|
|
12
|
+
for (const reference of manager.globalScope?.through ?? []) {
|
|
13
|
+
if (!reference.isValueReference)
|
|
14
|
+
continue;
|
|
15
|
+
globals.set(reference.identifier.range[0], reference.identifier.name);
|
|
16
|
+
}
|
|
17
|
+
const declarationCounts = new Map();
|
|
18
|
+
for (const scope of manager.scopes) {
|
|
19
|
+
for (const variable of scope.variables) {
|
|
20
|
+
if (variable.defs.length === 0)
|
|
21
|
+
continue;
|
|
22
|
+
declarationCounts.set(variable.name, (declarationCounts.get(variable.name) ?? 0) + variable.defs.length);
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
return { globals, declarationCounts };
|
|
26
|
+
}
|
|
27
|
+
/** Identifier start offset → name, for value references that resolve to the global scope. */
|
|
28
|
+
export function findGlobalReferences(program, file) {
|
|
29
|
+
return analyzeScopes(program, file).globals;
|
|
30
|
+
}
|
|
31
|
+
//# sourceMappingURL=scope.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope.js","sourceRoot":"","sources":["../../src/analysis/scope.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,kCAAkC,CAAC;AAW3D,yGAAyG;AACzG,MAAM,UAAU,aAAa,CAAC,OAAgB,EAAE,IAAY;IAC1D,MAAM,QAAQ,GAAG,OAAO,CAAC,UAAU,KAAK,QAAQ,IAAI,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IAC5E,MAAM,OAAO,GAAG,OAAO,CAAC,OAAsC,EAAE;QAC9D,UAAU,EAAE,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ;QAC1C,SAAS,EAAE,IAAI;QACf,2FAA2F;QAC3F,GAAG,EAAE,EAAE;KACR,CAAC,CAAC;IAEH,MAAM,OAAO,GAAG,IAAI,GAAG,EAAkB,CAAC;IAC1C,KAAK,MAAM,SAAS,IAAI,OAAO,CAAC,WAAW,EAAE,OAAO,IAAI,EAAE,EAAE,CAAC;QAC3D,IAAI,CAAC,SAAS,CAAC,gBAAgB;YAAE,SAAS;QAC1C,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,UAAU,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IACxE,CAAC;IAED,MAAM,iBAAiB,GAAG,IAAI,GAAG,EAAkB,CAAC;IACpD,KAAK,MAAM,KAAK,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC;QACnC,KAAK,MAAM,QAAQ,IAAI,KAAK,CAAC,SAAS,EAAE,CAAC;YACvC,IAAI,QAAQ,CAAC,IAAI,CAAC,MAAM,KAAK,CAAC;gBAAE,SAAS;YACzC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,EAAE,CAAC,iBAAiB,CAAC,GAAG,CAAC,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QAC3G,CAAC;IACH,CAAC;IACD,OAAO,EAAE,OAAO,EAAE,iBAAiB,EAAE,CAAC;AACxC,CAAC;AAED,6FAA6F;AAC7F,MAAM,UAAU,oBAAoB,CAAC,OAAgB,EAAE,IAAY;IACjE,OAAO,aAAa,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC,OAAO,CAAC;AAC9C,CAAC"}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { Finding } from '../model/types.js';
|
|
2
|
+
import { type ParseError, type ParsedFile } from './parse.js';
|
|
3
|
+
export interface FileAnalysis {
|
|
4
|
+
findings: Finding[];
|
|
5
|
+
errors: ParseError[];
|
|
6
|
+
parsed: ParsedFile;
|
|
7
|
+
}
|
|
8
|
+
/** Parses one file and returns its findings (unsorted). Files with syntax errors yield no findings. */
|
|
9
|
+
export declare function analyzeSource(file: string, code: string): FileAnalysis;
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { byId } from '../data/features.js';
|
|
2
|
+
import { SYNTAX_FEATURES } from '../data/syntax-map.js';
|
|
3
|
+
import { isNode, memberName, unwrap } from './ast.js';
|
|
4
|
+
import { detectInstanceCall, recordReceiver } from './detectors/builtins.js';
|
|
5
|
+
import { detectSyntax } from './detectors/syntax.js';
|
|
6
|
+
import { detectGlobalIdentifier, detectGlobalMember } from './detectors/web-apis.js';
|
|
7
|
+
import { guardedNames } from './guards.js';
|
|
8
|
+
import { parseFile } from './parse.js';
|
|
9
|
+
import { analyzeScopes } from './scope.js';
|
|
10
|
+
import { isWriteOnly } from './writes.js';
|
|
11
|
+
const SKIP_KEYS = new Set([
|
|
12
|
+
'type', 'start', 'end', 'range', 'loc', 'parent', 'hashbang',
|
|
13
|
+
'typeAnnotation', 'returnType', 'typeParameters', 'typeArguments', 'superTypeArguments', 'implements',
|
|
14
|
+
]);
|
|
15
|
+
const TYPE_ONLY = new Set(['TSInterfaceDeclaration', 'TSTypeAliasDeclaration', 'TSDeclareFunction', 'TSTypeAnnotation', 'TSEnumDeclaration']);
|
|
16
|
+
const FUNCTION_TYPES = new Set(['FunctionDeclaration', 'FunctionExpression', 'ArrowFunctionExpression']);
|
|
17
|
+
const SNIPPET_MAX = 120;
|
|
18
|
+
const COMPARISONS = new Set(['<', '>', '<=', '>=', '==', '===', '!=', '!==']);
|
|
19
|
+
/** Reading a property only to compare it never throws when it is missing: that is detection (research R6, R7). */
|
|
20
|
+
const isComparedRead = (node, parent) => parent?.type === 'BinaryExpression' && COMPARISONS.has(parent.operator) && (parent.left === node || parent.right === node);
|
|
21
|
+
/** Parses one file and returns its findings (unsorted). Files with syntax errors yield no findings. */
|
|
22
|
+
export function analyzeSource(file, code) {
|
|
23
|
+
const parsed = parseFile(file, code);
|
|
24
|
+
if (parsed.errors.length > 0)
|
|
25
|
+
return { findings: [], errors: parsed.errors, parsed };
|
|
26
|
+
const { globals, declarationCounts } = analyzeScopes(parsed.program, file);
|
|
27
|
+
const findings = [];
|
|
28
|
+
const ctx = {
|
|
29
|
+
file,
|
|
30
|
+
globals,
|
|
31
|
+
declarationCounts,
|
|
32
|
+
receivers: new Map(),
|
|
33
|
+
guards: [],
|
|
34
|
+
typeofDepth: 0,
|
|
35
|
+
functionDepth: 0,
|
|
36
|
+
findings,
|
|
37
|
+
report(feature, at, confidence, guardKey, name) {
|
|
38
|
+
const location = { file, ...parsed.locate(at.start) };
|
|
39
|
+
findings.push({
|
|
40
|
+
feature: feature.id,
|
|
41
|
+
name: name ?? feature.name,
|
|
42
|
+
location,
|
|
43
|
+
confidence,
|
|
44
|
+
origin: { type: 'project' },
|
|
45
|
+
guarded: ctx.typeofDepth > 0 || (guardKey !== null && ctx.guards.includes(guardKey)),
|
|
46
|
+
snippet: parsed.lineText(location.line).trim().slice(0, SNIPPET_MAX),
|
|
47
|
+
});
|
|
48
|
+
},
|
|
49
|
+
};
|
|
50
|
+
visit(parsed.program, null, ctx);
|
|
51
|
+
return { findings, errors: [], parsed };
|
|
52
|
+
}
|
|
53
|
+
function isTypeOnly(node) {
|
|
54
|
+
if (TYPE_ONLY.has(node.type) || node.declare === true)
|
|
55
|
+
return true;
|
|
56
|
+
if (node.type.startsWith('TS') && (node.type.endsWith('Type') || node.type.endsWith('Keyword')))
|
|
57
|
+
return true;
|
|
58
|
+
return (node.type === 'ImportDeclaration' && node.importKind === 'type') || (node.type === 'ExportNamedDeclaration' && node.exportKind === 'type');
|
|
59
|
+
}
|
|
60
|
+
function withGuards(ctx, names, fn) {
|
|
61
|
+
ctx.guards.push(...names);
|
|
62
|
+
try {
|
|
63
|
+
fn();
|
|
64
|
+
}
|
|
65
|
+
finally {
|
|
66
|
+
ctx.guards.length -= names.length;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
function visitChildren(node, ctx) {
|
|
70
|
+
for (const key of Object.keys(node)) {
|
|
71
|
+
if (SKIP_KEYS.has(key))
|
|
72
|
+
continue;
|
|
73
|
+
const value = node[key];
|
|
74
|
+
if (Array.isArray(value)) {
|
|
75
|
+
for (const child of value)
|
|
76
|
+
if (isNode(child))
|
|
77
|
+
visit(child, node, ctx);
|
|
78
|
+
}
|
|
79
|
+
else if (isNode(value)) {
|
|
80
|
+
visit(value, node, ctx);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
function visit(node, parent, ctx) {
|
|
85
|
+
if (isTypeOnly(node))
|
|
86
|
+
return;
|
|
87
|
+
for (const key of detectSyntax(node, parent, ctx.functionDepth)) {
|
|
88
|
+
const { id, name } = SYNTAX_FEATURES[key];
|
|
89
|
+
const feature = byId(id);
|
|
90
|
+
if (feature)
|
|
91
|
+
ctx.report(feature, node, 'certain', null, name);
|
|
92
|
+
}
|
|
93
|
+
switch (node.type) {
|
|
94
|
+
case 'IfStatement':
|
|
95
|
+
case 'ConditionalExpression': {
|
|
96
|
+
withGuards(ctx, guardedNames(node.test), () => {
|
|
97
|
+
visit(node.test, node, ctx);
|
|
98
|
+
visit(node.consequent, node, ctx);
|
|
99
|
+
});
|
|
100
|
+
if (isNode(node.alternate))
|
|
101
|
+
visit(node.alternate, node, ctx);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
case 'LogicalExpression': {
|
|
105
|
+
if (node.operator !== '&&')
|
|
106
|
+
break;
|
|
107
|
+
withGuards(ctx, guardedNames(node.left), () => {
|
|
108
|
+
visit(node.left, node, ctx);
|
|
109
|
+
visit(node.right, node, ctx);
|
|
110
|
+
});
|
|
111
|
+
return;
|
|
112
|
+
}
|
|
113
|
+
case 'UnaryExpression': {
|
|
114
|
+
if (node.operator !== 'typeof')
|
|
115
|
+
break;
|
|
116
|
+
ctx.typeofDepth++;
|
|
117
|
+
visit(node.argument, node, ctx);
|
|
118
|
+
ctx.typeofDepth--;
|
|
119
|
+
return;
|
|
120
|
+
}
|
|
121
|
+
case 'CallExpression': {
|
|
122
|
+
if (!node.optional)
|
|
123
|
+
break;
|
|
124
|
+
withGuards(ctx, guardedNames(node.callee), () => visit(node.callee, node, ctx));
|
|
125
|
+
for (const arg of node.arguments ?? [])
|
|
126
|
+
if (isNode(arg))
|
|
127
|
+
visit(arg, node, ctx);
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
case 'VariableDeclarator':
|
|
131
|
+
recordReceiver(node, parent, ctx);
|
|
132
|
+
break;
|
|
133
|
+
case 'Identifier':
|
|
134
|
+
if (ctx.globals.has(node.start) && !isWriteOnly(node, parent))
|
|
135
|
+
detectGlobalIdentifier(node, ctx);
|
|
136
|
+
return;
|
|
137
|
+
case 'MemberExpression': {
|
|
138
|
+
const object = unwrap(node.object);
|
|
139
|
+
const property = memberName(node);
|
|
140
|
+
const globalObject = object.type === 'Identifier' && ctx.globals.has(object.start);
|
|
141
|
+
if (property && !isWriteOnly(node, parent)) {
|
|
142
|
+
if (globalObject && isComparedRead(node, parent)) {
|
|
143
|
+
ctx.typeofDepth++;
|
|
144
|
+
detectGlobalMember(object.name, property, node, ctx);
|
|
145
|
+
ctx.typeofDepth--;
|
|
146
|
+
}
|
|
147
|
+
else if (globalObject)
|
|
148
|
+
detectGlobalMember(object.name, property, node, ctx);
|
|
149
|
+
else if (parent?.type === 'CallExpression' && parent.callee === node)
|
|
150
|
+
detectInstanceCall(node, object, property, ctx);
|
|
151
|
+
}
|
|
152
|
+
// The global object itself (`Object` in `Object.groupBy`) is not a separate use.
|
|
153
|
+
if (!globalObject)
|
|
154
|
+
visit(node.object, node, ctx);
|
|
155
|
+
if (node.computed)
|
|
156
|
+
visit(node.property, node, ctx);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
if (FUNCTION_TYPES.has(node.type)) {
|
|
161
|
+
ctx.functionDepth++;
|
|
162
|
+
visitChildren(node, ctx);
|
|
163
|
+
ctx.functionDepth--;
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
visitChildren(node, ctx);
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=walk.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"walk.js","sourceRoot":"","sources":["../../src/analysis/walk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAE,MAAM,qBAAqB,CAAC;AAC3C,OAAO,EAAE,eAAe,EAAE,MAAM,uBAAuB,CAAC;AAExD,OAAO,EAAgB,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAEpE,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,MAAM,y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MAAM,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;YACjD,IAAI,IAAI,CAAC,QAAQ;gBAAE,KAAK,CAAC,IAAI,CAAC,QAAQ,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC;YACnD,OAAO;QACT,CAAC;IACH,CAAC;IAED,IAAI,cAAc,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;QAClC,GAAG,CAAC,aAAa,EAAE,CAAC;QACpB,aAAa,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;QACzB,GAAG,CAAC,aAAa,EAAE,CAAC;QACpB,OAAO;IACT,CAAC;IACD,aAAa,CAAC,IAAI,EAAE,GAAG,CAAC,CAAC;AAC3B,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AstNode } from './ast.js';
|
|
2
|
+
/**
|
|
3
|
+
* True when `node` is only written, never read for its value: assignment targets (including
|
|
4
|
+
* compound and logical assignment), update operands and `delete` operands (research R7).
|
|
5
|
+
*/
|
|
6
|
+
export declare function isWriteOnly(node: AstNode, parent: AstNode | null): boolean;
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when `node` is only written, never read for its value: assignment targets (including
|
|
3
|
+
* compound and logical assignment), update operands and `delete` operands (research R7).
|
|
4
|
+
*/
|
|
5
|
+
export function isWriteOnly(node, parent) {
|
|
6
|
+
if (!parent)
|
|
7
|
+
return false;
|
|
8
|
+
if (parent.type === 'AssignmentExpression' && parent.left === node)
|
|
9
|
+
return true;
|
|
10
|
+
if (parent.type === 'UpdateExpression' && parent.argument === node)
|
|
11
|
+
return true;
|
|
12
|
+
if (parent.type === 'UnaryExpression' && parent.operator === 'delete' && parent.argument === node)
|
|
13
|
+
return true;
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=writes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writes.js","sourceRoot":"","sources":["../../src/analysis/writes.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAa,EAAE,MAAsB;IAC/D,IAAI,CAAC,MAAM;QAAE,OAAO,KAAK,CAAC;IAC1B,IAAI,MAAM,CAAC,IAAI,KAAK,sBAAsB,IAAI,MAAM,CAAC,IAAI,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAChF,IAAI,MAAM,CAAC,IAAI,KAAK,kBAAkB,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAChF,IAAI,MAAM,CAAC,IAAI,KAAK,iBAAiB,IAAI,MAAM,CAAC,QAAQ,KAAK,QAAQ,IAAI,MAAM,CAAC,QAAQ,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAC/G,OAAO,KAAK,CAAC;AACf,CAAC"}
|
package/dist/bin/cli.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { Command, CommanderError, InvalidArgumentError, Option } from 'commander';
|
|
5
|
+
import { analyze } from '../analysis/analyze.js';
|
|
6
|
+
import { ConfigError, findConfig, loadConfig } from '../config/load.js';
|
|
7
|
+
import { compare, reportErrors } from '../model/compare.js';
|
|
8
|
+
import { checkTargets, resolveTargets, targetBrowsers } from '../model/targets.js';
|
|
9
|
+
import { formatComparison } from '../output/comparison.js';
|
|
10
|
+
import { formatReport } from '../output/index.js';
|
|
11
|
+
import { shouldColor } from '../output/style.js';
|
|
12
|
+
import { targetCheckToText } from '../output/text.js';
|
|
13
|
+
import { TOOL_VERSION } from '../version.js';
|
|
14
|
+
const EXIT = { ok: 0, targetsNotMet: 1, usage: 2, internal: 3 };
|
|
15
|
+
class UsageError extends Error {
|
|
16
|
+
}
|
|
17
|
+
const list = (value) => value.split(',').map((v) => v.trim()).filter(Boolean);
|
|
18
|
+
const collect = (value, previous = []) => [...previous, value];
|
|
19
|
+
function write(output, content) {
|
|
20
|
+
if (output)
|
|
21
|
+
fs.writeFileSync(output, content);
|
|
22
|
+
else
|
|
23
|
+
process.stdout.write(content);
|
|
24
|
+
}
|
|
25
|
+
function readReport(file, label) {
|
|
26
|
+
let json;
|
|
27
|
+
try {
|
|
28
|
+
json = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
throw new UsageError(`cannot read the ${label} report ${file}: ${error.message}`);
|
|
32
|
+
}
|
|
33
|
+
const errors = reportErrors(json, label);
|
|
34
|
+
if (errors.length > 0)
|
|
35
|
+
throw new UsageError(`${file} is not a browser-requirements report: ${errors.join('; ')}`);
|
|
36
|
+
return json;
|
|
37
|
+
}
|
|
38
|
+
const program = new Command()
|
|
39
|
+
.name('browser-requirements')
|
|
40
|
+
.description('The minimum browser requirements of your web app, and the code that sets them.')
|
|
41
|
+
.version(TOOL_VERSION)
|
|
42
|
+
.exitOverride()
|
|
43
|
+
.configureOutput({ writeErr: (text) => process.stderr.write(text) });
|
|
44
|
+
function analyzeOptions(command, withFormat) {
|
|
45
|
+
return command
|
|
46
|
+
.argument('[paths...]', 'files or directories to analyse', ['.'])
|
|
47
|
+
.addOption(new Option('--format <format>', 'output format').choices(withFormat).default('text'))
|
|
48
|
+
.option('--output <file>', 'write the result to a file instead of stdout')
|
|
49
|
+
.option('--browsers <ids>', 'comma-separated BCD browser ids', list)
|
|
50
|
+
.addOption(new Option('--kind <kind>', 'what is being analysed').choices(['source', 'output']).default('source'))
|
|
51
|
+
.option('--config <file>', 'configuration file (default: browser-requirements.config.json, if present)')
|
|
52
|
+
.option('--ignore <glob>', 'extra ignore glob (repeatable)', collect)
|
|
53
|
+
.option('--details', 'text format: show next limiting features and all findings');
|
|
54
|
+
}
|
|
55
|
+
analyzeOptions(program.command('analyze').description('Compute the minimum browser versions the code needs, and why'), ['text', 'json']).action(async (paths, opts) => {
|
|
56
|
+
if (opts.browsers?.length === 0)
|
|
57
|
+
throw new UsageError('--browsers needs at least one browser id');
|
|
58
|
+
const report = await analyze({ paths, browsers: opts.browsers, kind: opts.kind, ignore: opts.ignore, config: opts.config });
|
|
59
|
+
const color = !opts.output && opts.format === 'text' && shouldColor();
|
|
60
|
+
write(opts.output, formatReport(report, opts.format, { details: opts.details, color }));
|
|
61
|
+
});
|
|
62
|
+
program
|
|
63
|
+
.command('compare')
|
|
64
|
+
.description('Compare two JSON reports and show which minimums changed and why')
|
|
65
|
+
.argument('<base>', 'report of the base revision (analyze --format json)')
|
|
66
|
+
.argument('<head>', 'report of the head revision')
|
|
67
|
+
.addOption(new Option('--format <format>', 'output format').choices(['text', 'markdown', 'json']).default('text'))
|
|
68
|
+
.option('--output <file>', 'write the result to a file instead of stdout')
|
|
69
|
+
.action((baseFile, headFile, opts) => {
|
|
70
|
+
const comparison = compare(readReport(baseFile, 'base'), readReport(headFile, 'head'));
|
|
71
|
+
write(opts.output, formatComparison(comparison, opts.format));
|
|
72
|
+
});
|
|
73
|
+
analyzeOptions(program.command('check').description('Fail when the minimums exceed the browser targets'), ['text', 'json'])
|
|
74
|
+
.option('--targets <query>', 'browserslist query (default: config targets, browserslist config, then "defaults")')
|
|
75
|
+
.action(async (paths, opts) => {
|
|
76
|
+
const root = process.cwd();
|
|
77
|
+
const configFile = opts.config ? path.resolve(opts.config) : findConfig(root, paths);
|
|
78
|
+
const config = configFile ? loadConfig(configFile) : {};
|
|
79
|
+
let targets;
|
|
80
|
+
try {
|
|
81
|
+
targets = resolveTargets(opts.targets, root, config.targets);
|
|
82
|
+
}
|
|
83
|
+
catch (error) {
|
|
84
|
+
throw new UsageError(`invalid targets: ${error.message}`);
|
|
85
|
+
}
|
|
86
|
+
const browsers = opts.browsers ?? targetBrowsers(targets);
|
|
87
|
+
const report = await analyze({ paths, browsers, kind: opts.kind, ignore: opts.ignore, config: configFile ? config : undefined, root });
|
|
88
|
+
const check = checkTargets(report, targets);
|
|
89
|
+
if (opts.format === 'json') {
|
|
90
|
+
write(opts.output, `${JSON.stringify({ report, targetCheck: check }, null, 2)}\n`);
|
|
91
|
+
}
|
|
92
|
+
else {
|
|
93
|
+
const color = !opts.output && shouldColor();
|
|
94
|
+
write(opts.output, `${formatReport(report, 'text', { details: opts.details, color })}\n${targetCheckToText(targets, check, { color })}`);
|
|
95
|
+
}
|
|
96
|
+
process.exitCode = check.met ? EXIT.ok : EXIT.targetsNotMet;
|
|
97
|
+
});
|
|
98
|
+
try {
|
|
99
|
+
await program.parseAsync(process.argv);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error instanceof CommanderError) {
|
|
103
|
+
process.exitCode = error.exitCode === 0 ? EXIT.ok : EXIT.usage;
|
|
104
|
+
}
|
|
105
|
+
else if (error instanceof UsageError || error instanceof InvalidArgumentError || error instanceof ConfigError) {
|
|
106
|
+
process.stderr.write(`error: ${error.message}\n`);
|
|
107
|
+
process.exitCode = EXIT.usage;
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
process.stderr.write(`internal error: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`);
|
|
111
|
+
process.exitCode = EXIT.internal;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
//# sourceMappingURL=cli.js.map
|