@whzxc/agent-design-gallery 0.8.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -1
- package/package.json +4 -1
- package/src/cli-output.mjs +40 -1
- package/src/cli.mjs +57 -8
- package/src/toolkit/arch-git.mjs +19 -0
- package/src/toolkit/build-store.mjs +6 -4
- package/src/toolkit/build-worker.mjs +5 -2
- package/src/toolkit/build.mjs +20 -5
- package/src/toolkit/commands.mjs +44 -14
- package/src/toolkit/config.mjs +6 -5
- package/src/toolkit/diff-inputs.mjs +5 -5
- package/src/toolkit/diff.mjs +14 -10
- package/src/toolkit/frame-document.mjs +6 -0
- package/src/toolkit/impact-eligibility.mjs +136 -0
- package/src/toolkit/impact-inputs.mjs +71 -0
- package/src/toolkit/impact-output.mjs +46 -0
- package/src/toolkit/impact-proof.mjs +67 -0
- package/src/toolkit/impact-selection.mjs +96 -0
- package/src/toolkit/impact.mjs +403 -0
- package/src/toolkit/implementation-map.mjs +129 -0
- package/src/toolkit/implementation-query.mjs +53 -0
- package/src/toolkit/index-store.mjs +99 -0
- package/src/toolkit/json-locations.mjs +28 -0
- package/src/toolkit/owner-authoring.mjs +39 -0
- package/src/toolkit/owner-colors.mjs +70 -0
- package/src/toolkit/owner-locators.mjs +73 -0
- package/src/toolkit/owner-observation.mjs +271 -0
- package/src/toolkit/owner-search.mjs +156 -0
- package/src/toolkit/owner.mjs +159 -0
- package/src/toolkit/project-index.mjs +188 -0
- package/src/toolkit/results.mjs +2 -2
- package/src/toolkit/runtime.d.ts +1 -1
- package/src/toolkit/runtime.mjs +1 -0
- package/src/toolkit/source-facts.mjs +25 -0
- package/src/toolkit/token-reachability.mjs +71 -0
- package/src/toolkit/tokens.mjs +9 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
+
import { mkdir, readFile, writeFile, rename, unlink, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const indexDigest = value => createHash('sha256').update(value).digest('hex');
|
|
6
|
+
const absent = error => error.code === 'ENOENT';
|
|
7
|
+
|
|
8
|
+
/** Disposable immutable shards. Each rename advertises one completed projection. */
|
|
9
|
+
export async function createIndexStore({ directory, persist = true, memoryLimit = 32 * 1024 * 1024, diskLimit = 256 * 1024 * 1024 }) {
|
|
10
|
+
const memory = new Map(), access = new Map(), disk = new Map();
|
|
11
|
+
let memoryBytes = 0, diskBytes = 0, queue = Promise.resolve(), closed = false, dirty = false;
|
|
12
|
+
const counters = { memoryHits: 0, diskHits: 0, writes: 0, directoryScans: 0, manifestWrites: 0 };
|
|
13
|
+
const touch = name => {
|
|
14
|
+
access.delete(name); access.set(name, Date.now());
|
|
15
|
+
if (access.size > 4096) access.delete(access.keys().next().value);
|
|
16
|
+
};
|
|
17
|
+
if (persist) await mkdir(directory, { recursive: true });
|
|
18
|
+
const remember = (key, bytes) => {
|
|
19
|
+
const old = memory.get(key);
|
|
20
|
+
if (old) { memory.delete(key); memoryBytes -= old.length; }
|
|
21
|
+
if (bytes.length > memoryLimit) return;
|
|
22
|
+
memory.set(key, bytes); memoryBytes += bytes.length;
|
|
23
|
+
while (memoryBytes > memoryLimit) { const [first, value] = memory.entries().next().value; memory.delete(first); memoryBytes -= value.length; }
|
|
24
|
+
};
|
|
25
|
+
async function inventory() {
|
|
26
|
+
counters.directoryScans++; disk.clear(); diskBytes = 0;
|
|
27
|
+
for (const name of await readdir(directory)) if (/^[a-f0-9]{64}\.json$/.test(name)) {
|
|
28
|
+
try { const info = await stat(path.join(directory, name)); disk.set(name, { bytes: info.size, accessed: access.get(name) ?? info.mtimeMs }); diskBytes += info.size; }
|
|
29
|
+
catch (error) { if (!absent(error)) throw error; }
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
async function trim() {
|
|
33
|
+
if (diskBytes <= diskLimit) return;
|
|
34
|
+
const retained = [...disk].sort(([a, x], [b, y]) => (access.get(a) ?? x.accessed) - (access.get(b) ?? y.accessed) || a.localeCompare(b));
|
|
35
|
+
// Evict a batch so subsequent writes do not repeatedly sort the whole cache.
|
|
36
|
+
const target = diskLimit * 0.9;
|
|
37
|
+
while (diskBytes > target && retained.length) {
|
|
38
|
+
const [name, file] = retained.shift();
|
|
39
|
+
try { await unlink(path.join(directory, name)); } catch (error) { if (!absent(error)) throw error; }
|
|
40
|
+
access.delete(name); disk.delete(name); diskBytes -= file.bytes; dirty = true;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
async function atomic(file, bytes) {
|
|
44
|
+
const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
|
|
45
|
+
try { await writeFile(temporary, bytes); await rename(temporary, file); }
|
|
46
|
+
finally { try { await unlink(temporary); } catch (error) { if (!absent(error)) throw error; } }
|
|
47
|
+
}
|
|
48
|
+
if (persist) { await inventory(); await trim(); }
|
|
49
|
+
return {
|
|
50
|
+
async get(key) {
|
|
51
|
+
if (closed) throw Error('Project index store is closed.');
|
|
52
|
+
const name = indexDigest(key) + '.json';
|
|
53
|
+
let bytes = memory.get(key);
|
|
54
|
+
if (bytes) { counters.memoryHits++; remember(key, bytes); }
|
|
55
|
+
else if (persist) {
|
|
56
|
+
try { bytes = await readFile(path.join(directory, name)); }
|
|
57
|
+
catch (error) { if (!absent(error)) throw error; }
|
|
58
|
+
if (bytes) counters.diskHits++;
|
|
59
|
+
}
|
|
60
|
+
if (!bytes) return null;
|
|
61
|
+
touch(name);
|
|
62
|
+
try {
|
|
63
|
+
const saved = JSON.parse(bytes.toString('utf8'));
|
|
64
|
+
if (saved.version !== 1 || saved.key !== key || !Object.hasOwn(saved, 'value')) return null;
|
|
65
|
+
remember(key, bytes);
|
|
66
|
+
return saved.value;
|
|
67
|
+
} catch (error) { if (error instanceof SyntaxError) return null; throw error; }
|
|
68
|
+
},
|
|
69
|
+
put(key, value) {
|
|
70
|
+
if (closed) throw Error('Project index store is closed.');
|
|
71
|
+
const bytes = Buffer.from(JSON.stringify({ version: 1, key, value }));
|
|
72
|
+
const operation = queue.then(async () => {
|
|
73
|
+
if (persist && bytes.length <= diskLimit) {
|
|
74
|
+
const name = indexDigest(key) + '.json';
|
|
75
|
+
await atomic(path.join(directory, name), bytes); touch(name);
|
|
76
|
+
diskBytes += bytes.length - (disk.get(name)?.bytes ?? 0);
|
|
77
|
+
disk.set(name, { bytes: bytes.length, accessed: Date.now() }); dirty = true;
|
|
78
|
+
await trim();
|
|
79
|
+
counters.writes++;
|
|
80
|
+
}
|
|
81
|
+
remember(key, bytes);
|
|
82
|
+
});
|
|
83
|
+
queue = operation.catch(() => {});
|
|
84
|
+
return operation;
|
|
85
|
+
},
|
|
86
|
+
stats: () => ({ ...counters, memoryBytes, diskBytes, entries: memory.size }),
|
|
87
|
+
async close() {
|
|
88
|
+
if (closed) return; closed = true; await queue;
|
|
89
|
+
try {
|
|
90
|
+
if (persist && dirty) {
|
|
91
|
+
// Reconcile other finite writers once, rather than on every shard write.
|
|
92
|
+
await inventory(); await trim();
|
|
93
|
+
await atomic(path.join(directory, 'manifest.json'), JSON.stringify({ version: 1, entries: [...disk].map(([file, { bytes }]) => ({ file, bytes })) }));
|
|
94
|
+
counters.manifestWrites++;
|
|
95
|
+
}
|
|
96
|
+
} finally { memory.clear(); memoryBytes = 0; access.clear(); disk.clear(); }
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/** Value-token locations for already validated JSON, keyed by JSON Pointer. */
|
|
2
|
+
export function jsonLocations(text) {
|
|
3
|
+
let offset = 0, line = 1, column = 1; const locations = {};
|
|
4
|
+
const advance = () => { if (text[offset++] === '\n') { line++; column = 1; } else column++; };
|
|
5
|
+
const whitespace = () => { while (/\s/.test(text[offset] ?? '') && offset < text.length) advance(); };
|
|
6
|
+
const string = () => {
|
|
7
|
+
const start = offset; advance();
|
|
8
|
+
while (offset < text.length) { if (text[offset] === '\\') { advance(); advance(); } else if (text[offset] === '"') { advance(); break; } else advance(); }
|
|
9
|
+
return JSON.parse(text.slice(start, offset));
|
|
10
|
+
};
|
|
11
|
+
const value = pointer => {
|
|
12
|
+
whitespace(); locations[pointer] = { line, column };
|
|
13
|
+
if (text[offset] === '{') {
|
|
14
|
+
advance(); whitespace();
|
|
15
|
+
while (text[offset] !== '}') {
|
|
16
|
+
const key = string().replaceAll('~', '~0').replaceAll('/', '~1'); whitespace(); advance(); value(pointer + '/' + key); whitespace();
|
|
17
|
+
if (text[offset] !== ',') break; advance(); whitespace();
|
|
18
|
+
}
|
|
19
|
+
advance();
|
|
20
|
+
} else if (text[offset] === '[') {
|
|
21
|
+
advance(); whitespace(); let index = 0;
|
|
22
|
+
while (text[offset] !== ']') { value(pointer + '/' + index++); whitespace(); if (text[offset] !== ',') break; advance(); }
|
|
23
|
+
advance();
|
|
24
|
+
} else if (text[offset] === '"') string();
|
|
25
|
+
else while (offset < text.length && !/[\s,}\]]/.test(text[offset])) advance();
|
|
26
|
+
};
|
|
27
|
+
value(''); return locations;
|
|
28
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { compareNames } from './owner.mjs';
|
|
5
|
+
|
|
6
|
+
export function orderAuthoredIn(locations, preferred) {
|
|
7
|
+
const priority = [...new Set(preferred)], rank = source => { const i = priority.indexOf(source); return i < 0 ? priority.length : i; };
|
|
8
|
+
return [...new Map(locations.map(location => [JSON.stringify(location), location])).values()]
|
|
9
|
+
.sort((a, b) => rank(a.source) - rank(b.source) || compareNames(a.source, b.source) || a.line - b.line);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/** Literal candidates, not source attribution: search only this build's code/data closure. */
|
|
13
|
+
export function textAuthoring(config, source, built) {
|
|
14
|
+
const root = realpathSync(config.root), design = realpathSync(config.design);
|
|
15
|
+
const files = [...new Set([source, ...built.dependencies.map(file => path.relative(root, path.isAbsolute(file) ? realpathSync(file) : path.join(design, file)).split(path.sep).join('/'))])]
|
|
16
|
+
.filter(file => /\.(?:[cm]?[jt]sx?|json)$/.test(file)).sort(compareNames);
|
|
17
|
+
const contents = new Map(), literals = new Map();
|
|
18
|
+
return async (match, ownerSources) => {
|
|
19
|
+
const raw = [...new Set(match.fragments.filter(fragment => /\/text-\d+$/.test(fragment.elementPath) && fragment.text.trim()).map(fragment => fragment.text))];
|
|
20
|
+
const locations = [];
|
|
21
|
+
for (const literal of raw) {
|
|
22
|
+
if (!literals.has(literal)) {
|
|
23
|
+
const found = [];
|
|
24
|
+
for (const file of files) {
|
|
25
|
+
if (!contents.has(file)) contents.set(file, await readFile(path.join(root, file), 'utf8'));
|
|
26
|
+
const text = contents.get(file);
|
|
27
|
+
let start = 0, offset;
|
|
28
|
+
while ((offset = text.indexOf(literal, start)) >= 0) {
|
|
29
|
+
found.push({ source: file, line: text.slice(0, offset).split('\n').length });
|
|
30
|
+
start = offset + literal.length;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
literals.set(literal, found);
|
|
34
|
+
}
|
|
35
|
+
locations.push(...literals.get(literal));
|
|
36
|
+
}
|
|
37
|
+
return orderAuthoredIn(locations, [ownerSources[0], source, ...ownerSources].filter(Boolean));
|
|
38
|
+
};
|
|
39
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { CliError } from '../cli-output.mjs';
|
|
2
|
+
|
|
3
|
+
const byte = value => Math.round(Math.max(0, Math.min(1, value)) * 255);
|
|
4
|
+
export const colorHex = rgba => '#' + rgba.map(value => value.toString(16).padStart(2, '0')).join('');
|
|
5
|
+
const alpha = raw => raw === undefined ? 255 : byte(Number(raw.replace('%', '')) / (raw.endsWith('%') ? 100 : 1));
|
|
6
|
+
|
|
7
|
+
/** Only syntax whose quantization is identical to the Chromium resolver is fast. */
|
|
8
|
+
export function fastColor(input) {
|
|
9
|
+
const value = input.trim().toLowerCase(); let rgba;
|
|
10
|
+
if (/^#[\da-f]{3,4}$/.test(value)) rgba = [...value.slice(1)].map(char => parseInt(char + char, 16));
|
|
11
|
+
else if (/^#(?:[\da-f]{6}|[\da-f]{8})$/.test(value)) rgba = value.slice(1).match(/../g).map(char => parseInt(char, 16));
|
|
12
|
+
else if (value === 'transparent') rgba = [0, 0, 0, 0];
|
|
13
|
+
else {
|
|
14
|
+
const rgb = /^rgba?\((.*)\)$/.exec(value);
|
|
15
|
+
if (rgb) {
|
|
16
|
+
const parts = rgb[1].includes(',') ? rgb[1].split(',').map(x => x.trim()) : rgb[1].split(/[\s/]+/).filter(Boolean);
|
|
17
|
+
const separators = rgb[1].includes(',') ? !rgb[1].includes('/') : (rgb[1].match(/\//g)?.length ?? 0) === (parts.length === 4 ? 1 : 0);
|
|
18
|
+
if (separators && parts.length >= 3 && parts.length <= 4 && parts.slice(0, 3).every(x => /^[-+]?\d+(?:\.0+)?$/.test(x)) && (parts[3] === undefined || /^[-+]?(?:\d*\.)?\d+%?$/.test(parts[3]))) rgba = [...parts.slice(0, 3).map(x => Math.round(Math.max(0, Math.min(255, Number(x))))), alpha(parts[3])];
|
|
19
|
+
}
|
|
20
|
+
const hsl = /^hsla?\(\s*([-+\d.]+)(deg)?(?:\s*,\s*|\s+)([\d.]+)%(?:\s*,\s*|\s+)([\d.]+)%(?:(?:\s*,\s*|\s*\/\s*)([\d.]+%?))?\s*\)$/.exec(value);
|
|
21
|
+
const validHslSeparators = value.includes(',') ? !value.includes('/') && [3,4].includes(value.split(',').length) : true;
|
|
22
|
+
if (!rgba && hsl && validHslSeparators) {
|
|
23
|
+
const h = ((Number(hsl[1]) % 360) + 360) % 360 / 60, s = Math.min(1, Number(hsl[3]) / 100), l = Math.min(1, Number(hsl[4]) / 100);
|
|
24
|
+
const c = (1 - Math.abs(2 * l - 1)) * s, x = c * (1 - Math.abs(h % 2 - 1)), m = l - c / 2;
|
|
25
|
+
const channels = (h < 1 ? [c, x, 0] : h < 2 ? [x, c, 0] : h < 3 ? [0, c, x] : h < 4 ? [0, x, c] : h < 5 ? [x, 0, c] : [c, 0, x]).map(v => (v + m) * 255);
|
|
26
|
+
if (channels.every(Number.isInteger)) rgba = [...channels, alpha(hsl[5])];
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if (!rgba) return null;
|
|
30
|
+
if (rgba.length === 3) rgba.push(255);
|
|
31
|
+
return rgba[3] ? rgba : [0, 0, 0, 0];
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function absoluteColor(input) {
|
|
35
|
+
return typeof input === 'string' && !!input.trim() && !/\b(?:var|env|light-dark)\s*\(|\bfrom\b|\b(?:currentcolor|inherit|initial|unset|revert(?:-layer)?|canvas(?:text)?|accentcolor(?:text)?|activetext|button(?:border|face|text)|field(?:text)?|graytext|highlight(?:text)?|linktext|mark(?:text)?|selecteditem(?:text)?|visitedtext)\b/i.test(input);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Install a bounded absolute-color resolver in the current Chromium realm. */
|
|
39
|
+
export function installColorResolver() {
|
|
40
|
+
if (globalThis.__adgOwnerColor) return;
|
|
41
|
+
const canvas = document.createElement('canvas'); canvas.width = canvas.height = 1;
|
|
42
|
+
const context = canvas.getContext('2d', { colorSpace: 'srgb', colorType: 'float16', willReadFrequently: true }); context.globalCompositeOperation = 'copy';
|
|
43
|
+
const sample = document.createElement('i'), cache = new Map();
|
|
44
|
+
globalThis.__adgOwnerColor = input => {
|
|
45
|
+
if (cache.has(input)) return cache.get(input);
|
|
46
|
+
if (!CSS.supports('color', input)) return null;
|
|
47
|
+
sample.style.color = ''; sample.style.color = input; document.body.append(sample);
|
|
48
|
+
const value = getComputedStyle(sample).color; sample.remove();
|
|
49
|
+
context.fillStyle = value; context.fillRect(0, 0, 1, 1);
|
|
50
|
+
let rgba = [...context.getImageData(0, 0, 1, 1, { colorSpace: 'srgb', pixelFormat: 'rgba-float16' }).data].map(channel => Math.round(Math.max(0, Math.min(1, channel)) * 255));
|
|
51
|
+
const rgb = /^rgba?\((.*)\)$/.exec(value);
|
|
52
|
+
if (rgb) {
|
|
53
|
+
const parts = rgb[1].split(/[,\s/]+/).filter(Boolean).map(Number);
|
|
54
|
+
if (parts.every(Number.isFinite)) rgba = [...parts.slice(0, 3).map(channel => Math.round(Math.max(0, Math.min(255, channel)))), Math.round(Math.max(0, Math.min(1, parts[3] ?? 1)) * 255)];
|
|
55
|
+
} else {
|
|
56
|
+
const a = /\/\s*([\d.e+-]+)(%)?\s*\)$/.exec(value);
|
|
57
|
+
if (a) rgba[3] = Math.round(Math.max(0, Math.min(1, Number(a[1]) / (a[2] ? 100 : 1))) * 255);
|
|
58
|
+
}
|
|
59
|
+
if (!rgba[3]) rgba = [0, 0, 0, 0];
|
|
60
|
+
cache.set(input, rgba); if (cache.size > 512) cache.delete(cache.keys().next().value);
|
|
61
|
+
return rgba;
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export async function resolveQueryColor(input, read) {
|
|
66
|
+
if (!absoluteColor(input)) throw new CliError('OWNER_COLOR_INVALID', 'Supply an absolute supported CSS color, or query a custom property with --token.');
|
|
67
|
+
const rgba = fastColor(input) ?? await read(input);
|
|
68
|
+
if (!rgba) throw new CliError('OWNER_COLOR_INVALID', 'Chromium rejected the CSS color; supply a supported absolute color.');
|
|
69
|
+
return rgba;
|
|
70
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
const javascript = /\.(?:ts|tsx|js|jsx|mjs|cjs)$/;
|
|
4
|
+
const declaration = '^export\\s+(?:default\\s+)?(?:async\\s+)?(?:function\\*?|class|const|let|var)\\s+';
|
|
5
|
+
const escape = value => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
|
|
7
|
+
/** Lexical boundaries deliberately follow declaration lines, not parsed scopes. */
|
|
8
|
+
export function exportBoundaries(text, file) {
|
|
9
|
+
if (!javascript.test(file)) return [];
|
|
10
|
+
return text.replaceAll('\r\n', '\n').split('\n').flatMap((line, index) => {
|
|
11
|
+
const match = new RegExp(declaration + '([\\p{ID_Start}_$][\\p{ID_Continue}$]*)', 'u').exec(line);
|
|
12
|
+
return match ? [{ line: index + 1, symbol: match[1] }] : [];
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function resolveLocator(text, selector) {
|
|
17
|
+
text = text.replaceAll('\r\n', '\n');
|
|
18
|
+
if (!selector.symbol) return { line: null, candidates: [], stale: false };
|
|
19
|
+
const candidates = [];
|
|
20
|
+
if (selector.anchor !== undefined) {
|
|
21
|
+
let start = 0, index;
|
|
22
|
+
const anchor = selector.anchor.replaceAll('\r\n', '\n');
|
|
23
|
+
while ((index = text.indexOf(anchor, start)) !== -1) {
|
|
24
|
+
candidates.push(text.slice(0, index).split('\n').length);
|
|
25
|
+
start = index + 1;
|
|
26
|
+
}
|
|
27
|
+
} else if (javascript.test(selector.file)) {
|
|
28
|
+
const pattern = new RegExp(declaration + escape(selector.symbol) + '\\b', 'u');
|
|
29
|
+
text.split('\n').forEach((line, index) => { if (pattern.test(line)) candidates.push(index + 1); });
|
|
30
|
+
}
|
|
31
|
+
return { line: candidates.length === 1 ? candidates[0] : null, candidates, stale: candidates.length !== 1 };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function symbolRegions(text, file, selectors) {
|
|
35
|
+
const boundaries = new Map(exportBoundaries(text, file).map(item => [item.line, { ...item, mapped: [] }]));
|
|
36
|
+
for (const selector of selectors) {
|
|
37
|
+
const locator = resolveLocator(text, selector);
|
|
38
|
+
if (locator.line !== null) {
|
|
39
|
+
const boundary = boundaries.get(locator.line) ?? { line: locator.line, symbol: selector.symbol, mapped: [] };
|
|
40
|
+
if (!boundary.mapped.includes(selector.symbol)) boundary.mapped.push(selector.symbol);
|
|
41
|
+
boundaries.set(locator.line, boundary);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const result = [...boundaries.values()].sort((a, b) => a.line - b.line);
|
|
45
|
+
return result.map((boundary, index) => ({ ...boundary, nextBoundaryLine: result[index + 1]?.line ?? sourceLineCount(text) + 1 }));
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const sourceLineCount = text => Math.max(1, text.replaceAll('\r\n', '\n').split('\n').length - Number(text.endsWith('\n')));
|
|
49
|
+
|
|
50
|
+
export function selectorMatches(selector, file) {
|
|
51
|
+
return selector.file !== undefined ? selector.file === file : selector.directory !== undefined ? file.startsWith(selector.directory) : globPattern(selector.glob).test(file);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function regionAt(regions, line) {
|
|
55
|
+
return regions.findLast(region => region.line <= line) ?? null;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function portablePath(value, { directory = false, glob = false } = {}) {
|
|
59
|
+
if (typeof value !== 'string' || !value.trim() || /[\\:#\x00-\x1f\x7f]/.test(value) || path.posix.isAbsolute(value)) return false;
|
|
60
|
+
const candidate = directory && value.endsWith('/') ? value.slice(0, -1) : value;
|
|
61
|
+
if (directory && !value.endsWith('/')) return false;
|
|
62
|
+
if (candidate.split('/').some(segment => !segment || segment === '.' || segment === '..')) return false;
|
|
63
|
+
if (!glob) return !/[?*]/.test(candidate);
|
|
64
|
+
if (/[\[\]{}()!]/.test(candidate)) return false;
|
|
65
|
+
return candidate.split('/').every(segment => !segment.includes('**') || segment === '**');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function globPattern(glob) {
|
|
69
|
+
return new RegExp('^' + glob.split('/').map((segment, index, all) => {
|
|
70
|
+
if (segment === '**') return index === all.length - 1 ? '.*' : '(?:[^/]+/)*';
|
|
71
|
+
return [...segment].map(char => char === '*' ? '[^/]*' : char === '?' ? '[^/]' : escape(char)).join('') + (index === all.length - 1 ? '' : '/');
|
|
72
|
+
}).join('') + '$');
|
|
73
|
+
}
|
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import os from 'node:os';
|
|
4
|
+
import { indexDigest } from './index-store.mjs';
|
|
5
|
+
import { CliError } from '../cli-output.mjs';
|
|
6
|
+
import { loadFrame, browserTask, readyResources } from './browser.mjs';
|
|
7
|
+
import { escape } from './runtime.mjs';
|
|
8
|
+
import { installColorResolver } from './owner-colors.mjs';
|
|
9
|
+
|
|
10
|
+
export const normalizeOwnerText = text => text.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
11
|
+
const contexts = new WeakMap();
|
|
12
|
+
|
|
13
|
+
export function occurrenceContext(observation, occurrence) {
|
|
14
|
+
if (!contexts.has(observation)) contexts.set(observation, new Map(observation.nodes.map(node => [node.path, node])));
|
|
15
|
+
const byPath = contexts.get(observation);
|
|
16
|
+
const path = occurrence.ownerPath ?? occurrence.path?.replace(/::(?:before|after)$|\/text-\d+$/g, '');
|
|
17
|
+
let node = byPath.get(path), distance = 0; const ancestors = [], owners = [];
|
|
18
|
+
while (node) {
|
|
19
|
+
ancestors.push(node.path);
|
|
20
|
+
if (!owners.length && node.owners?.length) owners.push(...node.owners.map(owner => ({ ...owner, distance })));
|
|
21
|
+
node = byPath.get(node.parentPath); distance++;
|
|
22
|
+
}
|
|
23
|
+
return { ...occurrence, ancestors: occurrence.ancestors ?? ancestors, owners: occurrence.owners ?? owners, box: occurrence.box ?? byPath.get(path)?.box, distance: owners[0]?.distance ?? distance };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export async function observeOwnerFrame(index, source, built, frame, theme, environment, getPage, tokens) {
|
|
27
|
+
return index.observation(source, built, frame, theme, environment, async () => {
|
|
28
|
+
const page = await getPage();
|
|
29
|
+
const rendered = { ...frame, document: value => `<!doctype html><html data-theme="${value}"><head><meta charset="utf-8"><style>${built.css.replace(/<\/style/gi, '<\\/style')}</style></head><body><div data-adg-frame="${escape(frame.name)}" style="${frame.width ? `width:${frame.width}px;` : 'width:max-content;'}${frame.height ? `height:${frame.height}px;` : ''}">${frame.html}</div></body></html>` };
|
|
30
|
+
await loadFrame(page, rendered, theme);
|
|
31
|
+
return browserTask(page.context().browser(), async () => {
|
|
32
|
+
await page.evaluate(readyResources); await page.evaluate(installColorResolver);
|
|
33
|
+
return settleOwnerObservation(() => page.evaluate(collectOwnerObservation, { tokens, theme }), () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve))));
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function collectOwnerPalette({ tokens }) {
|
|
39
|
+
return tokens.map(token => {
|
|
40
|
+
const resolved = getComputedStyle(document.documentElement).getPropertyValue(token.name).trim() || null;
|
|
41
|
+
return { name: token.name, resolved, rgba: resolved && !/\b(?:currentcolor|inherit|initial|unset|revert(?:-layer)?)\b/i.test(resolved) ? globalThis.__adgOwnerColor(resolved) : null };
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export async function observeOwnerPalette(index, tokens, theme, environment, getPage, tokenSource) {
|
|
46
|
+
return index.palette(tokens, theme, environment, async () => {
|
|
47
|
+
const page = await getPage();
|
|
48
|
+
return browserTask(page.context().browser(), async () => {
|
|
49
|
+
await page.emulateMedia({ colorScheme: theme, reducedMotion: 'reduce' });
|
|
50
|
+
await page.setContent(`<!doctype html><html data-theme="${theme}"><head><style>${tokenSource.replace(/<\/style/gi, '<\\/style')}</style></head><body></body></html>`);
|
|
51
|
+
await page.evaluate(installColorResolver);
|
|
52
|
+
return page.evaluate(collectOwnerPalette, { tokens });
|
|
53
|
+
});
|
|
54
|
+
});
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Font inventory plus platform/browser identity; computed once per finite query. */
|
|
58
|
+
export async function observationEnvironment() {
|
|
59
|
+
let chromium;
|
|
60
|
+
try { ({ chromium } = await import('playwright')); }
|
|
61
|
+
catch (cause) { throw new CliError('PLAYWRIGHT_UNAVAILABLE', 'Restore the packaged Playwright dependency before observing frames.', { cause }); }
|
|
62
|
+
const roots = process.platform === 'darwin' ? ['/System/Library/Fonts', '/Library/Fonts', path.join(os.homedir(), 'Library/Fonts')]
|
|
63
|
+
: process.platform === 'win32' ? [path.join(process.env.WINDIR ?? 'C:\\Windows', 'Fonts'), path.join(process.env.LOCALAPPDATA ?? os.homedir(), 'Microsoft/Windows/Fonts')]
|
|
64
|
+
: ['/usr/share/fonts', '/usr/local/share/fonts', path.join(os.homedir(), '.local/share/fonts'), path.join(os.homedir(), '.fonts')];
|
|
65
|
+
const files = [], seen = new Set();
|
|
66
|
+
async function visit(file) {
|
|
67
|
+
if (seen.has(file)) return; seen.add(file);
|
|
68
|
+
try {
|
|
69
|
+
const info = await stat(file);
|
|
70
|
+
if (info.isDirectory()) for (const name of await readdir(file)) await visit(path.join(file, name));
|
|
71
|
+
else files.push([file, info.size, info.mtimeMs, info.ctimeMs]);
|
|
72
|
+
} catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
|
|
73
|
+
}
|
|
74
|
+
try { for (const root of roots) await visit(root); await visit(chromium.executablePath()); }
|
|
75
|
+
catch (error) { if (['EACCES', 'EPERM'].includes(error.code)) return null; throw error; }
|
|
76
|
+
return indexDigest(JSON.stringify({ platform: process.platform, release: os.release(), arch: process.arch, locale: 'en-US', timezone: 'UTC', deviceScaleFactor: 1, files: files.sort() }));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Browser-side projection: provenance roots and authored references, no raster work. */
|
|
80
|
+
export function collectOwnerObservation({ tokens, theme }) {
|
|
81
|
+
const frame = document.querySelector('[data-adg-frame]'), root = frame?.firstElementChild;
|
|
82
|
+
if (!root || frame.children.length !== 1) throw Error('Ownership observation requires exactly one frame root.');
|
|
83
|
+
const origin = frame.getBoundingClientRect(), elements = [root, ...root.querySelectorAll('*')], paths = new Map(elements.map((node, i) => [node, String(i)]));
|
|
84
|
+
const tokenNames = new Set(tokens.map(token => token.name));
|
|
85
|
+
const definitions = new Map(tokens.map(token => [token.name, token.values.find(value => value.theme === theme).declaration]));
|
|
86
|
+
const box = rect => ({ x: rect.left - origin.left, y: rect.top - origin.top, width: Math.max(0, rect.right - rect.left), height: Math.max(0, rect.bottom - rect.top) });
|
|
87
|
+
const styleCache = new Map(), declarations = new Map(), rectCache = new Map();
|
|
88
|
+
const rect = node => { if (!rectCache.has(node)) rectCache.set(node, node.getBoundingClientRect()); return rectCache.get(node); };
|
|
89
|
+
const style = node => { if (!styleCache.has(node)) styleCache.set(node, getComputedStyle(node)); return styleCache.get(node); };
|
|
90
|
+
function clipped(node, r = rect(node), includeSelf = false) {
|
|
91
|
+
let left = Math.max(r.left, origin.left), right = Math.min(r.right, origin.right), top = Math.max(r.top, origin.top), bottom = Math.min(r.bottom, origin.bottom);
|
|
92
|
+
for (let p = node; p; p = p.parentElement) {
|
|
93
|
+
const s = style(p); if (s.display === 'none' || p === node && s.visibility !== 'visible' || Number(s.opacity) === 0) return null;
|
|
94
|
+
if ((p !== node || includeSelf) && s.display !== 'inline') {
|
|
95
|
+
const r = rect(p);
|
|
96
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, r.left); right = Math.min(right, r.right); }
|
|
97
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, r.top); bottom = Math.min(bottom, r.bottom); }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
101
|
+
}
|
|
102
|
+
const rules = [];
|
|
103
|
+
function visitRules(list, containers = [], parents = []) {
|
|
104
|
+
for (const rule of list) {
|
|
105
|
+
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
106
|
+
const nested = typeof CSSContainerRule !== 'undefined' && rule instanceof CSSContainerRule ? [...containers, rule.cssText.slice(0, rule.cssText.indexOf('{'))] : containers;
|
|
107
|
+
let resolved = parents;
|
|
108
|
+
if (rule.selectorText && rule.style) {
|
|
109
|
+
const own = selectors(rule.selectorText);
|
|
110
|
+
resolved = parents.length ? parents.flatMap(parent => own.map(selector => selector.includes('&') ? selector.replaceAll('&', `:is(${parent})`) : `${parent} ${selector}`)) : own;
|
|
111
|
+
if ([...rule.style].some(property => rule.style.getPropertyValue(property).includes('var('))) rules.push({ selectors: resolved, style: rule.style, containers });
|
|
112
|
+
}
|
|
113
|
+
if (rule.cssRules) visitRules(rule.cssRules, nested, resolved);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
|
|
117
|
+
function selectors(text) {
|
|
118
|
+
const out = []; let start = 0, depth = 0, quote = '';
|
|
119
|
+
for (let i = 0; i < text.length; i++) {
|
|
120
|
+
const char = text[i];
|
|
121
|
+
if (quote) { if (char === '\\') i++; else if (char === quote) quote = ''; }
|
|
122
|
+
else if (char === '"' || char === "'") quote = char;
|
|
123
|
+
else if (char === '(' || char === '[') depth++;
|
|
124
|
+
else if (char === ')' || char === ']') depth--;
|
|
125
|
+
else if (char === ',' && !depth) { out.push(text.slice(start, i)); start = i + 1; }
|
|
126
|
+
}
|
|
127
|
+
return [...out, text.slice(start)].map(value => value.trim());
|
|
128
|
+
}
|
|
129
|
+
const probe = document.createElement('style'); document.head.append(probe);
|
|
130
|
+
function containerActive(node, conditions) {
|
|
131
|
+
if (!conditions.length) return true;
|
|
132
|
+
const previous = node.getAttribute('data-adg-owner-probe');
|
|
133
|
+
try {
|
|
134
|
+
node.setAttribute('data-adg-owner-probe', 'active');
|
|
135
|
+
probe.textContent = conditions.reduceRight((inner, condition) => `${condition}{${inner}}`, '[data-adg-owner-probe="active"]{--adg-owner-condition:1!important}');
|
|
136
|
+
return getComputedStyle(node).getPropertyValue('--adg-owner-condition').trim() === '1';
|
|
137
|
+
} finally { probe.textContent = ''; if (previous === null) node.removeAttribute('data-adg-owner-probe'); else node.setAttribute('data-adg-owner-probe', previous); }
|
|
138
|
+
}
|
|
139
|
+
function declarationsFor(node, pseudo = '') {
|
|
140
|
+
const key = pseudo ? `${paths.get(node)}${pseudo}` : node;
|
|
141
|
+
if (declarations.has(key)) return declarations.get(key);
|
|
142
|
+
const result = [];
|
|
143
|
+
for (const rule of rules) {
|
|
144
|
+
const matched = rule.selectors.some(selector => {
|
|
145
|
+
const suffix = /::(before|after)\b/.exec(selector);
|
|
146
|
+
if ((suffix ? `::${suffix[1]}` : '') !== pseudo) return false;
|
|
147
|
+
try { return node.matches(selector.replace(/::(?:before|after)\b/g, '')); } catch { return false; }
|
|
148
|
+
});
|
|
149
|
+
if (matched && containerActive(node, rule.containers)) for (const property of rule.style) result.push({ property, declaration: rule.style.getPropertyValue(property) });
|
|
150
|
+
}
|
|
151
|
+
if (!pseudo) for (const property of node.style) result.push({ property, declaration: node.style.getPropertyValue(property) });
|
|
152
|
+
declarations.set(key, result); return result;
|
|
153
|
+
}
|
|
154
|
+
function variables(expression, fallback = false) {
|
|
155
|
+
const result = []; const regex = /var\(\s*(--[\w-]+)/g; let match;
|
|
156
|
+
while ((match = regex.exec(expression))) {
|
|
157
|
+
let depth = 1, comma = -1, end = regex.lastIndex;
|
|
158
|
+
for (; end < expression.length && depth; end++) {
|
|
159
|
+
if (expression[end] === '(') depth++; else if (expression[end] === ')') depth--;
|
|
160
|
+
else if (expression[end] === ',' && depth === 1 && comma < 0) comma = end;
|
|
161
|
+
}
|
|
162
|
+
result.push({ name: match[1], fallback });
|
|
163
|
+
if (comma >= 0) result.push(...variables(expression.slice(comma + 1, end - 1), true));
|
|
164
|
+
regex.lastIndex = end;
|
|
165
|
+
}
|
|
166
|
+
return result;
|
|
167
|
+
}
|
|
168
|
+
const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|cursor|fill|stroke(?:-.+)?)$/;
|
|
169
|
+
const nodes = [], references = [], paints = [], texts = [], groups = [];
|
|
170
|
+
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
171
|
+
function paint(style, property, node, bounds, pseudo = '') {
|
|
172
|
+
const computed = style.getPropertyValue(property);
|
|
173
|
+
if (!computed || computed === 'none') return;
|
|
174
|
+
const values = property.includes('shadow') || property === 'background-image'
|
|
175
|
+
? computed.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|color(?:-mix)?)\((?:[^()]|\([^()]*\))*\)|#[\da-f]{3,8}\b/gi) ?? [] : [computed];
|
|
176
|
+
for (const value of values) {
|
|
177
|
+
const rgba = globalThis.__adgOwnerColor(value);
|
|
178
|
+
if (rgba?.[3]) paints.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), box: bounds, property, computed: value, rgba });
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
function fragment(node) {
|
|
182
|
+
const parent = node.parentElement;
|
|
183
|
+
if (!parent || parent.closest('script,style,input,textarea,select')) return null;
|
|
184
|
+
const range = document.createRange(); range.selectNodeContents(node);
|
|
185
|
+
const rects = [...range.getClientRects()]; if (!rects.length) return null;
|
|
186
|
+
const extent = { left: Math.min(...rects.map(r => r.left)), right: Math.max(...rects.map(r => r.right)), top: Math.min(...rects.map(r => r.top)), bottom: Math.max(...rects.map(r => r.bottom)) };
|
|
187
|
+
const bounds = clipped(parent, extent, true); if (!bounds) return null;
|
|
188
|
+
const clipRect = r => {
|
|
189
|
+
const left = Math.max(r.left, origin.left + bounds.x), right = Math.min(r.right, origin.left + bounds.x + bounds.width), top = Math.max(r.top, origin.top + bounds.y), bottom = Math.min(r.bottom, origin.top + bounds.y + bounds.height);
|
|
190
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
191
|
+
};
|
|
192
|
+
const boxes = rects.map(clipRect).filter(Boolean);
|
|
193
|
+
if (!boxes.length) return null;
|
|
194
|
+
let raw = node.data;
|
|
195
|
+
if (rects.some(r => r.left < origin.left + bounds.x - .5 || r.right > origin.left + bounds.x + bounds.width + .5 || r.top < origin.top + bounds.y - .5 || r.bottom > origin.top + bounds.y + bounds.height + .5)) {
|
|
196
|
+
raw = '';
|
|
197
|
+
for (let i = 0; i < node.length; i++) { range.setStart(node, i); range.setEnd(node, i + 1); if ([...range.getClientRects()].some(r => clipRect(r))) raw += node.data[i]; }
|
|
198
|
+
}
|
|
199
|
+
const transform = style(parent).textTransform;
|
|
200
|
+
const rendered = transform === 'uppercase' ? raw.toLocaleUpperCase(document.documentElement.lang || 'en') : transform === 'lowercase' ? raw.toLocaleLowerCase(document.documentElement.lang || 'en') : transform === 'capitalize' ? raw.replace(/\b\p{L}/gu, value => value.toLocaleUpperCase(document.documentElement.lang || 'en')) : raw;
|
|
201
|
+
return { parent, raw, rendered, elementPath: `${paths.get(parent)}/text-${[...parent.childNodes].indexOf(node)}`, text: raw, boxes };
|
|
202
|
+
}
|
|
203
|
+
function textGroup(node) {
|
|
204
|
+
for (let p = node; p && p !== frame; p = p.parentElement) if (p.matches('button,a,label,input,textarea,select,text') || !['inline','contents'].includes(style(p).display)) return p;
|
|
205
|
+
return root;
|
|
206
|
+
}
|
|
207
|
+
try {
|
|
208
|
+
for (const node of elements) {
|
|
209
|
+
const bounds = clipped(node);
|
|
210
|
+
const own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
|
|
211
|
+
nodes.push({ path: paths.get(node), parentPath: paths.get(node.parentElement) ?? null, box: bounds, owners: own });
|
|
212
|
+
if (!bounds) continue;
|
|
213
|
+
const customs = new Map();
|
|
214
|
+
for (let p = node; p; p = p.parentElement) for (const declaration of declarationsFor(p)) if (declaration.property.startsWith('--') && !customs.has(declaration.property)) customs.set(declaration.property, declaration.declaration);
|
|
215
|
+
function expand(name, property, declaration, via = [], fallback = false) {
|
|
216
|
+
if (via.includes(name)) return;
|
|
217
|
+
if (tokenNames.has(name)) references.push({ path: paths.get(node), token: name, property, declaration, via,
|
|
218
|
+
matchKind: fallback ? 'token_fallback_reference' : via.length ? 'token_alias_reference' : 'token_reference' });
|
|
219
|
+
const expression = tokenNames.has(name) ? definitions.get(name) : customs.get(name);
|
|
220
|
+
if (expression) for (const variable of variables(expression)) expand(variable.name, property, declaration, [...via, name], fallback || variable.fallback);
|
|
221
|
+
}
|
|
222
|
+
for (const pseudo of ['', '::before', '::after']) {
|
|
223
|
+
const s = pseudo ? getComputedStyle(node, pseudo) : style(node);
|
|
224
|
+
if (pseudo && (['none', 'normal'].includes(s.content) || s.display === 'none' || s.visibility !== 'visible' || Number(s.opacity) === 0)) continue;
|
|
225
|
+
const active = [...declarationsFor(node, pseudo)];
|
|
226
|
+
if (!pseudo && (own.length || node === root)) for (let p = node.parentElement; p; p = p.parentElement) active.push(...declarationsFor(p).filter(d => inherited.test(d.property)));
|
|
227
|
+
for (const { property, declaration } of active) if (!property.startsWith('--')) for (const variable of variables(declaration)) expand(variable.name, property, declaration, [], variable.fallback);
|
|
228
|
+
const hasText = pseudo ? !['""', "''", 'none', 'normal'].includes(s.content) : node.matches('input,textarea,select') ? !!String(node.value || node.placeholder || [...(node.selectedOptions ?? [])].map(option => option.text).join('')).trim() : [...node.childNodes].some(n => n.nodeType === 3 && n.textContent.trim() && fragment(n));
|
|
229
|
+
if (hasText && !(node instanceof SVGElement)) paint(!pseudo && node.matches('input,textarea') && !node.value && node.placeholder ? getComputedStyle(node, '::placeholder') : s, 'color', node, bounds, pseudo);
|
|
230
|
+
paint(s, 'background-color', node, bounds, pseudo);
|
|
231
|
+
for (const side of ['top','right','bottom','left']) if (parseFloat(s.getPropertyValue(`border-${side}-width`)) > 0 && s.getPropertyValue(`border-${side}-style`) !== 'none') paint(s, `border-${side}-color`, node, bounds, pseudo);
|
|
232
|
+
if (parseFloat(s.outlineWidth) > 0 && s.outlineStyle !== 'none') paint(s, 'outline-color', node, bounds, pseudo);
|
|
233
|
+
if (node instanceof SVGElement && /^(path|rect|circle|ellipse|polygon|polyline|line|text|tspan)$/.test(node.localName) && (!/^(text|tspan)$/.test(node.localName) || hasText)) { paint(s, 'fill', node, bounds, pseudo); if (parseFloat(s.strokeWidth) > 0) paint(s, 'stroke', node, bounds, pseudo); }
|
|
234
|
+
for (const property of ['box-shadow','text-shadow','background-image']) if (property !== 'text-shadow' || hasText) paint(s, property, node, bounds, pseudo);
|
|
235
|
+
if (pseudo && !/\b(?:url|attr|counter)\(/.test(s.content)) {
|
|
236
|
+
const raw = [...s.content.matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)].map(match => (match[1] ?? match[2]).replace(/\\([\da-f]{1,6})\s?|\\(.)/gi, (_, hex, char) => hex ? String.fromCodePoint(parseInt(hex, 16) || 0xfffd) : char)).join('');
|
|
237
|
+
if (normalize(raw)) texts.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: paths.get(node) + pseudo, text: raw, boxes: [bounds] }] });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (node.matches('input,textarea,select') && !(node.matches('input[type=password]') && node.value)) {
|
|
241
|
+
const raw = node.matches('select') ? [...node.selectedOptions].map(option => option.text).join(' ') : node.value || node.placeholder || '';
|
|
242
|
+
if (normalize(raw)) texts.push({ path: `${paths.get(node)}/value`, ownerPath: paths.get(node), raw, normalized: normalize(raw), fragments: [{ elementPath: `${paths.get(node)}/value`, text: raw, boxes: [bounds] }] });
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
246
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
247
|
+
const f = fragment(node); if (!f) continue;
|
|
248
|
+
const group = textGroup(f.parent);
|
|
249
|
+
if (groups.at(-1)?.[0] !== group) groups.push([group, []]);
|
|
250
|
+
groups.at(-1)[1].push(f);
|
|
251
|
+
}
|
|
252
|
+
for (const [group, fragments] of groups) {
|
|
253
|
+
const raw = fragments.map(f => f.raw).join(''), normalized = normalize(fragments.map(f => f.rendered).join(''));
|
|
254
|
+
if (!normalized) continue;
|
|
255
|
+
let common = fragments[0].parent;
|
|
256
|
+
while (common && !fragments.every(f => common.contains(f.parent))) common = common.parentElement;
|
|
257
|
+
texts.push({ path: `${paths.get(group)}/run-${texts.length}`, ownerPath: paths.get(common ?? group), raw, normalized, fragments: fragments.map(({ elementPath, text, boxes }) => ({ elementPath, text, boxes })) });
|
|
258
|
+
}
|
|
259
|
+
return { nodes, references: [...new Map(references.map(ref => [JSON.stringify(ref), ref])).values()], texts, paints };
|
|
260
|
+
} finally { probe.remove(); }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
export async function settleOwnerObservation(read, wait, now = () => performance.now()) {
|
|
264
|
+
const start = now(); let previous = JSON.stringify(await read());
|
|
265
|
+
while (true) {
|
|
266
|
+
await wait(); const value = await read(), current = JSON.stringify(value);
|
|
267
|
+
if (current === previous) return value;
|
|
268
|
+
if (now() - start >= 5000) throw new CliError('OWNER_UNSETTLED', 'Ownership observations did not settle within five seconds.');
|
|
269
|
+
previous = current;
|
|
270
|
+
}
|
|
271
|
+
}
|