@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
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
/** Rich facets attach to the existing frame walk; they never discover or walk a second DOM tree. */
|
|
2
|
+
export function installInspectFacets() {
|
|
3
|
+
if (globalThis.__adgInspectFacets) return;
|
|
4
|
+
globalThis.__adgInspectFacets = {
|
|
5
|
+
create({ elements, paths, style, rect, origin, declarationsFor, tokens, theme, properties }) {
|
|
6
|
+
const p = globalThis.__adgFramePrimitives, facts = [], runs = [], limitations = [], orderKeys=new Map();
|
|
7
|
+
const customCache = new Map(), variableDeclarations = new Map(),referenceCache=new Map(),customKeys=new Map();
|
|
8
|
+
const valueFacts=[],valueKeys=new Map();
|
|
9
|
+
const projectDeclarations=new Map(tokens.map(t=>[t.name,new Set(t.values.map(v=>v.declaration))]));
|
|
10
|
+
const definitions = new Map(tokens.map(t => [t.name, t.values.find(v => v.theme === theme)?.declaration]));
|
|
11
|
+
const round = n => Math.round(n * 100) / 100 || 0;
|
|
12
|
+
const box = r => Object.fromEntries(Object.entries(p.relativeBox(r, origin)).map(([k,v]) => [k,round(v)]));
|
|
13
|
+
const limit = (code, path, accuracy='unavailable', property) => limitations.push({code,path,accuracy,...(property?{property}:{})});
|
|
14
|
+
const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|direction|writing-mode|white-space|word-break|overflow-wrap|fill|stroke(?:-.+)?)$/;
|
|
15
|
+
const relevant = (decl, prop) => decl === prop || ['font','background','border','margin','padding','gap','grid-row','grid-column','outline','text-decoration'].some(short => decl === short && (prop.startsWith(short+'-') || short === 'font' && prop === 'line-height' || short === 'gap' && /^(row|column)-gap$/.test(prop)));
|
|
16
|
+
function variableDeclarationsFor(node,pseudo=''){
|
|
17
|
+
let byPseudo=variableDeclarations.get(node);if(!byPseudo){byPseudo=new Map();variableDeclarations.set(node,byPseudo);}
|
|
18
|
+
if(!byPseudo.has(pseudo))byPseudo.set(pseudo,declarationsFor(node,pseudo).filter(d=>!d.property.startsWith('--')&&d.declaration.includes('var(')));
|
|
19
|
+
return byPseudo.get(pseudo);
|
|
20
|
+
}
|
|
21
|
+
function references(node, property, pseudo='') {
|
|
22
|
+
const candidates = [];
|
|
23
|
+
for (let parent=node; parent; parent=parent.parentElement) {
|
|
24
|
+
if (parent!==node && !inherited.test(property)) break;
|
|
25
|
+
for (const d of [...variableDeclarationsFor(parent, parent===node ? pseudo : ''), ...(pseudo&&parent===node&&inherited.test(property)?variableDeclarationsFor(parent):[])]) if (relevant(d.property,property)) {
|
|
26
|
+
candidates.push({...d,inherited:parent!==node});
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if(!candidates.length)return {refs:[],unresolved:[]};
|
|
30
|
+
if(!customCache.has(node)){
|
|
31
|
+
const custom=new Map();
|
|
32
|
+
for(let parent=node;parent;parent=parent.parentElement)for(const d of declarationsFor(parent)){
|
|
33
|
+
if(parent===document.documentElement&&projectDeclarations.get(d.property)?.has(d.declaration))continue;
|
|
34
|
+
if(d.property.startsWith('--')&&!custom.has(d.property))custom.set(d.property,d.declaration);
|
|
35
|
+
}
|
|
36
|
+
customCache.set(node,custom);customKeys.set(node,JSON.stringify([...custom].sort(([a],[b])=>a.localeCompare(b))));
|
|
37
|
+
}
|
|
38
|
+
const custom=customCache.get(node),cacheKey=JSON.stringify([candidates,customKeys.get(node)]);
|
|
39
|
+
if(referenceCache.has(cacheKey))return referenceCache.get(cacheKey);
|
|
40
|
+
const refs=[], unresolved=[];
|
|
41
|
+
for (const d of candidates) {
|
|
42
|
+
function expand(name, via=[], fallback=false) {
|
|
43
|
+
if (via.includes(name)) { unresolved.push('token_cycle:'+name);return; }
|
|
44
|
+
const project=definitions.has(name), local=custom.has(name)&&custom.get(name)!==definitions.get(name);
|
|
45
|
+
if (project) refs.push({token:name,kind:fallback?'fallback':via.length?'alias':'direct',expression:d.declaration,via,inherited:d.inherited,basis:'authored_reference',
|
|
46
|
+
...(d.property!==property?{shorthand:d.property}:{}),
|
|
47
|
+
...(via.some(n=>custom.has(n)&&custom.get(n)!==definitions.get(n)) || local ? {localOverrides:[...new Set([...via,name])].filter(n=>custom.has(n)&&custom.get(n)!==definitions.get(n)).map(name=>({name,declaration:custom.get(name)}))}: {})});
|
|
48
|
+
const expression = local ? custom.get(name) : definitions.get(name);
|
|
49
|
+
if (expression===undefined) { unresolved.push('missing_variable:'+name);return; }
|
|
50
|
+
for (const v of p.variables(expression)) expand(v.name,[...via,name],fallback||v.fallback);
|
|
51
|
+
}
|
|
52
|
+
for (const v of p.variables(d.declaration)) expand(v.name,[],v.fallback);
|
|
53
|
+
}
|
|
54
|
+
const result={refs:[...new Map(refs.map(r=>[JSON.stringify(r),r])).values()],unresolved:[...new Set(unresolved)]};referenceCache.set(cacheKey,result);return result;
|
|
55
|
+
}
|
|
56
|
+
function styles(node, pseudo='') {
|
|
57
|
+
const s=pseudo?getComputedStyle(node,pseudo):style(node);
|
|
58
|
+
return properties.map(property=>{
|
|
59
|
+
const value={css:s.getPropertyValue(property),...references(node,property,pseudo)},key=JSON.stringify(value);
|
|
60
|
+
if(valueKeys.has(key))return valueKeys.get(key);
|
|
61
|
+
const index=valueFacts.length;valueFacts.push(value);valueKeys.set(key,index);return index;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
const ancestors=new Map(),frameNode=document.querySelector('[data-adg-frame]');
|
|
65
|
+
function ancestry(node){
|
|
66
|
+
if(ancestors.has(node))return ancestors.get(node);
|
|
67
|
+
const parent=node===frameNode?null:node.parentElement,above=parent?ancestry(parent):null,s=style(node),r=rect(node);
|
|
68
|
+
const clip={...(above?.childClip??{left:origin.left,top:origin.top,right:origin.right,bottom:origin.bottom})},childClip={...clip};
|
|
69
|
+
if(s.display!=='inline'){
|
|
70
|
+
const sx=r.width/(node.offsetWidth||r.width||1),sy=r.height/(node.offsetHeight||r.height||1);
|
|
71
|
+
if(/hidden|clip|scroll|auto/.test(s.overflowX)){childClip.left=Math.max(childClip.left,r.left+(node.clientLeft||0)*sx);childClip.right=Math.min(childClip.right,r.left+((node.clientLeft||0)+node.clientWidth)*sx);}
|
|
72
|
+
if(/hidden|clip|scroll|auto/.test(s.overflowY)){childClip.top=Math.max(childClip.top,r.top+(node.clientTop||0)*sy);childClip.bottom=Math.min(childClip.bottom,r.top+((node.clientTop||0)+node.clientHeight)*sy);}
|
|
73
|
+
}
|
|
74
|
+
const rounded=(above?.rounded??0)+Number(s.display!=='inline'&&/hidden|clip|scroll|auto/.test(s.overflowX+s.overflowY)&&!!parseFloat(s.borderRadius));
|
|
75
|
+
const masks=(above?.masks??0)+Number(s.clipPath!=='none'||s.maskImage!=='none');
|
|
76
|
+
const result={clip,childClip,rounded,masks,ancestorRounded:above?.rounded??0,hidden:(above?.hidden??false)||s.display==='none'||Number(s.opacity)===0};ancestors.set(node,result);return result;
|
|
77
|
+
}
|
|
78
|
+
function geometry(node) {
|
|
79
|
+
const s=style(node), r=rect(node);
|
|
80
|
+
const laidOut=s.display!=='none' && s.display!=='contents' && node.getClientRects().length>0;
|
|
81
|
+
const g={box:laidOut?box(r):null,visibility:laidOut?'visible':'not_laid_out'};
|
|
82
|
+
if (!laidOut) return g;
|
|
83
|
+
const rects=[...node.getClientRects()].map(box);
|
|
84
|
+
if(rects.length>1)g.clientRects=rects;
|
|
85
|
+
if(node instanceof HTMLElement)g.layoutSize={width:node.offsetWidth,height:node.offsetHeight};
|
|
86
|
+
const inherited=ancestry(node),clip=inherited.clip,hidden=s.visibility!=='visible'||inherited.hidden;
|
|
87
|
+
for(let i=0;i<inherited.ancestorRounded;i++)limit('CLIP_SHAPE_APPROXIMATE',paths.get(node),'bounds','border-radius');
|
|
88
|
+
for(let i=0;i<inherited.masks;i++)limit('CLIP_SHAPE_APPROXIMATE',paths.get(node),'bounds','clip-path');
|
|
89
|
+
if(inherited.masks)g.clipAccuracy='bounds';
|
|
90
|
+
g.clip={x:round(clip.left-origin.left),y:round(clip.top-origin.top),width:round(Math.max(0,clip.right-clip.left)),height:round(Math.max(0,clip.bottom-clip.top))};
|
|
91
|
+
const visible={left:Math.max(r.left,clip.left),top:Math.max(r.top,clip.top),right:Math.min(r.right,clip.right),bottom:Math.min(r.bottom,clip.bottom)};
|
|
92
|
+
g.visibleBox=visible.right>visible.left&&visible.bottom>visible.top?box({...visible,width:visible.right-visible.left,height:visible.bottom-visible.top}):null;
|
|
93
|
+
g.visibility=hidden?'hidden':!g.visibleBox?'clipped':visible.left>r.left||visible.top>r.top||visible.right<r.right||visible.bottom<r.bottom?'partial':'visible';
|
|
94
|
+
g.clipAccuracy??='rect';
|
|
95
|
+
if(node.scrollWidth>node.clientWidth||node.scrollHeight>node.clientHeight||node.scrollTop||node.scrollLeft)g.scroll={x:node.scrollLeft||0,y:node.scrollTop||0,width:node.scrollWidth||0,height:node.scrollHeight||0,clientWidth:node.clientWidth||0,clientHeight:node.clientHeight||0};
|
|
96
|
+
if(s.transform!=='none'||s.rotate!=='none'||s.scale!=='none'||s.translate!=='none')limit('TRANSFORM_QUAD_UNAVAILABLE',paths.get(node),'bounds','transform');
|
|
97
|
+
return g;
|
|
98
|
+
}
|
|
99
|
+
function attributes(node) {
|
|
100
|
+
const attrs={};
|
|
101
|
+
for(const a of node.attributes) if (/^(?:id|data-part|data-adg-id|role|aria-.+|title|lang|dir|alt|for|type|placeholder|disabled|readonly|checked|selected|required|multiple|tabindex|href|target|rel)$/.test(a.name) && !/^data:/.test(a.value))attrs[a.name]=a.value;
|
|
102
|
+
if(node.matches('input,textarea,select')){
|
|
103
|
+
if(node.type==='password')attrs.valueRedacted=true;
|
|
104
|
+
else {attrs.value=node.value; if('checked'in node)attrs.checked=node.checked;}
|
|
105
|
+
}
|
|
106
|
+
return attrs;
|
|
107
|
+
}
|
|
108
|
+
function addRun(node, raw, kind, slot, boxes, accuracy='range', pseudo) {
|
|
109
|
+
const path=paths.get(node);
|
|
110
|
+
const run={path,slot,kind,raw,normalized:p.normalizeText(raw),boxes,accuracy,...(pseudo?{pseudo}:{})};
|
|
111
|
+
let group=node;for(;group&&group.parentElement;group=group.parentElement)if(group.matches('button,a,label,input,textarea,select,text')||!['inline','contents'].includes(style(group).display))break;
|
|
112
|
+
run.group=paths.get(group)??path;
|
|
113
|
+
const indices=[];let anchor=kind==='dom'?node.childNodes[slot]:node;
|
|
114
|
+
for(let current=anchor;current&¤t!==document.querySelector('[data-adg-frame]');current=current.parentNode)indices.unshift([...current.parentNode.childNodes].indexOf(current));
|
|
115
|
+
if(kind!=='dom')indices.push(pseudo==='after'?Number.MAX_SAFE_INTEGER:-2);
|
|
116
|
+
orderKeys.set(run,indices);runs.push(run);
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
node(node) {
|
|
120
|
+
const path=paths.get(node),s=style(node),g=geometry(node),attrs=attributes(node);
|
|
121
|
+
const fact={path,tag:node.localName,namespace:node.namespaceURI,attributes:attrs,geometry:g,values:styles(node),effects:{},pseudo:[]};
|
|
122
|
+
for(const property of ['filter','backdrop-filter','mix-blend-mode','isolation','contain','clip-path','mask-image','perspective']){
|
|
123
|
+
const value=s.getPropertyValue(property);
|
|
124
|
+
if(value && !['none','normal','auto'].includes(value)){fact.effects[property]=value;limit(property.includes('clip')||property.includes('mask')?'CLIP_SHAPE_APPROXIMATE':'INK_BOUNDS_UNAVAILABLE',path,'bounds',property);}
|
|
125
|
+
}
|
|
126
|
+
if(s.boxShadow!=='none'||s.textShadow!=='none')limit('INK_BOUNDS_UNAVAILABLE',path,'unavailable','shadow');
|
|
127
|
+
if(node.matches('canvas,video,object,embed,foreignObject')){limit('OPAQUE_RESOURCE',path);limit('DYNAMIC_PAINT',path);}
|
|
128
|
+
if(node.matches('animate,animateTransform,set'))limit('DYNAMIC_PAINT',path);
|
|
129
|
+
for(const kind of ['before','after','marker','placeholder']){
|
|
130
|
+
if(kind==='placeholder' && (!node.matches('input,textarea')||node.value||!node.placeholder))continue;
|
|
131
|
+
if(kind==='marker' && s.display!=='list-item')continue;
|
|
132
|
+
const ps=getComputedStyle(node,'::'+kind);
|
|
133
|
+
const content=kind==='placeholder'?node.placeholder:ps.content;
|
|
134
|
+
if(!['placeholder','marker'].includes(kind)&&['none','normal',''].includes(content))continue;
|
|
135
|
+
if(ps.display==='none')continue;
|
|
136
|
+
const pseudo={kind,content,values:styles(node,'::'+kind),geometry:{box:null,visibility:g.visibility}};
|
|
137
|
+
fact.pseudo.push(pseudo);limit('PSEUDO_BOX_UNAVAILABLE',path,'unavailable',kind);
|
|
138
|
+
let raw=kind==='placeholder'?content:[...content.matchAll(/"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'/g)].map(m=>(m[1]??m[2]).replace(/\\([\da-f]{1,6})\s?|\\(.)/gi,(_,hex,char)=>hex?String.fromCodePoint(parseInt(hex,16)||0xfffd):char)).join('');
|
|
139
|
+
if(kind==='marker'&&content==='normal'||/\b(?:attr|counter|counters|url)\(/.test(content)){raw=content;limit('GENERATED_TEXT_UNRESOLVED',path,'unavailable',kind);}
|
|
140
|
+
if(raw)addRun(node,raw,'pseudo',kind,[],'owner_box',kind);
|
|
141
|
+
}
|
|
142
|
+
if(!node.matches('script,style,defs,title,metadata') && !node.closest('defs')){
|
|
143
|
+
for(const [slot,child]of [...node.childNodes].entries())if(child.nodeType===3 && child.data.length){
|
|
144
|
+
const {rects}=p.textRects(child);addRun(node,child.data,'dom',slot,rects.map(box));
|
|
145
|
+
}
|
|
146
|
+
if(node.matches('input,textarea,select')&&node.type!=='password'){
|
|
147
|
+
const value=node.matches('select')?[...node.selectedOptions].map(o=>o.text).join(' '):node.value;
|
|
148
|
+
if(value)addRun(node,value,'control','value',g.box?[g.box]:[],'control_box');
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const svg=node instanceof SVGElement;
|
|
152
|
+
if(svg){fact.svgAttributes={};for(const a of node.attributes)if(/^(?:d|points|x|y|width|height|cx|cy|r|rx|ry|viewBox|transform|href|xlink:href|gradientUnits|gradientTransform|offset|clipPathUnits|maskUnits|maskContentUnits|preserveAspectRatio|id)$/.test(a.name))fact.svgAttributes[a.name]=a.value;}
|
|
153
|
+
if(node.matches('svg,img,image,canvas,video')){
|
|
154
|
+
const url=node.currentSrc||node.getAttribute('src')||node.getAttribute('href')||node.getAttribute('xlink:href');
|
|
155
|
+
fact.resource={kind:node.matches('svg')?(node.hasAttribute('data-adg-icon')?'icon':'svg'):node.matches('img,image')?'raster':'opaque',source:node.getAttribute('data-adg-art'),url,
|
|
156
|
+
intrinsic:node instanceof HTMLImageElement?{width:node.naturalWidth,height:node.naturalHeight}:svg?{width:node.width?.baseVal?.value||g.box?.width||0,height:node.height?.baseVal?.value||g.box?.height||0}:null,
|
|
157
|
+
viewBox:node.getAttribute('viewBox'),icon:node.getAttribute('data-adg-icon')};
|
|
158
|
+
}
|
|
159
|
+
const urls=[...s.backgroundImage.matchAll(/url\(["']?([^)'"\s]+)["']?\)/g)].map(m=>m[1]);
|
|
160
|
+
if(urls.length)fact.backgrounds=urls;
|
|
161
|
+
facts.push(fact);
|
|
162
|
+
},
|
|
163
|
+
finish(){runs.sort((a,b)=>{const x=orderKeys.get(a),y=orderKeys.get(b);for(let i=0;i<Math.min(x.length,y.length);i++)if(x[i]!==y[i])return x[i]-y[i];return x.length-y.length;});return {properties,valueFacts,nodes:facts,runs,limitations,size:{width:round(origin.width),height:round(origin.height)},palette:Object.fromEntries(tokens.map(t=>[t.name,getComputedStyle(document.documentElement).getPropertyValue(t.name).trim()||null]))};},
|
|
164
|
+
};
|
|
165
|
+
},
|
|
166
|
+
};
|
|
167
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { CliError } from '../cli-output.mjs';
|
|
3
|
+
|
|
4
|
+
export const identityVersion = 1;
|
|
5
|
+
const digest = value => createHash('sha256').update(value).digest('hex').slice(0, 24);
|
|
6
|
+
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
7
|
+
const namingAttributes = new Set(['id', 'data-part', 'role', 'aria-label', 'aria-labelledby', 'aria-describedby']);
|
|
8
|
+
|
|
9
|
+
export function resourceSlotIdentity(scope,slot,tag,namespace,hash=digest){
|
|
10
|
+
return {id:`e1_${hash(JSON.stringify([scope,['resource-slot',slot]]))}`,identity:{stability:'resource',guard:hash(JSON.stringify(['resource-slot',scope,slot,tag,namespace])),slot}};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Assign on the complete raw inventory, before selection, folding or theme deltas. */
|
|
14
|
+
export function elementIdentities(nodes, { source, frame }, { hash = digest, metadata = true } = {}) {
|
|
15
|
+
const children=new Map(nodes.map(n=>[n.path,[]])), byPath=new Map(nodes.map(n=>[n.path,n]));
|
|
16
|
+
for(const n of nodes)children.get(n.parentPath)?.push(n);
|
|
17
|
+
const result=new Map(),seen=new Map(),rootScope=JSON.stringify([identityVersion,source,frame]);
|
|
18
|
+
const conflict=message=>{throw new CliError('INSPECT_IDENTITY_CONFLICT',message);};
|
|
19
|
+
function describe(node){
|
|
20
|
+
const attrs=node.attributes??{},owners=node.owners??[],keys=node.keys??[],anchor=attrs['data-adg-id'];
|
|
21
|
+
let defining=owners,ancestor=byPath.get(node.parentPath);
|
|
22
|
+
while(!defining.length&&ancestor){defining=ancestor.owners??[];ancestor=byPath.get(ancestor.parentPath);}
|
|
23
|
+
if(anchor!==undefined&&(typeof anchor!=='string'||!anchor.trim()))conflict('data-adg-id must be a nonempty string.');
|
|
24
|
+
const naming=Object.entries(attrs).filter(([name])=>namingAttributes.has(name)).sort(([a],[b])=>a.localeCompare(b));
|
|
25
|
+
const signature=[node.namespace,node.tag,naming,node.semantic??null,node.password?'':normalize(node.directText??'')];
|
|
26
|
+
const seed=anchor!==undefined?['anchor',anchor,owners,...keys]:keys.length?['key',keys,owners]:[node.neutral?'wrapper':'semantic',signature,defining];
|
|
27
|
+
const boundary=!node.neutral&&(anchor!==undefined||keys.length||owners.length||naming.length||node.semantic?.name);
|
|
28
|
+
return {node,signature,seed,defining,candidate:boundary,boundary:false,fixed:anchor!==undefined||keys.length>0,authored:anchor!==undefined||keys.length>0,strict:keys.length>0||anchor!==undefined&&!owners.length};
|
|
29
|
+
}
|
|
30
|
+
const descriptors=new Map(nodes.map(n=>[n.path,describe(n)]));
|
|
31
|
+
function assign(record,scope,ordinal,count,inherited,resourceSlot){
|
|
32
|
+
const duplicate=count>1, id=`e1_${hash(JSON.stringify([scope,record.seed,...(!record.strict&&duplicate?[ordinal]:[])]))}`;
|
|
33
|
+
if(seen.has(id))conflict(`Element identity conflicts at ${source}#${frame}, paths ${seen.get(id)} and ${record.node.path}; use unique anchors or instance keys.`);
|
|
34
|
+
seen.set(id,record.node.path);
|
|
35
|
+
const positional=inherited||!record.strict&&duplicate;
|
|
36
|
+
const identity=metadata?{stability:resourceSlot!==undefined?'resource':positional?'positional':record.authored?'authored':'semantic',guard:hash(JSON.stringify([record.node.namespace,record.node.tag,record.signature,scope,record.defining]))}:undefined;
|
|
37
|
+
if(identity){
|
|
38
|
+
if(resourceSlot!==undefined)identity.guard=resourceSlotIdentity(scope,resourceSlot,record.node.tag,record.node.namespace,hash).identity.guard;
|
|
39
|
+
if(record.node.attributes?.['data-adg-id']!==undefined)identity.anchor=record.node.attributes['data-adg-id'];
|
|
40
|
+
if(record.node.keys?.length)identity.key=record.node.keys.at(-1).key;
|
|
41
|
+
if(resourceSlot!==undefined)identity.slot=resourceSlot;
|
|
42
|
+
else if(!record.strict&&duplicate)identity.duplicate={group:hash(JSON.stringify([scope,record.seed])),ordinal,count};
|
|
43
|
+
}
|
|
44
|
+
const value={path:record.node.path,id,...(identity?{identity}:{})};result.set(record.node.path,value);
|
|
45
|
+
return {id,positional};
|
|
46
|
+
}
|
|
47
|
+
function resource(root,scope){
|
|
48
|
+
let slot=0;
|
|
49
|
+
function visit(node){const r=descriptors.get(node.path),local=slot++;
|
|
50
|
+
// Slots are local to this artwork instance, not ranked among frame elements.
|
|
51
|
+
const original=r.seed;r.seed=['resource-slot',local];assign(r,scope,0,1,false,local);r.seed=original;
|
|
52
|
+
for(const child of children.get(node.path))visit(child);
|
|
53
|
+
}
|
|
54
|
+
for(const child of children.get(root.path))visit(child);
|
|
55
|
+
}
|
|
56
|
+
function scope(roots,address,inherited=false){
|
|
57
|
+
let pool=[];
|
|
58
|
+
function gather(node){const r=descriptors.get(node.path);pool.push(r);if(!r.boundary&&!node.resource)for(const child of children.get(node.path))gather(child);}
|
|
59
|
+
// Unique semantic candidates open scopes. Repeated unkeyed owner roots do not
|
|
60
|
+
// impose their positional ordinal on every distinguishable descendant.
|
|
61
|
+
for(let changed=true;changed;){
|
|
62
|
+
changed=false;pool=[];roots.forEach(gather);
|
|
63
|
+
const candidates=new Map();
|
|
64
|
+
for(const r of pool)if(r.candidate){const key=JSON.stringify(r.seed);candidates.set(key,(candidates.get(key)??0)+1);}
|
|
65
|
+
for(const r of pool)if(r.candidate&&!r.boundary&&(r.fixed||candidates.get(JSON.stringify(r.seed))===1)){r.boundary=true;changed=true;}
|
|
66
|
+
}
|
|
67
|
+
const groups=new Map();
|
|
68
|
+
for(const r of pool){
|
|
69
|
+
// JSX keys belong to sibling lists, even where an unnamed parent is not an identity scope.
|
|
70
|
+
let parent=byPath.get(r.node.parentPath);while(parent?.neutral)parent=byPath.get(parent.parentPath);
|
|
71
|
+
const key=JSON.stringify([r.seed,...(r.node.keys?.length?[parent?.path??null]:[])]);
|
|
72
|
+
const peers=groups.get(key)??[];peers.push(r);groups.set(key,peers);r.peers=peers;
|
|
73
|
+
}
|
|
74
|
+
// Keyed children need their non-neutral parent's address before resolution.
|
|
75
|
+
const resolved=new Map();
|
|
76
|
+
function resolve(r){if(resolved.has(r.node.path))return resolved.get(r.node.path);
|
|
77
|
+
let local=address,localPositional=inherited;
|
|
78
|
+
if(r.node.attributes?.['data-adg-id']!==undefined&&!r.node.owners?.length){
|
|
79
|
+
let owner=byPath.get(r.node.parentPath);while(owner&&!owner.owners?.length)owner=byPath.get(owner.parentPath);
|
|
80
|
+
const ownerRecord=pool.find(p=>p.node===owner),value=ownerRecord?resolve(ownerRecord):null;
|
|
81
|
+
if(value){local=value.id;localPositional||=value.positional;}
|
|
82
|
+
}
|
|
83
|
+
if(r.node.keys?.length){let parent=byPath.get(r.node.parentPath);while(parent?.neutral)parent=byPath.get(parent.parentPath);
|
|
84
|
+
const parentRecord=pool.find(p=>p.node===parent),parentValue=parentRecord?resolve(parentRecord):null;
|
|
85
|
+
local=parentValue?.id??result.get(parent?.path)?.id??address;localPositional||=parentValue?.positional??false;}
|
|
86
|
+
const value=assign(r,local,r.peers.indexOf(r),r.peers.length,localPositional);resolved.set(r.node.path,value);return value;
|
|
87
|
+
}
|
|
88
|
+
for(const r of pool)resolve(r);
|
|
89
|
+
for(const r of pool){const value=resolved.get(r.node.path);
|
|
90
|
+
if(r.node.resource)resource(r.node,value.id);
|
|
91
|
+
else if(r.boundary)scope(children.get(r.node.path),value.id,value.positional);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for(const root of nodes.filter(n=>!byPath.has(n.parentPath))){
|
|
95
|
+
const record=descriptors.get(root.path),seed=record.seed;record.seed=['frame-root'];
|
|
96
|
+
const value=assign(record,rootScope,0,1,false);record.seed=seed;
|
|
97
|
+
if(root.resource)resource(root,value.id);else scope(children.get(root.path),value.id);
|
|
98
|
+
}
|
|
99
|
+
return nodes.map(node=>result.get(node.path));
|
|
100
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { installFramePrimitives } from './frame-primitives.mjs';
|
|
2
|
+
export { installFramePrimitives };
|
|
3
|
+
|
|
4
|
+
/** Browser-side projection: provenance roots and authored references, no raster work. */
|
|
5
|
+
export function collectOwnerObservation({ tokens, theme, rich = false, properties = [], serialized = false }) {
|
|
6
|
+
const frame = document.querySelector('[data-adg-frame]'), root = frame?.firstElementChild;
|
|
7
|
+
if (!root || frame.children.length !== 1) throw Error('Ownership observation requires exactly one frame root.');
|
|
8
|
+
const { inventory, relativeBox, variables, selectors, reads, identityNode, styleRules, textRects } = globalThis.__adgFramePrimitives;
|
|
9
|
+
const origin = frame.getBoundingClientRect(), {elements,paths,neutralCandidates}=inventory(root), identities=[];
|
|
10
|
+
const tokenNames = new Set(tokens.map(token => token.name));
|
|
11
|
+
const definitions = new Map(tokens.map(token => [token.name, token.values.find(value => value.theme === theme).declaration]));
|
|
12
|
+
const box = r => relativeBox(r,origin,true), {style,rect}=reads(), declarations=new Map();
|
|
13
|
+
function clipped(node, r = rect(node), includeSelf = false) {
|
|
14
|
+
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);
|
|
15
|
+
for (let p = node; p; p = p.parentElement) {
|
|
16
|
+
const s = style(p); if (s.display === 'none' || p === node && s.visibility !== 'visible' || Number(s.opacity) === 0) return null;
|
|
17
|
+
if ((p !== node || includeSelf) && s.display !== 'inline') {
|
|
18
|
+
const r = rect(p);
|
|
19
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowX)) { left = Math.max(left, r.left); right = Math.min(right, r.right); }
|
|
20
|
+
if (/(hidden|clip|scroll|auto)/.test(s.overflowY)) { top = Math.max(top, r.top); bottom = Math.min(bottom, r.bottom); }
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
24
|
+
}
|
|
25
|
+
const rules=styleRules({referencesOnly:true,includeCustom:rich,resolveNesting:true});
|
|
26
|
+
const probe = document.createElement('style'); document.head.append(probe);
|
|
27
|
+
function containerActive(node, conditions) {
|
|
28
|
+
if (!conditions.length) return true;
|
|
29
|
+
const previous = node.getAttribute('data-adg-owner-probe');
|
|
30
|
+
try {
|
|
31
|
+
node.setAttribute('data-adg-owner-probe', 'active');
|
|
32
|
+
probe.textContent = conditions.reduceRight((inner, condition) => `${condition}{${inner}}`, '[data-adg-owner-probe="active"]{--adg-owner-condition:1!important}');
|
|
33
|
+
return getComputedStyle(node).getPropertyValue('--adg-owner-condition').trim() === '1';
|
|
34
|
+
} finally { probe.textContent = ''; if (previous === null) node.removeAttribute('data-adg-owner-probe'); else node.setAttribute('data-adg-owner-probe', previous); }
|
|
35
|
+
}
|
|
36
|
+
function declarationsFor(node, pseudo = '') {
|
|
37
|
+
const key = pseudo ? `${paths.get(node)}${pseudo}` : node;
|
|
38
|
+
if (declarations.has(key)) return declarations.get(key);
|
|
39
|
+
const result = [];
|
|
40
|
+
for (const rule of rules) {
|
|
41
|
+
const matched = rule.selectors.some(selector => {
|
|
42
|
+
const suffix = /::(before|after)\b/.exec(selector);
|
|
43
|
+
if ((suffix ? `::${suffix[1]}` : '') !== pseudo) return false;
|
|
44
|
+
try { return node.matches(selector.replace(/::(?:before|after)\b/g, '')); } catch { return false; }
|
|
45
|
+
});
|
|
46
|
+
if (matched && containerActive(node, rule.containers)) for (const property of rule.style) result.push({ property, declaration: rule.style.getPropertyValue(property) });
|
|
47
|
+
}
|
|
48
|
+
if (!pseudo) for (const property of node.style) result.push({ property, declaration: node.style.getPropertyValue(property) });
|
|
49
|
+
declarations.set(key, result); return result;
|
|
50
|
+
}
|
|
51
|
+
const details = rich ? globalThis.__adgInspectFacets.create({elements,paths,style,rect,origin,declarationsFor,tokens,theme,properties}) : null;
|
|
52
|
+
const inherited = /^(?:color|font(?:-.+)?|line-height|letter-spacing|word-spacing|text-align|text-indent|text-transform|visibility|cursor|fill|stroke(?:-.+)?)$/;
|
|
53
|
+
const nodes = [], references = [], paints = [], texts = [], groups = [];
|
|
54
|
+
const normalize = value => value.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
55
|
+
function paint(style, property, node, bounds, pseudo = '') {
|
|
56
|
+
const computed = style.getPropertyValue(property);
|
|
57
|
+
if (!computed || computed === 'none') return;
|
|
58
|
+
const values = property.includes('shadow') || property === 'background-image'
|
|
59
|
+
? computed.match(/(?:rgba?|hsla?|oklch|oklab|lab|lch|color(?:-mix)?)\((?:[^()]|\([^()]*\))*\)|#[\da-f]{3,8}\b/gi) ?? [] : [computed];
|
|
60
|
+
for (const value of values) {
|
|
61
|
+
const rgba = globalThis.__adgOwnerColor(value);
|
|
62
|
+
if (rgba?.[3]) paints.push({ path: paths.get(node) + pseudo, ownerPath: paths.get(node), box: bounds, property, computed: value, rgba });
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function fragment(node) {
|
|
66
|
+
const parent = node.parentElement;
|
|
67
|
+
if (!parent || parent.closest('script,style,input,textarea,select')) return null;
|
|
68
|
+
const {range,rects}=textRects(node); if (!rects.length) return null;
|
|
69
|
+
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)) };
|
|
70
|
+
const bounds = clipped(parent, extent, true); if (!bounds) return null;
|
|
71
|
+
const clipRect = r => {
|
|
72
|
+
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);
|
|
73
|
+
return right > left && bottom > top ? box({ left, right, top, bottom }) : null;
|
|
74
|
+
};
|
|
75
|
+
const boxes = rects.map(clipRect).filter(Boolean);
|
|
76
|
+
if (!boxes.length) return null;
|
|
77
|
+
let raw = node.data;
|
|
78
|
+
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)) {
|
|
79
|
+
raw = '';
|
|
80
|
+
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]; }
|
|
81
|
+
}
|
|
82
|
+
const transform = style(parent).textTransform;
|
|
83
|
+
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;
|
|
84
|
+
return { parent, raw, rendered, elementPath: `${paths.get(parent)}/text-${[...parent.childNodes].indexOf(node)}`, text: raw, boxes };
|
|
85
|
+
}
|
|
86
|
+
function textGroup(node) {
|
|
87
|
+
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;
|
|
88
|
+
return root;
|
|
89
|
+
}
|
|
90
|
+
try {
|
|
91
|
+
for (const node of elements) {
|
|
92
|
+
details?.node(node);
|
|
93
|
+
const bounds = clipped(node);
|
|
94
|
+
const own = JSON.parse(node.getAttribute('data-adg-owners') ?? '[]');
|
|
95
|
+
identities.push(identityNode(node,paths.get(node),paths.get(node.parentElement)??null,own,style(node),neutralCandidates.has(node)));
|
|
96
|
+
nodes.push({ path: paths.get(node), parentPath: paths.get(node.parentElement) ?? null, box: bounds, owners: own });
|
|
97
|
+
if (!bounds) continue;
|
|
98
|
+
const customs = new Map();
|
|
99
|
+
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);
|
|
100
|
+
function expand(name, property, declaration, via = [], fallback = false) {
|
|
101
|
+
if (via.includes(name)) return;
|
|
102
|
+
if (tokenNames.has(name)) references.push({ path: paths.get(node), token: name, property, declaration, via,
|
|
103
|
+
matchKind: fallback ? 'token_fallback_reference' : via.length ? 'token_alias_reference' : 'token_reference' });
|
|
104
|
+
const expression = tokenNames.has(name) ? definitions.get(name) : customs.get(name);
|
|
105
|
+
if (expression) for (const variable of variables(expression)) expand(variable.name, property, declaration, [...via, name], fallback || variable.fallback);
|
|
106
|
+
}
|
|
107
|
+
for (const pseudo of ['', '::before', '::after']) {
|
|
108
|
+
const s = pseudo ? getComputedStyle(node, pseudo) : style(node);
|
|
109
|
+
if (pseudo && (['none', 'normal'].includes(s.content) || s.display === 'none' || s.visibility !== 'visible' || Number(s.opacity) === 0)) continue;
|
|
110
|
+
const active = [...declarationsFor(node, pseudo)];
|
|
111
|
+
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)));
|
|
112
|
+
for (const { property, declaration } of active) if (!property.startsWith('--')) for (const variable of variables(declaration)) expand(variable.name, property, declaration, [], variable.fallback);
|
|
113
|
+
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));
|
|
114
|
+
if (hasText && !(node instanceof SVGElement)) paint(!pseudo && node.matches('input,textarea') && !node.value && node.placeholder ? getComputedStyle(node, '::placeholder') : s, 'color', node, bounds, pseudo);
|
|
115
|
+
paint(s, 'background-color', node, bounds, pseudo);
|
|
116
|
+
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);
|
|
117
|
+
if (parseFloat(s.outlineWidth) > 0 && s.outlineStyle !== 'none') paint(s, 'outline-color', node, bounds, pseudo);
|
|
118
|
+
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); }
|
|
119
|
+
for (const property of ['box-shadow','text-shadow','background-image']) if (property !== 'text-shadow' || hasText) paint(s, property, node, bounds, pseudo);
|
|
120
|
+
if (pseudo && !/\b(?:url|attr|counter)\(/.test(s.content)) {
|
|
121
|
+
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('');
|
|
122
|
+
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] }] });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (node.matches('input,textarea,select') && !(node.matches('input[type=password]') && node.value)) {
|
|
126
|
+
const raw = node.matches('select') ? [...node.selectedOptions].map(option => option.text).join(' ') : node.value || node.placeholder || '';
|
|
127
|
+
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] }] });
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
|
|
131
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
132
|
+
const f = fragment(node); if (!f) continue;
|
|
133
|
+
const group = textGroup(f.parent);
|
|
134
|
+
if (groups.at(-1)?.[0] !== group) groups.push([group, []]);
|
|
135
|
+
groups.at(-1)[1].push(f);
|
|
136
|
+
}
|
|
137
|
+
for (const [group, fragments] of groups) {
|
|
138
|
+
const raw = fragments.map(f => f.raw).join(''), normalized = normalize(fragments.map(f => f.rendered).join(''));
|
|
139
|
+
if (!normalized) continue;
|
|
140
|
+
let common = fragments[0].parent;
|
|
141
|
+
while (common && !fragments.every(f => common.contains(f.parent))) common = common.parentElement;
|
|
142
|
+
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 })) });
|
|
143
|
+
}
|
|
144
|
+
const result={ ...(rich?{rich:details.finish()}:{}), identities, nodes, references: [...new Map(references.map(ref => [JSON.stringify(ref), ref])).values()], texts, paints };
|
|
145
|
+
return serialized?JSON.stringify(result):result;
|
|
146
|
+
} finally { probe.remove(); }
|
|
147
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/** Installed once per page; browser collectors share these exact, synchronous primitives. */
|
|
2
|
+
export function installFramePrimitives() {
|
|
3
|
+
if (globalThis.__adgFramePrimitives) return;
|
|
4
|
+
const normalizeText = text => text.normalize('NFC').replace(/\p{White_Space}+/gu, ' ').trim();
|
|
5
|
+
function inventory(root) {
|
|
6
|
+
const elements=[root,...root.querySelectorAll('*')];
|
|
7
|
+
const neutralCandidates=new Set(elements);
|
|
8
|
+
for(const keyed of root.querySelectorAll('[data-adg-keys]'))for(let parent=keyed.parentElement;parent&&parent!==root;parent=parent.parentElement)neutralCandidates.add(parent);
|
|
9
|
+
return {elements, paths:new Map(elements.map((node,i)=>[node,String(i)])),neutralCandidates};
|
|
10
|
+
}
|
|
11
|
+
function relativeBox(rect, origin, clamp=false) {
|
|
12
|
+
const clean=n=>n===0?0:n;
|
|
13
|
+
return {x:clean(rect.left-origin.left),y:clean(rect.top-origin.top),width:clamp?Math.max(0,rect.right-rect.left):rect.width,height:clamp?Math.max(0,rect.bottom-rect.top):rect.height};
|
|
14
|
+
}
|
|
15
|
+
function variables(expression, fallback=false) {
|
|
16
|
+
const result=[]; const regex=/var\(\s*(--[\w-]+)/g;let match;
|
|
17
|
+
while((match=regex.exec(expression))){
|
|
18
|
+
let depth=1,comma=-1,end=regex.lastIndex;
|
|
19
|
+
for(;end<expression.length&&depth;end++){
|
|
20
|
+
if(expression[end]==='(')depth++;else if(expression[end]===')')depth--;
|
|
21
|
+
else if(expression[end]===','&&depth===1&&comma<0)comma=end;
|
|
22
|
+
}
|
|
23
|
+
result.push({name:match[1],fallback});
|
|
24
|
+
if(comma>=0)result.push(...variables(expression.slice(comma+1,end-1),true));
|
|
25
|
+
regex.lastIndex=end;
|
|
26
|
+
}return result;
|
|
27
|
+
}
|
|
28
|
+
function selectors(text) {
|
|
29
|
+
const out=[];let start=0,depth=0,quote='';
|
|
30
|
+
for(let i=0;i<text.length;i++){
|
|
31
|
+
const char=text[i];
|
|
32
|
+
if(quote){if(char==='\\')i++;else if(char===quote)quote='';}
|
|
33
|
+
else if(char==='"'||char==="'")quote=char;
|
|
34
|
+
else if(char==='('||char==='[')depth++;
|
|
35
|
+
else if(char===')'||char===']')depth--;
|
|
36
|
+
else if(char===','&&!depth){out.push(text.slice(start,i));start=i+1;}
|
|
37
|
+
}return [...out,text.slice(start)].map(v=>v.trim());
|
|
38
|
+
}
|
|
39
|
+
function reads(){
|
|
40
|
+
const styles=new Map(),rects=new Map();
|
|
41
|
+
return {style:node=>{if(!styles.has(node))styles.set(node,getComputedStyle(node));return styles.get(node);},
|
|
42
|
+
rect:node=>{if(!rects.has(node))rects.set(node,node.getBoundingClientRect());return rects.get(node);}};
|
|
43
|
+
}
|
|
44
|
+
function styleRules({referencesOnly=false,includeCustom=false,resolveNesting=false}={}) {
|
|
45
|
+
const rules=[];
|
|
46
|
+
function visitRules(list, containers = [], parents = []) {
|
|
47
|
+
for (const rule of list) {
|
|
48
|
+
if (rule instanceof CSSMediaRule && !matchMedia(rule.conditionText).matches || rule instanceof CSSSupportsRule && !CSS.supports(rule.conditionText)) continue;
|
|
49
|
+
const nested = typeof CSSContainerRule !== 'undefined' && rule instanceof CSSContainerRule ? [...containers, rule.cssText.slice(0, rule.cssText.indexOf('{'))] : containers;
|
|
50
|
+
let resolved = parents;
|
|
51
|
+
if (rule.selectorText && rule.style) {
|
|
52
|
+
const own = selectors(rule.selectorText);
|
|
53
|
+
resolved = resolveNesting && parents.length ? parents.flatMap(parent => own.map(selector => selector.includes('&') ? selector.replaceAll('&', `:is(${parent})`) : `${parent} ${selector}`)) : own;
|
|
54
|
+
if (!referencesOnly || [...rule.style].some(property => rule.style.getPropertyValue(property).includes('var(')||includeCustom&&property.startsWith('--'))) rules.push({ rule, selectors: resolved, style: rule.style, containers });
|
|
55
|
+
}
|
|
56
|
+
if (rule.cssRules) visitRules(rule.cssRules, nested, resolved);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
for(const sheet of document.styleSheets)visitRules(sheet.cssRules);return rules;
|
|
60
|
+
}
|
|
61
|
+
function textRects(node) {const range=document.createRange();range.selectNodeContents(node);return {range,rects:[...range.getClientRects()]};}
|
|
62
|
+
function identityNode(node,path,parentPath,owners,style,checkNeutral=true){
|
|
63
|
+
const attributes={};
|
|
64
|
+
for(const name of ['id','data-part','data-adg-id','role','aria-label','aria-labelledby','aria-describedby'])if(node.hasAttribute(name))attributes[name]=node.getAttribute(name);
|
|
65
|
+
const password=node.matches('input[type=password]');
|
|
66
|
+
const neutral = checkNeutral && !owners.length && !node.hasAttribute('data-adg-id') && !node.hasAttribute('data-adg-keys') &&
|
|
67
|
+
!Object.keys(attributes).length && /^(div|span)$/.test(node.localName) && (node.children.length===1 || style?.display==='contents') &&
|
|
68
|
+
![...node.childNodes].some(n=>n.nodeType===3 && n.data.trim()) && style &&
|
|
69
|
+
['block','inline','contents'].includes(style.display) && style.position==='static' &&
|
|
70
|
+
style.transform==='none' && style.overflowX==='visible' && style.overflowY==='visible' &&
|
|
71
|
+
style.opacity==='1' && style.backgroundColor==='rgba(0, 0, 0, 0)' && style.boxShadow==='none' &&
|
|
72
|
+
['Top','Right','Bottom','Left'].every(side=>parseFloat(style[`margin${side}`])===0 && parseFloat(style[`padding${side}`])===0 && parseFloat(style[`border${side}Width`])===0);
|
|
73
|
+
const native={button:'button',a:node.hasAttribute('href')?'link':null,input:node.type==='checkbox'?'checkbox':node.type==='radio'?'radio':node.type==='button'||node.type==='submit'?'button':'textbox',select:'combobox',textarea:'textbox',h1:'heading',h2:'heading',h3:'heading',h4:'heading',h5:'heading',h6:'heading',img:'img'};
|
|
74
|
+
const role=node.getAttribute('role')??native[node.localName];
|
|
75
|
+
const labelled=node.getAttribute('aria-labelledby')?.split(/\s+/).map(id=>node.ownerDocument.getElementById(id)?.textContent??'').join(' ');
|
|
76
|
+
// Theme-independent naming evidence; AX exposure/hidden state never changes an address.
|
|
77
|
+
const name=normalizeText(labelled||node.getAttribute('aria-label')||node.getAttribute('alt')||(role==='textbox'||role==='combobox'?Array.from(node.labels??[]).map(l=>l.textContent).join(' '):role?node.textContent:'')||'');
|
|
78
|
+
const resource=node.localName==='svg'&&(node.hasAttribute('data-adg-icon')||node.getAttribute('aria-hidden')==='true'||!node.querySelector('text,foreignObject')&&!node.hasAttribute('role'));
|
|
79
|
+
return {path,parentPath,tag:node.localName,namespace:node.namespaceURI,attributes,owners,neutral,resource,
|
|
80
|
+
...(role&&name?{semantic:{role,name}}:{}),
|
|
81
|
+
keys:JSON.parse(node.getAttribute('data-adg-keys')??'[]'),password,
|
|
82
|
+
directText:password?'':[...node.childNodes].filter(n=>n.nodeType===3).map(n=>n.data).join('')};
|
|
83
|
+
}
|
|
84
|
+
globalThis.__adgFramePrimitives={inventory,relativeBox,variables,selectors,reads,normalizeText,identityNode,styleRules,textRects};
|
|
85
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const escape = value => String(value).replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
|
@@ -1,6 +1,5 @@
|
|
|
1
1
|
import path from 'node:path';
|
|
2
|
-
import {
|
|
3
|
-
import { configFile } from './config.mjs';
|
|
2
|
+
import { realpath } from 'node:fs/promises';
|
|
4
3
|
import { prepareDiffInputs } from './diff-inputs.mjs';
|
|
5
4
|
import { revisionChanges, currentHead } from './arch-git.mjs';
|
|
6
5
|
import { cleanup } from './results.mjs';
|
|
@@ -9,25 +8,7 @@ import { CliError } from '../cli-output.mjs';
|
|
|
9
8
|
const slash = name => name.split(path.sep).join('/');
|
|
10
9
|
const within = (name, directory) => !directory || name === directory || name.startsWith(directory + '/');
|
|
11
10
|
|
|
12
|
-
|
|
13
|
-
export async function configInputFiles(config) {
|
|
14
|
-
const found = new Set(), entry = configFile(config.root);
|
|
15
|
-
async function visit(file) {
|
|
16
|
-
file = await realpath(file);
|
|
17
|
-
if (found.has(file)) return;
|
|
18
|
-
found.add(file);
|
|
19
|
-
const text = await readFile(file, 'utf8');
|
|
20
|
-
for (const [, specifier] of text.matchAll(/\b(?:from\s*|import\s*(?:\(\s*)?|require\(\s*)['"](\.[^'"]+)['"]/g)) {
|
|
21
|
-
const requested = path.resolve(path.dirname(file), specifier);
|
|
22
|
-
for (const candidate of [requested, ...['.ts', '.js', '.mjs', '/index.ts', '/index.js'].map(extension => requested + extension)]) {
|
|
23
|
-
try { if ((await stat(candidate)).isFile()) { await visit(candidate); break; } }
|
|
24
|
-
catch (error) { if (!['ENOENT', 'ENOTDIR'].includes(error.code)) throw error; }
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
if (entry) await visit(entry);
|
|
29
|
-
return [...found];
|
|
30
|
-
}
|
|
11
|
+
export { configInputFiles } from './input-generation.mjs';
|
|
31
12
|
|
|
32
13
|
/** Reuse diff's historical config, dependency environment and disposable-tree lifecycle. */
|
|
33
14
|
export async function prepareImpactInputs(config, values) {
|
package/src/toolkit/impact.mjs
CHANGED
|
@@ -12,8 +12,8 @@ import { relatedSources } from '../../public/relationships.js';
|
|
|
12
12
|
import { commandFailure, cleanup } from './results.mjs';
|
|
13
13
|
import { indexDigest } from './index-store.mjs';
|
|
14
14
|
import { groupImpactFrames, impactFrameCount } from './impact-output.mjs';
|
|
15
|
-
import { loadConfig } from './config.mjs';
|
|
16
15
|
import { canonicalBytes, capturePolicy, entryProjection, equalEntryProof, architectureProjection, equalProof } from './impact-proof.mjs';
|
|
16
|
+
import { trackedHash, inputBytes as bytes, verifyInputGeneration } from './input-generation.mjs';
|
|
17
17
|
import { createEligibilityChecker } from './impact-eligibility.mjs';
|
|
18
18
|
|
|
19
19
|
const slash = name => name.split(path.sep).join('/');
|
|
@@ -21,10 +21,6 @@ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
|
21
21
|
const outside = name => name === '..' || name.startsWith('../') || path.isAbsolute(name);
|
|
22
22
|
const array = value => value === undefined ? [] : Array.isArray(value) ? value : [value];
|
|
23
23
|
const themesFor = values => values.theme && values.theme !== 'both' ? [values.theme] : ['light', 'dark'];
|
|
24
|
-
const trackedHash = contents => indexDigest(contents === null ? 'missing\0' : Buffer.concat([Buffer.from('present\0'), contents]));
|
|
25
|
-
async function bytes(file) {
|
|
26
|
-
try { return await readFile(file); } catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return null; throw error; }
|
|
27
|
-
}
|
|
28
24
|
|
|
29
25
|
async function sourceInput(config, input, inventory) {
|
|
30
26
|
try { return relative(config, selectSources(config, [input], { write: false })[0]); }
|
|
@@ -55,25 +51,8 @@ export async function impact(config, values, { log = console.log, openIndex = op
|
|
|
55
51
|
async function track(file) { if (!tracked.has(file)) tracked.set(file, trackedHash(await bytes(file))); }
|
|
56
52
|
const warn = (code, message, next = []) => { if (!warnings.some(warning => warning.code === code)) warnings.push({ code, message, next }); };
|
|
57
53
|
const checkNext = reason => [{ argv: ['adg', 'check', '--read-only', '--json'], reason }];
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
// check again after evaluation so a config hook cannot mutate a tracked input.
|
|
61
|
-
for (const [file, expected] of tracked) if (trackedHash(await bytes(file)) !== expected) throw new CliError('IMPACT_INPUT_CHANGED', `Input changed during impact query: ${file}.`);
|
|
62
|
-
for (const view of views) {
|
|
63
|
-
await view.index.verifyInputs();
|
|
64
|
-
if (inputs) {
|
|
65
|
-
let resolved;
|
|
66
|
-
try { resolved = await loadConfig(view.config.root, { discover: false, fresh: true }); }
|
|
67
|
-
catch (cause) { throw new CliError('IMPACT_INPUT_CHANGED', `Configuration could not be revalidated: ${view.config.root}. ${cause.message}`, { cause }); }
|
|
68
|
-
if (canonicalBytes(resolved) !== view.resolved) throw new CliError('IMPACT_INPUT_CHANGED', `Resolved configuration changed during query: ${view.config.root}.`);
|
|
69
|
-
const files = await configInputFiles(resolved);
|
|
70
|
-
const names = files.map(file => slash(path.relative(resolved.root, file))).sort(compare);
|
|
71
|
-
if (canonicalBytes(names) !== canonicalBytes([...view.configInputs].sort(compare))) throw new CliError('IMPACT_INPUT_CHANGED', 'Configuration dependency inventory changed during query.');
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
for (const [file, expected] of tracked) if (trackedHash(await bytes(file)) !== expected) throw new CliError('IMPACT_INPUT_CHANGED', `Input changed during impact query: ${file}.`);
|
|
75
|
-
await inputs?.verifyChanges();
|
|
76
|
-
}
|
|
54
|
+
const verifyGeneration=()=>verifyInputGeneration({tracked,views,inputs});
|
|
55
|
+
|
|
77
56
|
try {
|
|
78
57
|
let query, fileInput;
|
|
79
58
|
await timed('prepareMs', async () => {
|