mirror of
https://github.com/pbakaus/impeccable.git
synced 2026-09-11 21:57:14 +03:00
Compare commits
90
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9434dde9af | ||
|
|
10f7c7b6f8 | ||
|
|
af109a85ae | ||
|
|
0d2df39339 | ||
|
|
64001fe213 | ||
|
|
18e8c287b5 | ||
|
|
09ddc1758e | ||
|
|
3818a5655b | ||
|
|
7edc5a43da | ||
|
|
c75f9f1086 | ||
|
|
ea360025b5 | ||
|
|
00095adb26 | ||
|
|
46f13989eb | ||
|
|
152d6940b0 | ||
|
|
09506a9bb5 | ||
|
|
cbd7870159 | ||
|
|
30b3628f5b | ||
|
|
5c82d58b7e | ||
|
|
77a2eae861 | ||
|
|
0c2517884d | ||
|
|
08b03e8763 | ||
|
|
3df4c4b10d | ||
|
|
f379c4c76f | ||
|
|
31dcc687c6 | ||
|
|
45943c3b1f | ||
|
|
ce1c9f8dad | ||
|
|
5330fa358e | ||
|
|
ae42c0c3ce | ||
|
|
2896e28613 | ||
|
|
1117672934 | ||
|
|
9ca77151de | ||
|
|
bef185360f | ||
|
|
2debb7078f | ||
|
|
866bd94b7e | ||
|
|
38170564c6 | ||
|
|
9746567ea9 | ||
|
|
77acd73cd3 | ||
|
|
7cea970c6c | ||
|
|
36e6864d56 | ||
|
|
693953806c | ||
|
|
f80846ad85 | ||
|
|
07e3fad3b6 | ||
|
|
1931066107 | ||
|
|
bae0c24f45 | ||
|
|
9a1daacd76 | ||
|
|
00a180380e | ||
|
|
ba26730411 | ||
|
|
356362a410 | ||
|
|
f5819fbd6a | ||
|
|
3e7e85daf7 | ||
|
|
2cc60a5348 | ||
|
|
08ce88f565 | ||
|
|
4f2de6a0b6 | ||
|
|
caf9744763 | ||
|
|
99f73390db | ||
|
|
919c68d2b9 | ||
|
|
48350ffb14 | ||
|
|
95294e464a | ||
|
|
cacb2868ac | ||
|
|
62f59a3934 | ||
|
|
cbe89a1969 | ||
|
|
f5751c4d75 | ||
|
|
b015e26ddf | ||
|
|
f704fca29c | ||
|
|
bfa6014796 | ||
|
|
af4ac68805 | ||
|
|
e618357a69 | ||
|
|
24773eeedf | ||
|
|
d9a155be8c | ||
|
|
e0ec77b4bb | ||
|
|
6dd15238c4 | ||
|
|
2fbfef0b43 | ||
|
|
2dcaacbcd1 | ||
|
|
b450da2082 | ||
|
|
f4987eebba | ||
|
|
63dd7faa0e | ||
|
|
34ef9ac2c4 | ||
|
|
5856161014 | ||
|
|
b0fc2e8801 | ||
|
|
f86473ba7d | ||
|
|
377fb112b0 | ||
|
|
7982002dac | ||
|
|
2e075dc58c | ||
|
|
eaaecbd1fe | ||
|
|
d690349db1 | ||
|
|
d5873ff8eb | ||
|
|
1df992ade0 | ||
|
|
be87f5eb86 | ||
|
|
af2e8b3ac3 | ||
|
|
5d932f9fbe |
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -162,7 +162,68 @@ async function runVisualContrastFallback(page, serializedGroups, options, profil
|
||||
// Puppeteer detection (for URLs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
async function detectUrl(url, options = {}) {
|
||||
function decodeUrlComponent(value) {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
} catch {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
function splitScanUrl(url) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
if (!parsed.username && !parsed.password) {
|
||||
return { href: url, credentials: null };
|
||||
}
|
||||
const credentials =
|
||||
parsed.protocol === 'http:' || parsed.protocol === 'https:'
|
||||
? {
|
||||
username: decodeUrlComponent(parsed.username),
|
||||
password: decodeUrlComponent(parsed.password),
|
||||
}
|
||||
: null;
|
||||
parsed.username = '';
|
||||
parsed.password = '';
|
||||
return { href: parsed.href, credentials };
|
||||
}
|
||||
|
||||
function basicAuthHeader(credentials) {
|
||||
return `Basic ${Buffer.from(`${credentials.username}:${credentials.password}`).toString('base64')}`;
|
||||
}
|
||||
|
||||
// page.authenticate is page-wide: a cross-origin redirect that then 401s
|
||||
// would receive these credentials. Attach Authorization only to the scan origin.
|
||||
async function applyOriginScopedAuth(page, href, credentials) {
|
||||
if (!credentials) return;
|
||||
let origin = '';
|
||||
try {
|
||||
origin = new URL(href).origin;
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!origin) return;
|
||||
const header = basicAuthHeader(credentials);
|
||||
await page.setRequestInterception(true);
|
||||
page.on('request', (request) => {
|
||||
let headers;
|
||||
try {
|
||||
if (new URL(request.url()).origin === origin) {
|
||||
headers = { ...request.headers(), authorization: header };
|
||||
}
|
||||
} catch {
|
||||
// invalid request URL: continue without auth
|
||||
}
|
||||
void request.continue(headers ? { headers } : undefined).catch(() => {});
|
||||
});
|
||||
}
|
||||
|
||||
async function detectUrl(rawUrl, options = {}) {
|
||||
const { href: url, credentials } = splitScanUrl(rawUrl);
|
||||
const profile = options?.profile;
|
||||
const waitUntil = options?.waitUntil || 'networkidle0';
|
||||
const settleMs = Number.isFinite(options?.settleMs) ? options.settleMs : 0;
|
||||
@@ -238,6 +299,7 @@ async function detectUrl(url, options = {}) {
|
||||
ruleId: 'set-viewport',
|
||||
target: url,
|
||||
}, () => page.setViewport(viewport));
|
||||
await applyOriginScopedAuth(page, url, credentials);
|
||||
await profileStepAsync(profile, {
|
||||
engine: 'browser',
|
||||
phase: 'load',
|
||||
@@ -369,4 +431,4 @@ async function createBrowserDetector(options = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser };
|
||||
export { runVisualContrastFallback, detectUrl, createBrowserDetector, launchBrowser, splitScanUrl };
|
||||
|
||||
@@ -35,6 +35,7 @@ import {
|
||||
ensureHookGitExcludes,
|
||||
normalizeIgnoreValue,
|
||||
normalizeIgnoreValueEntries,
|
||||
extractFindingIgnoreValue,
|
||||
} from './hook-lib.mjs';
|
||||
|
||||
const ACTIONS = new Set(['status', 'on', 'off', 'ignore-rule', 'ignore-file', 'ignore-value', 'reset']);
|
||||
@@ -713,6 +714,10 @@ function addIgnoreValue(cwd, args) {
|
||||
throw new Error(`Wildcard value ignores must be scoped with --file <glob>, e.g. ${IMPECCABLE_COMMAND} hooks ignore-value design-system-font-size "*" --file "src/widget.js". To suppress the rule project-wide use ${projectWide}.`);
|
||||
}
|
||||
|
||||
if (parsed.value !== '*' && !extractFindingIgnoreValue({ antipattern: parsed.rule, ignoreValue: parsed.value })) {
|
||||
throw new Error(`${parsed.rule} has no extractable ignore value. Use ${IMPECCABLE_COMMAND} hooks ignore-value ${parsed.rule} "*" --file <glob> to suppress it in matching files.`);
|
||||
}
|
||||
|
||||
const local = parsed.local;
|
||||
const config = mergeDetectorConfig(readRawDetectorConfig(cwd, { local }));
|
||||
// Key on the file scope too: the same rule/value legitimately appears more than
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
* `cli/engine/detect-antipatterns.mjs` (running from source).
|
||||
*/
|
||||
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
@@ -210,12 +211,49 @@ export function getLocalConfigPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'config.local.json');
|
||||
}
|
||||
|
||||
// Where mutable hook state (cache + pending) lives. Defaults to the
|
||||
// project-local `.impeccable/` dir. When IMPECCABLE_CACHE_ROOT is set, state
|
||||
// relocates to a per-project subdirectory of that root instead, keyed by a
|
||||
// slug of the project path (`[:\\/.]` → `-`, mirroring Claude Code's
|
||||
// `~/.claude/projects/` convention), so project roots stay free of tool
|
||||
// artifacts (issue #422). User-authored config (config.json,
|
||||
// config.local.json, design.json) deliberately stays project-local — only
|
||||
// disposable state relocates.
|
||||
// Read from process.env (not runHook's injected env): the cache root is a
|
||||
// machine-scoped setting like CURSOR_PROJECT_DIR, not a per-invocation
|
||||
// switch. Trim guards against stray whitespace in env files; `~/` (or the
|
||||
// Windows `~\` spelling) expands via os.homedir(), and when no home dir can
|
||||
// be determined the expansion is rejected — state falls back to the
|
||||
// project-local default rather than anchoring under the hook process's cwd.
|
||||
// Resolving both sides makes the slug deterministic when callers hand in a
|
||||
// trailing separator or unnormalized cwd. The slug is the readable
|
||||
// separator-mapped path PLUS an 8-hex sha256 of the resolved path: the
|
||||
// readable part alone is lossy (`/x/my.app` and `/x/my-app` would both map
|
||||
// to `-x-my-app` and share state), so the digest disambiguates while keeping
|
||||
// the dir name human-scannable.
|
||||
function hookStateDir(cwd) {
|
||||
const raw = process.env.IMPECCABLE_CACHE_ROOT;
|
||||
let root = typeof raw === 'string' ? raw.trim() : '';
|
||||
if (root.startsWith('~/') || root.startsWith('~\\') || root === '~') {
|
||||
let home = '';
|
||||
try { home = os.homedir() || ''; } catch { home = ''; }
|
||||
root = home ? path.join(home, root.slice(2)) : '';
|
||||
}
|
||||
if (root) {
|
||||
const resolved = path.resolve(String(cwd));
|
||||
const slug = resolved.replace(/[:\\/.]/g, '-');
|
||||
const digest = crypto.createHash('sha256').update(resolved).digest('hex').slice(0, 8);
|
||||
return path.join(path.resolve(root), `${slug}-${digest}`);
|
||||
}
|
||||
return path.join(cwd, '.impeccable');
|
||||
}
|
||||
|
||||
export function getCachePath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.cache.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.cache.json');
|
||||
}
|
||||
|
||||
export function getPendingPath(cwd) {
|
||||
return path.join(cwd, '.impeccable', 'hook.pending.json');
|
||||
return path.join(hookStateDir(cwd), 'hook.pending.json');
|
||||
}
|
||||
|
||||
export function resolveProjectCwd(event, fallback = process.cwd()) {
|
||||
@@ -2122,8 +2160,13 @@ export async function runHook({ stdinJson, env = {}, cwd = process.cwd(), now =
|
||||
// touched-file list for the Stop deep pass, and an already-present
|
||||
// `.impeccable/` dir marks a project that opted in. A non-UI edit, or a
|
||||
// clean UI edit in a project with no Impeccable footprint, must be a
|
||||
// no-op on disk (issues #344, #305).
|
||||
if (deferredTotal > 0 || (cacheDirty && fs.existsSync(path.join(projectCwd, '.impeccable')))) {
|
||||
// no-op on disk (issues #344, #305). An existing cache file also counts
|
||||
// as opted in: under IMPECCABLE_CACHE_ROOT (issue #422) state lives
|
||||
// outside the project, so the project dir alone can't carry the marker —
|
||||
// without this, clean-edit editCount bumps would stop persisting the
|
||||
// moment state relocates. Under stock paths the cache sits inside
|
||||
// `.impeccable/`, so the extra check changes nothing there.
|
||||
if (deferredTotal > 0 || (cacheDirty && (fs.existsSync(path.join(projectCwd, '.impeccable')) || fs.existsSync(getCachePath(projectCwd))))) {
|
||||
persistCache(projectCwd, cache);
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* Convert a live-config glob pattern to a RegExp.
|
||||
*
|
||||
* Supports `**` across path segments, `*` within one segment, and `?` for one
|
||||
* character. Callers normalize project-relative paths to forward slashes.
|
||||
*/
|
||||
export function livePathGlobToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp(`^${re}$`);
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* Browser-side resolution of project detector waivers for Impeccable live mode.
|
||||
*
|
||||
* The live server serializes `.impeccable/config.json` + `config.local.json`
|
||||
* detector ignores (plus the served-root prefixes from the inject config's
|
||||
* `files` globs) into `window.__IMPECCABLE_PROJECT_IGNORES__`. This part
|
||||
* resolves that config against the current page's URL path when a detect scan
|
||||
* starts, so the overlay suppresses the same findings the CLI and the edit
|
||||
* hook do (issue #639).
|
||||
*
|
||||
* Mirrors filterDetectionFindings in cli/lib/impeccable-config.mjs:
|
||||
* 1. `ignoreRules` suppress a rule project-wide.
|
||||
* 2. `ignoreValues` entries with `value: "*"` suppress their rule in the
|
||||
* files their globs name. The CLI never applies an unscoped wildcard
|
||||
* (isIgnoredFindingValue returns false for it), so neither does this.
|
||||
* 3. Remaining `ignoreValues` entries match on the finding's own value;
|
||||
* those are forwarded as `disabledValues` for the detector bundle to
|
||||
* apply where the findings are assembled.
|
||||
* 4. `ignoreFiles` globs that name the page waive it wholesale: the
|
||||
* resolver reports `skipScan: true` and the detector answers the scan
|
||||
* with zero findings, mirroring shouldIgnoreDetectionFile in the CLI
|
||||
* and the edit hook's own ignoreFiles gate.
|
||||
*
|
||||
* `pageFiles`, when the server could resolve it, lists the real project
|
||||
* files the inject config serves. A URL that suffix-matches exactly one of
|
||||
* them takes that file as its only project identity; an ambiguous or absent
|
||||
* match falls back to the served-root common ancestor below.
|
||||
*
|
||||
* Known gap, unchanged from PR #645: framework apps inject into source files
|
||||
* (src/routes/about/+page.svelte) while scans see route URLs (/about), so
|
||||
* entries scoped to source or asset paths never match a page candidate and
|
||||
* are dropped. That shows the finding, which is the conservative direction.
|
||||
*
|
||||
* Kept separate from live-browser.js so the glob and page-scope logic can be
|
||||
* unit tested in Node (tests/live-browser-ignores.test.mjs) without the full
|
||||
* overlay UI bundle.
|
||||
*/
|
||||
(function (root) {
|
||||
'use strict';
|
||||
if (!root) return;
|
||||
|
||||
// Keep in step with normalizeIgnoreRule / normalizeIgnoreValue in
|
||||
// cli/lib/impeccable-config.mjs.
|
||||
function normalizeIgnoreRule(rule) {
|
||||
return String(rule || '').trim().toLowerCase();
|
||||
}
|
||||
|
||||
function normalizeIgnoreValue(value) {
|
||||
return String(value || '')
|
||||
.trim()
|
||||
.replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// Glob -> RegExp. Supports `**`, `*`, `?`, and `{a,b}` alternation.
|
||||
// Keep in step with globToRegex in cli/lib/impeccable-config.mjs.
|
||||
function globToRegex(glob) {
|
||||
let re = '^';
|
||||
let i = 0;
|
||||
while (i < glob.length) {
|
||||
const c = glob[i];
|
||||
if (c === '*') {
|
||||
if (glob[i + 1] === '*') {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
if (glob[i] === '/') i += 1;
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (c === '{') {
|
||||
const end = glob.indexOf('}', i);
|
||||
if (end === -1) { re += '\\{'; i += 1; continue; }
|
||||
const parts = glob.slice(i + 1, end).split(',').map((p) => p.replace(/[.+^$()|[\]\\]/g, '\\$&'));
|
||||
re += `(?:${parts.join('|')})`;
|
||||
i = end + 1;
|
||||
} else if (/[.+^$()|[\]\\]/.test(c)) {
|
||||
re += `\\${c}`;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
re += '$';
|
||||
return new RegExp(re);
|
||||
}
|
||||
|
||||
// The project-relative paths this page could be known as. Ignore globs are
|
||||
// project-relative (prototype/foo.html) and the URL is site-relative
|
||||
// (/foo.html), because a static server's root usually sits inside the
|
||||
// project; `roots` carries that prefix. The server reads it from the inject
|
||||
// config's own `files` globs, which already state where the served pages
|
||||
// are. Do not derive it from the ignore globs: a single entry scoped to
|
||||
// prototype/library/** would then lend prototype/library/ as a candidate
|
||||
// prefix to every page, and that rule would suppress site-wide.
|
||||
//
|
||||
// Each prefixed path also contributes its slash suffixes, mirroring
|
||||
// findingMatchesScopedIgnoreFile in cli/lib/impeccable-config.mjs (which
|
||||
// matches globs against every path suffix of the finding's file).
|
||||
//
|
||||
// One live session is served by one server, so a single document root must
|
||||
// sit at or above every configured page. The only prefix that can safely
|
||||
// be asserted is therefore the deepest common ancestor of the glob roots.
|
||||
// Treating each glob's own prefix as an identity goes wrong in both
|
||||
// directions: disjoint roots (src/ and public/) invent simultaneous
|
||||
// identities for one URL, so a waiver scoped to src/foo.html hides a
|
||||
// finding on a page served from public/foo.html; nested roots (prototype/
|
||||
// and prototype/library/, from globs at two depths in one tree) are not
|
||||
// alternatives at all, and demanding a waiver match under both stops
|
||||
// prototype/index.html from applying anywhere. When the globs share no
|
||||
// common root, no prefix is asserted and only the URL path itself matches.
|
||||
function pageCandidates(pathname, roots, pageFiles) {
|
||||
let pagePath = String(pathname || '');
|
||||
try {
|
||||
pagePath = decodeURIComponent(pagePath);
|
||||
} catch {
|
||||
// Malformed percent-escape: match on the raw path rather than throwing.
|
||||
}
|
||||
pagePath = pagePath.replace(/^\/+/, '');
|
||||
// A directory URL serves that directory's index, and the ignore globs
|
||||
// name files. Without this, /news/ never matches prototype/news/index.html.
|
||||
if (pagePath === '' || pagePath.endsWith('/')) pagePath += 'index.html';
|
||||
|
||||
const candidates = new Set();
|
||||
const addSuffixes = (fullPath) => {
|
||||
const parts = fullPath.split('/').filter(Boolean);
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
candidates.add(parts.slice(i).join('/'));
|
||||
}
|
||||
};
|
||||
addSuffixes(pagePath);
|
||||
|
||||
// The served page list names the real files the inject config serves.
|
||||
// A URL that suffix-matches exactly one of them has an unambiguous
|
||||
// project identity; assert that identity and stop guessing from roots
|
||||
// (PR #645 review: with src/ and public/ both served, /foo.html must not
|
||||
// borrow src/foo.html's waivers while actually serving public/foo.html).
|
||||
// Zero matches or several fall through to the common-ancestor fallback:
|
||||
// ambiguity resolves toward showing the finding.
|
||||
const knownPages = [];
|
||||
for (const entry of Array.isArray(pageFiles) ? pageFiles : []) {
|
||||
if (typeof entry !== 'string' || !entry) continue;
|
||||
if (entry === pagePath || entry.endsWith('/' + pagePath)) knownPages.push(entry);
|
||||
}
|
||||
if (knownPages.length === 1) {
|
||||
addSuffixes(knownPages[0]);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
const prefixes = [];
|
||||
for (const entry of Array.isArray(roots) ? roots : []) {
|
||||
if (typeof entry !== 'string') continue;
|
||||
prefixes.push(entry.split('/').filter(Boolean));
|
||||
}
|
||||
let common = prefixes.length > 0 ? prefixes[0] : [];
|
||||
for (const segments of prefixes.slice(1)) {
|
||||
let i = 0;
|
||||
while (i < common.length && i < segments.length && common[i] === segments[i]) i += 1;
|
||||
common = common.slice(0, i);
|
||||
}
|
||||
|
||||
if (common.length > 0) addSuffixes(common.join('/') + '/' + pagePath);
|
||||
return [...candidates];
|
||||
}
|
||||
|
||||
function matchesScope(globs, candidates) {
|
||||
return globs.some((glob) => {
|
||||
let re;
|
||||
try {
|
||||
re = globToRegex(String(glob));
|
||||
} catch {
|
||||
// Malformed glob: skip it, as matchesAnyGlob does in the CLI.
|
||||
return false;
|
||||
}
|
||||
return candidates.some((candidate) => re.test(candidate));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the serialized project ignores for one page.
|
||||
*
|
||||
* @param {object} options
|
||||
* @param {object} options.ignores window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
* in whatever state it arrived: absent, null, or hand-edited into the
|
||||
* wrong shape. Every read tolerates that and degrades to no filtering.
|
||||
* @param {string} options.pathname location.pathname of the scanned page.
|
||||
* @returns {{ disabledRules: string[], disabledValues: Array<{rule: string, value: string}>, skipScan: boolean }}
|
||||
*/
|
||||
function resolveDetectIgnores({ ignores, pathname } = {}) {
|
||||
const config = ignores && typeof ignores === 'object' ? ignores : {};
|
||||
const asArray = (value) => (Array.isArray(value) ? value : []);
|
||||
const candidates = pageCandidates(pathname, config.roots, config.pageFiles);
|
||||
|
||||
// detector.ignoreFiles waives whole files. When any glob names this
|
||||
// page, the scan itself is skipped; rule and value lists are returned
|
||||
// empty because nothing will run.
|
||||
const ignoreFileGlobs = asArray(config.ignoreFiles)
|
||||
.filter((glob) => typeof glob === 'string' && glob.trim());
|
||||
if (ignoreFileGlobs.length > 0 && matchesScope(ignoreFileGlobs, candidates)) {
|
||||
return { disabledRules: [], disabledValues: [], skipScan: true };
|
||||
}
|
||||
|
||||
const disabledRules = new Set(
|
||||
asArray(config.ignoreRules)
|
||||
.filter((rule) => typeof rule === 'string')
|
||||
.map(normalizeIgnoreRule)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const disabledValues = [];
|
||||
|
||||
for (const entry of asArray(config.ignoreValues)) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
const rule = normalizeIgnoreRule(entry.rule);
|
||||
const value = normalizeIgnoreValue(entry.value);
|
||||
if (!rule || !value) continue;
|
||||
const files = [
|
||||
...(typeof entry.file === 'string' && entry.file.trim() ? [entry.file.trim()] : []),
|
||||
...asArray(entry.files).filter((glob) => typeof glob === 'string' && glob.trim()),
|
||||
];
|
||||
if (value === '*') {
|
||||
// Wildcards suppress their rule only inside the files they name.
|
||||
if (files.length > 0 && matchesScope(files, candidates)) disabledRules.add(rule);
|
||||
continue;
|
||||
}
|
||||
if (files.length > 0 && !matchesScope(files, candidates)) continue;
|
||||
disabledValues.push({ rule, value });
|
||||
}
|
||||
|
||||
return { disabledRules: [...disabledRules], disabledValues, skipScan: false };
|
||||
}
|
||||
|
||||
root.__IMPECCABLE_LIVE_IGNORES__ = {
|
||||
version: 1,
|
||||
resolveDetectIgnores,
|
||||
};
|
||||
})(typeof window !== 'undefined' ? window : globalThis);
|
||||
@@ -11143,10 +11143,36 @@ void main() {
|
||||
const scanId = String(++detectScanSeq);
|
||||
activeDetectScanId = scanId;
|
||||
pendingDetectScanId = scanId;
|
||||
// Send the project's detector waivers with the scan so the overlay
|
||||
// filters the same findings the CLI and the edit hook do (issue #639).
|
||||
// live-browser-ignores.js resolves .impeccable config for this page:
|
||||
// ignoreRules suppress outright, wildcard ignoreValues suppress their
|
||||
// rule in the files they name, ignoreFiles that name the page skip the
|
||||
// scan wholesale, and the rest match on the finding's own value inside
|
||||
// the detector. Guarded twice: a stale cached live.js without the
|
||||
// resolver part still scans, and a resolver that throws must not brick
|
||||
// the detect toggle; both degrade to an unfiltered scan.
|
||||
const ignoresApi = window.__IMPECCABLE_LIVE_IGNORES__;
|
||||
let ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
if (typeof ignoresApi?.resolveDetectIgnores === 'function') {
|
||||
try {
|
||||
ignores = ignoresApi.resolveDetectIgnores({
|
||||
ignores: window.__IMPECCABLE_PROJECT_IGNORES__,
|
||||
pathname: location.pathname,
|
||||
}) || ignores;
|
||||
} catch (e) {
|
||||
ignores = { disabledRules: [], disabledValues: [], skipScan: false };
|
||||
}
|
||||
}
|
||||
window.postMessage({
|
||||
source: 'impeccable-command',
|
||||
action: 'scan',
|
||||
config: { scanId },
|
||||
config: {
|
||||
scanId,
|
||||
disabledRules: ignores.disabledRules || [],
|
||||
disabledValues: ignores.disabledValues || [],
|
||||
skipScan: ignores.skipScan === true,
|
||||
},
|
||||
}, '*');
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { resolveLiveConfigPath } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import {
|
||||
describeInjectArtifacts,
|
||||
frameworkIgnorePatterns,
|
||||
@@ -364,7 +365,7 @@ export function resolveFiles(rootDir, config) {
|
||||
const patterns = config.files;
|
||||
const userExcludes = Array.isArray(config.exclude) ? config.exclude : [];
|
||||
const allExcludes = [...HARD_EXCLUDES, ...userExcludes];
|
||||
const excludeRegexes = allExcludes.map(globToRegex);
|
||||
const excludeRegexes = allExcludes.map(livePathGlobToRegex);
|
||||
|
||||
const isExcluded = (relPath) => excludeRegexes.some((re) => re.test(relPath));
|
||||
const isGlob = (s) => /[*?[]/.test(s);
|
||||
@@ -401,47 +402,6 @@ export function resolveFiles(rootDir, config) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a glob pattern to a RegExp. Supports:
|
||||
* ** → any number of path segments (including zero)
|
||||
* * → any chars except `/`
|
||||
* ? → any single char except `/`
|
||||
* Paths are normalized to forward slashes before matching.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
// ** — any number of segments, including zero. Handle the common
|
||||
// **/ and /** forms so `a/**/b` matches `a/b` as well as `a/x/y/b`.
|
||||
if (pattern[i + 2] === '/') {
|
||||
re += '(?:.*/)?';
|
||||
i += 3;
|
||||
} else {
|
||||
re += '.*';
|
||||
i += 2;
|
||||
}
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Core operations
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
writeLiveServerInfo,
|
||||
} from './lib/impeccable-paths.mjs';
|
||||
import { countByPage as countPendingByPage } from './live/manual-edits-buffer.mjs';
|
||||
import { collectProjectDetectorIgnores } from './live/project-ignores.mjs';
|
||||
import {
|
||||
createManualApplyController,
|
||||
summarizeManualApplyFailures,
|
||||
@@ -754,6 +755,17 @@ function createRequestHandler({ detectScript, liveScriptParts }) {
|
||||
commandPrefix: IMPECCABLE_COMMAND_PREFIX,
|
||||
appRoot: process.cwd(),
|
||||
parts,
|
||||
// Read per request rather than cached, so editing the config and
|
||||
// reloading the tab is enough to pick up a new waiver. Config comes
|
||||
// from every root the session spans (appRoot, contextRoot, repoRoot):
|
||||
// in a monorepo the hook and the CLI key it at the repo root, which
|
||||
// is not the appRoot this process chdir'd onto.
|
||||
projectIgnores: collectProjectDetectorIgnores({
|
||||
appRoot: process.cwd(),
|
||||
contextRoot: LIVE_ROOTS?.contextRoot,
|
||||
repoRoot: LIVE_ROOTS?.repoRoot,
|
||||
scriptsDir: __dirname,
|
||||
}),
|
||||
});
|
||||
res.writeHead(200, {
|
||||
'Content-Type': 'application/javascript',
|
||||
|
||||
@@ -24,6 +24,7 @@ import { fileURLToPath } from 'node:url';
|
||||
import { resolveTargetSelection } from './context.mjs';
|
||||
import { resolveFiles } from './live-inject.mjs';
|
||||
import { readLiveServerInfo } from './lib/impeccable-paths.mjs';
|
||||
import { livePathGlobToRegex } from './lib/live-path-globs.mjs';
|
||||
import { resolveSurfaceBrief } from './lib/surface-briefs.mjs';
|
||||
import { resolveLiveTarget } from './live-target.mjs';
|
||||
import { bootInstructions } from './live/instructions.mjs';
|
||||
@@ -240,7 +241,7 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
// Files matching the user's `exclude` globs are intentional omissions,
|
||||
// not drift. Compile them to regexes so the orphan list stays signal.
|
||||
const userExcludeRegexes = (Array.isArray(config.exclude) ? config.exclude : [])
|
||||
.map((p) => globToRegex(p));
|
||||
.map(livePathGlobToRegex);
|
||||
const isUserExcluded = (rel) => userExcludeRegexes.some((re) => re.test(rel));
|
||||
|
||||
const orphans = [];
|
||||
@@ -278,38 +279,6 @@ function scanForDrift(rootDir, resolvedFiles, config) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Same glob-to-regex mapping used by live-inject.mjs. Kept inline here
|
||||
* to avoid a circular import (live-inject.mjs already imports nothing
|
||||
* from live.mjs). The two must stay in sync.
|
||||
*/
|
||||
function globToRegex(pattern) {
|
||||
let re = '';
|
||||
let i = 0;
|
||||
while (i < pattern.length) {
|
||||
const c = pattern[i];
|
||||
if (c === '*') {
|
||||
if (pattern[i + 1] === '*') {
|
||||
if (pattern[i + 2] === '/') { re += '(?:.*/)?'; i += 3; }
|
||||
else { re += '.*'; i += 2; }
|
||||
} else {
|
||||
re += '[^/]*';
|
||||
i += 1;
|
||||
}
|
||||
} else if (c === '?') {
|
||||
re += '[^/]';
|
||||
i += 1;
|
||||
} else if (/[.+^${}()|[\]\\]/.test(c)) {
|
||||
re += '\\' + c;
|
||||
i += 1;
|
||||
} else {
|
||||
re += c;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
return new RegExp('^' + re + '$');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -6,6 +6,7 @@ import { LIVE_CHROME_MOUNT_CONTRACT, LIVE_UI_SURFACES } from './ui-surfaces.mjs'
|
||||
export const LIVE_BROWSER_SCRIPT_PARTS = Object.freeze([
|
||||
Object.freeze({ name: 'session-state', file: 'live-browser-session.js' }),
|
||||
Object.freeze({ name: 'dom-helpers', file: 'live-browser-dom.js' }),
|
||||
Object.freeze({ name: 'project-ignores', file: 'live-browser-ignores.js' }),
|
||||
Object.freeze({ name: 'browser-ui', file: 'live-browser.js' }),
|
||||
]);
|
||||
|
||||
@@ -47,6 +48,11 @@ export function assembleLiveBrowserScript({
|
||||
// so tests can assemble with a stand-in.
|
||||
uiSurfaces = LIVE_UI_SURFACES,
|
||||
mountContract = LIVE_CHROME_MOUNT_CONTRACT,
|
||||
// Project detector waivers ({ ignoreRules, ignoreValues, roots }), read from
|
||||
// .impeccable config by live-server.mjs. live-browser-ignores.js resolves
|
||||
// them against the page when a detect scan starts, so the overlay filters
|
||||
// the same findings the CLI and the edit hook do (issue #639).
|
||||
projectIgnores = null,
|
||||
}) {
|
||||
const prelude =
|
||||
`window.__IMPECCABLE_TOKEN__ = '${token}';\n` +
|
||||
@@ -66,7 +72,8 @@ export function assembleLiveBrowserScript({
|
||||
// repo's tests, the impeccable-site Live UI lab) import the module directly,
|
||||
// which is what keeps the two from drifting.
|
||||
`window.__IMPECCABLE_LIVE_UI_SURFACES__ = ${JSON.stringify(uiSurfaces)};\n` +
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n`;
|
||||
`window.__IMPECCABLE_LIVE_MOUNT_CONTRACT__ = ${JSON.stringify(mountContract)};\n` +
|
||||
`window.__IMPECCABLE_PROJECT_IGNORES__ = ${JSON.stringify(projectIgnores)};\n`;
|
||||
|
||||
const body = parts.map((part) => {
|
||||
const file = part.file || path.basename(part.path || '');
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
/**
|
||||
* Project detector waivers for the live overlay (issue #639, hardened in the
|
||||
* PR #645 follow-up). One place decides what the /live.js prelude serializes
|
||||
* as window.__IMPECCABLE_PROJECT_IGNORES__:
|
||||
*
|
||||
* ignoreRules detector.ignoreRules, unioned across every live root.
|
||||
* ignoreValues detector.ignoreValues entries ({rule, value, files?}),
|
||||
* deduped across roots; createdAt/reason stay local.
|
||||
* ignoreFiles detector.ignoreFiles globs, unioned across roots, so a
|
||||
* wholly waived page scans to zero findings in the overlay
|
||||
* just as it reports nothing through the CLI and the hook.
|
||||
* roots served-root prefixes derived from the inject config's own
|
||||
* `files` globs. Never derived from the ignore globs: one
|
||||
* entry scoped to prototype/library/** would lend
|
||||
* prototype/library/ as a candidate prefix to every page,
|
||||
* and that rule would suppress site-wide (issue #639).
|
||||
* pageFiles the inject config's `files` expanded to real project
|
||||
* files, so the browser can resolve a URL to the one file it
|
||||
* actually serves instead of trying every root (PR #645
|
||||
* review: with src/ and public/ both served, /foo.html must
|
||||
* not borrow src/foo.html's waivers while actually serving
|
||||
* public/foo.html).
|
||||
*
|
||||
* Config is read from every root the live session spans: the appRoot the
|
||||
* server chdir'd onto, plus contextRoot and repoRoot when they differ. The
|
||||
* edit hook keys the same config at the session cwd (the repo root in a
|
||||
* monorepo, via resolveCacheCwd), and `impeccable detect` reads it from its
|
||||
* invocation cwd, so reading only the appRoot silently dropped every waiver
|
||||
* in exactly the monorepo layouts the roots manifest exists for. Reading is
|
||||
* additive across roots, matching readConfig's own union of config.json and
|
||||
* config.local.json.
|
||||
*
|
||||
* In a monorepo, roots and pageFiles are serialized repo-relative (the
|
||||
* appRoot's path inside the repo is prefixed), so waivers spelled from
|
||||
* either root match through the resolver's suffix expansion.
|
||||
*/
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { readConfig } from '../hook-lib.mjs';
|
||||
import { resolveFiles } from '../live-inject.mjs';
|
||||
import { resolveLiveConfigPath } from '../lib/impeccable-paths.mjs';
|
||||
|
||||
// Serializing thousands of page identities into every /live.js response
|
||||
// helps nobody; past this cap pageFiles is omitted and the resolver falls
|
||||
// back to the served-root common ancestor, which is correct, just less
|
||||
// precise about cross-root duplicates.
|
||||
const PAGE_FILES_CAP = 500;
|
||||
|
||||
export function collectProjectDetectorIgnores({ appRoot, contextRoot, repoRoot, scriptsDir } = {}) {
|
||||
const configRoots = [];
|
||||
for (const dir of [appRoot, contextRoot, repoRoot]) {
|
||||
if (typeof dir !== 'string' || !dir) continue;
|
||||
const resolved = path.resolve(dir);
|
||||
if (!configRoots.includes(resolved)) configRoots.push(resolved);
|
||||
}
|
||||
if (configRoots.length === 0) configRoots.push(process.cwd());
|
||||
|
||||
const ignoreRules = new Set();
|
||||
const ignoreFiles = new Set();
|
||||
const valueEntries = new Map();
|
||||
for (const dir of configRoots) {
|
||||
// readConfig merges config.json with the gitignored config.local.json
|
||||
// and type-checks both, exactly as the edit hook reads the same pair.
|
||||
const config = readConfig(dir);
|
||||
for (const rule of Array.isArray(config.ignoreRules) ? config.ignoreRules : []) {
|
||||
if (typeof rule === 'string' && rule.trim()) ignoreRules.add(rule);
|
||||
}
|
||||
for (const glob of Array.isArray(config.ignoreFiles) ? config.ignoreFiles : []) {
|
||||
if (typeof glob === 'string' && glob.trim()) ignoreFiles.add(glob);
|
||||
}
|
||||
for (const entry of Array.isArray(config.ignoreValues) ? config.ignoreValues : []) {
|
||||
if (!entry || typeof entry !== 'object') continue;
|
||||
// readConfig already normalized rule/value and folded `file` into
|
||||
// `files`; serve only what the browser matches on.
|
||||
const serialized = {
|
||||
rule: entry.rule,
|
||||
value: entry.value,
|
||||
...(Array.isArray(entry.files) && entry.files.length > 0 ? { files: entry.files } : {}),
|
||||
};
|
||||
const key = JSON.stringify([serialized.rule, serialized.value,
|
||||
Array.isArray(serialized.files) ? [...serialized.files].sort() : []]);
|
||||
if (!valueEntries.has(key)) valueEntries.set(key, serialized);
|
||||
}
|
||||
}
|
||||
|
||||
const served = readLiveServedPages({ appRoot: configRoots[0], repoRoot, scriptsDir });
|
||||
return {
|
||||
ignoreRules: [...ignoreRules],
|
||||
ignoreValues: [...valueEntries.values()],
|
||||
ignoreFiles: [...ignoreFiles],
|
||||
roots: served.roots,
|
||||
pageFiles: served.pageFiles,
|
||||
};
|
||||
}
|
||||
|
||||
function readLiveServedPages({ appRoot, repoRoot, scriptsDir }) {
|
||||
let live = null;
|
||||
try {
|
||||
const configPath = resolveLiveConfigPath({ cwd: appRoot, scriptsDir });
|
||||
live = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
|
||||
} catch {
|
||||
// No readable inject config: the browser matches URL paths as-is.
|
||||
return { roots: [], pageFiles: [] };
|
||||
}
|
||||
const files = Array.isArray(live?.files)
|
||||
? live.files.filter((glob) => typeof glob === 'string' && glob)
|
||||
: [];
|
||||
|
||||
// A monorepo appRoot serializes identities repo-relative, so waivers
|
||||
// spelled from either root match through the resolver's suffix expansion.
|
||||
let prefix = '';
|
||||
if (typeof repoRoot === 'string' && repoRoot) {
|
||||
const rel = path.relative(path.resolve(repoRoot), path.resolve(appRoot)).split(path.sep).join('/');
|
||||
if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) prefix = `${rel}/`;
|
||||
}
|
||||
|
||||
const roots = [...new Set(files.map((glob) => {
|
||||
const wildcardAt = glob.search(/[*?{]/);
|
||||
const head = wildcardAt === -1 ? glob : glob.slice(0, wildcardAt);
|
||||
const cut = head.lastIndexOf('/');
|
||||
return prefix + (cut > -1 ? head.slice(0, cut + 1) : '');
|
||||
}))];
|
||||
|
||||
let pageFiles = [];
|
||||
try {
|
||||
pageFiles = resolveFiles(appRoot, { ...live, files })
|
||||
.filter((rel) => {
|
||||
// resolveFiles passes literal entries through even when they do not
|
||||
// exist; a missing file is nobody's identity.
|
||||
try { return fs.statSync(path.join(appRoot, rel)).isFile(); } catch { return false; }
|
||||
})
|
||||
.map((rel) => prefix + rel);
|
||||
} catch {
|
||||
pageFiles = [];
|
||||
}
|
||||
if (pageFiles.length > PAGE_FILES_CAP) pageFiles = [];
|
||||
|
||||
return { roots, pageFiles };
|
||||
}
|
||||
@@ -1019,7 +1019,9 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// exits on any pick and has no update channel, so a followup payload there
|
||||
// still gets the goodbye screen, never a loading hand nothing will resolve.
|
||||
const FOLLOWUP = ${payload.followup === true && Boolean(detachedKey) ? 'true' : 'false'};
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat'); } catch { fetch('/heartbeat', { method: 'POST' }); } };
|
||||
const KEY = ${JSON.stringify(detachedKey || '')};
|
||||
const keyQ = KEY ? '?key=' + encodeURIComponent(KEY) : '';
|
||||
const beat = () => { try { navigator.sendBeacon('/heartbeat' + keyQ); } catch { fetch('/heartbeat' + keyQ, { method: 'POST' }); } };
|
||||
${waiting && waitBudgetMs <= 0 ? '' : 'beat();'}
|
||||
const beatTimer = setInterval(beat, 5000);
|
||||
// A dead server must fail loudly: awaiting a rejected fetch here used to
|
||||
@@ -1030,7 +1032,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// is in flight would overwrite the answer being collected.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId, steer: steer() }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1304,7 +1306,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
};
|
||||
const apply = (value) => {
|
||||
set(value);
|
||||
fetch('/build-path', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
fetch('/build-path' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ value }) });
|
||||
if (value === 'comp') enterComp(); else exitComp();
|
||||
};
|
||||
// Flipping to comp starts real generation, so it confirms first; the
|
||||
@@ -1472,7 +1474,7 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
// re-roll and renewed the delivery deadline.
|
||||
document.querySelectorAll('.reroll-btn, #canon').forEach(b => b.setAttribute('disabled', ''));
|
||||
try {
|
||||
await fetch('/answer', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
await fetch('/answer' + keyQ, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ optionId: 'reroll', steer: steer(), ...(register ? { register } : {}) }) });
|
||||
} catch {
|
||||
document.body.innerHTML = '<div class="done">The question server went away before this choice could land.<br>Tell the agent your pick in the chat instead.</div>';
|
||||
return;
|
||||
@@ -1566,8 +1568,39 @@ ${buildPath?.toggle ? `<div id="bp-confirm" role="dialog" aria-modal="true" aria
|
||||
</script>`;
|
||||
}
|
||||
|
||||
// Browsers omit the :80 suffix on the default HTTP port, so a server on
|
||||
// --port 80 sees bare loopback hosts and origins.
|
||||
function allowedHost(host, port) {
|
||||
if (host === `127.0.0.1:${port}` || host === `localhost:${port}`) return true;
|
||||
return port === 80 && (host === '127.0.0.1' || host === 'localhost');
|
||||
}
|
||||
|
||||
function allowedOrigin(origin, port) {
|
||||
if (origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`) return true;
|
||||
return port === 80 && (origin === 'http://127.0.0.1' || origin === 'http://localhost');
|
||||
}
|
||||
|
||||
function rejectDetachedPost(req, res, url, port) {
|
||||
if (detachedKey && url.searchParams.get('key') !== detachedKey) {
|
||||
res.writeHead(401); res.end(); return true;
|
||||
}
|
||||
const origin = req.headers.origin;
|
||||
if (origin && !allowedOrigin(origin, port)) {
|
||||
res.writeHead(403); res.end(); return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const server = http.createServer((req, res) => {
|
||||
if (req.method === 'GET' && req.url === '/') {
|
||||
const { port } = server.address();
|
||||
if (!allowedHost(req.headers.host, port)) {
|
||||
res.writeHead(403); res.end(); return;
|
||||
}
|
||||
let url;
|
||||
try { url = new URL(req.url, 'http://127.0.0.1'); }
|
||||
catch { res.writeHead(400); res.end(); return; }
|
||||
const pathname = url.pathname;
|
||||
if (req.method === 'GET' && pathname === '/') {
|
||||
const pending = nextFile();
|
||||
if (pending && fs.existsSync(pending)) {
|
||||
// A next file the round cannot load has to leave the disk either way:
|
||||
@@ -1593,7 +1626,8 @@ const server = http.createServer((req, res) => {
|
||||
res.end(page(awaitingNext));
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/heartbeat') {
|
||||
if (req.method === 'POST' && pathname === '/heartbeat') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
res.writeHead(204); res.end();
|
||||
server.lastBeatSeen = Date.now();
|
||||
if (detachedKey) {
|
||||
@@ -1609,13 +1643,13 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (req.method === 'GET' && req.url === '/next-status') {
|
||||
if (req.method === 'GET' && pathname === '/next-status') {
|
||||
const pending = nextFile();
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify({ ready: Boolean(pending && fs.existsSync(pending)) }));
|
||||
return;
|
||||
}
|
||||
const imageMatch = req.method === 'GET' && req.url?.match(/^\/img\/(\d+)(?:\?.*)?$/);
|
||||
const imageMatch = req.method === 'GET' && pathname.match(/^\/img\/(\d+)$/);
|
||||
if (imageMatch) {
|
||||
const abs = localImages[Number(imageMatch[1])];
|
||||
if (!abs || !fs.existsSync(abs)) { res.writeHead(404); res.end(); return; }
|
||||
@@ -1628,27 +1662,34 @@ const server = http.createServer((req, res) => {
|
||||
fs.createReadStream(abs).pipe(res);
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/build-path') {
|
||||
if (req.method === 'POST' && pathname === '/build-path') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
let value = null;
|
||||
try { value = JSON.parse(body).value; } catch { /* ignore */ }
|
||||
if (value !== 'comp' && value !== 'code') return;
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
if (value === 'comp' || value === 'code') {
|
||||
const wasComp = liveBuildPath === 'comp';
|
||||
liveBuildPath = value;
|
||||
// Only a flip TO comp needs the agent mid-round: comps must start
|
||||
// rendering into the declared slots. The reverse is free.
|
||||
if (detachedKey && value === 'comp' && !wasComp) {
|
||||
fs.mkdirSync(QUESTION_DIR, { recursive: true });
|
||||
fs.writeFileSync(flipFile(detachedKey), JSON.stringify({ buildPath: 'comp' }) + '\n');
|
||||
}
|
||||
}
|
||||
// Answer only once the flip is on disk. Responding first raced the
|
||||
// caller: the 200 reached the client (a separate process) while this
|
||||
// one could still be preempted before the write landed, so a poller
|
||||
// that trusted the 200 could look for the flip file and miss it.
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
res.end('{"ok":true}');
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (req.method === 'POST' && req.url === '/answer') {
|
||||
if (req.method === 'POST' && pathname === '/answer') {
|
||||
if (rejectDetachedPost(req, res, url, port)) return;
|
||||
let body = '';
|
||||
req.on('data', (chunk) => { body += chunk; });
|
||||
req.on('end', () => {
|
||||
|
||||
@@ -1472,7 +1472,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -1675,6 +1687,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -1892,6 +2017,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -1945,7 +2076,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
@@ -8131,7 +8131,19 @@ if (IS_BROWSER) {
|
||||
return findings;
|
||||
}
|
||||
|
||||
// A page matched by detector.ignoreFiles is waived wholesale: every scan
|
||||
// stage answers empty so the badge and toast read zero. Mirrors
|
||||
// shouldIgnoreDetectionFile in cli/lib/impeccable-config.mjs; the live
|
||||
// overlay resolves the globs per page (live-browser-ignores.js) and
|
||||
// forwards the verdict as config.skipScan.
|
||||
function skipScanActive() {
|
||||
return EXTENSION_MODE && window.__IMPECCABLE_CONFIG__?.skipScan === true;
|
||||
}
|
||||
|
||||
function collectBrowserFindings() {
|
||||
if (skipScanActive()) {
|
||||
return { groupMap: new Map(), allFindings: [], pageLevelFindings: [] };
|
||||
}
|
||||
const groupMap = new Map();
|
||||
const _disabled = EXTENSION_MODE ? (window.__IMPECCABLE_CONFIG__?.disabledRules || []) : [];
|
||||
const _ruleOk = (id) => !_disabled.length || !_disabled.includes(id);
|
||||
@@ -8334,6 +8346,119 @@ if (IS_BROWSER) {
|
||||
addBrowserFindings(groupMap, document.body, mapped);
|
||||
}
|
||||
|
||||
// Value-level suppression (issue #639). `disabledRules` above handles
|
||||
// whole rules; this applies the config's remaining ignoreValues entries,
|
||||
// which the CLI filters through isIgnoredFindingValue in
|
||||
// cli/lib/impeccable-config.mjs, so a project waiver like
|
||||
// overused-font = "geist mono" reaches the overlay and extension too.
|
||||
const _normValue = (v) => String(v || '').trim().replace(/^["']|["']$/g, '')
|
||||
.replace(/\+/g, ' ').replace(/\s+/g, ' ').toLowerCase();
|
||||
const _disabledValues = EXTENSION_MODE
|
||||
? (Array.isArray(window.__IMPECCABLE_CONFIG__?.disabledValues) ? window.__IMPECCABLE_CONFIG__.disabledValues : [])
|
||||
.filter(e => e && typeof e === 'object' && e.rule && e.value)
|
||||
.map(e => ({ rule: String(e.rule).trim().toLowerCase(), value: _normValue(e.value) }))
|
||||
: [];
|
||||
if (_disabledValues.length > 0) {
|
||||
// The six rules whose findings carry a matchable value; keep in step
|
||||
// with extractFindingIgnoreValue in cli/lib/impeccable-config.mjs.
|
||||
// Everything else is suppressed by rule or by file scope, both already
|
||||
// resolved into disabledRules before the scan message was sent.
|
||||
const _directValueRules = new Set([
|
||||
'overused-font',
|
||||
'bounce-easing',
|
||||
'design-system-font',
|
||||
'design-system-color',
|
||||
'design-system-radius',
|
||||
'design-system-font-size',
|
||||
]);
|
||||
// The design-system checks set `ignoreValue` on their findings; the
|
||||
// detail fallbacks catch overused-font, whose value lives in its
|
||||
// sentence. One CLI matcher is not mirrored here: the motion extractor
|
||||
// (a value-scoped bounce-easing waiver only matches when the finding
|
||||
// carries ignoreValue directly). The CLI's [?&]family= URL fallback is
|
||||
// also omitted on purpose: browser findings for these rules always
|
||||
// carry ignoreValue or a "Primary font:" / "Google Fonts:" /
|
||||
// font-family sentence, so it is unreachable here.
|
||||
const _findingValue = (f) => {
|
||||
if (!f || !_directValueRules.has(f.type || f.id)) return '';
|
||||
const direct = f.ignoreValue || f.value;
|
||||
if (direct) return _normValue(direct);
|
||||
// The CLI routes bounce-easing through extractMotionIgnoreValue and
|
||||
// never the font regexes; without a direct ignoreValue there is no
|
||||
// value to match, so do not invent one from unrelated CSS text.
|
||||
if ((f.type || f.id) === 'bounce-easing') return '';
|
||||
for (const text of [f.detail, f.snippet]) {
|
||||
if (typeof text !== 'string' || !text) continue;
|
||||
const primary = text.match(/Primary font:\s*([^()\n;]+)/i);
|
||||
if (primary) return _normValue(primary[1]);
|
||||
const google = text.match(/Google Fonts:\s*([^()\n;]+)/i);
|
||||
if (google) return _normValue(google[1]);
|
||||
const family = text.match(/font-family\s*:\s*["']?([^'",;\n]+)/i);
|
||||
if (family) return _normValue(family[1]);
|
||||
}
|
||||
return '';
|
||||
};
|
||||
// design-system-color compares by color value, not by spelling: the
|
||||
// browser reports computed rgb(...) strings while waivers are usually
|
||||
// written as hex. Mirrors ignoreValueMatches -> colorIgnoreKey in
|
||||
// cli/lib/impeccable-config.mjs for the hex and rgb()/rgba() forms;
|
||||
// hsl stays CLI-only.
|
||||
const _colorKey = (value) => {
|
||||
const text = String(value || '').trim().toLowerCase();
|
||||
const hex = text.match(/^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/);
|
||||
if (hex) {
|
||||
const expanded = hex[1].length <= 4 ? [...hex[1]].map(d => d + d).join('') : hex[1];
|
||||
const [r, g, b, a = 255] = expanded.match(/../g).map(ch => parseInt(ch, 16));
|
||||
return `${r},${g},${b},${a}`;
|
||||
}
|
||||
const rgb = text.match(/^rgba?\((.*)\)$/);
|
||||
if (!rgb) return '';
|
||||
const body = rgb[1].trim().replace(/\s*\/\s*/g, ' / ');
|
||||
let parts;
|
||||
if (body.includes(',')) {
|
||||
parts = body.split(',').map(p => p.trim()).filter(Boolean);
|
||||
const last = parts[parts.length - 1];
|
||||
if (last && last.includes('/')) {
|
||||
parts = [...parts.slice(0, -1), ...last.split('/').map(p => p.trim()).filter(Boolean)];
|
||||
}
|
||||
} else {
|
||||
parts = body.split(/\s+/).filter(p => p && p !== '/');
|
||||
}
|
||||
if (parts.length < 3 || parts.length > 4) return '';
|
||||
const channel = (raw, isAlpha) => {
|
||||
const m = String(raw).trim().match(/^(-?\d*\.?\d+)(%)?$/);
|
||||
if (!m) return null;
|
||||
let v = parseFloat(m[1]);
|
||||
if (m[2]) v = isAlpha ? v / 100 : v * 2.55;
|
||||
const max = isAlpha ? 1 : 255;
|
||||
if (!Number.isFinite(v) || v < 0 || v > max) return null;
|
||||
return isAlpha ? v : Math.round(v);
|
||||
};
|
||||
const r = channel(parts[0], false);
|
||||
const g = channel(parts[1], false);
|
||||
const b = channel(parts[2], false);
|
||||
const a = parts[3] === undefined ? 1 : channel(parts[3], true);
|
||||
if ([r, g, b, a].some(v => v === null)) return '';
|
||||
return `${r},${g},${b},${Math.round(a * 255)}`;
|
||||
};
|
||||
const _valueIgnored = (f) => {
|
||||
const value = _findingValue(f);
|
||||
if (!value) return false;
|
||||
const rule = f.type || f.id;
|
||||
return _disabledValues.some(e => e.rule === rule && (e.value === value
|
||||
|| (rule === 'design-system-color'
|
||||
&& _colorKey(e.value) !== '' && _colorKey(e.value) === _colorKey(value))));
|
||||
};
|
||||
for (const [el, list] of [...groupMap.entries()]) {
|
||||
const kept = list.filter(f => !_valueIgnored(f));
|
||||
if (kept.length > 0) groupMap.set(el, kept);
|
||||
else groupMap.delete(el);
|
||||
}
|
||||
for (let i = pageLevelFindings.length - 1; i >= 0; i--) {
|
||||
if (_valueIgnored(pageLevelFindings[i])) pageLevelFindings.splice(i, 1);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
groupMap,
|
||||
allFindings: browserFindingsFromMap(groupMap),
|
||||
@@ -8551,6 +8676,12 @@ if (IS_BROWSER) {
|
||||
|
||||
async function collectBrowserFindingsAsync(options = {}, runtime = {}) {
|
||||
const collected = collectBrowserFindings();
|
||||
// The visual pass walks the DOM on its own; on a skipScan page it would
|
||||
// repopulate the emptied scan, so it is skipped with everything else.
|
||||
if (skipScanActive()) {
|
||||
lastVisualContrastAnalyses = [];
|
||||
return { ...collected, allFindings: [], visualContrastAnalyses: [] };
|
||||
}
|
||||
await addVisualContrastFindings(collected.groupMap, options, runtime);
|
||||
return {
|
||||
...collected,
|
||||
@@ -8604,7 +8735,7 @@ if (IS_BROWSER) {
|
||||
const generation = scanGeneration;
|
||||
const collected = collectBrowserFindings();
|
||||
const allFindings = renderBrowserFindings(collected, options);
|
||||
if (shouldRunVisualContrast(options)) {
|
||||
if (!skipScanActive() && shouldRunVisualContrast(options)) {
|
||||
addVisualContrastFindings(collected.groupMap, options, { decorate: true, generation })
|
||||
.then(() => {
|
||||
if (generation === scanGeneration) postSerializedFindings(collected.groupMap, options);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user