@dcaldeira/tooling 0.1.0 → 0.2.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.
Files changed (49) hide show
  1. package/README.md +34 -34
  2. package/checks/a11y.mjs +206 -206
  3. package/checks/architecture.mjs +137 -137
  4. package/checks/audit.mjs +121 -121
  5. package/checks/bundle.mjs +126 -126
  6. package/checks/dependencies.mjs +277 -277
  7. package/checks/duplication.mjs +135 -0
  8. package/checks/lint-scss.mjs +363 -349
  9. package/checks/package.mjs +30 -30
  10. package/checks/playwright-summary.mjs +53 -53
  11. package/checks/sass.mjs +67 -67
  12. package/checks/scan-secrets.mjs +58 -58
  13. package/checks/shared.mjs +86 -86
  14. package/checks/translations.mjs +55 -55
  15. package/checks/visual-compare.mjs +148 -148
  16. package/checks/visual-report-html.mjs +470 -470
  17. package/checks/visual-report.mjs +13 -13
  18. package/config.schema.json +977 -927
  19. package/configs/eslint.mjs +27 -27
  20. package/configs/knip.json +11 -11
  21. package/configs/playwright.mjs +15 -15
  22. package/configs/vitest.mjs +16 -16
  23. package/package.json +105 -105
  24. package/release/finalize.mjs +65 -65
  25. package/release/github.mjs +64 -64
  26. package/release/prepare.mjs +30 -30
  27. package/runner/browsers.mjs +73 -73
  28. package/runner/cache.mjs +121 -121
  29. package/runner/ci-plan.mjs +54 -54
  30. package/runner/cli.mjs +250 -248
  31. package/runner/config.mjs +148 -148
  32. package/runner/docs-install.mjs +93 -93
  33. package/runner/execute.mjs +298 -286
  34. package/runner/generate.mjs +122 -122
  35. package/runner/git.mjs +122 -122
  36. package/runner/graph.mjs +250 -243
  37. package/runner/insights.mjs +313 -313
  38. package/runner/provision.mjs +53 -53
  39. package/runner/repo-standard.mjs +104 -0
  40. package/runner/report.mjs +35 -35
  41. package/runner/serve-static.mjs +76 -76
  42. package/runner/setup.mjs +241 -237
  43. package/runner/summary.mjs +112 -112
  44. package/runner/watch.mjs +82 -82
  45. package/templates/ci.yml +25 -25
  46. package/templates/dependabot-merge.yml +13 -13
  47. package/templates/dependabot.yml +26 -26
  48. package/templates/pre-push +13 -13
  49. package/templates/release.yml +23 -23
@@ -1,137 +1,137 @@
1
- import { join, relative, resolve } from 'node:path';
2
- import { existsSync } from 'node:fs';
3
- import { pathToFileURL } from 'node:url';
4
- import { loadConfig, inside } from '../runner/config.mjs';
5
- import { matches } from '../runner/graph.mjs';
6
- import {
7
- compilerOptions,
8
- importsIn,
9
- peer,
10
- rootDirectory,
11
- sourceFiles,
12
- writeDetails,
13
- } from './shared.mjs';
14
-
15
- export function analyseArchitecture(root, settings = {}, files, ts = peer('typescript', root)) {
16
- files ??= sourceFiles(root, settings.include ?? ['src/**'], settings.exclude ?? []);
17
- files = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file) && !file.endsWith('.d.ts'));
18
- if (!files.length)
19
- throw new Error(
20
- 'No architecture source files matched; configure architecture.include for this project',
21
- );
22
- const included = new Set(files.map((file) => resolve(root, file)));
23
- const graph = new Map(files.map((file) => [file, []]));
24
- const options = compilerOptions(ts, root, settings.tsconfig);
25
- const resolutionCache = ts.createModuleResolutionCache(
26
- root,
27
- (file) => (ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase()),
28
- options,
29
- );
30
- const issues = [];
31
- if (settings.tsconfig && !existsSync(inside(root, settings.tsconfig)))
32
- throw new Error(`Missing architecture tsconfig: ${settings.tsconfig}`);
33
- const layers = settings.layers ?? [];
34
- const layerOf = (file) =>
35
- layers.find((layer) => layer.paths.some((pattern) => matches(file, pattern)));
36
- const under = (file, directory) =>
37
- file === directory || file.startsWith(directory.replace(/\/$/, '') + '/');
38
- for (const file of files) {
39
- const fromLayer = layerOf(file);
40
- for (const { specifier, line } of importsIn(ts, inside(root, file))) {
41
- if (/\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|woff2?|json)(?:\?|$)/i.test(specifier))
42
- continue;
43
- const resolved = ts.resolveModuleName(
44
- specifier,
45
- join(root, file),
46
- options,
47
- ts.sys,
48
- resolutionCache,
49
- ).resolvedModule;
50
- if (!resolved) {
51
- const local =
52
- specifier.startsWith('.') ||
53
- Object.keys(options.paths ?? {}).some((pattern) => matches(specifier, pattern));
54
- if (local)
55
- issues.push({
56
- file,
57
- line,
58
- rule: 'unresolved-import',
59
- message: `Cannot resolve ${specifier}`,
60
- });
61
- continue;
62
- }
63
- const target = relative(root, resolved.resolvedFileName).replaceAll('\\', '/');
64
- if (target.startsWith('../') || target.split('/').includes('node_modules')) continue;
65
- if (included.has(resolve(resolved.resolvedFileName))) graph.get(file).push(target);
66
- const toLayer = layerOf(target);
67
- if (
68
- fromLayer &&
69
- toLayer &&
70
- fromLayer.name !== toLayer.name &&
71
- !fromLayer.allow.includes(toLayer.name)
72
- )
73
- issues.push({
74
- file,
75
- line,
76
- rule: 'import-boundary',
77
- message: `${fromLayer.name} cannot import ${toLayer.name}: ${target}`,
78
- });
79
- for (const module of settings.modules ?? []) {
80
- const directory = module.root.replaceAll('\\', '/').replace(/\/$/, '');
81
- if (
82
- under(target, directory) &&
83
- !under(file, directory) &&
84
- !module.public.some((pattern) => matches(target, pattern))
85
- )
86
- issues.push({
87
- file,
88
- line,
89
- rule: 'private-module',
90
- message: `Import ${module.name} through a public entry, not ${target}`,
91
- });
92
- }
93
- }
94
- }
95
- if (settings.cycles !== false) {
96
- const visited = new Set(),
97
- active = new Set(),
98
- stack = [],
99
- reported = new Set();
100
- function visit(file) {
101
- if (active.has(file)) {
102
- const cycle = [...stack.slice(stack.indexOf(file)), file];
103
- const key = [...new Set(cycle)].sort().join('\0');
104
- if (!reported.has(key))
105
- issues.push({ file, rule: 'circular-import', message: cycle.join(' -> ') });
106
- reported.add(key);
107
- return;
108
- }
109
- if (visited.has(file)) return;
110
- active.add(file);
111
- stack.push(file);
112
- for (const target of graph.get(file) ?? []) visit(target);
113
- stack.pop();
114
- active.delete(file);
115
- visited.add(file);
116
- }
117
- for (const file of files) visit(file);
118
- }
119
- return {
120
- files: files.length,
121
- edges: [...graph.values()].reduce((sum, edges) => sum + edges.length, 0),
122
- issues,
123
- };
124
- }
125
-
126
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
127
- const root = rootDirectory(),
128
- { config } = loadConfig(root);
129
- const result = analyseArchitecture(root, config.architecture, undefined, peer('typescript'));
130
- writeDetails({ architecture: result });
131
- for (const issue of result.issues)
132
- console.error(`${issue.file}:${issue.line ?? 1} ${issue.message} (${issue.rule})`);
133
- console.log(
134
- `Architecture: ${result.files} source files, ${result.edges} imports, ${result.issues.length} issues`,
135
- );
136
- process.exitCode = result.issues.length ? 1 : 0;
137
- }
1
+ import { join, relative, resolve } from 'node:path';
2
+ import { existsSync } from 'node:fs';
3
+ import { pathToFileURL } from 'node:url';
4
+ import { loadConfig, inside } from '../runner/config.mjs';
5
+ import { matches } from '../runner/graph.mjs';
6
+ import {
7
+ compilerOptions,
8
+ importsIn,
9
+ peer,
10
+ rootDirectory,
11
+ sourceFiles,
12
+ writeDetails,
13
+ } from './shared.mjs';
14
+
15
+ export function analyseArchitecture(root, settings = {}, files, ts = peer('typescript', root)) {
16
+ files ??= sourceFiles(root, settings.include ?? ['src/**'], settings.exclude ?? []);
17
+ files = files.filter((file) => /\.[cm]?[jt]sx?$/.test(file) && !file.endsWith('.d.ts'));
18
+ if (!files.length)
19
+ throw new Error(
20
+ 'No architecture source files matched; configure architecture.include for this project',
21
+ );
22
+ const included = new Set(files.map((file) => resolve(root, file)));
23
+ const graph = new Map(files.map((file) => [file, []]));
24
+ const options = compilerOptions(ts, root, settings.tsconfig);
25
+ const resolutionCache = ts.createModuleResolutionCache(
26
+ root,
27
+ (file) => (ts.sys.useCaseSensitiveFileNames ? file : file.toLowerCase()),
28
+ options,
29
+ );
30
+ const issues = [];
31
+ if (settings.tsconfig && !existsSync(inside(root, settings.tsconfig)))
32
+ throw new Error(`Missing architecture tsconfig: ${settings.tsconfig}`);
33
+ const layers = settings.layers ?? [];
34
+ const layerOf = (file) =>
35
+ layers.find((layer) => layer.paths.some((pattern) => matches(file, pattern)));
36
+ const under = (file, directory) =>
37
+ file === directory || file.startsWith(directory.replace(/\/$/, '') + '/');
38
+ for (const file of files) {
39
+ const fromLayer = layerOf(file);
40
+ for (const { specifier, line } of importsIn(ts, inside(root, file))) {
41
+ if (/\.(?:css|scss|sass|less|svg|png|jpe?g|gif|webp|woff2?|json)(?:\?|$)/i.test(specifier))
42
+ continue;
43
+ const resolved = ts.resolveModuleName(
44
+ specifier,
45
+ join(root, file),
46
+ options,
47
+ ts.sys,
48
+ resolutionCache,
49
+ ).resolvedModule;
50
+ if (!resolved) {
51
+ const local =
52
+ specifier.startsWith('.') ||
53
+ Object.keys(options.paths ?? {}).some((pattern) => matches(specifier, pattern));
54
+ if (local)
55
+ issues.push({
56
+ file,
57
+ line,
58
+ rule: 'unresolved-import',
59
+ message: `Cannot resolve ${specifier}`,
60
+ });
61
+ continue;
62
+ }
63
+ const target = relative(root, resolved.resolvedFileName).replaceAll('\\', '/');
64
+ if (target.startsWith('../') || target.split('/').includes('node_modules')) continue;
65
+ if (included.has(resolve(resolved.resolvedFileName))) graph.get(file).push(target);
66
+ const toLayer = layerOf(target);
67
+ if (
68
+ fromLayer &&
69
+ toLayer &&
70
+ fromLayer.name !== toLayer.name &&
71
+ !fromLayer.allow.includes(toLayer.name)
72
+ )
73
+ issues.push({
74
+ file,
75
+ line,
76
+ rule: 'import-boundary',
77
+ message: `${fromLayer.name} cannot import ${toLayer.name}: ${target}`,
78
+ });
79
+ for (const module of settings.modules ?? []) {
80
+ const directory = module.root.replaceAll('\\', '/').replace(/\/$/, '');
81
+ if (
82
+ under(target, directory) &&
83
+ !under(file, directory) &&
84
+ !module.public.some((pattern) => matches(target, pattern))
85
+ )
86
+ issues.push({
87
+ file,
88
+ line,
89
+ rule: 'private-module',
90
+ message: `Import ${module.name} through a public entry, not ${target}`,
91
+ });
92
+ }
93
+ }
94
+ }
95
+ if (settings.cycles !== false) {
96
+ const visited = new Set(),
97
+ active = new Set(),
98
+ stack = [],
99
+ reported = new Set();
100
+ function visit(file) {
101
+ if (active.has(file)) {
102
+ const cycle = [...stack.slice(stack.indexOf(file)), file];
103
+ const key = [...new Set(cycle)].sort().join('\0');
104
+ if (!reported.has(key))
105
+ issues.push({ file, rule: 'circular-import', message: cycle.join(' -> ') });
106
+ reported.add(key);
107
+ return;
108
+ }
109
+ if (visited.has(file)) return;
110
+ active.add(file);
111
+ stack.push(file);
112
+ for (const target of graph.get(file) ?? []) visit(target);
113
+ stack.pop();
114
+ active.delete(file);
115
+ visited.add(file);
116
+ }
117
+ for (const file of files) visit(file);
118
+ }
119
+ return {
120
+ files: files.length,
121
+ edges: [...graph.values()].reduce((sum, edges) => sum + edges.length, 0),
122
+ issues,
123
+ };
124
+ }
125
+
126
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
127
+ const root = rootDirectory(),
128
+ { config } = loadConfig(root);
129
+ const result = analyseArchitecture(root, config.architecture, undefined, peer('typescript'));
130
+ writeDetails({ architecture: result });
131
+ for (const issue of result.issues)
132
+ console.error(`${issue.file}:${issue.line ?? 1} ${issue.message} (${issue.rule})`);
133
+ console.log(
134
+ `Architecture: ${result.files} source files, ${result.edges} imports, ${result.issues.length} issues`,
135
+ );
136
+ process.exitCode = result.issues.length ? 1 : 0;
137
+ }
package/checks/audit.mjs CHANGED
@@ -1,121 +1,121 @@
1
- #!/usr/bin/env node
2
- import { execFileSync } from 'node:child_process';
3
- import { readFileSync } from 'node:fs';
4
- import { resolve } from 'node:path';
5
- import { pathToFileURL } from 'node:url';
6
- import { executable } from '../runner/execute.mjs';
7
- import { rootDirectory, writeDetails } from './shared.mjs';
8
-
9
- export function advisories(report) {
10
- if (
11
- !report ||
12
- report.error ||
13
- !report.vulnerabilities ||
14
- typeof report.vulnerabilities !== 'object' ||
15
- Array.isArray(report.vulnerabilities)
16
- )
17
- throw new Error('npm audit did not return a valid vulnerability report');
18
- const found = new Map();
19
- for (const vuln of Object.values(report.vulnerabilities)) {
20
- if (!vuln || !Array.isArray(vuln.via))
21
- throw new Error('npm audit returned malformed vulnerability data');
22
- for (const via of vuln.via)
23
- if (via && typeof via === 'object' && ['high', 'critical'].includes(via.severity)) {
24
- if (typeof via.url !== 'string' || !via.url || typeof via.name !== 'string')
25
- throw new Error('npm audit returned malformed advisory data');
26
- found.set(via.url.split('/').pop(), via.name);
27
- }
28
- }
29
- return found;
30
- }
31
-
32
- export function readAllowlist(root, filename = process.env.TOOLING_AUDIT_ALLOWLIST) {
33
- let document;
34
- try {
35
- document = JSON.parse(
36
- readFileSync(resolve(root, filename ?? 'audit-allowlist.json'), 'utf8'),
37
- );
38
- } catch (error) {
39
- if (!filename && error.code === 'ENOENT') return new Map();
40
- throw error;
41
- }
42
- if (!Array.isArray(document?.advisories))
43
- throw new Error('Audit allowlist must contain an advisories array');
44
- const entries = new Map();
45
- for (const entry of document.advisories) {
46
- if (
47
- !entry ||
48
- typeof entry.id !== 'string' ||
49
- !entry.id.trim() ||
50
- entries.has(entry.id) ||
51
- typeof entry.reason !== 'string' ||
52
- !entry.reason.trim() ||
53
- typeof entry.expires !== 'string' ||
54
- !/^\d{4}-\d{2}-\d{2}$/.test(entry.expires) ||
55
- !Number.isFinite(Date.parse(entry.expires)) ||
56
- new Date(entry.expires).toISOString().slice(0, 10) !== entry.expires
57
- )
58
- throw new Error('Audit allowlist entries need unique IDs, a reason and a valid expiry date');
59
- entries.set(entry.id, entry);
60
- }
61
- return entries;
62
- }
63
-
64
- export function evaluateAudit(
65
- productionReport,
66
- fullReport,
67
- allow,
68
- today = new Date().toISOString().slice(0, 10),
69
- ) {
70
- const prod = advisories(productionReport);
71
- const all = advisories(fullReport);
72
- const problems = [],
73
- notices = [];
74
- for (const [id, pkg] of prod)
75
- problems.push(`${id} (${pkg}) is in a production dependency`);
76
- for (const [id, pkg] of all) {
77
- if (prod.has(id)) continue;
78
- const entry = allow.get(id);
79
- if (!entry) problems.push(`${id} (${pkg}) is not allowlisted`);
80
- else if (entry.expires < today)
81
- problems.push(`${id} (${pkg}) allowlist entry expired on ${entry.expires}`);
82
- else notices.push(`allowlisted until ${entry.expires}: ${id} (${pkg}) — ${entry.reason}`);
83
- }
84
- for (const id of allow.keys())
85
- if (!all.has(id)) notices.push(`note: ${id} no longer reported; remove it from the allowlist`);
86
- return { problems, notices };
87
- }
88
-
89
- export function audit(root, ...args) {
90
- const command = executable(root, 'npm');
91
- if (!command) throw new Error('Missing npm executable');
92
- let output;
93
- try {
94
- output = execFileSync(command[0], [...command.slice(1), 'audit', '--json', ...args], {
95
- cwd: root,
96
- encoding: 'utf8',
97
- maxBuffer: 64 * 1024 * 1024,
98
- timeout: 120000,
99
- shell: process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(command[0]),
100
- stdio: ['ignore', 'pipe', 'pipe'],
101
- });
102
- } catch (error) {
103
- if (error.status !== 1 || !error.stdout) throw error;
104
- output = error.stdout;
105
- }
106
- const report = JSON.parse(output);
107
- advisories(report);
108
- return report;
109
- }
110
-
111
- if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
112
- const root = rootDirectory();
113
- const allow = readAllowlist(root);
114
- const result = evaluateAudit(audit(root, '--omit=dev'), audit(root), allow);
115
- writeDetails({ audit: result });
116
- for (const notice of result.notices) console.log(notice);
117
- if (result.problems.length) {
118
- console.error(`npm audit (high/critical):\n- ${result.problems.join('\n- ')}\nRun \`npm audit\` for details.`);
119
- process.exitCode = 1;
120
- } else console.log('npm audit: no unallowlisted high or critical advisories.');
121
- }
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from 'node:child_process';
3
+ import { readFileSync } from 'node:fs';
4
+ import { resolve } from 'node:path';
5
+ import { pathToFileURL } from 'node:url';
6
+ import { executable } from '../runner/execute.mjs';
7
+ import { rootDirectory, writeDetails } from './shared.mjs';
8
+
9
+ export function advisories(report) {
10
+ if (
11
+ !report ||
12
+ report.error ||
13
+ !report.vulnerabilities ||
14
+ typeof report.vulnerabilities !== 'object' ||
15
+ Array.isArray(report.vulnerabilities)
16
+ )
17
+ throw new Error('npm audit did not return a valid vulnerability report');
18
+ const found = new Map();
19
+ for (const vuln of Object.values(report.vulnerabilities)) {
20
+ if (!vuln || !Array.isArray(vuln.via))
21
+ throw new Error('npm audit returned malformed vulnerability data');
22
+ for (const via of vuln.via)
23
+ if (via && typeof via === 'object' && ['high', 'critical'].includes(via.severity)) {
24
+ if (typeof via.url !== 'string' || !via.url || typeof via.name !== 'string')
25
+ throw new Error('npm audit returned malformed advisory data');
26
+ found.set(via.url.split('/').pop(), via.name);
27
+ }
28
+ }
29
+ return found;
30
+ }
31
+
32
+ export function readAllowlist(root, filename = process.env.TOOLING_AUDIT_ALLOWLIST) {
33
+ let document;
34
+ try {
35
+ document = JSON.parse(
36
+ readFileSync(resolve(root, filename ?? 'audit-allowlist.json'), 'utf8'),
37
+ );
38
+ } catch (error) {
39
+ if (!filename && error.code === 'ENOENT') return new Map();
40
+ throw error;
41
+ }
42
+ if (!Array.isArray(document?.advisories))
43
+ throw new Error('Audit allowlist must contain an advisories array');
44
+ const entries = new Map();
45
+ for (const entry of document.advisories) {
46
+ if (
47
+ !entry ||
48
+ typeof entry.id !== 'string' ||
49
+ !entry.id.trim() ||
50
+ entries.has(entry.id) ||
51
+ typeof entry.reason !== 'string' ||
52
+ !entry.reason.trim() ||
53
+ typeof entry.expires !== 'string' ||
54
+ !/^\d{4}-\d{2}-\d{2}$/.test(entry.expires) ||
55
+ !Number.isFinite(Date.parse(entry.expires)) ||
56
+ new Date(entry.expires).toISOString().slice(0, 10) !== entry.expires
57
+ )
58
+ throw new Error('Audit allowlist entries need unique IDs, a reason and a valid expiry date');
59
+ entries.set(entry.id, entry);
60
+ }
61
+ return entries;
62
+ }
63
+
64
+ export function evaluateAudit(
65
+ productionReport,
66
+ fullReport,
67
+ allow,
68
+ today = new Date().toISOString().slice(0, 10),
69
+ ) {
70
+ const prod = advisories(productionReport);
71
+ const all = advisories(fullReport);
72
+ const problems = [],
73
+ notices = [];
74
+ for (const [id, pkg] of prod)
75
+ problems.push(`${id} (${pkg}) is in a production dependency`);
76
+ for (const [id, pkg] of all) {
77
+ if (prod.has(id)) continue;
78
+ const entry = allow.get(id);
79
+ if (!entry) problems.push(`${id} (${pkg}) is not allowlisted`);
80
+ else if (entry.expires < today)
81
+ problems.push(`${id} (${pkg}) allowlist entry expired on ${entry.expires}`);
82
+ else notices.push(`allowlisted until ${entry.expires}: ${id} (${pkg}) — ${entry.reason}`);
83
+ }
84
+ for (const id of allow.keys())
85
+ if (!all.has(id)) notices.push(`note: ${id} no longer reported; remove it from the allowlist`);
86
+ return { problems, notices };
87
+ }
88
+
89
+ export function audit(root, ...args) {
90
+ const command = executable(root, 'npm');
91
+ if (!command) throw new Error('Missing npm executable');
92
+ let output;
93
+ try {
94
+ output = execFileSync(command[0], [...command.slice(1), 'audit', '--json', ...args], {
95
+ cwd: root,
96
+ encoding: 'utf8',
97
+ maxBuffer: 64 * 1024 * 1024,
98
+ timeout: 120000,
99
+ shell: process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(command[0]),
100
+ stdio: ['ignore', 'pipe', 'pipe'],
101
+ });
102
+ } catch (error) {
103
+ if (error.status !== 1 || !error.stdout) throw error;
104
+ output = error.stdout;
105
+ }
106
+ const report = JSON.parse(output);
107
+ advisories(report);
108
+ return report;
109
+ }
110
+
111
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
112
+ const root = rootDirectory();
113
+ const allow = readAllowlist(root);
114
+ const result = evaluateAudit(audit(root, '--omit=dev'), audit(root), allow);
115
+ writeDetails({ audit: result });
116
+ for (const notice of result.notices) console.log(notice);
117
+ if (result.problems.length) {
118
+ console.error(`npm audit (high/critical):\n- ${result.problems.join('\n- ')}\nRun \`npm audit\` for details.`);
119
+ process.exitCode = 1;
120
+ } else console.log('npm audit: no unallowlisted high or critical advisories.');
121
+ }