@whzxc/agent-design-gallery 0.10.0 → 0.13.2
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 +3 -3
- package/package.json +2 -2
- package/public/annotations.js +816 -0
- package/public/app.js +245 -12
- package/public/assets.js +4 -13
- package/public/frame-identity.js +223 -0
- package/public/icons.js +1 -0
- package/public/index.html +3 -0
- package/public/selection.js +1 -1
- package/public/style.css +72 -2
- package/src/annotations.mjs +238 -0
- package/src/cli-output.mjs +25 -2
- package/src/cli.mjs +46 -7
- package/src/http.mjs +2 -1
- package/src/hub/instances.mjs +1 -1
- package/src/hub/registry.mjs +1 -1
- package/src/hub.mjs +2 -2
- package/src/server.mjs +59 -11
- package/src/service.mjs +1 -1
- package/src/toolkit/arch-overlay.mjs +1 -1
- package/src/toolkit/asset-rules.mjs +42 -3
- package/src/toolkit/build-store.mjs +1 -1
- package/src/toolkit/build-worker.mjs +1 -1
- package/src/toolkit/build.mjs +27 -11
- package/src/toolkit/commands.mjs +61 -8
- package/src/toolkit/config.mjs +2 -1
- package/src/toolkit/diff.mjs +4 -1
- package/src/toolkit/document.mjs +6 -6
- package/src/toolkit/frame-document.mjs +1 -1
- package/src/toolkit/frame-facets.mjs +167 -0
- package/src/toolkit/frame-identity.mjs +100 -0
- package/src/toolkit/frame-observation.mjs +147 -0
- package/src/toolkit/frame-primitives.mjs +85 -0
- package/src/toolkit/html.mjs +1 -0
- package/src/toolkit/impact-inputs.mjs +2 -21
- package/src/toolkit/impact.mjs +3 -24
- package/src/toolkit/input-generation.mjs +51 -0
- package/src/toolkit/inspect-encoding.mjs +459 -0
- package/src/toolkit/inspect-observation.mjs +56 -0
- package/src/toolkit/inspect-output.mjs +169 -0
- package/src/toolkit/inspect-styles.mjs +34 -0
- package/src/toolkit/inspect.d.ts +118 -0
- package/src/toolkit/inspect.mjs +125 -0
- package/src/toolkit/owner-observation.mjs +23 -189
- package/src/toolkit/owner-search.mjs +2 -2
- package/src/toolkit/owner.mjs +33 -4
- package/src/toolkit/part-diff.mjs +2 -0
- package/src/toolkit/part-snapshot.mjs +15 -23
- package/src/toolkit/project-index.mjs +22 -5
- package/src/toolkit/project.mjs +52 -6
- package/src/toolkit/runtime.d.ts +7 -5
- package/src/toolkit/runtime.mjs +20 -7
|
@@ -4,11 +4,15 @@ import os from 'node:os';
|
|
|
4
4
|
import { indexDigest } from './index-store.mjs';
|
|
5
5
|
import { CliError } from '../cli-output.mjs';
|
|
6
6
|
import { loadFrame, browserTask, readyResources } from './browser.mjs';
|
|
7
|
-
import {
|
|
7
|
+
import { frameDocument } from './frame-document.mjs';
|
|
8
|
+
import { collectOwnerObservation, installFramePrimitives } from './frame-observation.mjs';
|
|
9
|
+
import { elementIdentities } from './frame-identity.mjs';
|
|
10
|
+
export { collectOwnerObservation } from './frame-observation.mjs';
|
|
8
11
|
import { installColorResolver } from './owner-colors.mjs';
|
|
9
12
|
|
|
10
13
|
export const normalizeOwnerText = text => text.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
11
14
|
const contexts = new WeakMap();
|
|
15
|
+
const preparedPages = new WeakSet();
|
|
12
16
|
|
|
13
17
|
export function occurrenceContext(observation, occurrence) {
|
|
14
18
|
if (!contexts.has(observation)) contexts.set(observation, new Map(observation.nodes.map(node => [node.path, node])));
|
|
@@ -20,19 +24,32 @@ export function occurrenceContext(observation, occurrence) {
|
|
|
20
24
|
if (!owners.length && node.owners?.length) owners.push(...node.owners.map(owner => ({ ...owner, distance })));
|
|
21
25
|
node = byPath.get(node.parentPath); distance++;
|
|
22
26
|
}
|
|
23
|
-
return { ...occurrence, ancestors: occurrence.ancestors ?? ancestors, owners: occurrence.owners ?? owners, box: occurrence.box ?? byPath.get(path)?.box, distance: owners[0]?.distance ?? distance };
|
|
27
|
+
return { ...occurrence, ...(byPath.get(path)?.elementId ? {elementId:byPath.get(path).elementId} : {}), ancestors: occurrence.ancestors ?? ancestors, owners: occurrence.owners ?? owners, box: occurrence.box ?? byPath.get(path)?.box, distance: owners[0]?.distance ?? distance };
|
|
24
28
|
}
|
|
25
29
|
|
|
26
30
|
export async function observeOwnerFrame(index, source, built, frame, theme, environment, getPage, tokens) {
|
|
27
|
-
|
|
31
|
+
const observed=await index.observation(source, built, frame, theme, environment, async () => {
|
|
28
32
|
const page = await getPage();
|
|
29
|
-
const rendered = { ...frame, document: value =>
|
|
33
|
+
const rendered = { ...frame, document: value => frameDocument(frame,value,built.css) };
|
|
30
34
|
await loadFrame(page, rendered, theme);
|
|
31
35
|
return browserTask(page.context().browser(), async () => {
|
|
32
|
-
await page.evaluate(readyResources);
|
|
33
|
-
|
|
36
|
+
await page.evaluate(readyResources);
|
|
37
|
+
if (!preparedPages.has(page)) {
|
|
38
|
+
await page.evaluate(installColorResolver); await page.evaluate(installFramePrimitives);
|
|
39
|
+
preparedPages.add(page);
|
|
40
|
+
}
|
|
41
|
+
const observation=await settleOwnerObservation(() => page.evaluate(collectOwnerObservation, { tokens, theme }), () => page.evaluate(() => new Promise(resolve => requestAnimationFrame(resolve))));
|
|
42
|
+
if(observation.identities){
|
|
43
|
+
const ids=new Map(elementIdentities(observation.identities,{source,frame:frame.name},{metadata:false}).map(n=>[n.path,n]));
|
|
44
|
+
for(const node of observation.nodes){node.elementId=ids.get(node.path).id;}
|
|
45
|
+
delete observation.identities;
|
|
46
|
+
}
|
|
47
|
+
return observation;
|
|
34
48
|
});
|
|
35
49
|
});
|
|
50
|
+
// A rich shared hit retains raw identity inputs for inspect; owner projects the same addresses.
|
|
51
|
+
if(observed.identities){const ids=new Map(elementIdentities(observed.identities,{source,frame:frame.name},{metadata:false}).map(n=>[n.path,n.id]));for(const node of observed.nodes)node.elementId=ids.get(node.path);}
|
|
52
|
+
return observed;
|
|
36
53
|
}
|
|
37
54
|
|
|
38
55
|
export function collectOwnerPalette({ tokens }) {
|
|
@@ -76,189 +93,6 @@ export async function observationEnvironment() {
|
|
|
76
93
|
return indexDigest(JSON.stringify({ platform: process.platform, release: os.release(), arch: process.arch, locale: 'en-US', timezone: 'UTC', deviceScaleFactor: 1, files: files.sort() }));
|
|
77
94
|
}
|
|
78
95
|
|
|
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
96
|
|
|
263
97
|
export async function settleOwnerObservation(read, wait, now = () => performance.now()) {
|
|
264
98
|
const start = now(); let previous = JSON.stringify(await read());
|
|
@@ -98,7 +98,7 @@ export async function searchOwner(config, values, { log = console.log, openIndex
|
|
|
98
98
|
const detail = query.kind === 'text' ? { kind: 'text', raw: match.raw, normalized: match.normalized, fragments: match.fragments }
|
|
99
99
|
: query.kind === 'color' ? { kind: 'paint', property: match.property, computed: match.computed, rgba: match.rgba, usage: 'computed_value' }
|
|
100
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 };
|
|
101
|
+
const evidence = { matchKind: kind, frame: ref, theme, elementPath: match.path, ...(ctx.elementId ? {elementId:ctx.elementId} : {}), boxes: query.kind === 'text' ? match.fragments.flatMap(f => f.boxes) : ctx.box ? [ctx.box] : [], owners, detail };
|
|
102
102
|
const scope = new Set(ctx.ancestors);
|
|
103
103
|
for (const fragment of match.fragments ?? []) for (const ancestor of occurrenceContext(observation, { path: fragment.elementPath }).ancestors) scope.add(ancestor);
|
|
104
104
|
const references = query.kind === 'token' ? [match] : query.kind === 'color'
|
|
@@ -113,7 +113,7 @@ export async function searchOwner(config, values, { log = console.log, openIndex
|
|
|
113
113
|
const key = JSON.stringify([target.source, target.part]);
|
|
114
114
|
if (!rows.has(key)) rows.set(key, { source: target.source, part: target.part, matchKind: kind, rank, frames: [], tokens: [], evidence: [] });
|
|
115
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 });
|
|
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, proposed: frame.proposed ?? null });
|
|
117
117
|
row.evidence.push(evidence);
|
|
118
118
|
if (query.kind === 'text') row.authoredIn = orderAuthoredIn([...(row.authoredIn ?? []), ...evidence.authoredIn], [row.source, ...row.frames.map(frame => frame.source)]);
|
|
119
119
|
for (const reference of references) {
|
package/src/toolkit/owner.mjs
CHANGED
|
@@ -2,14 +2,16 @@ import { readFile } from 'node:fs/promises';
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { CliError, nextActions } from '../cli-output.mjs';
|
|
4
4
|
import { openProjectIndex } from './project-index.mjs';
|
|
5
|
-
import { loadImplementationMap, implementationFiles } from './implementation-map.mjs';
|
|
5
|
+
import { loadImplementationMap, implementationFiles, validateImplementationMap } from './implementation-map.mjs';
|
|
6
6
|
import { regionAt } from './owner-locators.mjs';
|
|
7
7
|
import { normalizeFileQuery, implementationScope } from './implementation-query.mjs';
|
|
8
8
|
import { launch, loadFrame, readyResources, browserTask } from './browser.mjs';
|
|
9
9
|
import { observeOwnerFrame, observeOwnerPalette, occurrenceContext, observationEnvironment } from './owner-observation.mjs';
|
|
10
10
|
import { commandFailure, cleanup } from './results.mjs';
|
|
11
|
-
import { escape } from './
|
|
11
|
+
import { escape } from './html.mjs';
|
|
12
12
|
import { indexDigest } from './index-store.mjs';
|
|
13
|
+
import { buildSource } from './build.mjs';
|
|
14
|
+
import { listSources, sourceDirectories, selectSources, relative } from './project.mjs';
|
|
13
15
|
|
|
14
16
|
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
17
|
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; };
|
|
@@ -27,7 +29,34 @@ function bindingKind(selector, query) {
|
|
|
27
29
|
: selector.file ? 'mapping_file' : selector.directory ? 'mapping_directory' : 'mapping_glob';
|
|
28
30
|
}
|
|
29
31
|
|
|
32
|
+
async function ownerPart(config, values, { log = console.log } = {}) {
|
|
33
|
+
const raw = values.part, split = raw.indexOf('#'), sourceInput = split < 0 ? raw : raw.slice(0, split), part = split < 0 ? null : raw.slice(split + 1);
|
|
34
|
+
if (!sourceInput.trim() || (part !== null && !part.trim())) throw new CliError('USAGE_INVALID', 'Use --part=<source> or --part=<source>#<Export>.');
|
|
35
|
+
const selected = selectSources(config, [sourceInput], { write: false });
|
|
36
|
+
const source = relative(config, selected[0]), designSource = source;
|
|
37
|
+
const data = { project: config.root, complete: false, query: { kind: 'part', input: raw, normalized: raw, source, part }, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [], coverage: { discoveredSources: listSources(config.design, sourceDirectories(config)).length, builtSources: 0, requestedObservations: 0, completedObservations: 0, mappingState: 'absent', activeBindings: 0, excludedBindings: 0, domain: 'tsx' } };
|
|
38
|
+
const map = await loadImplementationMap(config);
|
|
39
|
+
data.coverage.mappingState = map.present ? 'valid' : 'absent';
|
|
40
|
+
if (!map.present) { data.complete = true; const missingWarning = { code: 'OWNER_MAPPING_MISSING', message: 'Add implementation.json to declare implementation ownership.', next: [] }; return { data, warnings: [missingWarning] }; }
|
|
41
|
+
const validated = await validateImplementationMap(config, map, { sources: listSources(config.design, sourceDirectories(config)).map(file => relative(config, file)), getBuild: target => buildSource(config, path.join(config.root, target), { write: false, allowLegacy: false }) });
|
|
42
|
+
data.mappingFindings = validated.findings; data.coverage.mappingState = validated.findings.length ? 'stale' : 'valid';
|
|
43
|
+
const warnings = validated.findings.length ? [{ code: 'OWNER_MAPPING_STALE', message: 'Repair the reported implementation mapping findings, then repeat the query.', next: [] }] : [];
|
|
44
|
+
for (const binding of validated.bindings.filter(binding => binding.active && binding.design.source === designSource && (part === null ? binding.design.part === undefined : binding.design.part === part))) {
|
|
45
|
+
data.coverage.activeBindings++;
|
|
46
|
+
const selector = binding.implementation;
|
|
47
|
+
const implementations = binding.files.map(file => ({ file, symbol: selector.symbol ?? null, region: binding.anchorLine === null ? null : (validated.regions[file] ?? []).find(region => region.line === binding.anchorLine) ?? null }));
|
|
48
|
+
const row = { source, part, matchKind: 'mapping_part', rank: fileRank(selector, 'mapping_symbol'), frames: binding.frames.map(frame => ({ source, frame, theme: null, locale: null, proposed: null })), tokens: [], evidence: [], implementation: selector };
|
|
49
|
+
for (const implementation of implementations) row.evidence.push({ matchKind: 'mapping_part', frame: null, theme: null, elementPath: null, boxes: [], owners: [], detail: { kind: 'mapping', file: map.source, pointer: binding.pointer, implementation: implementation.file, selector, symbol: selector.symbol ?? null, region: implementation.region } });
|
|
50
|
+
data.owners.push(row);
|
|
51
|
+
}
|
|
52
|
+
data.complete = true;
|
|
53
|
+
if (!data.owners.length) warnings.push({ code: 'OWNER_NO_MATCH', message: 'No implementation binding matched the requested design part.', next: [] });
|
|
54
|
+
if (!values.json) for (const row of data.owners) log(`${row.source}${row.part ? `#${row.part}` : ''} [${row.matchKind}] ${row.evidence.map(e => e.detail.implementation).join(', ')}`);
|
|
55
|
+
return { data, warnings };
|
|
56
|
+
}
|
|
57
|
+
|
|
30
58
|
export async function owner(config, values, { log = console.log, openIndex = openProjectIndex, launchBrowser = launch, environment = observationEnvironment } = {}) {
|
|
59
|
+
if (values.part !== undefined) return ownerPart(config, values, { log });
|
|
31
60
|
if (values.file === undefined) return (await import('./owner-search.mjs')).searchOwner(config, values, { log, openIndex, launchBrowser, environment });
|
|
32
61
|
const { query, text } = await normalizeFileQuery(config, values);
|
|
33
62
|
const data = { project: config.root, complete: false, query, region: null, owners: [], tokens: [], ambiguous: false, tokenAmbiguous: false, matchedImplementationFiles: [], mappingFindings: [],
|
|
@@ -74,7 +103,7 @@ export async function owner(config, values, { log = console.log, openIndex = ope
|
|
|
74
103
|
for (const implementation of binding.files) {
|
|
75
104
|
const boundary = binding.anchorLine === null ? null : regionAt(validated.regions[implementation] ?? [], binding.anchorLine);
|
|
76
105
|
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) : [],
|
|
106
|
+
for (const node of matches) row.evidence.push({ matchKind: kind, frame: ref, theme, elementPath: node?.path ?? null, ...(node?.elementId ? {elementId:node.elementId} : {}), boxes: node ? [node.box] : [], owners: node ? projectOwners(node.owners) : [],
|
|
78
107
|
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
108
|
anchorLine: binding.anchorLine, nextBoundaryLine: boundary?.nextBoundaryLine ?? null } });
|
|
80
109
|
}
|
|
@@ -98,7 +127,7 @@ export async function owner(config, values, { log = console.log, openIndex = ope
|
|
|
98
127
|
for (const { row, binding } of task.bindings) {
|
|
99
128
|
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
129
|
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 });
|
|
130
|
+
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, proposed: frame.proposed ?? null });
|
|
102
131
|
addMapping(row, binding, ref, task.theme, roots);
|
|
103
132
|
for (const rawReference of observation.references) {
|
|
104
133
|
const reference = occurrenceContext(observation, rawReference);
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { installFramePrimitives } from './frame-observation.mjs';
|
|
1
2
|
import { loadTokens } from './project.mjs';
|
|
2
3
|
import { loadFrame, readyResources } from './browser.mjs';
|
|
3
4
|
import { collectPartSnapshot, normalizeSnapshot, snapshotFindings, settlePart } from './part-snapshot.mjs';
|
|
@@ -25,6 +26,7 @@ export function partContext(built, inputs, scale, themes, clock) {
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
async function readSnapshot(page, args) {
|
|
29
|
+
await page.evaluate(installFramePrimitives);
|
|
28
30
|
const snapshot = await page.evaluate(collectPartSnapshot, args);
|
|
29
31
|
if (snapshot.referenceError) throw new CliError('DIFF_REFERENCE_INVALID', snapshot.referenceError);
|
|
30
32
|
if (snapshot.unsupported.length) {
|
|
@@ -10,13 +10,13 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
10
10
|
if (roots.length !== 1) return { referenceError: `Expected one target for ${selector ?? 'the part root'}, found ${roots.length}.` };
|
|
11
11
|
const root = roots[0], origin = root.getBoundingClientRect(), frameBox = frame.getBoundingClientRect();
|
|
12
12
|
if (!origin.width || !origin.height || getComputedStyle(root).visibility !== 'visible') return { referenceError: 'The parent/part target must be visible.' };
|
|
13
|
-
const
|
|
14
|
-
const box = rect => (
|
|
13
|
+
const { inventory,relativeBox,reads,styleRules,textRects }=globalThis.__adgFramePrimitives;
|
|
14
|
+
const box = rect => relativeBox(rect,origin);
|
|
15
15
|
const cssCrop = { x: origin.x - frameBox.x, y: origin.y - frameBox.y, width: origin.width, height: origin.height };
|
|
16
16
|
const left = Math.floor(cssCrop.x * scale), top = Math.floor(cssCrop.y * scale);
|
|
17
17
|
const deviceCrop = { x: left, y: top, width: Math.ceil((cssCrop.x + origin.width) * scale) - left, height: Math.ceil((cssCrop.y + origin.height) * scale) - top };
|
|
18
18
|
const fractionalOrigin = { x: cssCrop.x * scale - left, y: cssCrop.y * scale - top };
|
|
19
|
-
const nodes
|
|
19
|
+
const {elements:nodes,paths}=inventory(root), {style:styleFor,rect:rectFor}=reads();
|
|
20
20
|
const ids = new Map(nodes.filter(node => node.id).map(node => [node.id, `node-${paths.get(node)}`]));
|
|
21
21
|
const unsupported = [], resources = [], resourceCache = new Map(), decoded = new Map();
|
|
22
22
|
const internalIds = value => value.replace(/url\(["']?#([^)'"\s]+)["']?\)/g, (_, id) => `url(#${ids.get(id) ?? id})`);
|
|
@@ -67,18 +67,10 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
67
67
|
};
|
|
68
68
|
const paintProperty = property => /color|background|fill|stroke|shadow|opacity|filter|blend|mask|clip-path/.test(property);
|
|
69
69
|
const ignored = /^(?:--|animation|transition|cursor$|pointer-events$|user-select$|touch-action$|scroll-behavior$|caret-color$)/;
|
|
70
|
-
const tokenRules
|
|
71
|
-
const visitRules = rules => {
|
|
72
|
-
for (const rule of rules) {
|
|
73
|
-
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
74
|
-
if (rule.selectorText && rule.style) tokenRules.push(rule);
|
|
75
|
-
if (rule.cssRules) visitRules(rule.cssRules);
|
|
76
|
-
}
|
|
77
|
-
};
|
|
78
|
-
for (const sheet of document.styleSheets) visitRules(sheet.cssRules);
|
|
70
|
+
const tokenRules=styleRules().map(item=>item.rule);
|
|
79
71
|
const elements = [], texts = [], rasters = [], edgeBoxes = [];
|
|
80
72
|
for (const node of nodes) {
|
|
81
|
-
const path = paths.get(node), style =
|
|
73
|
+
const path = paths.get(node), style = styleFor(node), rect = rectFor(node);
|
|
82
74
|
inspectPaint(style, path);
|
|
83
75
|
if (node.matches('canvas,video,object,embed,foreignObject')) unsupported.push({ path, property: 'paint', value: node.localName });
|
|
84
76
|
const computedStyle = await normalizeStyle(style), layout = {}, paint = {};
|
|
@@ -118,8 +110,7 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
118
110
|
owners: JSON.parse(node.getAttribute('data-adg-owners') ?? '[]') });
|
|
119
111
|
for (const [index, child] of [...node.childNodes].entries()) {
|
|
120
112
|
if (child.nodeType !== 3 || !child.textContent.trim()) continue;
|
|
121
|
-
const
|
|
122
|
-
const lines = [...range.getClientRects()].map(rect => ({ text: child.textContent, box: box(rect) }));
|
|
113
|
+
const lines = textRects(child).rects.map(rect => ({ text: child.textContent, box: box(rect) }));
|
|
123
114
|
texts.push({ path: `${path}/text-${index}`, parentPath: path, text: child.textContent, lines });
|
|
124
115
|
edgeBoxes.push(...lines.map(line => line.box));
|
|
125
116
|
}
|
|
@@ -208,15 +199,16 @@ export async function collectPartSnapshot({ selector, tokens, scale, ref, theme
|
|
|
208
199
|
frameAligned: selector !== null || cssCrop.x === 0 && cssCrop.y === 0 && origin.width === frameBox.width && origin.height === frameBox.height };
|
|
209
200
|
}
|
|
210
201
|
|
|
211
|
-
export function
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const comma = content.indexOf(',');
|
|
216
|
-
content = content.slice(0, comma).includes(';base64') ? Buffer.from(content.slice(comma + 1), 'base64') : Buffer.from(decodeURIComponent(content.slice(comma + 1)));
|
|
217
|
-
}
|
|
218
|
-
resource.contentIdentity = createHash('sha256').update(content).digest('hex');
|
|
202
|
+
export function resourceContentIdentity(content) {
|
|
203
|
+
if (content.startsWith('data:')) {
|
|
204
|
+
const comma=content.indexOf(',');
|
|
205
|
+
content=content.slice(0,comma).includes(';base64') ? Buffer.from(content.slice(comma+1),'base64') : Buffer.from(decodeURIComponent(content.slice(comma+1)));
|
|
219
206
|
}
|
|
207
|
+
return createHash('sha256').update(content).digest('hex');
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
export function normalizeSnapshot(snapshot) {
|
|
211
|
+
for(const resource of snapshot.resources)resource.contentIdentity=resourceContentIdentity(resource.contentIdentity);
|
|
220
212
|
return snapshot;
|
|
221
213
|
}
|
|
222
214
|
|
|
@@ -4,7 +4,6 @@ import path from 'node:path';
|
|
|
4
4
|
import { listSources, archFiles, sourceDirectories, relative, loadTokens } from './project.mjs';
|
|
5
5
|
import { tokenLocations } from './tokens.mjs';
|
|
6
6
|
import { CliError } from '../cli-output.mjs';
|
|
7
|
-
import { buildSource } from './build.mjs';
|
|
8
7
|
import { createBuildStore, BuildPool } from './build-store.mjs';
|
|
9
8
|
import { sourceFacts } from './source-facts.mjs';
|
|
10
9
|
import { sidecar } from './arch.mjs';
|
|
@@ -13,10 +12,12 @@ import { createIndexStore, indexDigest } from './index-store.mjs';
|
|
|
13
12
|
import { defaultStateDirectory } from '../hub/registry.mjs';
|
|
14
13
|
import { sourceRelationships } from '../../public/relationships.js';
|
|
15
14
|
import { entryTokenReachability } from './token-reachability.mjs';
|
|
15
|
+
import { identityVersion } from './frame-identity.mjs';
|
|
16
|
+
import { inspectVersion } from './inspect-styles.mjs';
|
|
16
17
|
import { frameDocument } from './frame-document.mjs';
|
|
17
18
|
export { sourceFacts } from './source-facts.mjs';
|
|
18
19
|
|
|
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
|
+
const collectorIdentity = indexDigest(Buffer.concat(await Promise.all(['project-index.mjs', 'source-facts.mjs', 'implementation-map.mjs', 'owner-locators.mjs', 'owner-observation.mjs', 'frame-observation.mjs', 'frame-facets.mjs', 'frame-primitives.mjs', 'frame-identity.mjs', 'inspect-styles.mjs', 'owner-colors.mjs', 'tokens.mjs', 'token-reachability.mjs', 'arch.mjs'].map(name => readFile(new URL(name, import.meta.url))))));
|
|
20
21
|
|
|
21
22
|
export function discoverProject(config) {
|
|
22
23
|
const tsx = listSources(config.design, sourceDirectories(config)).map(file => relative(config, file));
|
|
@@ -65,6 +66,7 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
|
|
|
65
66
|
if (!buildPromises.has(source)) buildPromises.set(source, (async () => {
|
|
66
67
|
let built;
|
|
67
68
|
if (!persist) {
|
|
69
|
+
const {buildSource}=await import('./build.mjs');
|
|
68
70
|
const snapshot = new Map();
|
|
69
71
|
built = await buildSource(config, path.join(config.root, source), { write: false, allowLegacy: false, snapshot });
|
|
70
72
|
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]))]));
|
|
@@ -108,6 +110,10 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
|
|
|
108
110
|
inventory,
|
|
109
111
|
getBuild,
|
|
110
112
|
materialize,
|
|
113
|
+
async releaseMaterializers() {
|
|
114
|
+
// A finite frame query keeps the built bytes, not an idle compiler isolate during observation.
|
|
115
|
+
const pool=freshPool;freshPool=undefined;await pool?.close();
|
|
116
|
+
},
|
|
111
117
|
async source(source, { tokens = false, fresh = false } = {}) {
|
|
112
118
|
const built = fresh ? await materialize(source) : await getBuild(source);
|
|
113
119
|
const inputs = fresh ? null : { source, build: built.inputHash ?? indexDigest(JSON.stringify({ ...built, frames: built.frames.map(({ document, ...frame }) => frame) })) };
|
|
@@ -130,11 +136,22 @@ export async function openProjectIndex(config, { stateDirectory = defaultStateDi
|
|
|
130
136
|
const map = supplied ?? await loadImplementationMap(config);
|
|
131
137
|
return { map, ...await validateImplementationMap(config, map, { sources: inventory.tsx, selected, getBuild, ...selection }) };
|
|
132
138
|
},
|
|
133
|
-
async observation(source, built, frame, theme, environment, collect) {
|
|
139
|
+
async observation(source, built, frame, theme, environment, collect, { facets = ['owner','identity'], policy = null } = {}) {
|
|
134
140
|
assertOpen();
|
|
135
141
|
if (environment === null) return collect();
|
|
136
|
-
const
|
|
137
|
-
|
|
142
|
+
const coverage=[...new Set(facets)].sort();
|
|
143
|
+
const inputs={source,document:indexDigest(frameDocument(frame,theme,built.css)),
|
|
144
|
+
metadata:{width:frame.width??null,height:frame.height??null,parent:frame.parent??null},
|
|
145
|
+
theme,environment,policy,identityVersion,inspectVersion};
|
|
146
|
+
const keyFor=facets=>JSON.stringify({version:1,collectorIdentity,projection:'frame-observation',inputs,facets});
|
|
147
|
+
const key=keyFor(coverage), saved=await shards.get(key);
|
|
148
|
+
if(Array.isArray(saved?.facets) && Object.hasOwn(saved,'value') && saved.facets.every(f=>coverage.includes(f)) && coverage.every(f=>saved.facets.includes(f)))return saved.value;
|
|
149
|
+
const full=['a11y','color','identity','layout','owner','structure','text','typography'];
|
|
150
|
+
if(coverage.every(f=>full.includes(f)) && coverage.length<full.length){
|
|
151
|
+
const richer=await shards.get(keyFor(full));
|
|
152
|
+
if(Array.isArray(richer?.facets) && Object.hasOwn(richer,'value') && coverage.every(f=>richer.facets.includes(f)))return richer.value;
|
|
153
|
+
}
|
|
154
|
+
const value=await collect();await shards.put(key,{facets:coverage,value});return value;
|
|
138
155
|
},
|
|
139
156
|
async palette(tokens, theme, environment, collect) {
|
|
140
157
|
assertOpen();
|
package/src/toolkit/project.mjs
CHANGED
|
@@ -71,7 +71,7 @@ export function init(config, log = console.log) {
|
|
|
71
71
|
const sources=sourceDirectories(config), fresh=sources.some(name=>name!=='studies') &&
|
|
72
72
|
!listSources(config.design,sources).length && !existsSync(path.join(config.design,'fixtures/example.ts'));
|
|
73
73
|
for (const [file, content] of [
|
|
74
|
-
[path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design' };\n"],
|
|
74
|
+
[path.join(config.root, 'adg.config.mjs'), "export default { requires: '>=0.5.0', design: 'design', output: 'output/design', check: { strictLayers: true, lifecycle: true } };\n"],
|
|
75
75
|
[path.join(config.design, 'tokens.css'), starterTokens],
|
|
76
76
|
...[...sources.filter(name=>name!=='studies'), 'fixtures', 'art'].map(name => [path.join(config.design, name), null]),
|
|
77
77
|
...(fresh ? [
|
|
@@ -105,14 +105,60 @@ export function listSources(directory, sources = sourceDirectories({design:direc
|
|
|
105
105
|
return sources.flatMap(name => {
|
|
106
106
|
const base = path.join(directory, name);
|
|
107
107
|
if (!existsSync(base)) return [];
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
108
|
+
const files = [], production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
109
|
+
const addDirect = folder => {
|
|
110
|
+
for (const entry of readdirSync(folder, { withFileTypes: true })) {
|
|
111
|
+
const source = `${name}/${entry.name}`;
|
|
112
|
+
if (entry.isFile() && isSourcePath(source, sources)) files.push(path.join(folder, entry.name));
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
addDirect(base);
|
|
116
|
+
if (name === moduleLayer) for (const entry of readdirSync(base, { withFileTypes: true })) if (entry.isDirectory()) {
|
|
117
|
+
const folder = path.join(base, entry.name);
|
|
118
|
+
for (const child of readdirSync(folder, { withFileTypes: true })) {
|
|
119
|
+
const source = `${name}/${entry.name}/${child.name}`;
|
|
120
|
+
if (child.isFile() && isSourcePath(source, sources)) files.push(path.join(folder, child.name));
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return files;
|
|
111
124
|
}).sort();
|
|
112
125
|
}
|
|
113
126
|
export function isSourcePath(name, sources = defaultSources) {
|
|
114
|
-
const
|
|
115
|
-
|
|
127
|
+
const parts = name.split('/'), layer = parts[0], production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
128
|
+
if (!sources.includes(layer) || parts.length < 2 || parts.some(part => !part || part === '.' || part === '..')) return false;
|
|
129
|
+
if (!/^([^/.][^/]*)\.tsx$/.test(parts.at(-1))) return false;
|
|
130
|
+
return parts.length === 2 || layer === moduleLayer && parts.length === 3;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export function sourceFeature(name, sources = defaultSources) {
|
|
134
|
+
const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
135
|
+
if (parts[0] !== moduleLayer) return name;
|
|
136
|
+
return parts.length >= 3 ? `${parts[0]}/${parts[1]}` : name;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function isFeatureInternal(name, sources = defaultSources) {
|
|
140
|
+
const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
141
|
+
return !!moduleLayer && parts[0] === moduleLayer && parts.length === 3 && parts.at(-1) !== 'index.tsx';
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export function featureFolderProblems(directory, sources = sourceDirectories({design: directory})) {
|
|
145
|
+
const production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
146
|
+
if (!moduleLayer) return [];
|
|
147
|
+
const base = path.join(directory, moduleLayer), problems = [];
|
|
148
|
+
if (!existsSync(base)) return problems;
|
|
149
|
+
for (const entry of readdirSync(base, { withFileTypes: true })) if (entry.isDirectory()) {
|
|
150
|
+
const folder = path.join(base, entry.name), index = path.join(folder, 'index.tsx');
|
|
151
|
+
if (!existsSync(index)) problems.push({ code: 'FEATURE_INDEX_MISSING', file: folder, message: `${moduleLayer}/${entry.name} is a feature folder without index.tsx; add the public entry before using internal files` });
|
|
152
|
+
for (const child of readdirSync(folder, { withFileTypes: true })) if (child.isDirectory()) {
|
|
153
|
+
problems.push({ code: 'FEATURE_SOURCE_NESTED', file: path.join(folder, child.name), message: `${moduleLayer}/${entry.name}/${child.name} is nested deeper than one feature level; keep source files directly beside index.tsx` });
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return problems;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function isFeatureEntry(name, sources = defaultSources) {
|
|
160
|
+
const parts = name.split('/'), production = sources.filter(item => item !== 'studies'), moduleLayer = production.length >= 3 ? production[1] : null;
|
|
161
|
+
return parts[0] !== moduleLayer || parts.length === 2 || parts.length === 3 && parts.at(-1) === 'index.tsx';
|
|
116
162
|
}
|
|
117
163
|
export function readGroups(directory, sources = sourceDirectories({design:directory})) {
|
|
118
164
|
try {
|
package/src/toolkit/runtime.d.ts
CHANGED
|
@@ -1,15 +1,17 @@
|
|
|
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; locale?: string; children?: Content }
|
|
5
|
-
export interface IconProps { name: string; size?: number; class?: string }
|
|
4
|
+
export interface FrameProps { name: string; width?: number; height?: number; fixture?: string; capture?: Capture; parent?: FrameParent; note?: string; locale?: string; proposed?: string; children?: Content }
|
|
5
|
+
export interface IconProps { "data-adg-id"?: string; name: string; size?: number; class?: string }
|
|
6
6
|
export function Frame(props: FrameProps): JSX.Element;
|
|
7
7
|
export function Icon(props: IconProps): JSX.Element;
|
|
8
|
-
export function jsx(type: unknown, props: unknown): JSX.Element;
|
|
9
|
-
export { jsx as jsxs
|
|
8
|
+
export function jsx(type: unknown, props: unknown, key?: string | number): JSX.Element;
|
|
9
|
+
export { jsx as jsxs };
|
|
10
|
+
export function jsxDEV(type: unknown, props: unknown, key?: string | number, isStatic?: boolean, source?: { fileName: string; lineNumber: number; columnNumber: number }): JSX.Element;
|
|
10
11
|
export function Fragment(props: { children?: Content }): JSX.Element;
|
|
11
12
|
export namespace JSX {
|
|
12
13
|
type Element = any;
|
|
14
|
+
interface IntrinsicAttributes { key?: string | number }
|
|
13
15
|
interface ElementChildrenAttribute { children: {} }
|
|
14
|
-
interface IntrinsicElements { [name: string]: { class?: string; children?: Content; [attribute: string]: unknown } }
|
|
16
|
+
interface IntrinsicElements { [name: string]: { class?: string; "data-adg-id"?: string; children?: Content; [attribute: string]: unknown } }
|
|
15
17
|
}
|