rtl-analyzer 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +82 -2
- package/dist/bootstrap.js +27 -0
- package/dist/cli.js +76 -0
- package/dist/codemod.js +53 -0
- package/dist/coverage.js +36 -0
- package/dist/css.js +61 -0
- package/dist/dashboard-client.js +167 -0
- package/dist/dashboard-data.js +22 -0
- package/dist/dashboard-html.js +27 -0
- package/dist/discovery.js +71 -0
- package/dist/eligibility.js +19 -0
- package/dist/html.js +34 -0
- package/dist/model.js +9 -0
- package/dist/policy-audit.js +109 -0
- package/dist/policy-validation.js +137 -0
- package/dist/policy.js +32 -0
- package/dist/presentation-adapter.js +52 -0
- package/dist/preview-manifest.js +15 -0
- package/dist/report-publisher.js +110 -0
- package/dist/report.js +8 -0
- package/dist/review-session.js +153 -0
- package/dist/rules.js +215 -0
- package/dist/runtime-direction.js +334 -0
- package/dist/scan.js +59 -0
- package/dist/source-snippets.js +177 -0
- package/dist/standalone-cli.js +107 -0
- package/dist/structured-markdown.js +36 -0
- package/dist/tailwind.js +21 -0
- package/dist/typescript.js +191 -0
- package/package.json +30 -4
|
@@ -0,0 +1,167 @@
|
|
|
1
|
+
export const dashboardClientSource = [
|
|
2
|
+
`(()=>{const d=JSON.parse(document.getElementById('rtl-dashboard-data').textContent),companionOrigin=window.__RTL_COMPANION_ORIGIN__||'http://127.0.0.1:4318',r=document.getElementById('dashboard'),el=(t,x='',c='')=>{const n=document.createElement(t);`,
|
|
3
|
+
`if(c)n.className=c;`,
|
|
4
|
+
`if(x!==undefined)n.textContent=String(x);`,
|
|
5
|
+
`return n},severityLabel=x=>(__SEVERITY_LABELS__[x]??x),b=x=>{const n=el('bdi',x);`,
|
|
6
|
+
`n.dir='auto';`,
|
|
7
|
+
`return n},all=Object.values(d.queue).flat().sort((a,z)=>a.path<z.path?-1:a.path>z.path?1:a.line-z.line||a.column-z.column),by=new Map(all.map(f=>[f.id,f])),sn=new Map((d.sourceSnippets?.sources||[]).map(x=>[x.id,x])),rf=new Map((d.sourceSnippets?.findings||[]).map(x=>[x.findingId,x])),s={file:null,finding:null,app:'all',q:'',severity:'all',status:'all',eligibility:'all',category:'all',sort:'path'},app=el('div','','app'),top=el('header','','top'),brand=el('div','RTL Migration Analyzer v3','brand');`,
|
|
8
|
+
`brand.append(el('small','Analyze · Explore · Fix · Migrate to RTL'));`,
|
|
9
|
+
`top.append(brand);`,
|
|
10
|
+
`const nav=el('nav','','nav');`,
|
|
11
|
+
`['▥ Overview','</> Code Explorer','⚠ Findings','∿ Diagnostics','▤ Rules','▤ Reports'].forEach((x,i)=>{const q=el('button',x,i===1?'active':'disabled');`,
|
|
12
|
+
`q.type='button';`,
|
|
13
|
+
`if(i!==1){q.disabled=true;`,
|
|
14
|
+
`q.title='Coming soon'}nav.append(q)});`,
|
|
15
|
+
`top.append(nav);`,
|
|
16
|
+
`const tools=el('div','','tools'),sw=el('div','','search-wrap');`,
|
|
17
|
+
`sw.append(el('span','⌕'));`,
|
|
18
|
+
`const search=el('input');`,
|
|
19
|
+
`search.placeholder='Search findings';`,
|
|
20
|
+
`search.setAttribute('aria-label','Search findings');`,
|
|
21
|
+
`sw.append(search);`,
|
|
22
|
+
`tools.append(sw);`,
|
|
23
|
+
`const filters=el('section','','finding-filters'),filterTitle=el('strong','Findings: search and filters'),filterSummary=el('span','','filter-summary'),makeSelect=(label,values,key)=>{const wrap=el('label','', 'filter-control'),select=el('select');wrap.append(el('span',label),select);values.forEach(x=>select.append(new Option(x[1],x[0])));select.value=s[key];select.onchange=()=>{s[key]=select.value;writeUrl();refresh()};filters.append(wrap);return select};`,
|
|
24
|
+
`filters.append(filterTitle);`,
|
|
25
|
+
`const severityFilter=makeSelect('Severity',[['all','All severities'],['Major','Major'],['Minor','Minor'],['Info','Info']], 'severity'),statusFilter=makeSelect('Review status',[['all','All review statuses'],['Not Reviewed','Not Reviewed'],['Needs Manual Investigation','Needs Manual Investigation'],['Candidate Proposed','Candidate Proposed'],['Validation Failed','Validation Failed'],['Ready for Review','Ready for Review'],['Approved','Approved'],['Rejected','Rejected']], 'status'),eligibilityFilter=makeSelect('Codemod eligibility',[['all','All eligibility'],['MANUAL','Manual'],['ASSISTED','Assisted'],['AUTOMATED_ELIGIBLE','Automated eligible']], 'eligibility'),categoryFilter=makeSelect('Rule category',[['all','All categories'],...([...new Set(all.map(f=>f.category))].sort().map(x=>[x,x]))], 'category'),sortFilter=makeSelect('Sort by',[['path','File path'],['severity','Severity'],['status','Review status'],['rule','Rule ID']], 'sort');`,
|
|
26
|
+
`const clear=el('button','Clear filters');clear.type='button';clear.onclick=()=>{s.q='';search.value='';s.app='all';s.severity=s.status=s.eligibility=s.category='all';s.sort='path';sel.value='all';severityFilter.value=statusFilter.value=eligibilityFilter.value=categoryFilter.value='all';sortFilter.value='path';writeUrl();refresh()};filters.append(clear,filterSummary);`,
|
|
27
|
+
`app.append(filters);`,
|
|
28
|
+
`top.append(tools,el('span',d.complete?'SCAN COMPLETE':'SCAN INCOMPLETE','status '+(d.complete?'':'warn')));`,
|
|
29
|
+
`const rescan=el('section','','rescan-panel'),rescanButton=el('button','Rescan authoritative report'),rescanState=el('p','No rescan submitted','rescan-state'),rescanHistory=el('div','','rescan-history'),showRescan=x=>{if(!x)return;rescanState.textContent='Rescan persisted: '+x.reconciliation.length+' findings reconciled';rescanHistory.replaceChildren(...x.reconciliation.map(y=>el('p',y.findingId+' · '+y.status+' · '+y.confidence)))};fetch(companionOrigin+'/review/rescan').then(r=>r.ok?r.json():Promise.reject()).then(x=>showRescan(x.scans?.[0])).catch(()=>{});rescanButton.onclick=()=>{rescanButton.disabled=true;const findings=Object.values(d.queue).flat(),manifest={scanId:crypto.randomUUID?.()||String(Date.now()),inputDigest:d.inputDigest,policyDigest:d.policyDigest,timestamp:new Date().toISOString(),sourceCoverage:{complete:d.complete,filesAnalyzed:d.filesAnalyzed,filesExpected:d.filesAnalyzed},findings};fetch(companionOrigin+'/review/rescan',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({project:'invoicing',manifest})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'RESCAN_FAILED')))).then(showRescan).catch(e=>{rescanState.textContent=e.message}).finally(()=>{rescanButton.disabled=false})};rescan.append(el('h2','Durable Rescan'),rescanState,rescanButton,rescanHistory);app.append(rescan);`,
|
|
30
|
+
`const progress=el('section','','migration-progress'),progressBody=el('div','','progress-body');progress.append(el('h2','Migration Progress'),progressBody);const renderProgress=x=>{progressBody.replaceChildren(el('p','Total current findings: '+x.totalFindings),el('p','Validated: '+x.validated+' · Outstanding: '+x.outstanding),el('p','Progress: '+x.progressPercent+'%'),el('p','Recommendations: '+Object.entries(x.recommendationDistribution).map(([k,v])=>k+' '+v).join(' · ')),el('p','Lifecycle: '+Object.entries(x.lifecycleDistribution).map(([k,v])=>k+' '+v).join(' · ')),el('p','Rescan: '+Object.entries(x.reconciliationDistribution).map(([k,v])=>k+' '+v).join(' · ')),...x.findings.map(f=>el('p',f.findingId+' · '+f.recommendation+' · '+f.lifecycle+' · '+f.reconciliation+' · evidence '+f.evidenceCount)))};fetch(companionOrigin+'/review/progress').then(r=>r.ok?r.json():Promise.reject()).then(renderProgress).catch(()=>progressBody.append(el('p','Progress unavailable; companion required')));app.append(progress);`,
|
|
31
|
+
`app.append(top);`,
|
|
32
|
+
`const sv=d.breakdowns.severity||[],major=sv.find(x=>x.name==='Major')?.count||0,minor=sv.find(x=>x.name==='Minor')?.count||0,info=sv.find(x=>x.name==='Info')?.count||0,rawTotal=major+minor+info,total=rawTotal||1,pct=x=>Math.round(x/total*100),sum=el('section','','summary'),wc=el('div','','card workspace-card');`,
|
|
33
|
+
`wc.append(el('span','◈','workspace-icon'),el('div'));`,
|
|
34
|
+
`wc.lastChild.append(el('strong','Workspace'),el('span',d.filesAnalyzed+' files analyzed · '+d.findings+' findings'),el('span',d.uniqueAffectedFiles+' affected files · '+d.diagnostics+' diagnostics · '+d.blockingDiagnostics+' blocking','workspace-secondary'),el('b',d.complete?'✓ Scan complete':'! Scan incomplete','workspace-status'));`,
|
|
35
|
+
`sum.append(wc);`,
|
|
36
|
+
`[['Total findings',d.findings,'']].forEach(x=>{const c=el('div','','card '+x[2]);`,
|
|
37
|
+
`c.append(el('strong',x[1]),el('span',x[0]));`,
|
|
38
|
+
`sum.append(c)});`,
|
|
39
|
+
`[['⚠','High Priority','Major',major,'red'],['△','Low Priority','Minor',minor,'amber'],['ⓘ','Informational','Info',info,'blue']].forEach(x=>{const c=el('div','','card severity-card '+x[4]);c.setAttribute('aria-label',x[1]+' ('+x[2]+'): '+x[3]+' findings');c.append(el('strong',x[0]+' '+x[3]),el('span',x[1]+' · '+x[2]));sum.append(c)});`,
|
|
40
|
+
`const actionCard=el('div','','card green');actionCard.append(el('strong',d.actionableFindings),el('span','Actionable findings'));sum.append(actionCard);`,
|
|
41
|
+
`const chart=el('div','','card severity-chart'),donut=el('div','','donut');`,
|
|
42
|
+
`donut.style.setProperty('--major',(major/total*100)+'%');`,
|
|
43
|
+
`donut.style.setProperty('--minor',((major+minor)/total*100)+'%');`,
|
|
44
|
+
`donut.setAttribute('role','img');donut.setAttribute('aria-label','Severity distribution: '+major+' Major, '+minor+' Minor, '+info+' Info; '+rawTotal+' total findings');donut.style.position='relative';`,
|
|
45
|
+
`const totalText=el('strong',String(rawTotal));totalText.style.position='absolute';totalText.style.inset='18px 0 auto';totalText.style.textAlign='center';totalText.style.fontSize='16px';const totalLabel=el('span','Total Findings');totalLabel.style.position='absolute';totalLabel.style.top='37px';totalLabel.style.left='0';totalLabel.style.right='0';totalLabel.style.textAlign='center';totalLabel.style.fontSize='7px';donut.append(totalText,totalLabel);`,
|
|
46
|
+
`chart.append(donut);`,
|
|
47
|
+
`const lg=el('div','','legend');`,
|
|
48
|
+
`[['r','Major',major],['a','Minor',minor],['b','Info',info]].forEach(x=>{const p=el('div');`,
|
|
49
|
+
`p.append(el('i','',x[0]),el('span',severityLabel(x[1])+' · '+x[2]+' · '+pct(x[2])+'%'));`,
|
|
50
|
+
`lg.append(p)});`,
|
|
51
|
+
`chart.append(lg);`,
|
|
52
|
+
`sum.append(chart);`,
|
|
53
|
+
`app.append(sum);`,
|
|
54
|
+
`const sr=el('section','','scope-row'),scope=el('div','','scope');`,
|
|
55
|
+
`scope.append(el('span','◎','scope-icon'),el('div'));`,
|
|
56
|
+
`scope.children[1].append(el('h2','Analysis Scope'),el('p','Choose what to explore'));`,
|
|
57
|
+
`const sel=el('select');`,
|
|
58
|
+
`[['all','Entire Workspace'],...(d.scopeBreakdown?.directApplications||[]).map(x=>[x.name,x.name])].forEach(x=>sel.append(new Option(x[1],x[0])));`,
|
|
59
|
+
`scope.append(sel);`,
|
|
60
|
+
`const projects=el('div','','projects');`,
|
|
61
|
+
`const scopeCards=[...(d.scopeBreakdown?.directApplications||[]).map(x=>({name:x.name,count:x.count,kind:'Direct application'})),{name:'Shared library ownership',count:d.scopeBreakdown?.sharedLibraryOwnership??'Not available',kind:'Ownership'}, {name:'Shared library impact',count:d.scopeBreakdown?.sharedLibraryImpact??'Not available',kind:'Impact'}, {name:'Unresolved reachability',count:d.scopeBreakdown?.unresolvedReachability??'Not available',kind:'Unknown attribution'}];`,
|
|
62
|
+
`scopeCards.forEach(x=>{const q=el('button','','project');`,
|
|
63
|
+
`q.type='button';q.disabled=x.kind!=='Direct application';q.setAttribute('aria-label',x.kind+': '+x.name+' '+x.count+' findings; counts are not additive and may overlap; attribution is not verified for unavailable dimensions');q.append(el('strong',x.name),el('span',x.kind+' · '+x.count+' findings'));`,
|
|
64
|
+
`q.onclick=()=>{if(x.kind!=='Direct application')return;sel.value=x.name;`,
|
|
65
|
+
`s.app=x.name;`,
|
|
66
|
+
`writeUrl();refresh()};`,
|
|
67
|
+
`projects.append(q)});`,
|
|
68
|
+
`sr.append(scope,projects);`,
|
|
69
|
+
`app.append(sr);`,
|
|
70
|
+
`const wr=el('main','','workspace'),side=el('section','','pane'),tp=el('section','','pane'),fp=el('section','','pane'),sp=el('section','','pane'),dp=el('section','','pane'),sideBody=el('div','','side'),tree=el('div','','scroll tree'),finds=el('div','','scroll finding-list'),meta=el('div','','meta'),code=el('div','','code-scroll'),details=el('div','','scroll details');`,
|
|
71
|
+
`['Code Explorer','Findings','Diagnostics','Rules & Heuristics','Reports'].forEach((x,i)=>{const q=el('button',x,i===0?'active':'disabled');`,
|
|
72
|
+
`q.type='button';`,
|
|
73
|
+
`q.disabled=i!==0;`,
|
|
74
|
+
`sideBody.append(q)});`,
|
|
75
|
+
`side.append(el('div','NAVIGATION','head'),sideBody);`,
|
|
76
|
+
`tp.append(el('div','PROJECT EXPLORER','head'),tree);`,
|
|
77
|
+
`fp.append(el('div','FINDINGS','head'),finds);`,
|
|
78
|
+
`const cw=el('div','','code');`,
|
|
79
|
+
`cw.append(meta,code);`,
|
|
80
|
+
`sp.append(el('div','SOURCE PREVIEW','head'),cw);`,
|
|
81
|
+
`dp.append(el('div','FINDING DETAILS','head'),details);`,
|
|
82
|
+
`wr.append(side,tp,fp,sp,dp);`,
|
|
83
|
+
`app.append(wr);`,
|
|
84
|
+
`const srLive=el('div','','sr-only');srLive.setAttribute('role','status');srLive.setAttribute('aria-live','polite');srLive.setAttribute('aria-atomic','true');app.append(srLive);r.append(app);document.addEventListener('keydown',e=>{const q=document.querySelector('dialog[open]');if(!q||e.key!=='Tab')return;const focus=[...q.querySelectorAll('button:not(:disabled),input:not(:disabled),textarea:not(:disabled),select:not(:disabled),a[href]')];if(!focus.length)return;const first=focus[0],last=focus[focus.length-1];if(e.shiftKey&&document.activeElement===first){e.preventDefault();last.focus()}else if(!e.shiftKey&&document.activeElement===last){e.preventDefault();first.focus()}});`,
|
|
85
|
+
`const match=()=>all.filter(f=>(s.app==='all'||f.applications.includes(s.app))&&(s.severity==='all'||f.severity===s.severity)&&(s.status==='all'||f.reviewStatus===s.status)&&(s.eligibility==='all'||f.eligibility===s.eligibility)&&(s.category==='all'||f.category===s.category)&&(!s.q||[f.id,f.ruleId,f.path,f.title,f.owner].some(x=>String(x).toLowerCase().includes(s.q.toLowerCase())))),sortRows=rows=>rows.slice().sort((a,z)=>s.sort==='severity'?({Major:0,Minor:1,Info:2}[a.severity]??9)-({Major:0,Minor:1,Info:2}[z.severity]??9)||a.path.localeCompare(z.path):s.sort==='status'?a.reviewStatus.localeCompare(z.reviewStatus)||a.path.localeCompare(z.path):s.sort==='rule'?a.ruleId.localeCompare(z.ruleId)||a.path.localeCompare(z.path):a.path.localeCompare(z.path)||a.line-z.line||a.column-z.column),vis=()=>sortRows(match()).filter(f=>!s.file||f.path===s.file);`,
|
|
86
|
+
`const previewOrigin='http://127.0.0.1:4318',previewState={available:false,checked:false};`,
|
|
87
|
+
`function treeRender(){tree.replaceChildren();`,
|
|
88
|
+
`const walk=(f,p)=>{f.folders.forEach(c=>{const z=document.createElement('details');`,
|
|
89
|
+
`z.open=true;`,
|
|
90
|
+
`z.className='folder';`,
|
|
91
|
+
`z.append(el('summary',c.name+' ('+c.findingCount+')'));`,
|
|
92
|
+
`walk(c,z);`,
|
|
93
|
+
`p.append(z)});`,
|
|
94
|
+
`f.files.forEach(x=>{if(!match().some(f=>f.path===x.path))return;`,
|
|
95
|
+
`const q=el('button','','file'+(s.file===x.path?' selected':''));`,
|
|
96
|
+
`q.type='button';`,
|
|
97
|
+
`q.append(el('span','▣'),b(x.name),el('span',x.findingCount,'count'));`,
|
|
98
|
+
`q.onclick=()=>selectFile(x.path);`,
|
|
99
|
+
`p.append(q)})};`,
|
|
100
|
+
`walk(d.explorer.root,tree)}function listRender(){finds.replaceChildren();`,
|
|
101
|
+
`const rows=vis(),matching=match();filterSummary.textContent=matching.length+' matching of '+all.length+' findings · '+all.filter(f=>!['INFORMATIONAL','INTENTIONAL_LTR'].includes(f.category)).length+' actionable · '+all.filter(f=>f.reviewStatus!=='Not Reviewed').length+'/'+all.length+' reviewed';`,
|
|
102
|
+
`if(!rows.length){finds.append(el('p','No findings match this scope.','empty'));`,
|
|
103
|
+
`return}rows.forEach(f=>{const q=el('button','','finding'+(s.finding?.id===f.id?' selected':''));`,
|
|
104
|
+
`q.type='button';`,
|
|
105
|
+
`q.append(el('strong',f.title),el('small',f.ruleId+' · '+f.path+':'+f.line+':'+f.column));`,
|
|
106
|
+
`q.onclick=()=>select(f.id);`,
|
|
107
|
+
`finds.append(q)})}function source(f){code.replaceChildren();`,
|
|
108
|
+
`meta.replaceChildren();`,
|
|
109
|
+
`if(!f){code.append(el('p','Select a finding to inspect source.','empty'));`,
|
|
110
|
+
`return}meta.append(b(f.path+':'+f.line+':'+f.column));`,
|
|
111
|
+
`if(!d.sourceEmbeddingEnabled){code.append(el('p','Source preview unavailable. Regenerate with --embed-source-snippets.','empty'));`,
|
|
112
|
+
`return}const x=rf.get(f.id),w=x?.available?sn.get(x.sourceId):null;`,
|
|
113
|
+
`if(!w){code.append(el('p','Source preview unavailable: '+(x?.reason||'UNAVAILABLE'),'empty'));`,
|
|
114
|
+
`return}w.lines.forEach(l=>{const q=el('div','','line'+(l.highlighted?' hit':''));`,
|
|
115
|
+
`q.append(el('span',l.number,'no'),el('span',l.text,'text'));`,
|
|
116
|
+
`code.append(q)})}let reviewSession=null;function reviewPanel(f){const box=el('div','','review-panel'),state=el('span','Offline assessment: '+f.reviewStatus,'review-state');box.append(el('strong','Finding Review'),el('p','Embedded offline assessment (not persisted). Persisted decisions require the local companion.'),state);const start=el('button','Propose Candidate');start.onclick=()=>{const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};fetch(previewOrigin+'/review/sessions',{method:'POST'}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'CANDIDATE_SESSION_FAILED')))).then(x=>{reviewSession=x;state.textContent='Candidate session proposed';start.disabled=true;box.append(el('p','Candidate session '+x.id+' created on '+x.candidateOrigin+'.','review-note'));return fetch(previewOrigin+'/review/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,status:'Candidate Proposed',reviewerNotes:'',evidenceReferences:[],candidateSessionId:x.id})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'CANDIDATE_REVIEW_PERSIST_FAILED')))).then(()=>{window.dispatchEvent(new Event('review-record-updated'));const runtime=el('button','Start Candidate Preview');runtime.onclick=()=>fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(x.id)+'/runtime/start',{method:'POST'}).then(r=>r.ok?r.json():Promise.reject()).then(info=>{if(info.runtime?.status!=='healthy')throw new Error();runtime.disabled=true;['ltr','rtl'].forEach(mode=>{const q=el('button','Open Candidate '+mode.toUpperCase()+' Preview');q.onclick=()=>window.open(info.urls[mode],'_blank','noopener,noreferrer');box.append(q)})}).catch(()=>{state.textContent='Candidate runtime unavailable';previewUnavailable(box)});box.append(runtime)}).catch(error=>{state.textContent=error.message;start.disabled=false})}).catch(error=>{state.textContent=error.message;previewUnavailable(box)});};box.append(start);return box}function decisionPanel(f){const box=el('section','','decision-panel'),identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion},recommendation=f.eligibility==='AUTOMATED_ELIGIBLE'?'Automated':f.eligibility==='ASSISTED'?'Assisted':'Manual',state=el('p','Loading persisted decision…','empty'),select=document.createElement('select'),reason=el('textarea'),save=el('button','Save Migration Decision');box.append(el('h3','Migration Treatment Decision'),el('p','Recommendation: '+recommendation),el('p','Rationale: '+f.eligibilityReason),el('p','Blockers: '+(f.eligibilityBlockers.join('; ')||'None')),state);['Automated','Assisted','Manual'].forEach(x=>select.append(new Option(x,x)));reason.placeholder='Override reason (required when changing the recommendation)';box.append(select,reason,save);let sourceDigest='';const url=previewOrigin+'/review/decisions?'+new URLSearchParams(identity);fetch(url).then(r=>r.json()).then(x=>{sourceDigest=x.sourceDigest||'';if(x.decision){select.value=x.decision.selectedTreatment;reason.value=x.decision.overrideReason||'';state.textContent='Saved '+x.decision.selectedTreatment+' decision at '+x.decision.timestamp}else{select.value=recommendation;state.textContent='No saved decision'}}).catch(()=>{state.textContent='Decision persistence unavailable';save.disabled=true});save.onclick=()=>{const selected=select.value;if(selected!==recommendation&&!reason.value.trim()){state.textContent='Override reason is required';return}if(selected==='Automated'&&recommendation!=='Automated'){state.textContent='Automated is blocked by eligibility';return}save.disabled=true;fetch(previewOrigin+'/review/decisions',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,sourceDigest,recommendation,recommendationRationale:f.eligibilityReason,eligibilityConstraints:f.eligibilityBlockers,blockers:f.eligibilityBlockers,selectedTreatment:selected,...(selected!==recommendation?{overrideReason:reason.value.trim()}:{})})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'DECISION_FAILED')))).then(x=>{state.textContent='Saved '+x.decision.selectedTreatment+' decision at '+x.decision.timestamp;save.disabled=false}).catch(e=>{state.textContent=e.message;save.disabled=false})};return box}function detail(f){details.replaceChildren();`,
|
|
117
|
+
`function reviewWorkspace(f){const box=el('section','','review-workspace'),evidence=el('div','','review-evidence'),candidate=el('div','','candidate-evidence'),notes=el('textarea'),refs=el('input'),actions=el('div','','actions'),live=el('p','','review-live');box.append(el('h3','Review Workspace'),el('p','The persisted companion record is authoritative when available. Approval is a review decision only; it never modifies source.'),evidence,candidate,el('h3','Decision'),notes,refs,actions,live);notes.placeholder='Reviewer notes';refs.placeholder='Evidence references, comma-separated';live.setAttribute('aria-live','polite');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const recordUrl=previewOrigin+'/review/records?'+new URLSearchParams(identity);let current=null;const blocked=message=>{const p=el('p',message,'review-blocked');actions.append(p)};const save=status=>{const evidenceReferences=refs.value.split(',').map(x=>x.trim()).filter(Boolean);if(status==='Rejected'&&!notes.value.trim()){live.textContent='Rejected decisions require reviewer notes';return}if((status==='Ready for Review'||status==='Approved')&&(!notes.value.trim()||!evidenceReferences.length)){live.textContent='Ready for Review and Approval require reviewer notes and evidence references';return}if(status==='Approved'&&!window.confirm('Approve this review decision? Approval does not modify source files.'))return;if(status==='Rejected'&&!window.confirm('Reject this review decision? The source remains unchanged.'))return;actions.querySelectorAll('button').forEach(b=>b.disabled=true);fetch(previewOrigin+'/review/records',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,status,reviewerNotes:notes.value,evidenceReferences,...(reviewSession?.id?{candidateSessionId:reviewSession.id}:{})})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'REVIEW_FAILED')))).then(x=>{current=x.record;renderRecord(x.record);live.textContent='Review state updated'}).catch(error=>{live.textContent=error.message;load()})};const renderRecord=record=>{current=record||null;actions.replaceChildren();evidence.replaceChildren(el('h3','Review Status'));if(record){evidence.append(el('p','Persisted review status: '+record.status,'review-state'),el('p','Last updated: '+record.timestamp),el('p','Reviewer notes: '+(record.reviewerNotes||'None')),el('p','Evidence readiness: '+(record.evidenceReferences?.length?'Evidence references present':'No evidence references')));notes.value=record.reviewerNotes||'';refs.value=(record.evidenceReferences||[]).join(', ')}else{evidence.append(el('p','No persisted review decision for this report identity.','empty'),el('p','Embedded offline assessment (not persisted): '+f.reviewStatus));notes.value='';refs.value=''}const status=record?.status||'Not Reviewed';const add=(label,next,enabled=true)=>{const b=el('button',label);b.disabled=!enabled;b.onclick=()=>save(next);actions.append(b)};if(status==='Not Reviewed'){add('Start Investigation','Needs Manual Investigation');add('Mark Verified Correct','Verified Correct')}if(status==='Needs Manual Investigation'){add('Mark Verified Correct','Verified Correct');add('Reject','Rejected')}if(status==='Candidate Proposed'||status==='Validation Failed'){const ready=!!notes.value.trim()&&!!refs.value.split(',').map(x=>x.trim()).filter(Boolean).length;add('Mark Ready for Review','Ready for Review',ready);if(!ready)blocked('Mark Ready for Review blocked: add reviewer notes and at least one evidence reference.');add('Request Manual Investigation','Needs Manual Investigation')}if(status==='Ready for Review'){const ready=!!notes.value.trim()&&!!refs.value.split(',').map(x=>x.trim()).filter(Boolean).length;add('Approve','Approved',ready);if(!ready)blocked('Approve blocked: add reviewer notes and at least one evidence reference.');add('Reject','Rejected')}if(status==='Approved'){add('Reject','Rejected')}if(status==='Rejected'){add('Start Investigation','Needs Manual Investigation')}};const load=()=>fetch(recordUrl).then(r=>r.ok?r.json():Promise.reject()).then(x=>{renderRecord(x.record);if(x.record?.candidateSessionId){const sid=encodeURIComponent(x.record.candidateSessionId);fetch(previewOrigin+'/review/sessions/'+sid).then(r=>r.ok?r.json():Promise.reject()).then(session=>{candidate.replaceChildren(el('h3','Candidate Evidence'),el('p','Session '+session.id+' · runtime '+(session.runtime?.status||'not started')));if(session.runtime?.status==='healthy'){['ltr','rtl'].forEach(mode=>{const q=el('button','Open Candidate '+mode.toUpperCase()+' Preview');q.onclick=()=>window.open((mode==='ltr'?session.candidateOrigin+'/invoices':session.candidateOrigin+'/invoices?demo=unmigrated-rtl&lang=ar'),'_blank','noopener,noreferrer');candidate.append(q)});fetch(previewOrigin+'/review/sessions/'+sid+'/diff').then(r=>r.ok?r.json():Promise.reject()).then(info=>candidate.append(el('pre',info.diff,'review-diff'))).catch(()=>candidate.append(el('p','Candidate diff unavailable.','empty')))}else candidate.append(el('p','Candidate runtime is not healthy; live preview unavailable. Archived evidence remains available separately.','empty'))}).catch(()=>candidate.append(el('p','Candidate session unavailable or stale; archived evidence may still be available.','empty')))}}).catch(()=>{evidence.replaceChildren(el('h3','Review Status'),el('p','Companion unavailable. Embedded offline assessment is shown; no persisted decision is available.','preview-unavailable'));actions.replaceChildren();notes.disabled=true;refs.disabled=true});load();return box}function detail(f){details.replaceChildren();}`,
|
|
118
|
+
`function recoverEvidence(f,box){const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};fetch(previewOrigin+'/review/evidence?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{const archive=el('section','','archived-evidence');archive.append(el('h3','Archived Evidence · Evidence Details'),el('p','Archived evidence is immutable and does not require a live candidate runtime.'));if(!x.snapshots?.length){archive.append(el('p','No archived evidence is available for this report identity.','empty'));box.append(archive);return}x.snapshots.forEach(s=>{const item=el('details');item.append(el('summary','Snapshot '+s.snapshotId+' · '+s.decision+' · '+s.timestamp));const grid=el('dl','evidence-grid');[['Finding',s.findingId],['Source',s.sourcePath],['Report identity',s.inputDigest+' / '+s.policyDigest],['Patch identity',s.candidatePatchIdentity.path+' · '+s.candidatePatchIdentity.expectedSha256],['Original hash',s.originalSourceSha256],['Candidate hash',s.candidateSourceSha256],['Integrity',s.integritySha256]].forEach(([k,v])=>{grid.append(el('dt',k),el('dd',v))});item.append(grid,el('h4','Archived Code Diff'),el('pre',s.codeDiff,'review-diff'));const validation=el('div','', 'validation-results');validation.append(el('h4','Archived Validation'),el('h4','Browser/DOM evidence'),el('p','Scanner before: '+(s.scannerBefore.findingPresent?'finding present':'finding absent')+' · after: '+(s.scannerAfter.findingPresent?'finding present':'finding absent')),el('p','DOM assertions: '+(s.browserDomValidation.join('; ')||'None recorded')),el('p','Screenshots: '+(s.screenshotReferences.length?s.screenshotReferences.join(', '):'No screenshot artifacts recorded')),s.screenshotReferences.length?s.screenshotReferences.map((reference,index)=>{const url=previewOrigin+'/review/evidence/'+encodeURIComponent(s.snapshotId)+'/screenshot/'+encodeURIComponent(reference)+'?'+new URLSearchParams(identity);const card=el('figure','', 'screenshot-preview');const image=document.createElement('img');image.src=url;image.alt=(reference.includes('original')?'Original ':'Candidate ')+(reference.includes('rtl')?'RTL':'LTR')+' validation screenshot';image.loading='lazy';const caption=el('figcaption',image.alt+' · '+reference);const open=el('a','Open larger preview');open.href=url;open.target='_blank';open.rel='noopener noreferrer';card.append(image,caption,open);return card}):el('p','No screenshot previews are available.','empty'));item.append(validation);archive.append(item)});box.append(archive)}).catch(()=>{const archive=el('section','','archived-evidence');archive.append(el('h3','Archived Evidence · Evidence Details'),el('p','Archived evidence is unavailable or stale for this report identity.','preview-unavailable'));box.append(archive)})}`,
|
|
119
|
+
`function controlledApplyPanel(f){const box=el('section','','controlled-apply');box.append(el('h3','Controlled Apply & Rollback'),el('p','Apply is a separate, explicit action. Review approval alone never modifies source.'));const status=el('p','Checking server-side eligibility…','empty'),evidence=el('div','','apply-evidence'),actions=el('div','','actions'),live=el('p','','apply-live');live.setAttribute('aria-live','polite');box.append(status,evidence,actions,live);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const showDialog=(title,message,confirmText,run)=>{const dialog=document.createElement('dialog');dialog.append(el('h3',title),el('p',message));const cancel=el('button','Cancel'),confirm=el('button',confirmText),row=el('div','','actions');row.append(cancel,confirm);dialog.append(row);cancel.onclick=()=>dialog.close();confirm.onclick=async()=>{confirm.disabled=true;cancel.disabled=true;dialog.close();await run()};document.body.append(dialog);dialog.addEventListener('close',()=>dialog.remove(),{once:true});dialog.showModal();confirm.focus()};const renderAudit=()=>fetch(previewOrigin+'/review/audit?sourcePath='+encodeURIComponent(f.path)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{if(!x.events?.length)return;const history=el('section','','audit-history');history.append(el('h4','Audit History'),el('p','Durable operation history; reviewer identity is not inferred.'));[...x.events].sort((a,b)=>Date.parse(a.timestamp)-Date.parse(b.timestamp)).forEach(e=>{const item=el('details');item.append(el('summary',e.type+' · '+e.timestamp));const grid=el('dl','audit-grid');[['Operation',e.type],['Result',e.reason?'Failed':'Recorded'],['Source hash',e.sourceSha256],['Resulting hash',e.resultingSha256||'Not recorded'],['Details',e.reason||'None']].forEach(([k,v])=>{grid.append(el('dt',k),el('dd',v))});history.append(item)});box.append(history)}).catch(()=>{box.append(el('p','Audit history unavailable.','preview-unavailable'))});fetch(previewOrigin+'/review/apply/eligibility?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(info=>{status.textContent=info.ready?'Ready to Apply':'Blocked: '+(info.reason||'Unavailable');status.className=info.ready?'apply-ready':'apply-blocked';if(!info.evidence){evidence.append(el('p','No approved immutable evidence is available. Apply remains disabled.','empty'));return}const e=info.evidence;evidence.append(el('p','Target: '+info.sourcePath),el('p','Finding: '+info.findingId),el('p','Original hash: '+e.originalSourceSha256),el('p','Candidate hash: '+e.candidateSourceSha256),el('h4','Approved Diff'),el('pre',e.codeDiff,'review-diff'));if(info.ready){const apply=el('button','Apply Change');apply.onclick=()=>showDialog('Confirm Controlled Apply','This will modify '+info.sourcePath+' in the original checkout. Confirm only after reviewing the exact diff above.','Confirm Apply',async()=>{status.textContent='Applying';live.textContent='Applying controlled patch…';try{const r=await fetch(previewOrigin+'/review/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({identity,confirmation:'APPLY_CONFIRMED'})});const x=await r.json();if(!r.ok)throw new Error(x.error||'APPLY_FAILED');status.textContent='Applied to Source';live.textContent='Applied successfully';const rollback=el('button','Rollback Change');rollback.onclick=()=>showDialog('Confirm Rollback','This restores the backed-up original source. If the file changed after apply, rollback will be rejected as a conflict.','Confirm Rollback',async()=>{const rr=await fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(x.receipt)});const rx=await rr.json();if(!rr.ok){status.textContent=rx.error==='ROLLBACK_CONFLICT'?'Recovery required':'Rollback failed';live.textContent=rx.error||'ROLLBACK_FAILED';renderAudit();return}status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;renderAudit()});actions.append(rollback);renderAudit()}catch(error){status.textContent=error.message==='ROLLBACK_CONFLICT'?'Recovery required':'Apply failed';live.textContent=error.message}});actions.append(apply)}}).catch(()=>{status.textContent='Controlled Apply unavailable offline';status.className='apply-blocked'});renderAudit();fetch(previewOrigin+'/review/rollback/eligibility?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(info=>{if(!info.eligible)return;const rollback=el('button','Rollback Change');rollback.onclick=()=>showDialog('Confirm Rollback','This restores the backed-up original source. If the file changed after apply, rollback will be rejected as a conflict.','Confirm Rollback',async()=>{const rr=await fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(info.receipt)});const rx=await rr.json();if(!rr.ok){status.textContent=rx.error==='ROLLBACK_CONFLICT'?'Recovery required':'Rollback failed';live.textContent=rx.error||'ROLLBACK_FAILED';renderAudit();return}status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;renderAudit()});actions.append(rollback)}).catch(()=>{});return box}`,
|
|
120
|
+
`function codemodPanel(f){const box=el('section','','codemod-panel');box.append(el('h3','Codemod Dry Run'),el('p','Analysis is read-only. Candidate application is isolated and never changes the original checkout.'));const state=el('p','Not analyzed','empty');const output=el('div','','codemod-output');const actions=el('div','','actions');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const finding={...f};const dialog=(run)=>{const q=document.createElement('dialog');q.append(el('h3','Confirm Candidate Apply'),el('p','This writes only to the isolated candidate session. It does not modify the original checkout or approve the review.'));const cancel=el('button','Cancel'),confirm=el('button','Apply to Candidate');const row=el('div','','actions');row.append(cancel,confirm);q.append(row);cancel.onclick=()=>q.close();confirm.onclick=async()=>{confirm.disabled=true;cancel.disabled=true;q.close();await run()};document.body.append(q);q.addEventListener('close',()=>q.remove(),{once:true});q.showModal();confirm.focus()};const analyze=el('button','Analyze Transformation');analyze.onclick=()=>{state.textContent='Analyzing…';fetch(previewOrigin+'/review/codemod/analyze',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'ANALYSIS_FAILED')))).then(x=>{state.textContent='Analyzed: '+x.transformationId;output.replaceChildren(el('p','Source hash: '+x.sourceSha256),el('p','Transformation: '+x.transformationId),el('p',x.reason),el('pre',JSON.stringify(x.patch,null,2),'review-diff'));const apply=el('button','Apply to Candidate');apply.onclick=()=>dialog(async()=>{state.textContent='Applying to candidate…';fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(reviewSession?.id||'')+'/codemod/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding,confirmation:'CANDIDATE_APPLY_CONFIRMED',sourceSha256:x.sourceSha256})}).then(r=>r.ok?r.json():r.json().then(y=>Promise.reject(new Error(y.error||'CANDIDATE_APPLY_FAILED')))).then(y=>{state.textContent='Candidate-applied patch';output.append(el('p','Candidate hash: '+y.candidateSha256));const diff=el('pre','','review-diff');fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(y.id)+'/diff').then(r=>r.json()).then(z=>{diff.textContent=z.diff;output.append(diff)});}).catch(error=>{state.textContent=error.message==='STALE_SOURCE'?'Stale source':'Candidate apply failed: '+error.message})});actions.append(apply)}).catch(error=>{state.textContent=error.message==='STALE_SOURCE'?'Stale source':'Unsupported or blocked: '+error.message})};box.append(state,output,actions,analyze);return box}`,
|
|
121
|
+
`function validationPanel(f){const box=el('section','','validation-panel');box.append(el('h3','Validation Results'),el('p','Current validation is distinct from archived evidence and review decisions.'));const state=el('p','Idle','validation-state'),output=el('div','','validation-output'),run=el('button','Run Validation'),archive=el('button','Archive Evidence');archive.disabled=true;const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const section=(title,content)=>{const q=el('details');q.open=true;q.append(el('summary',title),content);return q};run.onclick=()=>{if(!reviewSession?.id){state.textContent='Unavailable: create a candidate session first';return}state.textContent='Running';run.disabled=true;output.replaceChildren(el('p','Validation job running…','empty'));Promise.all([fetch(previewOrigin+'/review/codemod/analyze',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding:f})}),fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(reviewSession.id))]).then(async([a,s])=>{const analyzed=await a.json(),session=await s.json();if(!a.ok||!analyzed.patch)throw new Error(analyzed.error||'ANALYSIS_FAILED');return fetch(previewOrigin+'/review/sessions/'+encodeURIComponent(session.id)+'/validate',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({finding:f,patch:analyzed.patch})})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'VALIDATION_FAILED')))).then(x=>{const v=x.result;state.textContent=v.state;const scanner=el('div'); scanner.append(el('p','Completed: '+v.finishedAt));scanner.append(el('p','Scanner before: '+(v.scannerBefore.findingPresent?'finding present':'finding absent')+' · '+v.scannerBefore.resultDigest),el('p','Scanner after: '+(v.scannerAfter.findingPresent?'finding present':'finding absent')+' · '+v.scannerAfter.resultDigest));const browser=el('div');browser.append(el('p','Environment: '+v.environment.node+' · '+v.environment.viewport+' · '+v.environment.locale+' · '+v.environment.timezone),el('p','Original/Candidate LTR and RTL: '+(v.browserDomValidation.filter(x=>x.includes('ltr')||x.includes('rtl')).join('; ')||'No route results recorded')),el('p','DOM: '+(v.browserDomValidation.join('; ')||'None recorded')),el('p','Browser errors: '+(v.browserErrors.join('; ')||'None recorded')),el('p','Screenshots: '+(v.screenshotReferences.length?v.screenshotReferences.join(', '):'No screenshot artifacts recorded')));const identityView=el('dl','validation-identity');[['Job',v.jobId],['Original source hash',v.originalSourceSha256],['Candidate source hash',v.candidateSourceSha256],['Patch path',v.patch.path],['Patch range',v.patch.startOffset+'–'+v.patch.endOffset]].forEach(([k,val])=>{identityView.append(el('dt',k),el('dd',val))});output.replaceChildren(section('Scanner before / after',scanner),section('Browser, DOM and screenshots',browser),section('Source and patch identity',identityView));archive.disabled=v.state!=='Passed';archive.onclick=()=>fetch(previewOrigin+'/review/evidence',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,candidatePatchIdentity:{path:v.patch.path,expectedSha256:v.patch.expectedSha256,replacementSha256:null},originalSourceSha256:v.originalSourceSha256,candidateSourceSha256:v.candidateSourceSha256,codeDiff:'Validation result '+v.jobId,scannerBefore:v.scannerBefore,scannerAfter:v.scannerAfter,browserDomValidation:v.browserDomValidation,screenshotReferences:v.screenshotReferences,timestamp:v.finishedAt,decision:'Ready for Review',patch:v.patch})}).then(r=>{state.textContent=r.ok?'Evidence Archived':'Archive Failed'})}).catch(error=>{state.textContent=error.message;run.disabled=false;output.replaceChildren(el('p','Validation failed: '+error.message,'preview-unavailable'))})};box.append(state,output,run,archive);return box}`,
|
|
122
|
+
`if(!f){details.append(el('p','Select a finding to view details.','empty'));`,
|
|
123
|
+
`return}details.append(el('h2',f.title));`,
|
|
124
|
+
`const a=el('div','','actions'),back=el('button','← Back to Findings','mobile-back');back.type='button';back.onclick=()=>{document.querySelector('.finding-list')?.scrollIntoView({behavior:'smooth'});document.querySelector('.finding-list .finding.selected')?.focus()};const ordered=vis(),at=ordered.findIndex(x=>x.id===f.id),prev=el('button','Previous finding'),next=el('button','Next finding');prev.disabled=at<=0;next.disabled=at<0||at>=ordered.length-1;prev.onclick=()=>select(ordered[at-1].id);next.onclick=()=>select(ordered[at+1].id);a.append(back,prev,next);`,
|
|
125
|
+
`[['Copy relative path',f.path],['Copy location',f.path+':'+f.line+':'+f.column]].forEach(x=>{const q=el('button',x[0]);`,
|
|
126
|
+
`q.onclick=()=>navigator.clipboard?.writeText(x[1]);`,
|
|
127
|
+
`a.append(q)});`,
|
|
128
|
+
`details.append(a);details.append(el('section','Codemod Eligibility: '+f.eligibility,'eligibility-panel'));details.append(el('p',f.eligibilityReason,'eligibility-reason'));if(f.eligibilityTransformationId)details.append(el('p','Transformation: '+f.eligibilityTransformationId));if(f.eligibilityBlockers.length)details.append(el('p','Blockers: '+f.eligibilityBlockers.join(', '),'eligibility-blockers'));details.append(decisionPanel(f));details.append(reviewPanel(f));const workspace=reviewWorkspace(f);details.append(workspace);recoverEvidence(f,workspace);if(f.eligibilityTransformationId==='bidi-isolate-auto'){details.append(codemodPanel(f));details.append(validationPanel(f))}details.append(controlledApplyPanel(f));`,
|
|
129
|
+
`if(f.previewMappingId){const box=el('div','','preview-box');box.append(el('strong','Owning Route Preview'),el('p','Open the real Invoicing application route.'));const buttons=el('div','','actions');[['Open LTR Preview','ltr'],['Open RTL Preview','rtl']].forEach(x=>{const q=el('button',x[0]);q.disabled=!previewState.available;q.title=previewState.available?'Open validated preview':'Local preview unavailable';q.onclick=()=>fetch(previewOrigin+'/mappings/'+encodeURIComponent(f.previewMappingId)+'/preview?mode='+x[1]).then(r=>r.ok?r.json():Promise.reject()).then(info=>window.open(info.url,'_blank','noopener,noreferrer')).catch(()=>previewUnavailable(box));buttons.append(q)});box.append(buttons);details.append(box);if(!previewState.available)previewUnavailable(box)}`,
|
|
130
|
+
`[['Rule',f.ruleId],['Severity',severityLabel(f.severity)+' ('+f.severity+')'],['Category',f.category],['Confidence',f.confidence],['Location',f.path+':'+f.line+':'+f.column],['Owner',f.owner],['Rationale',f.rationale],['Treatment',f.treatment],['Limitation',f.limitation]].forEach(x=>details.append(el('h3',x[0]),b(x[1])))}function select(id){const f=by.get(id);`,
|
|
131
|
+
`if(!f)return;`,
|
|
132
|
+
`s.file=f.path;`,
|
|
133
|
+
`s.finding=f;`,
|
|
134
|
+
`treeRender();`,
|
|
135
|
+
`listRender();`,
|
|
136
|
+
`source(f);writeUrl();`,
|
|
137
|
+
`detail(f)}function selectFile(path){s.file=path;`,
|
|
138
|
+
`const f=vis()[0]||null;`,
|
|
139
|
+
`s.finding=f;`,
|
|
140
|
+
`treeRender();`,
|
|
141
|
+
`listRender();`,
|
|
142
|
+
`source(f);`,
|
|
143
|
+
`detail(f)}function refresh(){const a=vis();srLive.textContent=a.length+' findings available';`,
|
|
144
|
+
`if(!a.length){s.finding=null;`,
|
|
145
|
+
`treeRender();`,
|
|
146
|
+
`listRender();`,
|
|
147
|
+
`source(null);`,
|
|
148
|
+
`detail(null);`,
|
|
149
|
+
`return}if(!s.finding||!a.some(f=>f.id===s.finding.id)){s.finding=null;select(a[0].id)}`,
|
|
150
|
+
`else{treeRender();`,
|
|
151
|
+
`listRender()}}sel.onchange=()=>{s.app=sel.value;`,
|
|
152
|
+
`writeUrl();refresh()};`,
|
|
153
|
+
`const writeUrl=()=>{const p=new URLSearchParams();if(s.q)p.set('q',s.q);if(s.app!=='all')p.set('app',s.app);if(s.severity!=='all')p.set('severity',s.severity);if(s.status!=='all')p.set('status',s.status);if(s.eligibility!=='all')p.set('eligibility',s.eligibility);if(s.category!=='all')p.set('category',s.category);if(s.sort!=='path')p.set('sort',s.sort);if(s.finding?.id)p.set('finding',s.finding.id);const next='?'+p.toString();if(location.search!==next)history.pushState(null,'',next)};`,
|
|
154
|
+
`const readUrl=()=>{const p=new URLSearchParams(location.search);s.q=p.get('q')||'';s.app=p.get('app')||'all';s.severity=p.get('severity')||'all';s.status=p.get('status')||'all';s.eligibility=p.get('eligibility')||'all';s.category=p.get('category')||'all';s.sort=p.get('sort')||'path';search.value=s.q;sel.value=s.app;severityFilter.value=s.severity;statusFilter.value=s.status;eligibilityFilter.value=s.eligibility;categoryFilter.value=s.category;sortFilter.value=s.sort;return p.get('finding')};`,
|
|
155
|
+
`search.oninput=()=>{s.q=search.value;writeUrl();refresh()};`,
|
|
156
|
+
`window.onpopstate=()=>{const id=readUrl();if(id&&by.has(id)){s.finding=by.get(id);s.file=s.finding.path}refresh()};`,
|
|
157
|
+
`const requested=readUrl();setTimeout(()=>{if(requested&&by.has(requested))select(requested);else if(d.explorer.initialFindingId)select(d.explorer.initialFindingId);else refresh()},0);`,
|
|
158
|
+
`function previewUnavailable(box){if(!box.querySelector('.preview-unavailable')){const n=el('p','Local preview unavailable. Start the optional companion to enable owning-route previews.','preview-unavailable');box.append(n)}}fetch(previewOrigin+'/health').then(r=>r.ok?r.json():Promise.reject()).then(()=>{previewState.available=true;previewState.checked=true;if(s.finding)detail(s.finding)}).catch(()=>{previewState.checked=true;if(s.finding)detail(s.finding)});`,
|
|
159
|
+
`document.addEventListener('input',event=>{const target=event.target;if(!(target instanceof HTMLTextAreaElement||target instanceof HTMLInputElement))return;const panel=target.closest('.review-workspace');if(!panel)return;const notes=panel.querySelector('textarea')?.value.trim()||'';const refs=panel.querySelector('input')?.value.split(',').map(x=>x.trim()).filter(Boolean)||[];const ready=!!notes&&refs.length>0;panel.querySelectorAll('button').forEach(button=>{if(button.textContent==='Mark Ready for Review')button.disabled=!ready;if(button.textContent==='Approve')button.disabled=!ready})});`,
|
|
160
|
+
`function lifecyclePanel(f){const box=el('section','','lifecycle-panel'),state=el('p','Loading lifecycle…','lifecycle-state'),history=el('div','','lifecycle-history');box.append(el('h3','Implementation Lifecycle'),state,history);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const load=()=>fetch(previewOrigin+'/review/lifecycle?'+new URLSearchParams(identity)).then(r=>r.ok?r.json():Promise.reject()).then(x=>{state.textContent='State: '+x.lifecycle;history.replaceChildren(el('p','Persisted decisions: '+(x.decision?'Yes':'No')),el('p','Manual changes: '+(x.manualChanges?.length||0)),el('p','Source hash: '+(x.sourceSha256||'Unavailable')))}).catch(()=>{state.textContent='Lifecycle unavailable; companion required'});load();return box}`,
|
|
161
|
+
`function manualPanel(f){const box=el('section','','manual-workflow'),state=el('p','No manual implementation registered','manual-state'),before=document.createElement('textarea'),after=document.createElement('textarea'),register=el('button','Register Manual Change'),history=el('div','','manual-history');before.placeholder='Before source';after.placeholder='After source';box.append(el('h3','Manual Implementation'),state,before,after,register,history);const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};const load=()=>fetch(previewOrigin+'/review/manual-changes?'+new URLSearchParams(identity)).then(r=>r.json()).then(x=>{history.replaceChildren(...(x.changes||[]).map(c=>el('pre','Before/After · '+c.timestamp+'\\n'+c.beforeText+'\\n---\\n'+c.afterText,'manual-diff')));if(x.changes?.length)state.textContent='Manual change validated and persisted'}).catch(()=>{state.textContent='Manual history unavailable'});register.onclick=()=>{register.disabled=true;fetch(previewOrigin+'/review/manual-changes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({...identity,beforeText:before.value,afterText:after.value})}).then(r=>r.ok?r.json():r.json().then(x=>Promise.reject(new Error(x.error||'MANUAL_CHANGE_FAILED')))).then(()=>{state.textContent='Manual change registered and validated';load()}).catch(e=>{state.textContent=e.message;register.disabled=false})};load();return box}`,
|
|
162
|
+
`function controlledApplyPanel(f){const box=el('section','','controlled-apply'),status=el('p','Checking server-side eligibility…','empty'),evidence=el('div','','apply-evidence'),actions=el('div','','actions'),live=el('p','','apply-live');const identity={findingId:f.id,sourcePath:f.path,inputDigest:d.inputDigest,policyDigest:d.policyDigest,schemaVersion:d.schemaVersion};box.append(el('h3','Controlled Apply & Rollback'),el('p','Apply is a separate, explicit action. Review approval alone never modifies source.'),status,evidence,actions,live);const audit=()=>fetch(previewOrigin+'/review/audit?sourcePath='+encodeURIComponent(f.path)).then(r=>r.json()).then(x=>{box.querySelector('.audit-history')?.remove();if(!x.events?.length)return;const h=el('section','','audit-history');h.append(el('h4','Audit History'));x.events.forEach(e=>h.append(el('p',e.type+' · '+(e.resultingSha256||e.sourceSha256))));box.append(h)});const refresh=()=>fetch(previewOrigin+'/review/apply/eligibility?'+new URLSearchParams(identity)).then(r=>r.json()).then(info=>{status.textContent=info.ready?'Ready to Apply':'Blocked: '+(info.reason||'Unavailable');status.className=info.ready?'apply-ready':'apply-blocked';evidence.replaceChildren();actions.replaceChildren();if(!info.evidence||!info.ready)return;const e=info.evidence;evidence.append(el('p','Original hash: '+e.originalSourceSha256),el('p','Candidate hash: '+e.candidateSourceSha256),el('pre',e.codeDiff,'review-diff'));const apply=el('button','Apply Change');apply.onclick=()=>{if(!window.confirm('Confirm Apply'))return;fetch(previewOrigin+'/review/apply',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({identity,confirmation:'APPLY_CONFIRMED'})}).then(r=>r.json().then(x=>({ok:r.ok,x}))).then(({ok,x})=>{if(!ok)throw new Error(x.error||'APPLY_FAILED');status.textContent='Applied to Source';live.textContent='Applied successfully';const rollback=el('button','Rollback Change');rollback.onclick=()=>{if(!window.confirm('Confirm Rollback'))return;fetch(previewOrigin+'/review/rollback',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(x.receipt)}).then(r=>r.json().then(y=>({ok:r.ok,y}))).then(({ok,y})=>{if(!ok)throw new Error(y.error||'ROLLBACK_FAILED');status.textContent='Rolled Back';live.textContent='Rolled back successfully';rollback.disabled=true;audit()})};actions.append(rollback);audit()}).catch(error=>{status.textContent=error.message;live.textContent=error.message})};actions.append(apply)}).catch(()=>{status.textContent='Controlled Apply unavailable offline'});window.addEventListener('review-record-updated',refresh);refresh();audit();return box}`,
|
|
163
|
+
`const dashboardFetch=window.fetch.bind(window);window.fetch=(input,init)=>{const promise=dashboardFetch(input,init);if(String(input).includes('/review/records')&&init?.method==='POST'&&String(init.body||'').includes('"status":"Approved"'))promise.then(r=>{if(r.ok)window.dispatchEvent(new Event('review-approval-updated'))});return promise};window.addEventListener('review-approval-updated',()=>{if(s.finding)detail(s.finding)});`,
|
|
164
|
+
`const originalDetail=detail;detail=f=>{originalDetail(f);if(f){details.append(lifecyclePanel(f));if(f.eligibility!=='AUTOMATED_ELIGIBLE')details.append(manualPanel(f))}};if(s.finding){details.append(lifecyclePanel(s.finding));if(s.finding.eligibility!=='AUTOMATED_ELIGIBLE')details.append(manualPanel(s.finding))}`,
|
|
165
|
+
`const rollbackConflictFetch=window.fetch.bind(window);window.fetch=(input,init)=>{const promise=rollbackConflictFetch(input,init);if(String(input).includes('/review/rollback')&&init?.method==='POST')promise.then(async response=>{if(response.status!==409)return;const payload=await response.clone().json().catch(()=>null);if(payload?.error!=='ROLLBACK_CONFLICT')return;document.querySelectorAll('.controlled-apply').forEach(panel=>{const status=panel.querySelector('.apply-ready,.apply-blocked,.empty');const live=panel.querySelector('.apply-live');if(status)status.textContent='Recovery required';if(live)live.textContent='ROLLBACK_CONFLICT'})});return promise};`,
|
|
166
|
+
`})();`,
|
|
167
|
+
].join('');
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import { approvedPreviewForSource } from './preview-manifest.js';
|
|
2
|
+
import { classifyEligibility } from './eligibility.js';
|
|
3
|
+
export const severityDisplayLabel = (severity) => ({ Major: 'High Priority', Minor: 'Low Priority', Info: 'Informational' }[severity] ?? severity);
|
|
4
|
+
const sort = (a, b) => a < b ? -1 : a > b ? 1 : 0;
|
|
5
|
+
const breakdown = (values) => { const counts = new Map(); for (const value of values)
|
|
6
|
+
counts.set(value, (counts.get(value) ?? 0) + 1); return [...counts].sort((a, b) => sort(a[0], b[0])).map(([name, count]) => ({ name, count })); };
|
|
7
|
+
const findingSort = (a, b) => sort(a.path, b.path) || a.line - b.line || a.column - b.column || sort(a.id, b.id);
|
|
8
|
+
function mapFinding(f, ref, sourceText) { const eligibility = classifyEligibility(f, !ref?.missingEvidenceIds.length, sourceText); const reviewClassification = eligibility.eligibility === 'AUTOMATED_ELIGIBLE' ? 'Automated / Codemod Eligible' : eligibility.eligibility === 'ASSISTED' ? 'Assisted' : 'Manual'; return { id: f.id, ruleId: f.ruleId, ruleVersion: f.ruleVersion, category: f.category, severity: f.severity, confidence: f.confidence, title: f.title, sourceMechanism: f.sourceMechanism, path: f.path, line: f.range.start.line, column: f.range.start.column, owner: f.ownership, applications: f.applications.slice().sort(sort), rationale: f.rationale, treatment: f.treatment, limitation: f.limitation, evidenceIds: f.evidenceIds.slice(), missingEvidenceIds: ref?.missingEvidenceIds.slice() ?? [], duplicateEvidenceIds: ref?.duplicateEvidenceIds.slice() ?? [], relatedLocations: f.relatedLocations.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset).map(x => `${x.path}:${x.range.start.line}:${x.range.start.column}`), issueIds: f.issueIds.slice().sort(sort), suggestion: f.suggestion ? { property: f.suggestion.property, value: f.suggestion.value } : null, previewMappingId: approvedPreviewForSource(f.path)?.id ?? null, reviewStatus: f.id === 'RTL.ICON.PROGRESSION:237172da962fe4d0605ddd83' ? 'Needs Manual Investigation' : 'Not Reviewed', reviewClassification, eligibility: eligibility.eligibility, eligibilityReason: eligibility.reason, eligibilityEvidence: eligibility.evidence, eligibilityTransformationId: eligibility.transformationId, eligibilityBlockers: eligibility.blockers, ...(f.exceptionReason ? { exceptionReason: f.exceptionReason } : {}), ...(f.originalCategory ? { originalCategory: f.originalCategory } : {}) }; }
|
|
9
|
+
export function toDashboardData(report, snippets) { const refs = new Map(report.evidenceReferences.map(ref => [ref.findingId, ref])); const findings = report.findings.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.id, b.id)).map(f => mapFinding(f, refs.get(f.id), snippets?.sourceTextByPath?.[f.path])); const actionable = findings.filter(f => !['INFORMATIONAL', 'INTENTIONAL_LTR'].includes(f.category)); const queue = { critical: [], major: [], minor: [], runtimeConfig: [], informational: [], intentionalLtr: [] }; for (const f of findings) {
|
|
10
|
+
const key = f.category === 'INFORMATIONAL' ? 'informational' : f.category === 'INTENTIONAL_LTR' ? 'intentionalLtr' : f.category === 'RUNTIME_CONFIG' ? 'runtimeConfig' : f.severity.toLowerCase();
|
|
11
|
+
(queue[key] ??= []).push(f);
|
|
12
|
+
} for (const values of Object.values(queue))
|
|
13
|
+
values.sort(findingSort); const byPath = new Map(); for (const f of findings)
|
|
14
|
+
byPath.set(f.path, [...(byPath.get(f.path) ?? []), f]); const root = { name: 'Workspace', path: '', folders: new Map(), files: [], findingCount: findings.length }; for (const [path, fs] of byPath) {
|
|
15
|
+
const parts = path.split('/');
|
|
16
|
+
let folder = root;
|
|
17
|
+
parts.slice(0, -1).forEach((name, index) => { const childPath = parts.slice(0, index + 1).join('/'); let child = folder.folders.get(name); if (!child) {
|
|
18
|
+
child = { name, path: childPath, folders: new Map(), files: [], findingCount: 0 };
|
|
19
|
+
folder.folders.set(name, child);
|
|
20
|
+
} child.findingCount += fs.length; folder = child; });
|
|
21
|
+
folder.files.push({ name: parts.at(-1), path, findingCount: fs.length, findingIds: fs.map(f => f.id).sort(sort) });
|
|
22
|
+
} const freeze = (f) => ({ name: f.name, path: f.path, findingCount: f.findingCount, folders: [...f.folders.values()].sort((a, b) => sort(a.name, b.name)).map(freeze), files: f.files.sort((a, b) => sort(a.name, b.name) || sort(a.path, b.path)) }); const direct = findings.flatMap(f => f.applications); const sharedOwnership = null; const sharedImpact = null; const unresolved = null; const refsList = [...refs.values()]; return { viewModelVersion: 1, kind: report.kind, schemaVersion: report.schemaVersion, inputDigest: report.inputDigest, policyDigest: report.policyDigest, complete: report.complete, filesAnalyzed: report.files.length, skippedPaths: report.skipped.slice().sort(sort), findings: findings.length, actionableFindings: actionable.length, uniqueAffectedFiles: report.metrics.uniqueAffectedFiles, diagnostics: report.diagnostics.length, blockingDiagnostics: report.diagnostics.filter(d => d.blocking).length, breakdowns: { severity: breakdown(findings.map(f => f.severity)), category: breakdown(findings.map(f => f.category)), rule: breakdown(findings.map(f => f.ruleId)), confidence: breakdown(findings.map(f => f.confidence)), application: breakdown(direct) }, files: breakdown(findings.map(f => f.path)), owners: breakdown(findings.map(f => f.owner)), warnings: { unresolvedReachability: findings.filter(f => f.applications.length === 0).length, missingEvidence: refsList.reduce((n, r) => n + r.missingEvidenceIds.length, 0), duplicateEvidence: refsList.reduce((n, r) => n + r.duplicateEvidenceIds.length, 0) }, diagnosticsDetail: report.diagnostics.slice().sort((a, b) => sort(a.path, b.path) || a.range.start.offset - b.range.start.offset || sort(a.code, b.code)).map(d => ({ path: d.path, line: d.range.start.line, column: d.range.start.column, code: d.code, impact: d.impact ?? 'none', blocking: Boolean(d.blocking), message: d.message, rationale: d.rationale ?? '' })), queue, sourceEmbeddingEnabled: Boolean(snippets), explorer: { root: freeze(root), initialFindingId: actionable[0]?.id ?? findings[0]?.id ?? null }, scopeBreakdown: { directApplications: breakdown(direct), sharedLibraryOwnership: sharedOwnership, sharedLibraryImpact: sharedImpact, unresolvedReachability: unresolved }, ...(snippets ? { sourcePrivacyWarning: 'Embedded source may contain sensitive information; review and protect this dashboard accordingly.', sourceSnippets: { sources: snippets.sources, findings: snippets.findings, embeddedBytes: snippets.embeddedBytes } } : {}) }; }
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { dashboardClientSource } from './dashboard-client.js';
|
|
2
|
+
import { severityDisplayLabel, toDashboardData } from './dashboard-data.js';
|
|
3
|
+
const escapeJson = (v) => v.replace(/[<>&\u2028\u2029]/g, c => ({ '<': '\\u003c', '>': '\\u003e', '&': '\\u0026', '\u2028': '\\u2028', '\u2029': '\\u2029' }[c] ?? c));
|
|
4
|
+
const css = `:root{
|
|
5
|
+
color-scheme:dark;
|
|
6
|
+
--bg:#060d1a;--nav:#0a1426;--surface:#0e1a2e;--surface-hi:#14243c;--surface-soft:#101f35;
|
|
7
|
+
--line:#263c5d;--line-soft:#1c304e;--text:#f4f7ff;--muted:#9aaac1;--dim:#70819b;
|
|
8
|
+
--purple:#9a63ff;--purple-deep:#4e1d9d;--purple-glow:#b989ff;--red:#ff4564;--amber:#f4b72f;--blue:#42a4ff;--green:#35d995;
|
|
9
|
+
--code:#040a13;--focus:#c9a9ff;--r-sm:8px;--r-md:12px;--r-lg:15px;
|
|
10
|
+
font-family:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif
|
|
11
|
+
}
|
|
12
|
+
:where(.app){width:100%;max-width:100vw;min-width:0}:where(.top),:where(.nav),:where(.tools),:where(.search-wrap){min-width:0}
|
|
13
|
+
.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}@media(prefers-reduced-motion:reduce){*,*::before,*::after{scroll-behavior:auto!important;transition-duration:.01ms!important;animation-duration:.01ms!important}}
|
|
14
|
+
:root{--space-1:4px;--space-2:8px;--space-3:12px;--space-4:16px;--space-5:20px;--space-6:24px;--text-sm:12px;--text-md:14px;--text-lg:18px;--surface-raised:#14243a;--surface-panel:#0f1d31;--border-strong:#395477;--status-ok:#3fe0a0;--status-warn:#ffd166;--status-bad:#ff7188}.card,.scope,.project{background:var(--surface-raised);box-shadow:0 4px 14px #0003}.workspace{background:var(--border-strong);box-shadow:0 8px 24px #0004}.head{font-size:var(--text-sm);color:#c2cee0}.finding strong{font-size:var(--text-md);font-weight:750}.finding small,.file,.meta,.filter-control,.filter-summary{font-size:var(--text-sm)}.details{font-size:var(--text-md)}.details p,.review-panel p,.review-workspace p,.validation-panel p,.audit-history p{color:#c0ccdd}.details h3{font-size:var(--text-sm);color:#aebed3}.actions button,.finding-filters>button{font-size:var(--text-sm);min-height:38px}.actions button{background:#5f35b5;border-color:#a98ae8;box-shadow:none}.actions button:hover:not(:disabled){background:#7447cf}.actions button:disabled{opacity:.48}.review-state,.apply-ready,.validation-state{color:var(--status-ok);font-weight:750}.review-blocked,.apply-blocked,.preview-unavailable{color:var(--status-warn)}.review-diff{padding:var(--space-4);border:1px solid var(--border-strong);border-radius:var(--r-sm);background:#070e19;color:#e9eef8;line-height:1.55;white-space:pre-wrap;overflow:auto}.screenshot-preview{display:inline-flex;vertical-align:top;flex-direction:column;gap:var(--space-2);width:min(220px,100%);margin:var(--space-2)}.screenshot-preview img{border:1px solid var(--border-strong);border-radius:var(--r-sm);background:#080f1b}.screenshot-preview figcaption{font-size:var(--text-sm);color:#c0ccdd}.audit-history details,.archived-evidence details,.validation-panel details{border:1px solid var(--line);border-radius:var(--r-sm);margin:var(--space-2) 0;background:#132238}.audit-history summary,.archived-evidence summary,.validation-panel summary{padding:var(--space-3);font-size:var(--text-sm);font-weight:750}.audit-grid,.evidence-grid{gap:var(--space-2);font-size:var(--text-sm)}.line.hit{box-shadow:inset 3px 0 #ffd166}.mobile-back{background:#29466f!important;border-color:#6d8fbd!important}
|
|
15
|
+
@media(max-width:800px){.app{grid-template-rows:auto auto auto auto 1fr}.top{flex-wrap:wrap;min-height:118px;padding:10px 14px}.brand{min-width:0;flex:1;font-size:17px}.nav{order:3;width:100%;overflow:auto}.nav button{min-height:42px}.tools{width:100%;margin-left:0}.tools input{flex:1;width:auto}.finding-filters{display:flex;padding:0 10px 10px;align-items:stretch}.filter-control{flex:1 1 calc(50% - 8px);min-width:140px}.filter-control select,.finding-filters>button{width:100%;min-height:44px}.finding-filters>button{flex:1 1 100%}.filter-summary{width:100%;margin:0}.summary{grid-template-columns:repeat(2,1fr);padding:10px}.scope-row{padding:0 10px 10px}.scope{align-items:stretch;flex-wrap:wrap}.scope select{min-width:100%;min-height:44px}.projects{display:none}.workspace{display:flex;flex-direction:column;margin:0 10px 10px;border-radius:12px}.workspace>.pane:nth-child(1),.workspace>.pane:nth-child(2){display:none}.workspace>.pane:nth-child(3){order:1;height:420px}.workspace>.pane:nth-child(5){order:2;height:auto;min-height:520px}.workspace>.pane:nth-child(4){order:3;height:420px}.pane{width:100%}}
|
|
16
|
+
*{box-sizing:border-box}html,body{min-width:0;overflow-x:hidden}body{margin:0;background:radial-gradient(900px 420px at 52% -12%,#1b3155 0%,var(--bg) 64%);color:var(--text);line-height:1.4}button,input,select{font:inherit;max-width:100%}button{cursor:pointer}button:disabled{cursor:not-allowed}button:focus-visible,input:focus-visible,select:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
|
17
|
+
.app{min-height:100vh;display:grid;grid-template-rows:72px auto auto 1fr;gap:0}.top{display:flex;align-items:center;gap:22px;padding:10px 26px;border-bottom:1px solid var(--line-soft);background:linear-gradient(180deg,#0d192c,#091426);box-shadow:0 8px 26px #0005}.brand{position:relative;min-width:360px;padding-left:51px;font-size:20px;font-weight:850;letter-spacing:-.02em;white-space:nowrap}.brand:before{content:'RTL';position:absolute;left:0;top:-1px;display:grid;place-items:center;width:39px;height:39px;border-radius:10px;background:linear-gradient(145deg,#a855f7,#4c1d95);box-shadow:0 0 22px #8b5cf655;color:#fff;letter-spacing:0}.brand small{display:block;margin-top:2px;color:var(--muted);font-size:11px;font-weight:500;letter-spacing:0}.nav{display:flex;align-items:center;gap:7px}.nav button{border:1px solid transparent;border-radius:10px;background:transparent;color:#b0bdd0;padding:11px 15px;font-size:14px;font-weight:800;white-space:nowrap;transition:.15s ease}.nav button:not(:disabled):hover{background:#1b2b47;color:#fff;border-color:var(--line)}.nav .active{background:linear-gradient(180deg,#8447ed,#4e1da0);color:#fff;border-color:#bf92ff;box-shadow:0 0 24px #8b5cf677,inset 0 1px #e2cdff}.nav .disabled{opacity:.42}.tools{display:flex;align-items:center;gap:12px;margin-left:auto}.search-wrap{display:flex;align-items:center;border:1px solid #334b70;border-radius:10px;background:#07111f;padding:0 10px;box-shadow:inset 0 1px #ffffff08}.search-wrap span{color:var(--muted);font-size:19px}.tools input{width:190px;border:0;outline:0;background:transparent;color:var(--text);padding:10px 7px}.tools input::placeholder{color:#8090a7}.status{color:var(--green);font-size:11px;font-weight:900;letter-spacing:.04em;white-space:nowrap}.status.warn{color:var(--amber)}
|
|
18
|
+
.summary{display:grid;grid-template-columns:1.35fr .85fr .9fr .9fr .9fr .95fr 1.75fr;gap:10px;padding:14px 18px 12px}.card{min-height:82px;border:1px solid var(--line);border-radius:var(--r-md);background:linear-gradient(145deg,#152640,#0d182b);padding:13px 15px;box-shadow:0 8px 26px #0003,inset 0 1px #ffffff08}.workspace-card{display:flex;align-items:center;gap:13px;position:relative}.workspace-icon{font-size:32px;color:#bd77ff;text-shadow:0 0 16px #9a63ff99}.workspace-card strong{font-size:18px}.workspace-card span{display:block}.workspace-secondary{display:block!important;margin-top:3px;color:var(--dim)!important;font-size:10px!important}.workspace-status{display:inline-block!important;margin-top:5px;border-radius:99px;padding:3px 9px;background:#0d6a4b;color:#d9fff0!important;font-size:10px!important;font-weight:800}.card strong{display:block;font-size:27px;line-height:1.05;letter-spacing:-.02em}.card span{color:var(--muted);font-size:11px}.card.green{border-color:#197c55;background:linear-gradient(145deg,#12372f,#0d1d2b)}.card.blue{border-color:#225f99}.card.red{border-color:#933047;background:linear-gradient(145deg,#341629,#111a2b)}.severity-card{min-height:82px}.severity-card strong{font-size:24px}.severity-card span{font-size:11px}.severity-card.red{border-color:#8b2945}.severity-card.amber{border-color:#836020;background:linear-gradient(145deg,#342a1b,#151e2c)}.severity-card.blue{border-color:#225d96;background:linear-gradient(145deg,#122d4c,#101d2f)}.severity-chart{display:flex;align-items:center;justify-content:center;gap:18px;padding:8px 14px}.donut{position:relative;width:82px;height:82px;flex:0 0 auto;border-radius:50%;background:conic-gradient(var(--red) 0 var(--major),var(--amber) var(--major) var(--minor),var(--blue) var(--minor) 100%);display:grid;place-items:center;box-shadow:0 0 20px #0006}.donut:after{content:'';position:absolute;width:53px;height:53px;border-radius:50%;background:#101d31;box-shadow:inset 0 0 0 1px #ffffff0b}.legend{font-size:11px;line-height:1.95;min-width:125px}.legend i{display:inline-block;width:9px;height:9px;border-radius:50%;margin-right:7px}.legend .r{background:var(--red);box-shadow:0 0 7px var(--red)}.legend .a{background:var(--amber);box-shadow:0 0 7px var(--amber)}.legend .b{background:var(--blue);box-shadow:0 0 7px var(--blue)}
|
|
19
|
+
.scope-row{display:grid;grid-template-columns:1.1fr 2.2fr;gap:10px;padding:0 18px 13px}.scope,.project{border:1px solid var(--line);border-radius:var(--r-md);background:linear-gradient(145deg,#14243b,#0d182a);box-shadow:0 7px 22px #0003}.scope{display:flex;align-items:center;gap:14px;padding:12px 15px}.scope-icon{font-size:29px;color:#c07bff;text-shadow:0 0 12px #9a63ff88}.scope h2{margin:0;font-size:16px}.scope p{margin:2px 0;color:var(--muted);font-size:11px}.scope select{flex:1;min-width:190px;background:#07111f;color:var(--text);border:1px solid var(--purple);border-radius:9px;padding:10px;box-shadow:0 0 0 2px #8b5cf622}.projects{display:flex;gap:8px;overflow:auto}.project{min-width:145px;padding:10px 13px;border-color:transparent;color:var(--text);text-align:left}.project:not(:disabled):hover{border-color:#8558df}.project.active{background:linear-gradient(180deg,#7137c9,#421b8c);border-color:#b99cff;box-shadow:0 0 18px #8b5cf655}.project strong,.project span{display:block}.project strong{font-size:13px}.project span{color:var(--muted);font-size:10px}.project:disabled{opacity:.58}
|
|
20
|
+
.workspace{min-height:0;display:grid;grid-template-columns:205px 235px 300px minmax(430px,1fr) 320px;gap:1px;background:var(--line);margin:0 18px 17px;border:1px solid var(--line);border-radius:var(--r-lg);overflow:hidden;box-shadow:0 12px 34px #0004}.pane{min-width:0;min-height:0;background:var(--surface)}.head{height:45px;padding:0 14px;display:flex;align-items:center;background:linear-gradient(180deg,#172840,#142239);border-bottom:1px solid var(--line);font-size:10px;font-weight:900;letter-spacing:.1em;color:#a7b5c9}.scroll{height:calc(100% - 45px);overflow:auto}.side{padding:10px;background:linear-gradient(180deg,#122139,#0e1b2e)}.side button{display:block;width:100%;margin-bottom:5px;padding:11px;border:1px solid transparent;border-radius:9px;background:transparent;color:#b6c2d4;text-align:left;font-size:13px;font-weight:750}.side button.active{background:linear-gradient(180deg,#7137c9,#421b8c);color:#fff;border-color:#bd91ff;box-shadow:0 0 15px #8b5cf655}.side button.disabled{opacity:.35}.tree{padding:9px}.folder>summary{cursor:pointer;padding:6px;color:#aebbd0;list-style:none;font-weight:800}.folder>summary::-webkit-details-marker{display:none}.folder>summary:before{content:'▸';display:inline-block;width:17px;color:#8799b3}.folder[open]>summary:before{content:'▾'}.file,.finding{display:flex;width:100%;gap:8px;align-items:center;text-align:left;background:transparent;color:var(--text);border:1px solid transparent;border-radius:8px;padding:8px}.file:hover,.file.selected,.finding:hover,.finding.selected{background:#29466f;border-color:#9562ed;box-shadow:inset 3px 0 #c098ff}.file{font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.count{margin-left:auto;color:#9fb0c8}.finding-list{padding:9px}.finding{display:block;margin-bottom:8px}.finding strong{display:block;font-size:13px;line-height:1.28}.finding small{display:block;margin-top:5px;color:var(--muted);font-size:10px}.code{height:calc(100% - 45px);display:flex;flex-direction:column}.meta{padding:10px 14px;border-bottom:1px solid var(--line);color:#aab8cc;background:#0c1829;font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.code-scroll{overflow:auto;flex:1;background:var(--code);padding:17px 0}.line{display:grid;grid-template-columns:58px 1fr;font:13px/1.8 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre;color:#e6ebf5}.no{color:#657892;text-align:right;padding-right:15px;border-right:1px solid #1c2d45}.text{padding:0 17px}.line.hit{background:linear-gradient(90deg,#4c3716,#3d2d15 75%,transparent);box-shadow:inset 3px 0 #e5a82f}.details{padding:18px;background:linear-gradient(180deg,#101e32,#0d1829)}.details h2{margin:0 0 15px;font-size:19px;line-height:1.25}.details h3{margin:17px 0 4px;color:#91a2ba;font-size:10px;text-transform:uppercase;letter-spacing:.08em}.actions{display:flex;gap:7px;flex-wrap:wrap}.actions button{background:linear-gradient(180deg,#7440d1,#4f209c);border:1px solid #a477f5;border-radius:7px;color:#fff;padding:8px 10px;font-size:11px;font-weight:750;box-shadow:0 5px 12px #0003}.empty{padding:22px;color:var(--muted)}.rtl-value{unicode-bidi:isolate;direction:auto}
|
|
21
|
+
.finding-filters{display:flex;align-items:end;gap:8px;flex-wrap:wrap;min-width:0;padding:0 18px 12px}.finding-filters strong{width:100%;font-size:12px;color:#c5d2e6}.filter-control{display:flex;flex-direction:column;gap:4px;min-width:0;color:var(--muted);font-size:10px;font-weight:750}.filter-control select,.finding-filters>button{min-width:0;min-height:38px;background:#07111f;color:var(--text);border:1px solid var(--line);border-radius:8px;padding:7px 9px}.filter-control select{max-width:100%}.finding-filters>button{color:#fff;background:#253b5d}.filter-summary{align-self:center;color:var(--muted);font-size:10px;margin-left:auto;overflow-wrap:anywhere}.mobile-back{display:none}
|
|
22
|
+
@media(max-width:1450px){.brand{min-width:300px}.nav button{padding:10px 10px}.summary{grid-template-columns:1.3fr .8fr .85fr .85fr .85fr .9fr 1.5fr}.workspace{grid-template-columns:185px 215px 270px minmax(360px,1fr) 290px}}
|
|
23
|
+
@media(max-width:1350px){.workspace{grid-template-columns:185px 270px minmax(320px,1fr) 270px}.workspace>.pane:nth-child(2){display:none}.finding-filters{display:grid;grid-template-columns:repeat(5,minmax(0,1fr)) minmax(180px,1fr);align-items:end}.finding-filters strong{grid-column:1/-1}.filter-summary{margin-left:0}}
|
|
24
|
+
@media(max-width:1100px){.summary{grid-template-columns:repeat(4,1fr)}.severity-chart{grid-column:span 2}.scope-row{grid-template-columns:1fr}.workspace{grid-template-columns:175px 205px minmax(300px,1fr) 270px}.workspace>.pane:nth-child(2){display:none}.tools input{width:130px}.finding-filters{padding-left:12px;padding-right:12px}}
|
|
25
|
+
@media(max-width:760px){.app{grid-template-rows:auto auto auto auto 1fr}.top{flex-wrap:wrap;min-height:118px;padding:10px 14px}.brand{min-width:0;flex:1;font-size:17px}.nav{order:3;width:100%;overflow:auto}.nav button{min-height:42px}.tools{width:100%;margin-left:0}.tools input{flex:1;width:auto}.finding-filters{display:flex;padding:0 10px 10px;align-items:stretch}.filter-control{flex:1 1 calc(50% - 8px);min-width:140px}.filter-control select,.finding-filters>button{width:100%;min-height:44px}.finding-filters>button{flex:1 1 100%}.filter-summary{width:100%;margin:0}.summary{grid-template-columns:repeat(2,1fr);padding:10px}.summary .card{min-height:72px;padding:10px}.summary .card strong{font-size:21px}.severity-chart{grid-column:auto}.scope-row{padding:0 10px 10px}.scope{align-items:stretch;flex-wrap:wrap}.scope select{min-width:100%;min-height:44px}.projects{display:none}.workspace{display:flex;flex-direction:column;margin:0 10px 10px;border-radius:12px}.workspace>.pane:nth-child(1){display:none}.workspace>.pane:nth-child(2){display:none}.workspace>.pane:nth-child(3){order:1;height:420px}.workspace>.pane:nth-child(5){order:2;height:auto;min-height:520px}.workspace>.pane:nth-child(4){order:3;height:420px}.pane{width:100%}.head{min-height:45px}.scroll{height:calc(100% - 45px)}.details{padding:14px}.details h2{font-size:18px;overflow-wrap:anywhere}.details h3{margin-top:14px}.mobile-back{display:inline-flex!important;align-items:center;min-height:44px;margin-bottom:10px;background:#253b5d!important;border-color:#5778a9!important}.actions button,.actions a{min-height:44px}.review-diff,.code-scroll,.meta,.validation-results,.evidence-grid,.audit-grid{overflow-wrap:anywhere;word-break:break-word}.review-diff{white-space:pre-wrap;max-width:100%;overflow:auto}.screenshot-preview img{max-width:100%;height:auto}.details dialog{max-width:calc(100vw - 24px)}}
|
|
26
|
+
`;
|
|
27
|
+
export function dashboardHtml(report, includeArtifactLinks = false, snippets) { const data = escapeJson(JSON.stringify(toDashboardData(report, snippets))), links = includeArtifactLinks ? '<nav aria-label="Report artifacts"><a href="rtl-report.json">JSON</a> <a href="rtl-report.md">Markdown</a> <a href="rtl-report-structured.md">Structured Markdown</a></nav>' : ''; return `<!doctype html><html lang="en" dir="ltr"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>RTL Migration Analyzer v3 — Code Explorer</title><style>${css}.rtl-value{unicode-bidi:isolate;direction:auto}</style></head><body><div id="dashboard" aria-label="RTL code explorer"></div>${links}<script type="application/json" id="rtl-dashboard-data">${data}</script><script>${dashboardClientSource.replace('__SEVERITY_LABELS__', JSON.stringify({ Major: severityDisplayLabel('Major'), Minor: severityDisplayLabel('Minor'), Info: severityDisplayLabel('Info') }))}</script></body></html>\n`; }
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { lstat, readdir, readFile, realpath } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
const excludedDirectories = new Set(['node_modules', '.git', '.nx', 'dist', 'build', 'out', 'coverage', '.next', '.cache', 'test-results', 'playwright-report', '.vite', '.turbo']);
|
|
4
|
+
const supported = /\.(css|scss|tsx?|jsx?|html)$/;
|
|
5
|
+
const sourceLike = /\.(css|scss|sass|less|styl|tsx?|jsx?|html)$/;
|
|
6
|
+
const compareNames = (a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
|
|
7
|
+
async function walk(root, relative, files, skipped) {
|
|
8
|
+
for (const entry of (await readdir(join(root, relative), { withFileTypes: true })).sort(compareNames)) {
|
|
9
|
+
const path = relative ? `${relative}/${entry.name}` : entry.name;
|
|
10
|
+
if (entry.isSymbolicLink()) {
|
|
11
|
+
skipped.push(path);
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
if (entry.isDirectory()) {
|
|
15
|
+
if (!excludedDirectories.has(entry.name))
|
|
16
|
+
await walk(root, path, files, skipped);
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
if (/^rtl-report(?:-|\.)/.test(entry.name) || entry.name === 'rtl-report-dashboard.html')
|
|
20
|
+
continue;
|
|
21
|
+
if (supported.test(path) && !path.endsWith('.stories.tsx')) {
|
|
22
|
+
files.add(path);
|
|
23
|
+
}
|
|
24
|
+
else if (sourceLike.test(path) && !path.endsWith('.stories.tsx')) {
|
|
25
|
+
skipped.push(path);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function nxDiscovery(root) {
|
|
30
|
+
const files = new Set();
|
|
31
|
+
const skipped = [];
|
|
32
|
+
for (const group of ['apps', 'libs']) {
|
|
33
|
+
if ((await lstat(join(root, group))).isSymbolicLink())
|
|
34
|
+
throw new Error('Symlink project group not permitted');
|
|
35
|
+
}
|
|
36
|
+
for (const group of ['apps', 'libs'])
|
|
37
|
+
for (const dir of (await readdir(join(root, group))).sort()) {
|
|
38
|
+
const base = `${group}/${dir}`;
|
|
39
|
+
if (!(await lstat(join(root, base))).isDirectory())
|
|
40
|
+
continue;
|
|
41
|
+
const metadata = JSON.parse(await readFile(join(root, base, 'project.json'), 'utf8'));
|
|
42
|
+
if (!metadata.sourceRoot.startsWith(`${base}/`) || metadata.sourceRoot.includes('..'))
|
|
43
|
+
throw new Error('Invalid sourceRoot');
|
|
44
|
+
if ((await lstat(join(root, metadata.sourceRoot))).isSymbolicLink())
|
|
45
|
+
throw new Error('Symlink sourceRoot not permitted');
|
|
46
|
+
await walk(root, metadata.sourceRoot, files, skipped);
|
|
47
|
+
if (group === 'apps') {
|
|
48
|
+
if ((await lstat(join(root, base, 'index.html'))).isSymbolicLink())
|
|
49
|
+
throw new Error('Symlink HTML not permitted');
|
|
50
|
+
files.add(`${base}/index.html`);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { root, files: [...files].sort(), skipped: skipped.sort() };
|
|
54
|
+
}
|
|
55
|
+
export async function discover(rootInput) {
|
|
56
|
+
const root = await realpath(rootInput);
|
|
57
|
+
const stat = await lstat(root);
|
|
58
|
+
if (!stat.isDirectory())
|
|
59
|
+
throw new Error('Scan root must be a directory');
|
|
60
|
+
const apps = await lstat(join(root, 'apps')).catch(() => undefined);
|
|
61
|
+
const libs = await lstat(join(root, 'libs')).catch(() => undefined);
|
|
62
|
+
if (apps || libs) {
|
|
63
|
+
if (!apps?.isDirectory() || !libs?.isDirectory())
|
|
64
|
+
throw new Error('Incomplete Nx workspace: apps/ and libs/ are both required');
|
|
65
|
+
return nxDiscovery(root);
|
|
66
|
+
}
|
|
67
|
+
const files = new Set();
|
|
68
|
+
const skipped = [];
|
|
69
|
+
await walk(root, '', files, skipped);
|
|
70
|
+
return { root, files: [...files].sort(), skipped: skipped.sort() };
|
|
71
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { BIDI_TRANSFORMATION_ID, proposeBidiIsolation } from './codemod.js';
|
|
2
|
+
// Deliberately empty until a transformation implementation and its preconditions are verified.
|
|
3
|
+
export const verifiedTransformationStrategies = { 'RTL.BIDI.ISOLATION:invoice-id': { preconditions: ['exact InvoiceTable.tsx finding range', 'direct i.id JSX expression', 'no bdi or dir ancestor'], transformationId: BIDI_TRANSFORMATION_ID } };
|
|
4
|
+
export function classifyEligibility(finding, evidenceComplete = true, sourceText) {
|
|
5
|
+
if (!evidenceComplete)
|
|
6
|
+
return { eligibility: 'MANUAL', reason: 'Required evidence is incomplete or stale.', evidence: finding.evidenceIds, transformationId: null, blockers: ['INCOMPLETE_OR_STALE_EVIDENCE'] };
|
|
7
|
+
if (finding.ruleId === 'RTL.BIDI.ISOLATION' && sourceText) {
|
|
8
|
+
try {
|
|
9
|
+
const proposal = proposeBidiIsolation(finding, sourceText);
|
|
10
|
+
return { eligibility: 'AUTOMATED_ELIGIBLE', reason: 'The verified bidi-isolation transformation matches the exact supported AST shape and bounded source range.', evidence: finding.evidenceIds, transformationId: proposal.transformationId, blockers: [] };
|
|
11
|
+
}
|
|
12
|
+
catch (error) {
|
|
13
|
+
return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal exists, but the source does not satisfy the verified transformation preconditions.', evidence: finding.evidenceIds, transformationId: BIDI_TRANSFORMATION_ID, blockers: [error instanceof Error ? error.message : 'TRANSFORMATION_PRECONDITION_FAILED'] };
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
if (finding.ruleId === 'RTL.BIDI.ISOLATION' && finding.path === 'apps/invoicing/src/components/InvoiceTable.tsx')
|
|
17
|
+
return { eligibility: 'ASSISTED', reason: 'A bounded bidi-isolation proposal is possible, but rendered punctuation and product semantics still require human review.', evidence: finding.evidenceIds, transformationId: 'bidi-isolate-auto', blockers: ['HUMAN_SEMANTIC_REVIEW_REQUIRED', 'NO_VERIFIED_CODEMOD_IMPLEMENTATION'] };
|
|
18
|
+
return { eligibility: 'MANUAL', reason: 'Semantic intent, runtime behavior, or styling ownership is not established by static evidence.', evidence: finding.evidenceIds, transformationId: null, blockers: ['SEMANTIC_OR_RUNTIME_INTENT_UNPROVEN'] };
|
|
19
|
+
}
|
package/dist/html.js
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { parse } from "parse5";
|
|
2
|
+
import { fact, range } from "./model.js";
|
|
3
|
+
import { extractTailwind } from './tailwind.js';
|
|
4
|
+
import { extractBootstrap } from './bootstrap.js';
|
|
5
|
+
export function extractHtml(path, text) {
|
|
6
|
+
const evidence = [];
|
|
7
|
+
const diagnostics = [];
|
|
8
|
+
const doc = parse(text, { sourceCodeLocationInfo: true, onParseError: e => { if (e.code !== 'missing-doctype')
|
|
9
|
+
diagnostics.push({ path, code: 'HTML_PARSE', message: e.code, range: range(text, e.startOffset, e.endOffset) }); } });
|
|
10
|
+
function walk(n) {
|
|
11
|
+
if ('tagName' in n && n.tagName === 'html') {
|
|
12
|
+
for (const attr of n.attrs.filter(a => ['dir', 'lang'].includes(a.name))) {
|
|
13
|
+
const loc = n.sourceCodeLocation?.attrs?.[attr.name];
|
|
14
|
+
if (loc)
|
|
15
|
+
evidence.push(fact(path, text, 'html-root', 'html', attr.name, attr.value, loc.startOffset, loc.endOffset, 'initial-document-attribute'));
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if ('tagName' in n) {
|
|
19
|
+
for (const attr of n.attrs.filter(a => a.name === 'class' || a.name === 'className')) {
|
|
20
|
+
const loc = n.sourceCodeLocation?.attrs?.[attr.name];
|
|
21
|
+
if (loc) {
|
|
22
|
+
const segment = text.slice(loc.startOffset, loc.endOffset);
|
|
23
|
+
const valueOffset = loc.startOffset + segment.indexOf(attr.value);
|
|
24
|
+
evidence.push(...extractTailwind(path, text, attr.value, valueOffset, `${n.tagName}`));
|
|
25
|
+
evidence.push(...extractBootstrap(path, text, attr.value, valueOffset, `${n.tagName}`));
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
if ('childNodes' in n)
|
|
30
|
+
n.childNodes.forEach(walk);
|
|
31
|
+
}
|
|
32
|
+
walk(doc);
|
|
33
|
+
return { evidence, diagnostics };
|
|
34
|
+
}
|
package/dist/model.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
export const hash = (s) => createHash("sha256").update(s).digest("hex");
|
|
3
|
+
export function range(text, start, end) {
|
|
4
|
+
const point = (offset) => { const lines = text.slice(0, offset).split(/\r\n|\r|\n/); return { offset, line: lines.length, column: lines.at(-1).length + 1 }; };
|
|
5
|
+
return { start: point(start), end: point(end) };
|
|
6
|
+
}
|
|
7
|
+
export function fact(path, text, mechanism, context, property, value, start, end, semantics = "css", tokens) {
|
|
8
|
+
return { id: hash(`${path}|${mechanism}|${context}|${property}|${start}`).slice(0, 24), path, mechanism, context, property, value, original: text.slice(start, end), range: range(text, start, end), semantics, ...(tokens ? { tokens } : {}) };
|
|
9
|
+
}
|