@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,156 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError, nextActions } from '../cli-output.mjs';
|
|
4
|
+
import { openProjectIndex } from './project-index.mjs';
|
|
5
|
+
import { loadImplementationMap } from './implementation-map.mjs';
|
|
6
|
+
import { observeOwnerFrame, observeOwnerPalette, occurrenceContext, normalizeOwnerText, observationEnvironment } from './owner-observation.mjs';
|
|
7
|
+
import { installColorResolver, resolveQueryColor, colorHex } from './owner-colors.mjs';
|
|
8
|
+
import { launch, browserTask } from './browser.mjs';
|
|
9
|
+
import { commandFailure, cleanup } from './results.mjs';
|
|
10
|
+
import { compareNames, compareRanks } from './owner.mjs';
|
|
11
|
+
import { textAuthoring, orderAuthoredIn } from './owner-authoring.mjs';
|
|
12
|
+
|
|
13
|
+
function queryFor(values) {
|
|
14
|
+
const kinds = ['text', 'color', 'token'].filter(kind => values[kind] !== undefined);
|
|
15
|
+
if (kinds.length !== 1 || typeof values[kinds[0]] !== 'string' || !values[kinds[0]].trim()) throw new CliError('USAGE_INVALID', 'Choose one nonempty --text, --color or --token query.');
|
|
16
|
+
const kind = kinds[0], input = values[kind]; let locale = null;
|
|
17
|
+
if (values.locale !== undefined) {
|
|
18
|
+
try { locale = Intl.getCanonicalLocales(values.locale)[0]; if (!locale) throw Error(); }
|
|
19
|
+
catch { throw new CliError('USAGE_INVALID', '--locale requires a BCP 47 language tag.'); }
|
|
20
|
+
}
|
|
21
|
+
if (kind === 'token' && !/^--[\w-]+$/.test(input)) throw new CliError('USAGE_INVALID', 'Use an exact custom-property name such as --accent.');
|
|
22
|
+
if (values.theme !== undefined && !['both', 'light', 'dark'].includes(values.theme)) throw new CliError('USAGE_INVALID', 'Use --theme=both, light or dark.');
|
|
23
|
+
return { kind, input, normalized: kind === 'text' ? normalizeOwnerText(input) : input, pathKind: null, line: null, symbol: null, contains: !!values.contains, locale,
|
|
24
|
+
themes: !values.theme || values.theme === 'both' ? ['light', 'dark'] : [values.theme], rgba: null };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function searchOwner(config, values, { log = console.log, openIndex = openProjectIndex, launchBrowser = launch, environment = observationEnvironment } = {}) {
|
|
28
|
+
const query = queryFor(values);
|
|
29
|
+
if (!query.normalized) throw new CliError('USAGE_INVALID', 'Text must contain a non-whitespace character.');
|
|
30
|
+
const data = { project: config.root, complete: false, query, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [],
|
|
31
|
+
coverage: { discoveredSources: 0, builtSources: 0, requestedObservations: 0, completedObservations: 0, mappingState: 'absent', activeBindings: 0, excludedBindings: 0, domain: 'tsx' } };
|
|
32
|
+
const warnings = [], codes = new Set(), rows = new Map(), tokenResults = new Map(), frameOrder = new Map();
|
|
33
|
+
let index, browser, page, primary;
|
|
34
|
+
const warn = (code, message, retry = false) => {
|
|
35
|
+
if (codes.has(code)) return; codes.add(code);
|
|
36
|
+
warnings.push({ code, message, next: retry ? nextActions('OWNER_UNSETTLED', { command: 'owner', values }).map(action => ({ ...action, reason: message })) : [{ argv: ['adg','check','--read-only','--json'], reason: message }] });
|
|
37
|
+
};
|
|
38
|
+
const getPage = async () => { browser ??= await launchBrowser(); page ??= await browserTask(browser, () => browser.newPage({ locale: 'en-US', timezoneId: 'UTC' })); return page; };
|
|
39
|
+
try {
|
|
40
|
+
index = await openIndex(config, { stateDirectory: values['state-dir'] }); data.coverage.discoveredSources = index.inventory.tsx.length;
|
|
41
|
+
const mapping = await loadImplementationMap(config); data.coverage.mappingState = mapping.present ? 'valid' : 'absent';
|
|
42
|
+
const definitions = index.tokens(), byName = new Map(definitions.map(token => [token.name, token]));
|
|
43
|
+
const unknown = query.kind === 'token' && !byName.has(query.normalized);
|
|
44
|
+
const env = unknown ? null : await environment(), palettes = new Map();
|
|
45
|
+
const source = unknown ? '' : await readFile(path.join(config.design, 'tokens.css'), 'utf8');
|
|
46
|
+
async function palette(theme) {
|
|
47
|
+
if (!palettes.has(theme)) {
|
|
48
|
+
const values = await observeOwnerPalette(index, definitions, theme, env, getPage, source);
|
|
49
|
+
palettes.set(theme, new Map(values.map(value => [value.name, value])));
|
|
50
|
+
const unresolved = values.filter(value => value.resolved === null).map(value => value.name);
|
|
51
|
+
if (unresolved.length) warn('OWNER_TOKEN_UNRESOLVED', `Repair unresolved ${theme} tokens: ${unresolved.join(', ')}.`);
|
|
52
|
+
}
|
|
53
|
+
return palettes.get(theme);
|
|
54
|
+
}
|
|
55
|
+
if (query.kind === 'color') {
|
|
56
|
+
query.rgba = await resolveQueryColor(query.input, async input => index.color(input, env, async () => {
|
|
57
|
+
const page = await getPage();
|
|
58
|
+
return browserTask(browser, async () => { await page.setContent('<!doctype html><html><body></body></html>'); await page.evaluate(installColorResolver); return page.evaluate(value => globalThis.__adgOwnerColor(value), input); });
|
|
59
|
+
}));
|
|
60
|
+
query.normalized = colorHex(query.rgba);
|
|
61
|
+
}
|
|
62
|
+
const projectOwners = owners => owners.map(owner => ({ source: path.posix.join(path.relative(config.root, config.design).split(path.sep).join('/'), owner.source), part: owner.export }));
|
|
63
|
+
function via(name, theme, seen = new Set([name])) {
|
|
64
|
+
const names = [];
|
|
65
|
+
for (const ref of byName.get(name)?.values.find(v => v.theme === theme)?.references ?? []) if (!seen.has(ref)) { seen.add(ref); names.push(ref, ...via(ref, theme, seen)); }
|
|
66
|
+
return names;
|
|
67
|
+
}
|
|
68
|
+
async function addToken(name, theme, kind = 'token_name') {
|
|
69
|
+
const token = byName.get(name), observed = (await palette(theme)).get(name);
|
|
70
|
+
if (!token || !observed) return;
|
|
71
|
+
if (!tokenResults.has(name)) tokenResults.set(name, { name, source: token.source, matchKind: kind, values: [], evidence: [] });
|
|
72
|
+
const row = tokenResults.get(name); if (row.values.some(v => v.theme === theme)) return;
|
|
73
|
+
const value = token.values.find(v => v.theme === theme), aliases = via(name, theme);
|
|
74
|
+
row.values.push({ theme, declaration: value.declaration, line: value.line, inherited: value.inherited, resolved: observed.resolved, rgba: observed.rgba, via: aliases });
|
|
75
|
+
row.evidence.push({ matchKind: kind, frame: null, theme, elementPath: null, boxes: [], owners: [], detail: { kind: 'token', token: name, declaration: value.declaration, resolved: observed.resolved, via: aliases, source: token.source, line: value.line, inherited: value.inherited } });
|
|
76
|
+
if (observed.resolved === null) warn('OWNER_TOKEN_UNRESOLVED', `Repair unresolved token ${name} in its reported theme, then validate tokens.css.`);
|
|
77
|
+
}
|
|
78
|
+
if (!unknown && query.kind !== 'text') for (const theme of query.themes) {
|
|
79
|
+
if (query.kind === 'token') await addToken(query.normalized, theme);
|
|
80
|
+
else for (const token of definitions) if (JSON.stringify((await palette(theme)).get(token.name)?.rgba) === JSON.stringify(query.rgba)) await addToken(token.name, theme, 'token_value');
|
|
81
|
+
}
|
|
82
|
+
if (!unknown) for (const source of index.inventory.tsx) {
|
|
83
|
+
const built = await index.getBuild(source); frameOrder.set(source, built.frames.map(frame => frame.name));
|
|
84
|
+
const authoredIn = query.kind === 'text' ? textAuthoring(config, source, built) : null;
|
|
85
|
+
for (const frame of built.frames) {
|
|
86
|
+
if (query.locale !== null && frame.locale !== query.locale) continue;
|
|
87
|
+
data.coverage.requestedObservations += query.themes.length;
|
|
88
|
+
for (const theme of query.themes) {
|
|
89
|
+
const observation = await observeOwnerFrame(index, source, built, frame, theme, env, getPage, definitions), ref = { source, frame: frame.name };
|
|
90
|
+
const matches = query.kind === 'text' ? (observation.texts ?? []).filter(run => run.normalized === query.normalized || query.contains && run.normalized.includes(query.normalized))
|
|
91
|
+
: query.kind === 'color' ? (observation.paints ?? []).filter(paint => JSON.stringify(paint.rgba) === JSON.stringify(query.rgba))
|
|
92
|
+
: observation.references.filter(reference => reference.token === query.normalized);
|
|
93
|
+
for (const match of matches) {
|
|
94
|
+
const ctx = occurrenceContext(observation, match), owners = projectOwners(ctx.owners), owning = owners.length ? owners : [{ source, part: null }];
|
|
95
|
+
const kind = query.kind === 'text' ? match.normalized === query.normalized ? 'text_exact' : 'text_contains' : query.kind === 'color' ? 'color_value' : match.matchKind;
|
|
96
|
+
const rank = query.kind === 'text' ? [kind === 'text_exact' ? 0 : 1, [...match.normalized].length - [...query.normalized].length, ctx.distance]
|
|
97
|
+
: query.kind === 'color' ? [0, ctx.distance] : [kind === 'token_reference' ? 0 : kind === 'token_alias_reference' ? 1 : 2, match.via.length, ctx.distance];
|
|
98
|
+
const detail = query.kind === 'text' ? { kind: 'text', raw: match.raw, normalized: match.normalized, fragments: match.fragments }
|
|
99
|
+
: query.kind === 'color' ? { kind: 'paint', property: match.property, computed: match.computed, rgba: match.rgba, usage: 'computed_value' }
|
|
100
|
+
: { kind: 'reference', token: match.token, property: match.property, declaration: match.declaration, via: match.via, usage: 'authored_reference' };
|
|
101
|
+
const evidence = { matchKind: kind, frame: ref, theme, elementPath: match.path, boxes: query.kind === 'text' ? match.fragments.flatMap(f => f.boxes) : ctx.box ? [ctx.box] : [], owners, detail };
|
|
102
|
+
const scope = new Set(ctx.ancestors);
|
|
103
|
+
for (const fragment of match.fragments ?? []) for (const ancestor of occurrenceContext(observation, { path: fragment.elementPath }).ancestors) scope.add(ancestor);
|
|
104
|
+
const references = query.kind === 'token' ? [match] : query.kind === 'color'
|
|
105
|
+
? observation.references.filter(reference => reference.path === match.path && reference.property === match.property)
|
|
106
|
+
: observation.references.filter(reference => scope.has(reference.path));
|
|
107
|
+
if (query.kind === 'text') evidence.authoredIn = await authoredIn(match, owners.map(owner => owner.source));
|
|
108
|
+
if (query.kind === 'color') evidence.references = [...new Map(references.map(reference => {
|
|
109
|
+
const compact = { token: reference.token, kind: reference.matchKind, via: reference.via };
|
|
110
|
+
return [JSON.stringify(compact), compact];
|
|
111
|
+
})).values()];
|
|
112
|
+
for (const target of owning) {
|
|
113
|
+
const key = JSON.stringify([target.source, target.part]);
|
|
114
|
+
if (!rows.has(key)) rows.set(key, { source: target.source, part: target.part, matchKind: kind, rank, frames: [], tokens: [], evidence: [] });
|
|
115
|
+
const row = rows.get(key); if (compareRanks(rank, row.rank) < 0) { row.rank = rank; row.matchKind = kind; }
|
|
116
|
+
if (!row.frames.some(f => f.source === source && f.frame === frame.name && f.theme === theme)) row.frames.push({ ...ref, theme, locale: frame.locale ?? null });
|
|
117
|
+
row.evidence.push(evidence);
|
|
118
|
+
if (query.kind === 'text') row.authoredIn = orderAuthoredIn([...(row.authoredIn ?? []), ...evidence.authoredIn], [row.source, ...row.frames.map(frame => frame.source)]);
|
|
119
|
+
for (const reference of references) {
|
|
120
|
+
if (!row.tokens.includes(reference.token)) row.tokens.push(reference.token);
|
|
121
|
+
if (query.kind === 'text') await addToken(reference.token, theme);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
data.coverage.completedObservations++; data.owners = [...rows.values()]; data.tokens = [...tokenResults.values()];
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
await index.verifyInputs();
|
|
130
|
+
data.owners = [...rows.values()]; data.tokens = [...tokenResults.values()];
|
|
131
|
+
} catch (cause) { primary = commandFailure(cause, data, warnings); }
|
|
132
|
+
if (index) { try { data.coverage.builtSources = (await index.stats()).requestedSources?.length ?? 0; } catch (cause) { if (!primary) primary = commandFailure(cause, data, warnings); } }
|
|
133
|
+
for (const close of [() => page?.close(), () => browser?.close(), () => index?.close()]) { try { await cleanup(close, primary); } catch (cause) { primary = commandFailure(cause, data, warnings); } }
|
|
134
|
+
if (primary) throw primary;
|
|
135
|
+
data.owners.sort((a, b) => compareRanks(a.rank, b.rank) || compareNames(a.source, b.source) || compareNames(a.part, b.part));
|
|
136
|
+
const order = (a, b) => compareNames(a.source, b.source) || (frameOrder.get(a.source)?.indexOf(a.frame) ?? -1) - (frameOrder.get(b.source)?.indexOf(b.frame) ?? -1) || query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme);
|
|
137
|
+
for (const row of data.owners) {
|
|
138
|
+
row.frames.sort(order); row.tokens.sort(compareNames);
|
|
139
|
+
row.evidence = [...new Map(row.evidence.map(e => [JSON.stringify(e), e])).values()].sort((a, b) => order({ ...a.frame, theme: a.theme }, { ...b.frame, theme: b.theme }) || compareNames(a.elementPath, b.elementPath) || compareNames(a.matchKind, b.matchKind));
|
|
140
|
+
}
|
|
141
|
+
data.tokens.sort((a, b) => compareNames(a.name, b.name));
|
|
142
|
+
for (const token of data.tokens) { token.values.sort((a, b) => query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme)); token.evidence.sort((a, b) => query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme)); }
|
|
143
|
+
data.ambiguous = data.owners.length > 1 && compareRanks(data.owners[0].rank, data.owners[1].rank) === 0;
|
|
144
|
+
data.tokenAmbiguous = query.kind === 'color' && data.tokens.length > 1;
|
|
145
|
+
if (data.ambiguous || data.tokenAmbiguous) warn('OWNER_AMBIGUOUS', 'Several owner or token identities share this match; inspect their explicit evidence before choosing one.', true);
|
|
146
|
+
if (!data.owners.length && !data.tokens.length) warn('OWNER_NO_MATCH', 'No ownership evidence matched; inspect authored text or token declarations.');
|
|
147
|
+
if (!data.coverage.requestedObservations && query.kind !== 'token') warnings.push({ code: 'EMPTY_SELECTION', message: 'No TSX frames matched the query locale/domain.', next: [] });
|
|
148
|
+
data.complete = true;
|
|
149
|
+
if (!values.json) {
|
|
150
|
+
if (!data.owners.length && !data.tokens.length) log('No ownership evidence matched.');
|
|
151
|
+
for (const row of data.owners) log(`${row.source}${row.part ? '#' + row.part : ''} [${row.matchKind}] ${row.frames.length} frame/theme observations`);
|
|
152
|
+
for (const token of data.tokens) log(`${token.source}#${token.name} ${token.values.map(value => `${value.theme}: ${value.rgba ? colorHex(value.rgba) : value.resolved ?? 'unresolved'}`).join(', ')}`);
|
|
153
|
+
for (const warning of warnings) log(`${warning.code}: ${warning.message}`);
|
|
154
|
+
}
|
|
155
|
+
return { data, warnings };
|
|
156
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { CliError, nextActions } from '../cli-output.mjs';
|
|
4
|
+
import { openProjectIndex } from './project-index.mjs';
|
|
5
|
+
import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
|
|
6
|
+
import { regionAt } from './owner-locators.mjs';
|
|
7
|
+
import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
|
|
8
|
+
import { launch, loadFrame, readyResources, browserTask } from './browser.mjs';
|
|
9
|
+
import { observeOwnerFrame, observeOwnerPalette, occurrenceContext, observationEnvironment } from './owner-observation.mjs';
|
|
10
|
+
import { commandFailure, cleanup } from './results.mjs';
|
|
11
|
+
import { escape } from './runtime.mjs';
|
|
12
|
+
import { indexDigest } from './index-store.mjs';
|
|
13
|
+
|
|
14
|
+
export const compareRanks = (a, b) => { for (let i = 0; i < Math.max(a.length, b.length); i++) if ((a[i] ?? 0) !== (b[i] ?? 0)) return (a[i] ?? 0) - (b[i] ?? 0); return 0; };
|
|
15
|
+
export const compareNames = (a, b) => { const x = [...(a ?? '')], y = [...(b ?? '')]; for (let i = 0; i < Math.min(x.length, y.length); i++) if (x[i] !== y[i]) return x[i].codePointAt(0) - y[i].codePointAt(0); return x.length - y.length; };
|
|
16
|
+
export function fileRank(selector, locator = null) {
|
|
17
|
+
const rank = locator === 'mapping_symbol' ? 0 : locator === 'mapping_symbol_region' ? 1 : 2;
|
|
18
|
+
if (selector.file) return [0, 0, 0, 0, rank];
|
|
19
|
+
if (selector.directory) return [1, -selector.directory.split('/').filter(Boolean).length, 0, 0, rank];
|
|
20
|
+
const prefix = selector.glob.search(/[?*]/);
|
|
21
|
+
return [2, -(prefix < 0 ? selector.glob.length : prefix), selector.glob.split('/').filter(segment => /[?*]/.test(segment)).length, -selector.glob.replace(/[?*]/g, '').length, rank];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
function bindingKind(selector, query) {
|
|
26
|
+
return selector.symbol && query.symbol && query.line === null ? 'mapping_symbol' : selector.symbol && query.line !== null ? 'mapping_symbol_region'
|
|
27
|
+
: selector.file ? 'mapping_file' : selector.directory ? 'mapping_directory' : 'mapping_glob';
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function owner(config, values, { log = console.log, openIndex = openProjectIndex, launchBrowser = launch, environment = observationEnvironment } = {}) {
|
|
31
|
+
if (values.file === undefined) return (await import('./owner-search.mjs')).searchOwner(config, values, { log, openIndex, launchBrowser, environment });
|
|
32
|
+
const { query, text } = await normalizeFileQuery(config, values);
|
|
33
|
+
const data = { project: config.root, complete: false, query, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [],
|
|
34
|
+
coverage: { discoveredSources: 0, builtSources: 0, requestedObservations: 0, completedObservations: 0, mappingState: 'absent', activeBindings: 0, excludedBindings: 0, domain: 'tsx' } };
|
|
35
|
+
const warnings = [], context = { command: 'owner', values }, warned = new Set();
|
|
36
|
+
const warn = (code, message, retry = false) => {
|
|
37
|
+
if (warned.has(code)) return; warned.add(code);
|
|
38
|
+
warnings.push({ code, message, next: retry ? nextActions('OWNER_UNSETTLED', context).map(action => ({ ...action, reason: message })) : [{ argv: ['adg', 'check', '--read-only', '--json'], reason: message }] });
|
|
39
|
+
};
|
|
40
|
+
let index, browser, page, primary;
|
|
41
|
+
const rows = new Map(), tokenResults = new Map(), frameOrder = new Map();
|
|
42
|
+
try {
|
|
43
|
+
const selector = { [query.pathKind === 'directory' ? 'directory' : query.pathKind === 'glob' ? 'glob' : 'file']: query.normalized };
|
|
44
|
+
const files = await implementationFiles(config, selector); data.matchedImplementationFiles = files;
|
|
45
|
+
const map = await loadImplementationMap(config);
|
|
46
|
+
data.coverage.mappingState = map.present ? 'valid' : 'absent';
|
|
47
|
+
index = await openIndex(config, { stateDirectory: values['state-dir'] }); data.coverage.discoveredSources = index.inventory.tsx.length;
|
|
48
|
+
const { mappingIndices, region: queryRegion } = implementationScope(map, query, text, files);
|
|
49
|
+
if (query.line !== null && queryRegion) data.region = { boundaryLine: queryRegion.line, symbol: queryRegion.symbol, mapped: queryRegion.mapped.length > 0, nextBoundaryLine: queryRegion.nextBoundaryLine };
|
|
50
|
+
const validated = await index.mappings({ map, mappingIndices, implementationSelection: files, onFinding: finding => { data.mappingFindings.push(finding); data.coverage.mappingState = 'stale'; } });
|
|
51
|
+
data.mappingFindings = validated.findings;
|
|
52
|
+
data.coverage.mappingState = !map.present ? 'absent' : validated.findings.length ? 'stale' : 'valid';
|
|
53
|
+
const active = validated.bindings.filter(binding => binding.active);
|
|
54
|
+
data.coverage.activeBindings = active.length; data.coverage.excludedBindings = validated.bindings.length - active.length;
|
|
55
|
+
if (!map.present) warn('OWNER_MAPPING_MISSING', 'Add implementation.json to declare implementation ownership, then validate it.');
|
|
56
|
+
if (validated.findings.length) warn('OWNER_MAPPING_STALE', 'Repair the reported implementation mapping findings, then repeat the query.');
|
|
57
|
+
if ((query.line !== null || query.symbol !== null) && !active.some(binding => binding.implementation.symbol)) warn('OWNER_LOCATOR_UNMAPPED', 'Add or refine a symbol/anchor binding for this implementation region, then repeat the query.', true);
|
|
58
|
+
const tasks = new Map();
|
|
59
|
+
for (const binding of active) {
|
|
60
|
+
const target = binding.design, key = JSON.stringify([target.source, target.part ?? null]), kind = bindingKind(binding.implementation, query), rank = fileRank(binding.implementation, kind);
|
|
61
|
+
if (!rows.has(key)) rows.set(key, { source: target.source, part: target.part ?? null, matchKind: kind, rank, frames: [], tokens: [], evidence: [] });
|
|
62
|
+
const row = rows.get(key); if (compareRanks(rank, row.rank) < 0) { row.rank = rank; row.matchKind = kind; }
|
|
63
|
+
if (target.part && !binding.frames.length) warn('OWNER_PART_UNOBSERVED', 'The declared part has no rendered specimen in its owning source; add coverage when needed.');
|
|
64
|
+
if (!binding.frames.length) addMapping(row, binding, null, null, []);
|
|
65
|
+
for (const frame of binding.frames) for (const theme of query.themes) {
|
|
66
|
+
const identity = JSON.stringify([target.source, frame, theme]);
|
|
67
|
+
if (!tasks.has(identity)) tasks.set(identity, { source: target.source, frame, theme, bindings: [] });
|
|
68
|
+
tasks.get(identity).bindings.push({ row, binding });
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
function projectOwners(owners) { return owners.map(item => ({ source: path.posix.join(path.relative(config.root, config.design).split(path.sep).join('/'), item.source), part: item.export })); }
|
|
72
|
+
function addMapping(row, binding, ref, theme, roots) {
|
|
73
|
+
const kind = bindingKind(binding.implementation, query);
|
|
74
|
+
for (const implementation of binding.files) {
|
|
75
|
+
const boundary = binding.anchorLine === null ? null : regionAt(validated.regions[implementation] ?? [], binding.anchorLine);
|
|
76
|
+
const matches = roots.length ? roots : [null];
|
|
77
|
+
for (const node of matches) row.evidence.push({ matchKind: kind, frame: ref, theme, elementPath: node?.path ?? null, boxes: node ? [node.box] : [], owners: node ? projectOwners(node.owners) : [],
|
|
78
|
+
detail: { kind: 'mapping', file: map.source, pointer: binding.pointer, implementation, selector: binding.implementation, locatorMatched: query.line === null && query.symbol === null ? null : !!binding.implementation.symbol,
|
|
79
|
+
anchorLine: binding.anchorLine, nextBoundaryLine: boundary?.nextBoundaryLine ?? null } });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const definitions = tasks.size ? index.tokens() : [], byName = new Map(definitions.map(token => [token.name, token]));
|
|
83
|
+
data.coverage.requestedObservations = tasks.size;
|
|
84
|
+
const env = tasks.size ? await environment() : null;
|
|
85
|
+
const getPage = async () => { browser ??= await launchBrowser(); page ??= await browserTask(browser, () => browser.newPage({ locale: 'en-US', timezoneId: 'UTC' })); return page; };
|
|
86
|
+
const palettes = new Map(), tokenSource = tasks.size ? await readFile(path.join(config.design, 'tokens.css'), 'utf8') : '';
|
|
87
|
+
function tokenVia(name, theme, seen = new Set([name])) {
|
|
88
|
+
const result = [];
|
|
89
|
+
for (const ref of byName.get(name)?.values.find(value => value.theme === theme)?.references ?? []) if (!seen.has(ref)) { seen.add(ref); result.push(ref, ...tokenVia(ref, theme, seen)); }
|
|
90
|
+
return result;
|
|
91
|
+
}
|
|
92
|
+
for (const task of tasks.values()) {
|
|
93
|
+
const built = await index.getBuild(task.source), frame = built.frames.find(frame => frame.name === task.frame);
|
|
94
|
+
frameOrder.set(task.source, built.frames.map(frame => frame.name));
|
|
95
|
+
const observation = await observeOwnerFrame(index, task.source, built, frame, task.theme, env, getPage, definitions);
|
|
96
|
+
if (!palettes.has(task.theme)) palettes.set(task.theme, await observeOwnerPalette(index, definitions, task.theme, env, getPage, tokenSource));
|
|
97
|
+
const ref = { source: task.source, frame: task.frame }, palette = new Map(palettes.get(task.theme).map(value => [value.name, value]));
|
|
98
|
+
for (const { row, binding } of task.bindings) {
|
|
99
|
+
const roots = binding.design.part ? observation.nodes.filter(node => node.box && node.owners.some(owner => projectOwners([owner]).some(part => part.source === row.source && part.part === row.part))) : observation.nodes.filter(node => node.path === '0' && node.box);
|
|
100
|
+
if (row.part && !roots.length) warn('OWNER_PART_UNOBSERVED', 'The declared part has no painted occurrence in a bound frame; inspect its authored coverage.');
|
|
101
|
+
if (!row.frames.some(frame => frame.source === ref.source && frame.frame === ref.frame && frame.theme === task.theme)) row.frames.push({ ...ref, theme: task.theme, locale: frame.locale ?? null });
|
|
102
|
+
addMapping(row, binding, ref, task.theme, roots);
|
|
103
|
+
for (const rawReference of observation.references) {
|
|
104
|
+
const reference = occurrenceContext(observation, rawReference);
|
|
105
|
+
if (row.part && !roots.some(root => reference.ancestors.includes(root.path))) continue;
|
|
106
|
+
if (!row.tokens.includes(reference.token)) row.tokens.push(reference.token);
|
|
107
|
+
const token = byName.get(reference.token), value = token?.values.find(value => value.theme === task.theme), observed = palette.get(reference.token);
|
|
108
|
+
if (!value || !observed) continue;
|
|
109
|
+
if (!tokenResults.has(token.name)) tokenResults.set(token.name, { name: token.name, source: token.source, matchKind: 'token_name', values: [], evidence: [] });
|
|
110
|
+
const result = tokenResults.get(token.name);
|
|
111
|
+
if (!result.values.some(value => value.theme === task.theme)) {
|
|
112
|
+
const via = tokenVia(token.name, task.theme);
|
|
113
|
+
result.values.push({ theme: task.theme, declaration: value.declaration, line: value.line, inherited: value.inherited, resolved: observed.resolved, rgba: observed.rgba, via });
|
|
114
|
+
result.evidence.push({ matchKind: 'token_name', frame: null, theme: task.theme, elementPath: null, boxes: [], owners: [], detail: { kind: 'token', token: token.name, declaration: value.declaration, resolved: observed.resolved, via, source: token.source, line: value.line, inherited: value.inherited } });
|
|
115
|
+
if (observed.resolved === null) warn('OWNER_TOKEN_UNRESOLVED', `Repair unresolved token ${token.name} in its reported theme, then validate the token sheet.`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
data.coverage.completedObservations++;
|
|
120
|
+
data.owners = [...rows.values()]; data.tokens = [...tokenResults.values()];
|
|
121
|
+
}
|
|
122
|
+
await index.verifyInputs();
|
|
123
|
+
const inputs = { ...validated.implementationHashes, ...(text !== null ? { [query.normalized]: indexDigest(text) } : {}) };
|
|
124
|
+
for (const [file, expected] of Object.entries(inputs)) if (indexDigest(await readFile(path.join(config.root, file))) !== expected) throw new CliError('OWNER_INDEX_CHANGED', `Implementation locator changed during query: ${file}.`);
|
|
125
|
+
let mapHash = null;
|
|
126
|
+
try { mapHash = indexDigest(await readFile(map.file)); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
127
|
+
if (mapHash !== (map.inputHash ?? null)) throw new CliError('OWNER_INDEX_CHANGED', 'Implementation mappings changed during the query.');
|
|
128
|
+
data.owners = [...rows.values()]; data.tokens = [...tokenResults.values()];
|
|
129
|
+
} catch (cause) { primary = commandFailure(cause, data, warnings); }
|
|
130
|
+
if (index) {
|
|
131
|
+
try { const stats = await index.stats(); data.coverage.builtSources = stats.requestedSources?.length ?? 0; }
|
|
132
|
+
catch (cause) { if (!primary) primary = commandFailure(cause, data, warnings); }
|
|
133
|
+
}
|
|
134
|
+
for (const close of [() => page?.close(), () => browser?.close(), () => index?.close()]) {
|
|
135
|
+
try { await cleanup(close, primary); } catch (cause) { primary = commandFailure(cause, data, warnings); }
|
|
136
|
+
}
|
|
137
|
+
if (primary) throw primary;
|
|
138
|
+
data.owners.sort((a, b) => compareRanks(a.rank, b.rank) || compareNames(a.source, b.source) || compareNames(a.part, b.part));
|
|
139
|
+
for (const row of data.owners) {
|
|
140
|
+
const order = (a, b) => compareNames(a.source, b.source) || (frameOrder.get(a.source)?.indexOf(a.frame) ?? -1) - (frameOrder.get(b.source)?.indexOf(b.frame) ?? -1) || query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme);
|
|
141
|
+
row.frames.sort(order);
|
|
142
|
+
row.evidence.sort((a, b) => order(a.frame ? { ...a.frame, theme: a.theme } : { source: '', frame: '', theme: null }, b.frame ? { ...b.frame, theme: b.theme } : { source: '', frame: '', theme: null }) || Number(a.elementPath ?? -1) - Number(b.elementPath ?? -1) || compareNames(a.detail.kind, b.detail.kind) || compareNames(JSON.stringify(a.detail), JSON.stringify(b.detail)));
|
|
143
|
+
row.tokens.sort(compareNames); row.evidence = [...new Map(row.evidence.map(evidence => [JSON.stringify(evidence), evidence])).values()];
|
|
144
|
+
}
|
|
145
|
+
for (const token of data.tokens) { token.values.sort((a, b) => query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme)); token.evidence.sort((a, b) => query.themes.indexOf(a.theme) - query.themes.indexOf(b.theme)); }
|
|
146
|
+
data.tokens.sort((a, b) => compareNames(a.name, b.name));
|
|
147
|
+
data.ambiguous = data.owners.length > 1 && compareRanks(data.owners[0].rank, data.owners[1].rank) === 0;
|
|
148
|
+
if (data.ambiguous) warn('OWNER_AMBIGUOUS', 'Several owners share the best rank; narrow the file locator, text or theme before choosing an owner.', true);
|
|
149
|
+
if (!data.owners.length && !data.tokens.length) warn('OWNER_NO_MATCH', 'No ownership evidence matched. Validate current sources and add or refine an implementation mapping.');
|
|
150
|
+
if (!data.coverage.discoveredSources) warnings.push({ code: 'EMPTY_SELECTION', message: 'No TSX design sources were discovered.', next: [] });
|
|
151
|
+
data.complete = true;
|
|
152
|
+
if (!values.json) {
|
|
153
|
+
if (!data.owners.length) log('No ownership evidence matched.');
|
|
154
|
+
if (data.ambiguous) log('Multiple owners share the best rank.');
|
|
155
|
+
for (const row of data.owners) log(`${row.source}${row.part ? `#${row.part}` : ''} [${row.matchKind}] ${[...new Set(row.frames.map(frame => frame.frame))].join(', ')}${row.tokens.length ? `; tokens: ${row.tokens.join(', ')}` : ''}`);
|
|
156
|
+
for (const warning of warnings) log(`${warning.code}: ${warning.message}`);
|
|
157
|
+
}
|
|
158
|
+
return { data, warnings };
|
|
159
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { readFile, realpath, readdir } from 'node:fs/promises';
|
|
2
|
+
import { readFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { listSources, archFiles, sourceDirectories, relative, loadTokens } from './project.mjs';
|
|
5
|
+
import { tokenLocations } from './tokens.mjs';
|
|
6
|
+
import { CliError } from '../cli-output.mjs';
|
|
7
|
+
import { buildSource } from './build.mjs';
|
|
8
|
+
import { createBuildStore, BuildPool } from './build-store.mjs';
|
|
9
|
+
import { sourceFacts } from './source-facts.mjs';
|
|
10
|
+
import { sidecar } from './arch.mjs';
|
|
11
|
+
import { loadImplementationMap, validateImplementationMap } from './implementation-map.mjs';
|
|
12
|
+
import { createIndexStore, indexDigest } from './index-store.mjs';
|
|
13
|
+
import { defaultStateDirectory } from '../hub/registry.mjs';
|
|
14
|
+
import { sourceRelationships } from '../../public/relationships.js';
|
|
15
|
+
import { entryTokenReachability } from './token-reachability.mjs';
|
|
16
|
+
import { frameDocument } from './frame-document.mjs';
|
|
17
|
+
export { sourceFacts } from './source-facts.mjs';
|
|
18
|
+
|
|
19
|
+
const collectorIdentity = indexDigest(Buffer.concat(await Promise.all(['project-index.mjs', 'source-facts.mjs', 'implementation-map.mjs', 'owner-locators.mjs', 'owner-observation.mjs', 'owner-colors.mjs', 'tokens.mjs', 'token-reachability.mjs', 'arch.mjs'].map(name => readFile(new URL(name, import.meta.url))))));
|
|
20
|
+
|
|
21
|
+
export function discoverProject(config) {
|
|
22
|
+
const tsx = listSources(config.design, sourceDirectories(config)).map(file => relative(config, file));
|
|
23
|
+
return { tsx, architecture: archFiles(config.arch).map(file => relative(config, file)) };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function tokenFacts(config) {
|
|
27
|
+
const { light, dark } = loadTokens(config);
|
|
28
|
+
const locations = tokenLocations(readFileSync(path.join(config.design, 'tokens.css'), 'utf8'));
|
|
29
|
+
return [...light].map(([name, value]) => ({ name, source: relative(config, path.join(config.design, 'tokens.css')),
|
|
30
|
+
values: [{ theme: 'light', declaration: value, inherited: false }, { theme: 'dark', declaration: dark.get(name) ?? value, inherited: !dark.has(name) }]
|
|
31
|
+
.map(item => ({ ...item, line: (item.theme === 'dark' && !item.inherited ? locations.dark : locations.light).get(name), references: [...item.declaration.matchAll(/var\(\s*(--[\w-]+)/g)].map(match => match[1]) })) }));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function resolutionFiles(config, artifactDirectory) {
|
|
35
|
+
const files = [];
|
|
36
|
+
async function visit(directory) {
|
|
37
|
+
for (const entry of await readdir(directory, { withFileTypes: true })) {
|
|
38
|
+
if (['.git', '.adg', 'node_modules'].includes(entry.name)) continue;
|
|
39
|
+
const file = path.join(directory, entry.name);
|
|
40
|
+
if (file === config.output) continue;
|
|
41
|
+
if (entry.isDirectory()) await visit(file);
|
|
42
|
+
else if (!(artifactDirectory && !path.relative(artifactDirectory, file).startsWith('..') && !path.isAbsolute(path.relative(artifactDirectory, file)) && /\.(?:png|json)$/.test(file))) files.push(path.relative(config.design, file));
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
try { await visit(config.design); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
46
|
+
return files.sort();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function openProjectIndex(config, { stateDirectory = defaultStateDirectory, persist = true, fresh = false, artifactDirectory } = {}) {
|
|
50
|
+
const inventory = discoverProject(config), root = await realpath(config.root), buildPromises = new Map();
|
|
51
|
+
const directory = path.join(stateDirectory, 'cache', indexDigest(root), 'index-v1');
|
|
52
|
+
const shards = await createIndexStore({ directory, persist });
|
|
53
|
+
const buildDirectory = path.join(stateDirectory, 'cache', indexDigest(root), 'build');
|
|
54
|
+
let storePromise, closed = false;
|
|
55
|
+
let freshPool;
|
|
56
|
+
const materializations = new Map();
|
|
57
|
+
const resolution = fresh ? await resolutionFiles(config, artifactDirectory) : null;
|
|
58
|
+
const physicalDesign = inventory.tsx.length ? await realpath(config.design) : null;
|
|
59
|
+
const observedInputs = new Map(), requestedSources = new Set();
|
|
60
|
+
const assertOpen = () => { if (closed) throw Error('Project index is closed.'); };
|
|
61
|
+
async function getBuild(source) {
|
|
62
|
+
assertOpen();
|
|
63
|
+
if (!inventory.tsx.includes(source)) throw Error(`Undiscovered TSX source ${source}.`);
|
|
64
|
+
requestedSources.add(source);
|
|
65
|
+
if (!buildPromises.has(source)) buildPromises.set(source, (async () => {
|
|
66
|
+
let built;
|
|
67
|
+
if (!persist) {
|
|
68
|
+
const snapshot = new Map();
|
|
69
|
+
built = await buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false, snapshot });
|
|
70
|
+
built.dependencyHashes = Object.fromEntries([...snapshot].map(([file, bytes]) => [path.relative(config.design, file), indexDigest(bytes === null ? 'missing\0' : Buffer.concat([Buffer.from('present\0'), bytes]))]));
|
|
71
|
+
} else {
|
|
72
|
+
storePromise ??= createBuildStore({ config: { ...config, sourceFiles: inventory.tsx }, cacheDirectory: buildDirectory });
|
|
73
|
+
built = await (await storePromise).get(path.relative(config.design, path.join(config.root, source)).split(path.sep).join('/'));
|
|
74
|
+
}
|
|
75
|
+
return observeDependencies(built);
|
|
76
|
+
})().finally(() => buildPromises.delete(source)));
|
|
77
|
+
return buildPromises.get(source);
|
|
78
|
+
}
|
|
79
|
+
function observeDependencies(built) {
|
|
80
|
+
for (const [name, hash] of Object.entries(built.dependencyHashes)) {
|
|
81
|
+
if (observedInputs.has(name) && observedInputs.get(name) !== hash) throw new CliError('OWNER_INDEX_CHANGED', `Design dependency changed during query: ${name}.`);
|
|
82
|
+
observedInputs.set(name, hash);
|
|
83
|
+
}
|
|
84
|
+
return built;
|
|
85
|
+
}
|
|
86
|
+
function materialize(source) {
|
|
87
|
+
assertOpen();
|
|
88
|
+
if (!inventory.tsx.includes(source)) throw Error(`Undiscovered TSX source ${source}.`);
|
|
89
|
+
if (!materializations.has(source)) {
|
|
90
|
+
requestedSources.add(source); freshPool ??= new BuildPool();
|
|
91
|
+
materializations.set(source, freshPool.run({ config: { root, design: physicalDesign ?? config.design, output: config.output,
|
|
92
|
+
sources: config.sources, arch: config.arch, check: config.check, allowLegacy: false },
|
|
93
|
+
name: path.relative(physicalDesign ?? config.design, path.join(root, source)).split(path.sep).join('/') }, new AbortController().signal).then(built => {
|
|
94
|
+
observeDependencies(built);
|
|
95
|
+
for (const frame of built.frames) frame.document = theme => frameDocument(frame, theme, built.css);
|
|
96
|
+
return built;
|
|
97
|
+
}));
|
|
98
|
+
}
|
|
99
|
+
return materializations.get(source);
|
|
100
|
+
}
|
|
101
|
+
async function cached(projection, inputs, collect) {
|
|
102
|
+
const key = JSON.stringify({ version: 1, collectorIdentity, projection, inputs });
|
|
103
|
+
const hit = await shards.get(key);
|
|
104
|
+
if (hit !== null) return hit;
|
|
105
|
+
const value = await collect(); await shards.put(key, value); return value;
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
inventory,
|
|
109
|
+
getBuild,
|
|
110
|
+
materialize,
|
|
111
|
+
async source(source, { tokens = false, fresh = false } = {}) {
|
|
112
|
+
const built = fresh ? await materialize(source) : await getBuild(source);
|
|
113
|
+
const inputs = fresh ? null : { source, build: built.inputHash ?? indexDigest(JSON.stringify({ ...built, frames: built.frames.map(({ document, ...frame }) => frame) })) };
|
|
114
|
+
const facts = fresh ? sourceFacts(config, source, built) : await cached('source', inputs, () => sourceFacts(config, source, built));
|
|
115
|
+
if (!tokens) return facts;
|
|
116
|
+
const collect = () => {
|
|
117
|
+
const scan = entryTokenReachability((built.cssBeforeTokens + built.cssAfterTokens).replace(/<\/style/gi, '<\\/style'), built.tokenCss);
|
|
118
|
+
return built.frames.map(frame => {
|
|
119
|
+
const reach = scan(frameDocument(frame, 'light', ''));
|
|
120
|
+
return { frame: frame.name, themes: ['light', 'dark'].map(theme => ({ theme, ...reach(theme) })) };
|
|
121
|
+
});
|
|
122
|
+
};
|
|
123
|
+
const tokenDependencies = fresh ? collect() : await cached('token-dependencies', inputs, collect);
|
|
124
|
+
return { ...facts, tokenDependencies };
|
|
125
|
+
},
|
|
126
|
+
tokens() { assertOpen(); return tokenFacts(config); },
|
|
127
|
+
async mappings({ selected, map: supplied, ...selection } = {}) {
|
|
128
|
+
assertOpen();
|
|
129
|
+
// Implementation inventories and locator bytes are re-read each invocation.
|
|
130
|
+
const map = supplied ?? await loadImplementationMap(config);
|
|
131
|
+
return { map, ...await validateImplementationMap(config, map, { sources: inventory.tsx, selected, getBuild, ...selection }) };
|
|
132
|
+
},
|
|
133
|
+
async observation(source, built, frame, theme, environment, collect) {
|
|
134
|
+
assertOpen();
|
|
135
|
+
if (environment === null) return collect();
|
|
136
|
+
const build = built.inputHash ?? indexDigest(JSON.stringify({ css: built.css, frame }));
|
|
137
|
+
return cached('owner-observation', { source, build, frame: frame.name, theme, environment }, collect);
|
|
138
|
+
},
|
|
139
|
+
async palette(tokens, theme, environment, collect) {
|
|
140
|
+
assertOpen();
|
|
141
|
+
return environment === null ? collect() : cached('owner-palette', { tokens, theme, environment }, collect);
|
|
142
|
+
},
|
|
143
|
+
async color(input, environment, collect) {
|
|
144
|
+
assertOpen();
|
|
145
|
+
if (environment === null) return collect();
|
|
146
|
+
const key = JSON.stringify({ version: 1, collectorIdentity, projection: 'query-colors', environment });
|
|
147
|
+
const entries = new Map(await shards.get(key) ?? []);
|
|
148
|
+
if (entries.has(input)) return entries.get(input);
|
|
149
|
+
const value = await collect(); entries.set(input, value);
|
|
150
|
+
while (entries.size > 128) entries.delete(entries.keys().next().value);
|
|
151
|
+
await shards.put(key, [...entries]); return value;
|
|
152
|
+
},
|
|
153
|
+
async verifyInputs() {
|
|
154
|
+
if (JSON.stringify(discoverProject(config)) !== JSON.stringify(inventory)) throw new CliError('OWNER_INDEX_CHANGED', 'Design source inventory changed during query.');
|
|
155
|
+
if (resolution && JSON.stringify(await resolutionFiles(config, artifactDirectory)) !== JSON.stringify(resolution)) throw new CliError('OWNER_INDEX_CHANGED', 'Design resolution inventory changed during query.');
|
|
156
|
+
for (const [name, hash] of observedInputs) {
|
|
157
|
+
let value;
|
|
158
|
+
try { value = indexDigest(Buffer.concat([Buffer.from('present\0'), await readFile(path.join(config.design, name))])); }
|
|
159
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; value = indexDigest('missing\0'); }
|
|
160
|
+
if (value !== hash) throw new CliError('OWNER_INDEX_CHANGED', `Design dependency changed during query: ${name}.`);
|
|
161
|
+
}
|
|
162
|
+
},
|
|
163
|
+
async architecture(source) {
|
|
164
|
+
assertOpen();
|
|
165
|
+
if (!inventory.architecture.includes(source)) throw Error(`Undiscovered architecture source ${source}.`);
|
|
166
|
+
const side = source.replace(/\.mmd$/, '.md'); let text = '';
|
|
167
|
+
try { text = await readFile(path.join(config.root, side), 'utf8'); } catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
168
|
+
return cached('architecture', { source, text }, () => ({ source, sidecar: side, ...sidecar(text) }));
|
|
169
|
+
},
|
|
170
|
+
async relationships({ facts: supplied, projectPaths = false } = {}) {
|
|
171
|
+
const assets = await Promise.all(inventory.tsx.map(async source => {
|
|
172
|
+
const facts = supplied?.get(source) ?? await this.source(source);
|
|
173
|
+
if (projectPaths) return { path: source, imports: facts.imports };
|
|
174
|
+
const designRelative = file => path.relative(config.design, path.join(config.root, file)).split(path.sep).join('/');
|
|
175
|
+
return { path: designRelative(source), imports: facts.imports.map(designRelative) };
|
|
176
|
+
}));
|
|
177
|
+
assets.push(...inventory.architecture.map(source => ({ path: source, imports: [] })));
|
|
178
|
+
return sourceRelationships(assets);
|
|
179
|
+
},
|
|
180
|
+
stats: async () => ({ shards: shards.stats(), builds: storePromise ? (await storePromise).stats() : null,
|
|
181
|
+
materializations: freshPool?.stats() ?? null, requestedSources: [...requestedSources] }),
|
|
182
|
+
async close() {
|
|
183
|
+
closed = true;
|
|
184
|
+
try { if (storePromise) await (await storePromise).close(); }
|
|
185
|
+
finally { try { await freshPool?.close(); materializations.clear(); } finally { await shards.close(); } }
|
|
186
|
+
},
|
|
187
|
+
};
|
|
188
|
+
}
|
package/src/toolkit/results.mjs
CHANGED
|
@@ -3,9 +3,9 @@ import { CliError, classifyError } from '../cli-output.mjs';
|
|
|
3
3
|
/** @typedef {'light' | 'dark'} Theme */
|
|
4
4
|
/** @typedef {{source: string | null, frame: string | null, theme: Theme | null, line: number | null, column: number | null}} Location */
|
|
5
5
|
/** @typedef {Location & {code: string, message: string}} Finding */
|
|
6
|
-
/** @typedef {{project: string, readOnly: boolean, complete: boolean, sources: string[], summary: {sources: number, frames: number, evaluations: number, problems: number}, findings: Finding[]}} CheckData */
|
|
6
|
+
/** @typedef {{project: string, readOnly: boolean, complete: boolean, impact: object | null, sources: string[], summary: {sources: number, frames: number, evaluations: number, problems: number}, findings: Finding[]}} CheckData */
|
|
7
7
|
/** @typedef {{source: string, frame: string, theme: Theme, path: string, scale: number, width: number, height: number, pixelWidth: number, pixelHeight: number}} Capture */
|
|
8
|
-
/** @typedef {{project: string, outputDirectory: string, complete: boolean, base: {rev: string, sha: string} | null, captures: Capture[], deleted: string[]}} RenderData */
|
|
8
|
+
/** @typedef {{project: string, outputDirectory: string, complete: boolean, impact: object | null, base: {rev: string, sha: string} | null, captures: Capture[], deleted: string[]}} RenderData */
|
|
9
9
|
/** @typedef {{source: string, frame: string, fixture: string, theme: Theme, settled: boolean, size: {design: [number, number], implementation: [number, number]}, matched: number, offBy2px: {text: string, dx: number, dy: number, dw: number, off: number}[], missing: string[], extra: string[], paths: {design: string, implementation: string, overlay: string, report: string, html: string}}} Comparison */
|
|
10
10
|
/** @typedef {{project: string, complete: boolean, all: boolean, comparisons: Comparison[], skipped: {source: string, frame: string, reason: 'no_fixture'}[], summary: {frames: number, matched: number, offsets: number, missing: number, extra: number}, indexPath: string | null, summaryPath: string | null}} CompareData */
|
|
11
11
|
|
package/src/toolkit/runtime.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
export type Content = unknown;
|
|
2
2
|
export type Capture = ({ region: string; selector?: never; page?: never } | { selector: string; region?: never; page?: never } | { page: true; region?: never; selector?: never }) & { viewport?: string; origin?: string; clicks?: string[] };
|
|
3
3
|
export interface FrameParent { source: string; frame: string; selector: string }
|
|
4
|
-
export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; parent?: FrameParent; note?: string; children?: Content }
|
|
4
|
+
export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; parent?: FrameParent; note?: string; locale?: string; children?: Content }
|
|
5
5
|
export interface IconProps { name: string; size?: number; class?: string }
|
|
6
6
|
export function Frame(props: FrameProps): JSX.Element;
|
|
7
7
|
export function Icon(props: IconProps): JSX.Element;
|
package/src/toolkit/runtime.mjs
CHANGED
|
@@ -16,6 +16,7 @@ export function attributes(props) {
|
|
|
16
16
|
}).join('');
|
|
17
17
|
}
|
|
18
18
|
const componentOwners = new WeakMap();
|
|
19
|
+
export const componentOwner = component => componentOwners.get(component);
|
|
19
20
|
export function registerComponent(component, source, name) {
|
|
20
21
|
if (typeof component === 'function' && !componentOwners.has(component)) componentOwners.set(component, {source, export:name});
|
|
21
22
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import { realpathSync } from 'node:fs';
|
|
3
|
+
|
|
4
|
+
export function frameOwners(html) {
|
|
5
|
+
const result = new Map();
|
|
6
|
+
for (const [, encoded] of html.matchAll(/\bdata-adg-owners="([^"]*)"/g)) {
|
|
7
|
+
const value = encoded.replace(/&(quot|amp|lt|gt|#39);/g, (_, entity) => ({ quot: '"', amp: '&', lt: '<', gt: '>', '#39': "'" })[entity]);
|
|
8
|
+
for (const owner of JSON.parse(value)) result.set(JSON.stringify(owner), owner);
|
|
9
|
+
}
|
|
10
|
+
return [...result.values()];
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function mappingFacts(built) {
|
|
14
|
+
return { parts: built.parts ?? [], frames: built.frames.map(frame => ({ name: frame.name, owners: frame.owners ?? frameOwners(frame.html) })) };
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function sourceFacts(config, source, built) {
|
|
18
|
+
const root = realpathSync(config.root), design = realpathSync(config.design);
|
|
19
|
+
const projectPath = file => path.relative(root, file).split(path.sep).join('/');
|
|
20
|
+
const designPath = name => projectPath(path.join(design, name));
|
|
21
|
+
return { source, parts: built.parts ?? [],
|
|
22
|
+
imports: built.imports.map(designPath),
|
|
23
|
+
dependencies: built.dependencies.map(file => path.isAbsolute(file) ? projectPath(file) : designPath(file)),
|
|
24
|
+
frames: built.frames.map(({ html, document, ...frame }) => ({ ...frame, parts: frameOwners(html).map(owner => ({ source: designPath(owner.source), part: owner.export })) })) };
|
|
25
|
+
}
|