@dcaldeira/tooling 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 +9 -0
- package/README.md +34 -3
- package/checks/a11y.mjs +206 -0
- package/checks/architecture.mjs +137 -0
- package/checks/audit.mjs +121 -0
- package/checks/bundle.mjs +126 -0
- package/checks/dependencies.mjs +277 -0
- package/checks/lint-scss.mjs +349 -0
- package/checks/package.mjs +30 -0
- package/checks/playwright-summary.mjs +53 -0
- package/checks/sass.mjs +67 -0
- package/checks/scan-secrets.mjs +58 -0
- package/checks/shared.mjs +86 -0
- package/checks/style-property-order.json +498 -0
- package/checks/translations.mjs +55 -0
- package/checks/visual-compare.mjs +148 -0
- package/checks/visual-report-html.mjs +470 -0
- package/checks/visual-report.mjs +13 -0
- package/config.schema.json +927 -0
- package/configs/eslint.mjs +27 -0
- package/configs/knip.json +11 -0
- package/configs/playwright.mjs +15 -0
- package/configs/prettier.mjs +1 -0
- package/configs/tsconfig.json +16 -0
- package/configs/vitest.mjs +16 -0
- package/package.json +105 -6
- package/release/evidence.mjs +62 -0
- package/release/finalize.mjs +65 -0
- package/release/gh.mjs +25 -0
- package/release/github.mjs +64 -0
- package/release/prepare.mjs +30 -0
- package/runner/browsers.mjs +73 -0
- package/runner/cache.mjs +121 -0
- package/runner/ci-plan.mjs +54 -0
- package/runner/cli.mjs +249 -0
- package/runner/config.mjs +148 -0
- package/runner/docs-install.mjs +93 -0
- package/runner/execute.mjs +286 -0
- package/runner/generate.mjs +122 -0
- package/runner/git.mjs +122 -0
- package/runner/graph.mjs +243 -0
- package/runner/index.mjs +4 -0
- package/runner/insights.mjs +313 -0
- package/runner/provision.mjs +53 -0
- package/runner/report.mjs +35 -0
- package/runner/serve-static.mjs +76 -0
- package/runner/setup.mjs +237 -0
- package/runner/summary.mjs +112 -0
- package/runner/watch.mjs +82 -0
- package/templates/ci.yml +25 -0
- package/templates/dependabot-merge.yml +13 -0
- package/templates/dependabot.yml +26 -0
- package/templates/pre-push +13 -0
- package/templates/release.yml +23 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Duarte Caldeira
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
|
6
|
+
|
|
7
|
+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
|
8
|
+
|
|
9
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,34 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# Repository tooling
|
|
2
|
+
|
|
3
|
+
`@dcaldeira/tooling` shares one check graph between development, push gates and reusable GitHub Actions workflows. Node 22.13 or later; npm workspaces; no paid service is required.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm ci --ignore-scripts
|
|
7
|
+
npm test
|
|
8
|
+
npm run pack:tooling
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Consumers install an exact public npm version, commit their lockfile and pin reusable workflows to the full commit SHA. The initial version is **0.1.0**. No package or repository credentials are embedded.
|
|
12
|
+
|
|
13
|
+
| Command | Purpose |
|
|
14
|
+
| ---------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
|
15
|
+
| `tooling --profile=dev --changed` | Changed formatting/lint/styles, related unit tests and relevant translations |
|
|
16
|
+
| `tooling --profile=push --changed --bail` | Every applicable check; records a reusable pass only for a clean unchanged tree |
|
|
17
|
+
| `tooling --profile=ci --all` | Complete validation with prerequisites enforced |
|
|
18
|
+
| `tooling --profile=ci --changed --base=origin/main --plan` | Explain selection without running checks |
|
|
19
|
+
|
|
20
|
+
See [project features](https://github.com/DuarteCaldeira/tooling/blob/main/docs/project-features.md), [setup](https://github.com/DuarteCaldeira/tooling/blob/main/docs/setup.md), [configuration](https://github.com/DuarteCaldeira/tooling/blob/main/docs/configuration.md), [release trust](https://github.com/DuarteCaldeira/tooling/blob/main/docs/releases.md), [migration](https://github.com/DuarteCaldeira/tooling/blob/main/docs/migration.md) and [troubleshooting](https://github.com/DuarteCaldeira/tooling/blob/main/docs/troubleshooting.md). Rookie's configuration and adoption assets are in [examples/rookie](https://github.com/DuarteCaldeira/tooling/blob/main/examples/rookie).
|
|
21
|
+
|
|
22
|
+
Use `tooling init --preset=react-vite` or `tooling init --preset=workspace --app=frontend` to scaffold a consumer, then `tooling doctor` to check its setup. Pass `--tooling-sha=<40-character SHA>` to pin generated workflows. Templates ship inside the npm package.
|
|
23
|
+
|
|
24
|
+
Independent checks run with bounded concurrency and shared-resource locks. `--concurrency=1` runs sequentially. Development watch mode responds to filesystem events, with ignored generated files filtered out. Functional and visual browser suites are disjoint by default. Documentation CI can opt into a locked standalone formatter installation.
|
|
25
|
+
|
|
26
|
+
Workspace scopes follow declared shared-code dependencies, and deterministic diagnostics reuse successful results by their inputs. ESLint uses persistent content caches; noEmit TypeScript projects can opt into CI metadata persistence. Full validation with `--all` bypasses diagnostic success records, and `--no-cache` disables runner-managed reuse. Empty plans avoid installation and reports. Browser provisioning is shared by PR and release workflows and includes Lighthouse-only projects.
|
|
27
|
+
|
|
28
|
+
Docs select only formatting. Styles select formatting and style lint. Mixed changes use their union. Dependencies, shared tooling and unknown files broaden validation. Local push and hosted CI use the same definitions. Missing prerequisites, skipped required checks, failed dependencies and interrupted checks cannot record a pass.
|
|
29
|
+
|
|
30
|
+
The HTML summary links to Playwright's self-contained report, which contains expected/actual/diff images, scenario names, viewports, browser details and traces. Reports are retained for three days in Actions.
|
|
31
|
+
|
|
32
|
+
MIT licensed. Public publishing requires GitHub/npm credentials or npm trusted publishing to be configured by the owner. Local preparation alone does not publish anything.
|
|
33
|
+
|
|
34
|
+
Opt-in architecture, rendered accessibility and dependency-consistency checks share the same runner. Use `tooling generate component --name=UserCard` or `tooling generate hook --name=useProfile` for typed scaffolds, and `tooling history` for recent validation performance. PR/release workflows publish an Actions summary with report artifacts.
|
package/checks/a11y.mjs
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
2
|
+
import { mkdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { executable } from '../runner/execute.mjs';
|
|
7
|
+
import { inside, loadConfig } from '../runner/config.mjs';
|
|
8
|
+
import { peer, rootDirectory, writeDetails } from './shared.mjs';
|
|
9
|
+
|
|
10
|
+
export async function startServer(root, settings) {
|
|
11
|
+
const cwd = inside(root, settings.cwd ?? '.');
|
|
12
|
+
const command = executable(cwd, settings.command[0]);
|
|
13
|
+
if (!command) throw new Error(`Missing server executable ${settings.command[0]}`);
|
|
14
|
+
const child = spawn(command[0], [...command.slice(1), ...settings.command.slice(1)], {
|
|
15
|
+
cwd,
|
|
16
|
+
env: process.env,
|
|
17
|
+
stdio: ['ignore', 'ignore', 'pipe'],
|
|
18
|
+
windowsHide: true,
|
|
19
|
+
detached: process.platform !== 'win32',
|
|
20
|
+
});
|
|
21
|
+
let failure,
|
|
22
|
+
output = '';
|
|
23
|
+
child.once('error', (error) => {
|
|
24
|
+
failure = error;
|
|
25
|
+
});
|
|
26
|
+
child.stderr.on('data', (chunk) => {
|
|
27
|
+
output = (output + chunk).slice(-4000);
|
|
28
|
+
});
|
|
29
|
+
const stop = async () => {
|
|
30
|
+
if (!child.pid) return;
|
|
31
|
+
if (process.platform === 'win32') {
|
|
32
|
+
if (child.exitCode === null)
|
|
33
|
+
spawnSync('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
|
|
34
|
+
stdio: 'ignore',
|
|
35
|
+
windowsHide: true,
|
|
36
|
+
timeout: 5000,
|
|
37
|
+
});
|
|
38
|
+
} else {
|
|
39
|
+
try {
|
|
40
|
+
process.kill(-child.pid, 'SIGTERM');
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (error.code !== 'ESRCH') throw error;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
if (child.exitCode === null) {
|
|
46
|
+
await Promise.race([
|
|
47
|
+
new Promise((resolve) => child.once('exit', resolve)),
|
|
48
|
+
delay(1000, undefined, { ref: false }),
|
|
49
|
+
]);
|
|
50
|
+
if (child.exitCode === null && process.platform !== 'win32') {
|
|
51
|
+
try {
|
|
52
|
+
process.kill(-child.pid, 'SIGKILL');
|
|
53
|
+
} catch (error) {
|
|
54
|
+
if (error.code !== 'ESRCH') throw error;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
try {
|
|
60
|
+
const deadline = Date.now() + (settings.timeout ?? 30000);
|
|
61
|
+
while (Date.now() < deadline) {
|
|
62
|
+
if (failure || child.exitCode !== null)
|
|
63
|
+
throw new Error(
|
|
64
|
+
`Accessibility server did not stay running: ${failure?.message ?? (output || child.exitCode)}`,
|
|
65
|
+
);
|
|
66
|
+
try {
|
|
67
|
+
const response = await fetch(settings.url, { signal: AbortSignal.timeout(1000) });
|
|
68
|
+
if (response.ok) return stop;
|
|
69
|
+
} catch {}
|
|
70
|
+
await delay(100);
|
|
71
|
+
}
|
|
72
|
+
throw new Error(
|
|
73
|
+
`Accessibility server did not become ready within ${settings.timeout ?? 30000} ms`,
|
|
74
|
+
);
|
|
75
|
+
} catch (error) {
|
|
76
|
+
await stop();
|
|
77
|
+
throw error;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function scanAccessibility(
|
|
82
|
+
settings,
|
|
83
|
+
{ chromium, AxeBuilder, root = process.cwd(), server = startServer } = {},
|
|
84
|
+
) {
|
|
85
|
+
if (!settings?.routes?.length) throw new Error('Configure a11y.baseURL and at least one route');
|
|
86
|
+
const base = new URL(settings.baseURL);
|
|
87
|
+
if (!['http:', 'https:'].includes(base.protocol))
|
|
88
|
+
throw new Error('Accessibility baseURL must use HTTP or HTTPS');
|
|
89
|
+
const impacts = settings.failImpacts ?? ['minor', 'moderate', 'serious', 'critical'];
|
|
90
|
+
let stop, browser;
|
|
91
|
+
const pages = [],
|
|
92
|
+
errors = [];
|
|
93
|
+
try {
|
|
94
|
+
if (settings.server)
|
|
95
|
+
stop = await server(root, {
|
|
96
|
+
...settings.server,
|
|
97
|
+
url: settings.server.url ?? settings.baseURL,
|
|
98
|
+
});
|
|
99
|
+
mkdirSync(join(root, '.tooling'), { recursive: true });
|
|
100
|
+
browser = await chromium.launch({
|
|
101
|
+
headless: true,
|
|
102
|
+
args: [`--log-file=${join(root, '.tooling/a11y-chromium.log')}`],
|
|
103
|
+
...(settings.executablePath || process.env.PLAYWRIGHT_CHROMIUM_PATH
|
|
104
|
+
? { executablePath: settings.executablePath ?? process.env.PLAYWRIGHT_CHROMIUM_PATH }
|
|
105
|
+
: {}),
|
|
106
|
+
});
|
|
107
|
+
for (const viewport of settings.viewports ?? [{ name: 'desktop', width: 1280, height: 720 }]) {
|
|
108
|
+
const context = await browser.newContext({
|
|
109
|
+
viewport: { width: viewport.width, height: viewport.height },
|
|
110
|
+
...(settings.storageState ? { storageState: inside(root, settings.storageState) } : {}),
|
|
111
|
+
});
|
|
112
|
+
context.setDefaultTimeout?.(settings.timeout ?? 30000);
|
|
113
|
+
try {
|
|
114
|
+
for (const route of settings.routes) {
|
|
115
|
+
const url = new URL(route.path, base);
|
|
116
|
+
if (url.origin !== base.origin)
|
|
117
|
+
throw new Error('Accessibility routes must stay on baseURL origin');
|
|
118
|
+
const page = await context.newPage();
|
|
119
|
+
try {
|
|
120
|
+
const response = await page.goto(url.href, {
|
|
121
|
+
waitUntil: 'domcontentloaded',
|
|
122
|
+
timeout: settings.timeout ?? 30000,
|
|
123
|
+
});
|
|
124
|
+
if (response && !response.ok())
|
|
125
|
+
throw new Error(`Navigation returned HTTP ${response.status()}`);
|
|
126
|
+
if (new URL(page.url()).origin !== base.origin)
|
|
127
|
+
throw new Error(
|
|
128
|
+
'Accessibility route redirected outside baseURL origin; configure authentication state',
|
|
129
|
+
);
|
|
130
|
+
if (route.waitFor)
|
|
131
|
+
await page.locator(route.waitFor).waitFor({ timeout: settings.timeout ?? 30000 });
|
|
132
|
+
for (const action of route.actions ?? []) {
|
|
133
|
+
const locator = page.locator(action.selector);
|
|
134
|
+
if (action.type === 'click') await locator.click();
|
|
135
|
+
else if (action.type === 'fill') await locator.fill(action.value);
|
|
136
|
+
else if (action.type === 'press') await locator.press(action.value);
|
|
137
|
+
}
|
|
138
|
+
let axe = new AxeBuilder({ page });
|
|
139
|
+
axe = axe.withTags(settings.tags ?? ['wcag2a', 'wcag2aa', 'wcag21a', 'wcag21aa']);
|
|
140
|
+
for (const selector of route.include ?? []) axe = axe.include(selector);
|
|
141
|
+
for (const selector of route.exclude ?? []) axe = axe.exclude(selector);
|
|
142
|
+
const result = await axe.analyze();
|
|
143
|
+
pages.push({
|
|
144
|
+
route: route.name ?? route.path,
|
|
145
|
+
viewport: viewport.name,
|
|
146
|
+
violations: result.violations.map((violation) => ({
|
|
147
|
+
id: violation.id,
|
|
148
|
+
impact: violation.impact,
|
|
149
|
+
help: violation.help,
|
|
150
|
+
helpUrl: violation.helpUrl,
|
|
151
|
+
targets: violation.nodes.flatMap((node) => node.target),
|
|
152
|
+
failing: impacts.includes(violation.impact),
|
|
153
|
+
})),
|
|
154
|
+
incomplete: result.incomplete.map((rule) => ({ id: rule.id, help: rule.help })),
|
|
155
|
+
passedRules: result.passes.length,
|
|
156
|
+
});
|
|
157
|
+
} catch (error) {
|
|
158
|
+
errors.push({
|
|
159
|
+
route: route.name ?? route.path,
|
|
160
|
+
viewport: viewport.name,
|
|
161
|
+
message: error.message,
|
|
162
|
+
});
|
|
163
|
+
} finally {
|
|
164
|
+
await page.close();
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
} finally {
|
|
168
|
+
await context.close();
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
} finally {
|
|
172
|
+
try {
|
|
173
|
+
if (browser) await browser.close();
|
|
174
|
+
} finally {
|
|
175
|
+
if (stop) await stop();
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
const failures = pages.reduce(
|
|
179
|
+
(sum, page) => sum + page.violations.filter((violation) => violation.failing).length,
|
|
180
|
+
0,
|
|
181
|
+
);
|
|
182
|
+
return { pages, errors, failures, complete: !errors.length && failures === 0 };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
186
|
+
const root = rootDirectory(),
|
|
187
|
+
{ config } = loadConfig(root);
|
|
188
|
+
const { chromium } = peer('@playwright/test');
|
|
189
|
+
const axe = peer('@axe-core/playwright');
|
|
190
|
+
const result = await scanAccessibility(config.a11y, {
|
|
191
|
+
root,
|
|
192
|
+
chromium,
|
|
193
|
+
AxeBuilder: axe.default ?? axe.AxeBuilder,
|
|
194
|
+
});
|
|
195
|
+
writeDetails({ a11y: result });
|
|
196
|
+
for (const page of result.pages)
|
|
197
|
+
for (const violation of page.violations.filter((violation) => violation.failing))
|
|
198
|
+
console.error(
|
|
199
|
+
`${page.route} [${page.viewport}] ${violation.impact}: ${violation.help} (${violation.id})`,
|
|
200
|
+
);
|
|
201
|
+
for (const error of result.errors) console.error(`${error.route}: ${error.message}`);
|
|
202
|
+
console.log(
|
|
203
|
+
`Accessibility: ${result.pages.length} rendered pages, ${result.failures} violations, ${result.errors.length} scan errors`,
|
|
204
|
+
);
|
|
205
|
+
process.exitCode = result.complete ? 0 : 1;
|
|
206
|
+
}
|
|
@@ -0,0 +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
|
+
}
|
package/checks/audit.mjs
ADDED
|
@@ -0,0 +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
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { readdirSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { join, posix, relative } from 'node:path';
|
|
4
|
+
import { pathToFileURL } from 'node:url';
|
|
5
|
+
import { gzipSync } from 'node:zlib';
|
|
6
|
+
import { loadConfig, inside } from '../runner/config.mjs';
|
|
7
|
+
import { initSync, parse } from 'es-module-lexer';
|
|
8
|
+
import { writeDetails } from './shared.mjs';
|
|
9
|
+
|
|
10
|
+
initSync();
|
|
11
|
+
|
|
12
|
+
const jsFile = (file) => /\.[cm]?js$/.test(file);
|
|
13
|
+
const walk = (directory) =>
|
|
14
|
+
readdirSync(directory, { withFileTypes: true }).flatMap((entry) =>
|
|
15
|
+
entry.isDirectory() ? walk(join(directory, entry.name)) : [join(directory, entry.name)],
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
// The module lexer handles minified ESM, escapes, comments, strings and re-exports.
|
|
19
|
+
export function staticImports(source) {
|
|
20
|
+
const [imports] = parse(source);
|
|
21
|
+
return imports.filter((item) => item.d === -1 && item.n).map((item) => item.n);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function analyseBundle(root, budget) {
|
|
25
|
+
const dist = inside(root, budget.dist);
|
|
26
|
+
const chunks = walk(dist)
|
|
27
|
+
.map((file) => relative(dist, file).replaceAll('\\', '/'))
|
|
28
|
+
.filter(jsFile);
|
|
29
|
+
const available = new Set(chunks);
|
|
30
|
+
const resolveAsset = (url, importer = 'index.html') => {
|
|
31
|
+
if (/^(?:[a-z][a-z\d+.-]*:|\/\/|#)/i.test(url)) return null;
|
|
32
|
+
let path;
|
|
33
|
+
try {
|
|
34
|
+
path = decodeURIComponent(url.split(/[?#]/)[0]);
|
|
35
|
+
} catch {
|
|
36
|
+
throw new Error(`Invalid asset URL: ${url}`);
|
|
37
|
+
}
|
|
38
|
+
if (!jsFile(path)) return null;
|
|
39
|
+
const local = posix.normalize(
|
|
40
|
+
path.startsWith('/') ? path.slice(1) : posix.join(posix.dirname(importer), path),
|
|
41
|
+
);
|
|
42
|
+
if (available.has(local)) return local;
|
|
43
|
+
// Match the build's real asset path after a deployment prefix such as /my-app/.
|
|
44
|
+
if (path.startsWith('/')) {
|
|
45
|
+
const matches = chunks.filter((file) => path.endsWith('/' + file));
|
|
46
|
+
if (matches.length === 1) return matches[0];
|
|
47
|
+
}
|
|
48
|
+
throw new Error(`Missing local JavaScript asset: ${url} (from ${importer})`);
|
|
49
|
+
};
|
|
50
|
+
const html = readFileSync(join(dist, 'index.html'), 'utf8').replace(/<!--[\s\S]*?-->/g, '');
|
|
51
|
+
const entries = new Set();
|
|
52
|
+
for (const tag of html.matchAll(/<(script|link)\b[^>]*>/gi)) {
|
|
53
|
+
const attrs = Object.fromEntries(
|
|
54
|
+
[...tag[0].matchAll(/([\w-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))/g)].map((m) => [
|
|
55
|
+
m[1].toLowerCase(),
|
|
56
|
+
m[2] ?? m[3] ?? m[4],
|
|
57
|
+
]),
|
|
58
|
+
);
|
|
59
|
+
if (tag[1].toLowerCase() === 'link' && attrs.rel?.toLowerCase() !== 'modulepreload') continue;
|
|
60
|
+
const url = attrs.src ?? attrs.href;
|
|
61
|
+
if (!url) continue;
|
|
62
|
+
const asset = resolveAsset(url);
|
|
63
|
+
if (asset) entries.add(asset);
|
|
64
|
+
}
|
|
65
|
+
if (!entries.size) throw new Error('No local initial JavaScript found in dist/index.html');
|
|
66
|
+
const initial = new Set();
|
|
67
|
+
const visit = (file) => {
|
|
68
|
+
if (initial.has(file)) return;
|
|
69
|
+
initial.add(file);
|
|
70
|
+
for (const specifier of staticImports(readFileSync(join(dist, file), 'utf8'))) {
|
|
71
|
+
if (!specifier.startsWith('.') && !specifier.startsWith('/')) continue;
|
|
72
|
+
const dependency = resolveAsset(specifier, file);
|
|
73
|
+
if (dependency) visit(dependency);
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
entries.forEach(visit);
|
|
77
|
+
const gzip = (file) => gzipSync(readFileSync(join(dist, file))).length;
|
|
78
|
+
const initialKB = [...initial].reduce((sum, file) => sum + gzip(file), 0) / 1024;
|
|
79
|
+
const errors = [];
|
|
80
|
+
if (initialKB > budget.initialKB)
|
|
81
|
+
errors.push(`initial JS ${initialKB.toFixed(1)} KB > ${budget.initialKB} KB`);
|
|
82
|
+
for (const file of chunks) {
|
|
83
|
+
if (initial.has(file)) continue;
|
|
84
|
+
let vendor;
|
|
85
|
+
try {
|
|
86
|
+
const map = JSON.parse(readFileSync(join(dist, `${file}.map`), 'utf8'));
|
|
87
|
+
const weights = new Map();
|
|
88
|
+
map.sources.forEach((source, i) => {
|
|
89
|
+
const hit = (budget.vendors ?? []).find(([pkg]) =>
|
|
90
|
+
source.replaceAll('\\', '/').includes(`node_modules/${pkg}/`),
|
|
91
|
+
);
|
|
92
|
+
if (hit) weights.set(hit, (weights.get(hit) ?? 0) + (map.sourcesContent?.[i]?.length ?? 0));
|
|
93
|
+
});
|
|
94
|
+
const total = (map.sourcesContent ?? []).reduce(
|
|
95
|
+
(sum, content) => sum + (content?.length ?? 0),
|
|
96
|
+
0,
|
|
97
|
+
);
|
|
98
|
+
const best = [...weights].sort((a, b) => b[1] - a[1])[0];
|
|
99
|
+
if (best && best[1] > total / 2) vendor = best[0];
|
|
100
|
+
} catch (error) {
|
|
101
|
+
if (error.code !== 'ENOENT') throw error;
|
|
102
|
+
}
|
|
103
|
+
const size = gzip(file) / 1024;
|
|
104
|
+
const cap = vendor ? vendor[2] : budget.chunkKB;
|
|
105
|
+
if (size > cap)
|
|
106
|
+
errors.push(
|
|
107
|
+
`${file} (${vendor ? vendor[1] : 'route chunk'}) ${size.toFixed(1)} KB > ${cap} KB`,
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return { initialKB, initial: [...initial], chunks: chunks.length, errors };
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
|
|
114
|
+
const root = process.env.TOOLING_ROOT ?? process.cwd();
|
|
115
|
+
const { config } = loadConfig(root);
|
|
116
|
+
if (!config.budgets?.bundle) throw new Error('Configure budgets.bundle');
|
|
117
|
+
const result = analyseBundle(root, config.budgets.bundle);
|
|
118
|
+
writeDetails({ bundle: result });
|
|
119
|
+
console.log(
|
|
120
|
+
`initial JS: ${result.initialKB.toFixed(1)} KB gzip across ${result.initial.length} files; ${result.chunks} chunks checked`,
|
|
121
|
+
);
|
|
122
|
+
if (result.errors.length) {
|
|
123
|
+
console.error(result.errors.join('\n'));
|
|
124
|
+
process.exitCode = 1;
|
|
125
|
+
} else console.log('Bundle budgets OK.');
|
|
126
|
+
}
|