impeccable 3.6.0 → 4.0.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.
@@ -1,51 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * Anti-Pattern Detector for Impeccable
5
- * Copyright (c) 2026 Paul Bakaus
6
- * SPDX-License-Identifier: Apache-2.0
7
- *
8
- * Public API facade. Runtime engines live under cli/engine/engines/.
9
- */
10
-
11
- import { detectCli } from './cli/main.mjs';
12
-
13
- export { ANTIPATTERNS, RULE_ENGINE_SUPPORT, getAntipattern, getRulesForCategory, getRuleEngineSupport } from './registry/antipatterns.mjs';
14
- export { SAFE_TAGS, BORDER_SAFE_TAGS, OVERUSED_FONTS, GENERIC_FONTS, KNOWN_SERIF_FONTS } from './shared/constants.mjs';
15
- export { isNeutralColor, parseRgb, relativeLuminance, contrastRatio, parseGradientColors, hasChroma, getHue, colorToHex } from './shared/color.mjs';
16
- export { isFullPage } from './shared/page.mjs';
17
- export {
18
- checkElementBorders,
19
- checkElementMotion,
20
- checkElementGlow,
21
- checkPageTypography,
22
- checkPageLayout,
23
- checkHtmlPatterns,
24
- } from './rules/checks.mjs';
25
- export { createDetectorProfile, summarizeDetectorProfile } from './profile/profiler.mjs';
26
- export {
27
- parseFrontmatter as parseDesignFrontmatter,
28
- normalizeDesignSystem,
29
- loadDesignSystemForCwd,
30
- checkSourceDesignSystem,
31
- collectStaticDesignSystemFindings,
32
- } from './design-system.mjs';
33
- export { detectHtml } from './engines/static-html/detect-html.mjs';
34
- export { detectUrl, createBrowserDetector } from './engines/browser/detect-url.mjs';
35
- export { detectText, extractStyleBlocks, extractCSSinJS } from './engines/regex/detect-text.mjs';
36
- export {
37
- walkDir,
38
- hasScannableExtension,
39
- SCANNABLE_EXTENSIONS,
40
- SKIP_DIRS,
41
- buildImportGraph,
42
- resolveImport,
43
- detectFrameworkConfig,
44
- isPortListening,
45
- FRAMEWORK_CONFIGS,
46
- } from './node/file-system.mjs';
47
- export { formatFindings, detectCli } from './cli/main.mjs';
48
-
49
- const isMainModule = process.argv[1]?.endsWith('detect-antipatterns.mjs') ||
50
- process.argv[1]?.endsWith('detect-antipatterns.mjs/');
51
- if (isMainModule) detectCli();
@@ -1,372 +0,0 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { fileURLToPath } from 'node:url';
4
-
5
- import { finding } from '../../findings.mjs';
6
- import { profileFindingsAsync, profileStep, profileStepAsync } from '../../profile/profiler.mjs';
7
- import { captureVisualContrastCandidate } from '../visual/screenshot-contrast.mjs';
8
- import { checkContentHiddenAtRest } from '../../rules/checks.mjs';
9
-
10
- // On Windows, puppeteer's bundled Chrome lives in a user-writable cache
11
- // directory. Its GPU process can be denied (STATUS_ACCESS_DENIED) by security
12
- // software or the GPU sandbox because it launches from an untrusted path.
13
- // Chrome then crash-loops the GPU process, and each relaunch briefly flashes a
14
- // compositor surface, the black window users report during `detect <url>`
15
- // (issue #372). The system-installed Chrome runs from a trusted location with a
16
- // healthy GPU, so channel:'chrome' avoids the crash entirely; both use hardware
17
- // GPU, so contrast measurement is unaffected. Scope this to Windows only: other
18
- // platforms do not have the bug, so they keep the pinned bundled build for
19
- // consistent measurement across machines. Fall back to bundled when the switch
20
- // fails (Chrome not installed, or channel resolution fails). If the bundled
21
- // launch then also fails, surface the original system-Chrome error as the
22
- // cause so the real failure is not lost.
23
- async function launchBrowser(puppeteer, { headless = true, args = [] } = {}) {
24
- let channelError;
25
- if (process.platform === 'win32') {
26
- try {
27
- return await puppeteer.default.launch({ channel: 'chrome', headless, args });
28
- } catch (err) {
29
- // System Chrome unavailable or unlaunchable; fall through to the bundled
30
- // browser, but keep the error in case the fallback fails too.
31
- channelError = err;
32
- }
33
- }
34
- try {
35
- return await puppeteer.default.launch({ headless, args });
36
- } catch (err) {
37
- if (channelError && err && err.cause === undefined) err.cause = channelError;
38
- throw err;
39
- }
40
- }
41
-
42
- // Reveal sweep + invisible-text measurement for the content-hidden-at-rest
43
- // rule. Scrolls through the document with instant jumps (bypasses CSS
44
- // scroll-behavior: smooth) so IntersectionObserver / scroll reveal handlers
45
- // get every chance to fire, returns to the top, lets transitions settle,
46
- // then measures how much text still renders invisible. A healthy
47
- // reveal-on-scroll page drops to ~0 after the sweep; a page whose reveal
48
- // script died keeps most of its text at opacity 0.
49
- async function measureContentHiddenAfterReveal(page) {
50
- await page.evaluate(async () => {
51
- const step = Math.max(200, Math.floor(window.innerHeight * 0.7));
52
- const max = Math.max(
53
- document.documentElement.scrollHeight || 0,
54
- document.body?.scrollHeight || 0,
55
- );
56
- for (let y = 0; y <= max; y += step) {
57
- window.scrollTo({ top: y, left: 0, behavior: 'instant' });
58
- await new Promise(resolve => requestAnimationFrame(() => setTimeout(resolve, 40)));
59
- }
60
- window.scrollTo({ top: 0, left: 0, behavior: 'instant' });
61
- await new Promise(resolve => setTimeout(resolve, 700));
62
- });
63
- return page.evaluate(() => {
64
- if (typeof window.impeccableMeasureHiddenText !== 'function') return null;
65
- return window.impeccableMeasureHiddenText();
66
- });
67
- }
68
-
69
- function serializeDesignSystemForBrowser(designSystem) {
70
- if (!designSystem?.present) return null;
71
- return {
72
- present: true,
73
- hasFonts: designSystem.hasFonts === true,
74
- allowedFonts: Array.from(designSystem.allowedFonts || []),
75
- hasColors: designSystem.hasColors === true,
76
- allowedColors: Array.from(designSystem.allowedColorKeys?.values?.() || [])
77
- .map(entry => entry?.color)
78
- .filter(color => color && Number.isFinite(color.r) && Number.isFinite(color.g) && Number.isFinite(color.b))
79
- .map(color => ({ r: color.r, g: color.g, b: color.b })),
80
- hasRadii: designSystem.hasRadii === true,
81
- allowedRadii: (designSystem.allowedRadii || [])
82
- .map(entry => Number(entry?.px))
83
- .filter(px => Number.isFinite(px)),
84
- hasPillRadius: designSystem.hasPillRadius === true,
85
- };
86
- }
87
-
88
- async function runVisualContrastFallback(page, serializedGroups, options, profile, target) {
89
- if (options?.visualContrast === false) return [];
90
- const maxCandidates = Number.isFinite(options?.visualContrastMaxCandidates)
91
- ? options.visualContrastMaxCandidates
92
- : 12;
93
- const scrollOffscreen = options?.visualContrastScrollOffscreen !== false;
94
- const existingLowContrastSelectors = new Set(
95
- serializedGroups
96
- .filter(group => group.findings?.some(f => f.type === 'low-contrast'))
97
- .map(group => group.selector)
98
- .filter(Boolean)
99
- );
100
-
101
- let browserAnalyses = [];
102
- const findings = [];
103
- if (options?.visualContrastBrowser !== false) {
104
- const browserFindings = await profileFindingsAsync(profile, {
105
- engine: 'browser',
106
- phase: 'visual-contrast',
107
- ruleId: 'browser-fallback',
108
- target,
109
- }, async () => {
110
- browserAnalyses = await page.evaluate(async ({ maxCandidates, scrollOffscreen }) => {
111
- if (typeof window.impeccableAnalyzeVisualContrast !== 'function') return [];
112
- return window.impeccableAnalyzeVisualContrast({ maxCandidates, scrollOffscreen });
113
- }, { maxCandidates, scrollOffscreen });
114
- return browserAnalyses
115
- .filter(result => result.finding && !existingLowContrastSelectors.has(result.selector))
116
- .map(result => result.finding);
117
- });
118
- findings.push(...browserFindings);
119
- }
120
-
121
- let candidates = browserAnalyses.length > 0 ? browserAnalyses : [];
122
- if (candidates.length === 0) {
123
- candidates = await profileStepAsync(profile, {
124
- engine: 'browser',
125
- phase: 'visual-contrast',
126
- ruleId: 'collect-candidates',
127
- target,
128
- }, () => page.evaluate(({ maxCandidates }) => {
129
- if (typeof window.impeccableCollectVisualContrastCandidates !== 'function') return [];
130
- return window.impeccableCollectVisualContrastCandidates({ maxCandidates });
131
- }, { maxCandidates }));
132
- }
133
-
134
- const viewport = options?.viewport || { width: 1280, height: 800 };
135
- const browserResolvedSelectors = new Set(
136
- browserAnalyses
137
- .filter(result => result.status === 'fail' || result.status === 'pass')
138
- .map(result => result.selector)
139
- .filter(Boolean)
140
- );
141
- const filtered = candidates.filter(candidate =>
142
- !existingLowContrastSelectors.has(candidate.selector) &&
143
- !browserResolvedSelectors.has(candidate.selector)
144
- );
145
- if (options?.visualContrastPixel === false) return findings;
146
- for (const candidate of filtered) {
147
- const result = await profileFindingsAsync(profile, {
148
- engine: 'browser',
149
- phase: 'visual-contrast',
150
- ruleId: 'pixel-diff',
151
- target,
152
- }, async () => {
153
- const finding = await captureVisualContrastCandidate(page, candidate, viewport);
154
- return finding ? [finding] : [];
155
- });
156
- findings.push(...result);
157
- }
158
- return findings;
159
- }
160
-
161
- // ---------------------------------------------------------------------------
162
- // Puppeteer detection (for URLs)
163
- // ---------------------------------------------------------------------------
164
-
165
- async function detectUrl(url, options = {}) {
166
- const profile = options?.profile;
167
- const waitUntil = options?.waitUntil || 'networkidle0';
168
- const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
169
- const viewport = options?.viewport || { width: 1280, height: 800 };
170
- const externalBrowser = options?.browser || null;
171
- let puppeteer;
172
- if (!externalBrowser) {
173
- try {
174
- puppeteer = await profileStepAsync(profile, {
175
- engine: 'browser',
176
- phase: 'setup',
177
- ruleId: 'import-puppeteer',
178
- target: url,
179
- }, () => import('puppeteer'));
180
- } catch {
181
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
182
- }
183
- }
184
-
185
- // Read the browser detection script — reuse it instead of reimplementing
186
- const browserScriptPath = path.resolve(
187
- path.dirname(fileURLToPath(import.meta.url)),
188
- '..',
189
- '..',
190
- 'detect-antipatterns-browser.js'
191
- );
192
- let browserScript;
193
- try {
194
- browserScript = profileStep(profile, {
195
- engine: 'browser',
196
- phase: 'setup',
197
- ruleId: 'read-browser-script',
198
- target: url,
199
- }, () => fs.readFileSync(browserScriptPath, 'utf-8'));
200
- } catch {
201
- throw new Error(`Browser script not found at ${browserScriptPath}`);
202
- }
203
-
204
- // CI runners (GitHub Actions Ubuntu) block unprivileged user namespaces, so
205
- // Chrome can't initialize its sandbox there. Disable the sandbox only when
206
- // running in CI; local users keep the default hardened launch.
207
- const launchArgs = process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : [];
208
- const browser = externalBrowser || await profileStepAsync(profile, {
209
- engine: 'browser',
210
- phase: 'load',
211
- ruleId: 'launch-browser',
212
- target: url,
213
- }, () => launchBrowser(puppeteer, { headless: options?.headless ?? true, args: launchArgs }));
214
- const page = await profileStepAsync(profile, {
215
- engine: 'browser',
216
- phase: 'load',
217
- ruleId: 'new-page',
218
- target: url,
219
- }, () => browser.newPage());
220
-
221
- // Uncaught exceptions and parse errors surface as pageerror events. The
222
- // listener must attach before goto: a syntax error fires during the
223
- // initial parse, long before the load event. Dedupe by message; a single
224
- // broken loop can otherwise throw hundreds of identical errors.
225
- const pageErrors = [];
226
- if (options?.scriptErrors !== false) {
227
- page.on('pageerror', (err) => {
228
- const message = String(err?.message || err).split('\n')[0].trim().slice(0, 160);
229
- if (message && !pageErrors.includes(message)) pageErrors.push(message);
230
- });
231
- }
232
-
233
- let results = [];
234
- try {
235
- await profileStepAsync(profile, {
236
- engine: 'browser',
237
- phase: 'load',
238
- ruleId: 'set-viewport',
239
- target: url,
240
- }, () => page.setViewport(viewport));
241
- await profileStepAsync(profile, {
242
- engine: 'browser',
243
- phase: 'load',
244
- ruleId: `goto:${waitUntil}`,
245
- target: url,
246
- }, () => page.goto(url, { waitUntil, timeout: 30000 }));
247
- if (settleMs > 0) {
248
- await profileStepAsync(profile, {
249
- engine: 'browser',
250
- phase: 'load',
251
- ruleId: 'settle',
252
- target: url,
253
- }, () => new Promise(resolve => setTimeout(resolve, settleMs)));
254
- }
255
-
256
- // Inject the browser detection script and collect results
257
- const browserDesignSystem = serializeDesignSystemForBrowser(options?.designSystem);
258
- await profileStepAsync(profile, {
259
- engine: 'browser',
260
- phase: 'scan',
261
- ruleId: 'configure-pure-detect',
262
- target: url,
263
- }, () => page.evaluate((designSystem) => {
264
- window.__IMPECCABLE_CONFIG__ = {
265
- ...(window.__IMPECCABLE_CONFIG__ || {}),
266
- autoScan: false,
267
- ...(designSystem ? { designSystem } : {}),
268
- };
269
- }, browserDesignSystem));
270
- await profileStepAsync(profile, {
271
- engine: 'browser',
272
- phase: 'scan',
273
- ruleId: 'inject-browser-script',
274
- target: url,
275
- }, () => page.evaluate(browserScript));
276
- let serializedGroups = [];
277
- results = await profileFindingsAsync(profile, {
278
- engine: 'browser',
279
- phase: 'scan',
280
- ruleId: 'browser-scan',
281
- target: url,
282
- }, async () => {
283
- serializedGroups = await page.evaluate(() => {
284
- if (!window.impeccableDetect) return [];
285
- return window.impeccableDetect({ decorate: false, serialize: true });
286
- });
287
- return serializedGroups.flatMap(({ findings }) =>
288
- findings.map(f => ({ id: f.type, snippet: f.detail, ignoreValue: f.ignoreValue || '', severity: f.severity || '' }))
289
- );
290
- });
291
- // Content invisible at rest: reveal sweep, then re-measure. Runs after
292
- // the main scan (which must see the true at-rest state) and before the
293
- // visual contrast fallback (the sweep restores scroll to the top).
294
- if (options?.contentHidden !== false) {
295
- const hiddenFindings = await profileFindingsAsync(profile, {
296
- engine: 'browser',
297
- phase: 'scan',
298
- ruleId: 'content-hidden-at-rest',
299
- target: url,
300
- }, async () => {
301
- const measured = await measureContentHiddenAfterReveal(page);
302
- return measured ? checkContentHiddenAtRest(measured) : [];
303
- });
304
- results.push(...hiddenFindings);
305
- }
306
-
307
- for (const message of pageErrors.slice(0, 3)) {
308
- results.push({ id: 'script-error', snippet: message });
309
- }
310
-
311
- const visualFindings = await runVisualContrastFallback(page, serializedGroups, options, profile, url);
312
- results.push(...visualFindings);
313
- } finally {
314
- await profileStepAsync(profile, {
315
- engine: 'browser',
316
- phase: 'load',
317
- ruleId: 'close-page',
318
- target: url,
319
- }, () => page.close().catch(() => {}));
320
- if (!externalBrowser) {
321
- await profileStepAsync(profile, {
322
- engine: 'browser',
323
- phase: 'load',
324
- ruleId: 'close-browser',
325
- target: url,
326
- }, () => browser.close());
327
- }
328
- }
329
- return results.map(f => {
330
- const item = finding(f.id, url, f.snippet);
331
- if (f.ignoreValue) item.ignoreValue = f.ignoreValue;
332
- // Per-finding severity promotion (e.g. hero-region pulsing dot)
333
- // overrides the registry default carried by finding().
334
- if (f.severity && f.severity !== item.severity) item.severity = f.severity;
335
- return item;
336
- });
337
- }
338
-
339
- async function createBrowserDetector(options = {}) {
340
- let puppeteer;
341
- try {
342
- puppeteer = await import('puppeteer');
343
- } catch {
344
- throw new Error('puppeteer is required for URL scanning. Install: npm install puppeteer');
345
- }
346
- const launchArgs = options.launchArgs || (process.env.CI ? ['--no-sandbox', '--disable-setuid-sandbox'] : []);
347
- const browser = options.browser || await launchBrowser(puppeteer, {
348
- headless: options.headless ?? true,
349
- args: launchArgs,
350
- });
351
- const ownsBrowser = !options.browser;
352
- const defaults = {
353
- waitUntil: options.waitUntil || 'load',
354
- settleMs: Number.isFinite(options.settleMs) ? options.settleMs : 100,
355
- viewport: options.viewport || { width: 1280, height: 800 },
356
- };
357
- return {
358
- browser,
359
- async detectUrl(url, scanOptions = {}) {
360
- return detectUrl(url, {
361
- ...defaults,
362
- ...scanOptions,
363
- browser,
364
- });
365
- },
366
- async close() {
367
- if (ownsBrowser) await browser.close().catch(() => {});
368
- },
369
- };
370
- }
371
-
372
- export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };